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"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || strlen(logmsg) == 0) {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3110 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3111 goto done;
3113 error = got_worktree_open(&worktree, worktree_path);
3114 if (error != NULL)
3115 goto done;
3117 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3118 path_prefix);
3119 if (error != NULL)
3120 goto done;
3121 if (!same_path_prefix) {
3122 error = got_error(GOT_ERR_PATH_PREFIX);
3123 goto done;
3126 if (commit_id_str) {
3127 struct got_reflist_head refs;
3128 TAILQ_INIT(&refs);
3129 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3130 NULL);
3131 if (error)
3132 goto done;
3133 error = got_repo_match_object_id(&commit_id, NULL,
3134 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3135 got_ref_list_free(&refs);
3136 if (error)
3137 goto done;
3138 error = check_linear_ancestry(commit_id,
3139 got_worktree_get_base_commit_id(worktree), 0, repo);
3140 if (error != NULL) {
3141 if (error->code == GOT_ERR_ANCESTRY) {
3142 error = checkout_ancestry_error(
3143 head_ref, commit_id_str);
3145 goto done;
3147 error = check_same_branch(commit_id, head_ref, repo);
3148 if (error) {
3149 if (error->code == GOT_ERR_ANCESTRY) {
3150 error = checkout_ancestry_error(
3151 head_ref, commit_id_str);
3153 goto done;
3155 error = got_worktree_set_base_commit_id(worktree, repo,
3156 commit_id);
3157 if (error)
3158 goto done;
3159 /* Expand potentially abbreviated commit ID string. */
3160 free(commit_id_str);
3161 error = got_object_id_str(&commit_id_str, commit_id);
3162 if (error)
3163 goto done;
3164 } else {
3165 commit_id = got_object_id_dup(
3166 got_worktree_get_base_commit_id(worktree));
3167 if (commit_id == NULL) {
3168 error = got_error_from_errno("got_object_id_dup");
3169 goto done;
3171 error = got_object_id_str(&commit_id_str, commit_id);
3172 if (error)
3173 goto done;
3176 error = got_pathlist_append(&paths, "", NULL);
3177 if (error)
3178 goto done;
3179 cpa.worktree_path = worktree_path;
3180 cpa.had_base_commit_ref_error = 0;
3181 cpa.verbosity = verbosity;
3182 error = got_worktree_checkout_files(worktree, &paths, repo,
3183 checkout_progress, &cpa, check_cancelled, NULL);
3184 if (error != NULL)
3185 goto done;
3187 if (got_ref_is_symbolic(head_ref)) {
3188 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3189 if (error)
3190 goto done;
3191 refname = got_ref_get_name(ref);
3192 } else
3193 refname = got_ref_get_name(head_ref);
3194 printf("Checked out %s: %s\n", refname, commit_id_str);
3195 printf("Now shut up and hack\n");
3196 if (cpa.had_base_commit_ref_error)
3197 show_worktree_base_ref_warning();
3198 done:
3199 if (pack_fds) {
3200 const struct got_error *pack_err =
3201 got_repo_pack_fds_close(pack_fds);
3202 if (error == NULL)
3203 error = pack_err;
3205 if (head_ref)
3206 got_ref_close(head_ref);
3207 if (ref)
3208 got_ref_close(ref);
3209 if (repo) {
3210 const struct got_error *close_err = got_repo_close(repo);
3211 if (error == NULL)
3212 error = close_err;
3214 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3215 free(commit_id_str);
3216 free(commit_id);
3217 free(repo_path);
3218 free(worktree_path);
3219 free(cwd);
3220 return error;
3223 struct got_update_progress_arg {
3224 int did_something;
3225 int conflicts;
3226 int obstructed;
3227 int not_updated;
3228 int missing;
3229 int not_deleted;
3230 int unversioned;
3231 int verbosity;
3234 static void
3235 print_update_progress_stats(struct got_update_progress_arg *upa)
3237 if (!upa->did_something)
3238 return;
3240 if (upa->conflicts > 0)
3241 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3242 if (upa->obstructed > 0)
3243 printf("File paths obstructed by a non-regular file: %d\n",
3244 upa->obstructed);
3245 if (upa->not_updated > 0)
3246 printf("Files not updated because of existing merge "
3247 "conflicts: %d\n", upa->not_updated);
3251 * The meaning of some status codes differs between merge-style operations and
3252 * update operations. For example, the ! status code means "file was missing"
3253 * if changes were merged into the work tree, and "missing file was restored"
3254 * if the work tree was updated. This function should be used by any operation
3255 * which merges changes into the work tree without updating the work tree.
3257 static void
3258 print_merge_progress_stats(struct got_update_progress_arg *upa)
3260 if (!upa->did_something)
3261 return;
3263 if (upa->conflicts > 0)
3264 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3265 if (upa->obstructed > 0)
3266 printf("File paths obstructed by a non-regular file: %d\n",
3267 upa->obstructed);
3268 if (upa->missing > 0)
3269 printf("Files which had incoming changes but could not be "
3270 "found in the work tree: %d\n", upa->missing);
3271 if (upa->not_deleted > 0)
3272 printf("Files not deleted due to differences in deleted "
3273 "content: %d\n", upa->not_deleted);
3274 if (upa->unversioned > 0)
3275 printf("Files not merged because an unversioned file was "
3276 "found in the work tree: %d\n", upa->unversioned);
3279 __dead static void
3280 usage_update(void)
3282 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3283 "[path ...]\n", getprogname());
3284 exit(1);
3287 static const struct got_error *
3288 update_progress(void *arg, unsigned char status, const char *path)
3290 struct got_update_progress_arg *upa = arg;
3292 if (status == GOT_STATUS_EXISTS ||
3293 status == GOT_STATUS_BASE_REF_ERR)
3294 return NULL;
3296 upa->did_something = 1;
3298 /* Base commit bump happens silently. */
3299 if (status == GOT_STATUS_BUMP_BASE)
3300 return NULL;
3302 if (status == GOT_STATUS_CONFLICT)
3303 upa->conflicts++;
3304 if (status == GOT_STATUS_OBSTRUCTED)
3305 upa->obstructed++;
3306 if (status == GOT_STATUS_CANNOT_UPDATE)
3307 upa->not_updated++;
3308 if (status == GOT_STATUS_MISSING)
3309 upa->missing++;
3310 if (status == GOT_STATUS_CANNOT_DELETE)
3311 upa->not_deleted++;
3312 if (status == GOT_STATUS_UNVERSIONED)
3313 upa->unversioned++;
3315 while (path[0] == '/')
3316 path++;
3317 if (upa->verbosity >= 0)
3318 printf("%c %s\n", status, path);
3320 return NULL;
3323 static const struct got_error *
3324 switch_head_ref(struct got_reference *head_ref,
3325 struct got_object_id *commit_id, struct got_worktree *worktree,
3326 struct got_repository *repo)
3328 const struct got_error *err = NULL;
3329 char *base_id_str;
3330 int ref_has_moved = 0;
3332 /* Trivial case: switching between two different references. */
3333 if (strcmp(got_ref_get_name(head_ref),
3334 got_worktree_get_head_ref_name(worktree)) != 0) {
3335 printf("Switching work tree from %s to %s\n",
3336 got_worktree_get_head_ref_name(worktree),
3337 got_ref_get_name(head_ref));
3338 return got_worktree_set_head_ref(worktree, head_ref);
3341 err = check_linear_ancestry(commit_id,
3342 got_worktree_get_base_commit_id(worktree), 0, repo);
3343 if (err) {
3344 if (err->code != GOT_ERR_ANCESTRY)
3345 return err;
3346 ref_has_moved = 1;
3348 if (!ref_has_moved)
3349 return NULL;
3351 /* Switching to a rebased branch with the same reference name. */
3352 err = got_object_id_str(&base_id_str,
3353 got_worktree_get_base_commit_id(worktree));
3354 if (err)
3355 return err;
3356 printf("Reference %s now points at a different branch\n",
3357 got_worktree_get_head_ref_name(worktree));
3358 printf("Switching work tree from %s to %s\n", base_id_str,
3359 got_worktree_get_head_ref_name(worktree));
3360 return NULL;
3363 static const struct got_error *
3364 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3366 const struct got_error *err;
3367 int in_progress;
3369 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3370 if (err)
3371 return err;
3372 if (in_progress)
3373 return got_error(GOT_ERR_REBASING);
3375 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3376 if (err)
3377 return err;
3378 if (in_progress)
3379 return got_error(GOT_ERR_HISTEDIT_BUSY);
3381 return NULL;
3384 static const struct got_error *
3385 check_merge_in_progress(struct got_worktree *worktree,
3386 struct got_repository *repo)
3388 const struct got_error *err;
3389 int in_progress;
3391 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3392 if (err)
3393 return err;
3394 if (in_progress)
3395 return got_error(GOT_ERR_MERGE_BUSY);
3397 return NULL;
3400 static const struct got_error *
3401 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3402 char *argv[], struct got_worktree *worktree)
3404 const struct got_error *err = NULL;
3405 char *path;
3406 struct got_pathlist_entry *new;
3407 int i;
3409 if (argc == 0) {
3410 path = strdup("");
3411 if (path == NULL)
3412 return got_error_from_errno("strdup");
3413 return got_pathlist_append(paths, path, NULL);
3416 for (i = 0; i < argc; i++) {
3417 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3418 if (err)
3419 break;
3420 err = got_pathlist_insert(&new, paths, path, NULL);
3421 if (err || new == NULL /* duplicate */) {
3422 free(path);
3423 if (err)
3424 break;
3428 return err;
3431 static const struct got_error *
3432 wrap_not_worktree_error(const struct got_error *orig_err,
3433 const char *cmdname, const char *path)
3435 const struct got_error *err;
3436 struct got_repository *repo;
3437 static char msg[512];
3438 int *pack_fds = NULL;
3440 err = got_repo_pack_fds_open(&pack_fds);
3441 if (err)
3442 return err;
3444 err = got_repo_open(&repo, path, NULL, pack_fds);
3445 if (err)
3446 return orig_err;
3448 snprintf(msg, sizeof(msg),
3449 "'got %s' needs a work tree in addition to a git repository\n"
3450 "Work trees can be checked out from this Git repository with "
3451 "'got checkout'.\n"
3452 "The got(1) manual page contains more information.", cmdname);
3453 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3454 if (repo) {
3455 const struct got_error *close_err = got_repo_close(repo);
3456 if (close_err == NULL)
3457 err = close_err;
3459 if (pack_fds) {
3460 const struct got_error *pack_err =
3461 got_repo_pack_fds_close(pack_fds);
3462 if (err == NULL)
3463 err = pack_err;
3465 return err;
3468 static const struct got_error *
3469 cmd_update(int argc, char *argv[])
3471 const struct got_error *error = NULL;
3472 struct got_repository *repo = NULL;
3473 struct got_worktree *worktree = NULL;
3474 char *worktree_path = NULL;
3475 struct got_object_id *commit_id = NULL;
3476 char *commit_id_str = NULL;
3477 const char *branch_name = NULL;
3478 struct got_reference *head_ref = NULL;
3479 struct got_pathlist_head paths;
3480 struct got_pathlist_entry *pe;
3481 int ch, verbosity = 0;
3482 struct got_update_progress_arg upa;
3483 int *pack_fds = NULL;
3485 TAILQ_INIT(&paths);
3487 #ifndef PROFILE
3488 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3489 "unveil", NULL) == -1)
3490 err(1, "pledge");
3491 #endif
3493 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3494 switch (ch) {
3495 case 'b':
3496 branch_name = optarg;
3497 break;
3498 case 'c':
3499 commit_id_str = strdup(optarg);
3500 if (commit_id_str == NULL)
3501 return got_error_from_errno("strdup");
3502 break;
3503 case 'q':
3504 verbosity = -1;
3505 break;
3506 default:
3507 usage_update();
3508 /* NOTREACHED */
3512 argc -= optind;
3513 argv += optind;
3515 worktree_path = getcwd(NULL, 0);
3516 if (worktree_path == NULL) {
3517 error = got_error_from_errno("getcwd");
3518 goto done;
3521 error = got_repo_pack_fds_open(&pack_fds);
3522 if (error != NULL)
3523 goto done;
3525 error = got_worktree_open(&worktree, worktree_path);
3526 if (error) {
3527 if (error->code == GOT_ERR_NOT_WORKTREE)
3528 error = wrap_not_worktree_error(error, "update",
3529 worktree_path);
3530 goto done;
3533 error = check_rebase_or_histedit_in_progress(worktree);
3534 if (error)
3535 goto done;
3537 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3538 NULL, pack_fds);
3539 if (error != NULL)
3540 goto done;
3542 error = apply_unveil(got_repo_get_path(repo), 0,
3543 got_worktree_get_root_path(worktree));
3544 if (error)
3545 goto done;
3547 error = check_merge_in_progress(worktree, repo);
3548 if (error)
3549 goto done;
3551 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3552 if (error)
3553 goto done;
3555 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3556 got_worktree_get_head_ref_name(worktree), 0);
3557 if (error != NULL)
3558 goto done;
3559 if (commit_id_str == NULL) {
3560 error = got_ref_resolve(&commit_id, repo, head_ref);
3561 if (error != NULL)
3562 goto done;
3563 error = got_object_id_str(&commit_id_str, commit_id);
3564 if (error != NULL)
3565 goto done;
3566 } else {
3567 struct got_reflist_head refs;
3568 TAILQ_INIT(&refs);
3569 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3570 NULL);
3571 if (error)
3572 goto done;
3573 error = got_repo_match_object_id(&commit_id, NULL,
3574 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3575 got_ref_list_free(&refs);
3576 free(commit_id_str);
3577 commit_id_str = NULL;
3578 if (error)
3579 goto done;
3580 error = got_object_id_str(&commit_id_str, commit_id);
3581 if (error)
3582 goto done;
3585 if (branch_name) {
3586 struct got_object_id *head_commit_id;
3587 TAILQ_FOREACH(pe, &paths, entry) {
3588 if (pe->path_len == 0)
3589 continue;
3590 error = got_error_msg(GOT_ERR_BAD_PATH,
3591 "switching between branches requires that "
3592 "the entire work tree gets updated");
3593 goto done;
3595 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3596 if (error)
3597 goto done;
3598 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3599 repo);
3600 free(head_commit_id);
3601 if (error != NULL)
3602 goto done;
3603 error = check_same_branch(commit_id, head_ref, repo);
3604 if (error)
3605 goto done;
3606 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3607 if (error)
3608 goto done;
3609 } else {
3610 error = check_linear_ancestry(commit_id,
3611 got_worktree_get_base_commit_id(worktree), 0, repo);
3612 if (error != NULL) {
3613 if (error->code == GOT_ERR_ANCESTRY)
3614 error = got_error(GOT_ERR_BRANCH_MOVED);
3615 goto done;
3617 error = check_same_branch(commit_id, head_ref, repo);
3618 if (error)
3619 goto done;
3622 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3623 commit_id) != 0) {
3624 error = got_worktree_set_base_commit_id(worktree, repo,
3625 commit_id);
3626 if (error)
3627 goto done;
3630 memset(&upa, 0, sizeof(upa));
3631 upa.verbosity = verbosity;
3632 error = got_worktree_checkout_files(worktree, &paths, repo,
3633 update_progress, &upa, check_cancelled, NULL);
3634 if (error != NULL)
3635 goto done;
3637 if (upa.did_something) {
3638 printf("Updated to %s: %s\n",
3639 got_worktree_get_head_ref_name(worktree), commit_id_str);
3640 } else
3641 printf("Already up-to-date\n");
3643 print_update_progress_stats(&upa);
3644 done:
3645 if (pack_fds) {
3646 const struct got_error *pack_err =
3647 got_repo_pack_fds_close(pack_fds);
3648 if (error == NULL)
3649 error = pack_err;
3651 if (repo) {
3652 const struct got_error *close_err = got_repo_close(repo);
3653 if (error == NULL)
3654 error = close_err;
3656 free(worktree_path);
3657 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3658 free(commit_id);
3659 free(commit_id_str);
3660 return error;
3663 static const struct got_error *
3664 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3665 const char *path, int diff_context, int ignore_whitespace,
3666 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3667 struct got_repository *repo, FILE *outfile)
3669 const struct got_error *err = NULL;
3670 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3671 FILE *f1 = NULL, *f2 = NULL;
3672 int fd1 = -1, fd2 = -1;
3674 fd1 = got_opentempfd();
3675 if (fd1 == -1)
3676 return got_error_from_errno("got_opentempfd");
3677 fd2 = got_opentempfd();
3678 if (fd2 == -1) {
3679 err = got_error_from_errno("got_opentempfd");
3680 goto done;
3683 if (blob_id1) {
3684 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3685 fd1);
3686 if (err)
3687 goto done;
3690 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3691 if (err)
3692 goto done;
3694 f1 = got_opentemp();
3695 if (f1 == NULL) {
3696 err = got_error_from_errno("got_opentemp");
3697 goto done;
3699 f2 = got_opentemp();
3700 if (f2 == NULL) {
3701 err = got_error_from_errno("got_opentemp");
3702 goto done;
3705 while (path[0] == '/')
3706 path++;
3707 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3708 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3709 force_text_diff, dsa, outfile);
3710 done:
3711 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3712 err = got_error_from_errno("close");
3713 if (blob1)
3714 got_object_blob_close(blob1);
3715 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3716 err = got_error_from_errno("close");
3717 if (blob2)
3718 got_object_blob_close(blob2);
3719 if (f1 && fclose(f1) == EOF && err == NULL)
3720 err = got_error_from_errno("fclose");
3721 if (f2 && fclose(f2) == EOF && err == NULL)
3722 err = got_error_from_errno("fclose");
3723 return err;
3726 static const struct got_error *
3727 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3728 const char *path, int diff_context, int ignore_whitespace,
3729 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3730 struct got_repository *repo, FILE *outfile)
3732 const struct got_error *err = NULL;
3733 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3734 struct got_diff_blob_output_unidiff_arg arg;
3735 FILE *f1 = NULL, *f2 = NULL;
3736 int fd1 = -1, fd2 = -1;
3738 if (tree_id1) {
3739 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3740 if (err)
3741 goto done;
3742 fd1 = got_opentempfd();
3743 if (fd1 == -1) {
3744 err = got_error_from_errno("got_opentempfd");
3745 goto done;
3749 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3750 if (err)
3751 goto done;
3753 f1 = got_opentemp();
3754 if (f1 == NULL) {
3755 err = got_error_from_errno("got_opentemp");
3756 goto done;
3759 f2 = got_opentemp();
3760 if (f2 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3764 fd2 = got_opentempfd();
3765 if (fd2 == -1) {
3766 err = got_error_from_errno("got_opentempfd");
3767 goto done;
3769 arg.diff_context = diff_context;
3770 arg.ignore_whitespace = ignore_whitespace;
3771 arg.force_text_diff = force_text_diff;
3772 arg.diffstat = dsa;
3773 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3774 arg.outfile = outfile;
3775 arg.lines = NULL;
3776 arg.nlines = 0;
3777 while (path[0] == '/')
3778 path++;
3779 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3780 got_diff_blob_output_unidiff, &arg, 1);
3781 done:
3782 if (tree1)
3783 got_object_tree_close(tree1);
3784 if (tree2)
3785 got_object_tree_close(tree2);
3786 if (f1 && fclose(f1) == EOF && err == NULL)
3787 err = got_error_from_errno("fclose");
3788 if (f2 && fclose(f2) == EOF && err == NULL)
3789 err = got_error_from_errno("fclose");
3790 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3791 err = got_error_from_errno("close");
3792 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3793 err = got_error_from_errno("close");
3794 return err;
3797 static const struct got_error *
3798 get_changed_paths(struct got_pathlist_head *paths,
3799 struct got_commit_object *commit, struct got_repository *repo,
3800 struct got_diffstat_cb_arg *dsa)
3802 const struct got_error *err = NULL;
3803 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3804 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3805 struct got_object_qid *qid;
3806 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3807 FILE *f1 = NULL, *f2 = NULL;
3808 int fd1 = -1, fd2 = -1;
3810 if (dsa) {
3811 cb = got_diff_tree_compute_diffstat;
3813 f1 = got_opentemp();
3814 if (f1 == NULL) {
3815 err = got_error_from_errno("got_opentemp");
3816 goto done;
3818 f2 = got_opentemp();
3819 if (f2 == NULL) {
3820 err = got_error_from_errno("got_opentemp");
3821 goto done;
3823 fd1 = got_opentempfd();
3824 if (fd1 == -1) {
3825 err = got_error_from_errno("got_opentempfd");
3826 goto done;
3828 fd2 = got_opentempfd();
3829 if (fd2 == -1) {
3830 err = got_error_from_errno("got_opentempfd");
3831 goto done;
3835 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3836 if (qid != NULL) {
3837 struct got_commit_object *pcommit;
3838 err = got_object_open_as_commit(&pcommit, repo,
3839 &qid->id);
3840 if (err)
3841 return err;
3843 tree_id1 = got_object_id_dup(
3844 got_object_commit_get_tree_id(pcommit));
3845 if (tree_id1 == NULL) {
3846 got_object_commit_close(pcommit);
3847 return got_error_from_errno("got_object_id_dup");
3849 got_object_commit_close(pcommit);
3853 if (tree_id1) {
3854 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3855 if (err)
3856 goto done;
3859 tree_id2 = got_object_commit_get_tree_id(commit);
3860 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3861 if (err)
3862 goto done;
3864 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3865 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3866 done:
3867 if (tree1)
3868 got_object_tree_close(tree1);
3869 if (tree2)
3870 got_object_tree_close(tree2);
3871 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3872 err = got_error_from_errno("close");
3873 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3874 err = got_error_from_errno("close");
3875 if (f1 && fclose(f1) == EOF && err == NULL)
3876 err = got_error_from_errno("fclose");
3877 if (f2 && fclose(f2) == EOF && err == NULL)
3878 err = got_error_from_errno("fclose");
3879 free(tree_id1);
3880 return err;
3883 static const struct got_error *
3884 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3885 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3886 struct got_repository *repo, FILE *outfile)
3888 const struct got_error *err = NULL;
3889 struct got_commit_object *pcommit = NULL;
3890 char *id_str1 = NULL, *id_str2 = NULL;
3891 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3892 struct got_object_qid *qid;
3894 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3895 if (qid != NULL) {
3896 err = got_object_open_as_commit(&pcommit, repo,
3897 &qid->id);
3898 if (err)
3899 return err;
3900 err = got_object_id_str(&id_str1, &qid->id);
3901 if (err)
3902 goto done;
3905 err = got_object_id_str(&id_str2, id);
3906 if (err)
3907 goto done;
3909 if (path && path[0] != '\0') {
3910 int obj_type;
3911 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3912 if (err)
3913 goto done;
3914 if (pcommit) {
3915 err = got_object_id_by_path(&obj_id1, repo,
3916 pcommit, path);
3917 if (err) {
3918 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3919 free(obj_id2);
3920 goto done;
3924 err = got_object_get_type(&obj_type, repo, obj_id2);
3925 if (err) {
3926 free(obj_id2);
3927 goto done;
3929 fprintf(outfile,
3930 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3931 fprintf(outfile, "commit - %s\n",
3932 id_str1 ? id_str1 : "/dev/null");
3933 fprintf(outfile, "commit + %s\n", id_str2);
3934 switch (obj_type) {
3935 case GOT_OBJ_TYPE_BLOB:
3936 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3937 0, 0, dsa, repo, outfile);
3938 break;
3939 case GOT_OBJ_TYPE_TREE:
3940 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3941 0, 0, dsa, repo, outfile);
3942 break;
3943 default:
3944 err = got_error(GOT_ERR_OBJ_TYPE);
3945 break;
3947 free(obj_id1);
3948 free(obj_id2);
3949 } else {
3950 obj_id2 = got_object_commit_get_tree_id(commit);
3951 if (pcommit)
3952 obj_id1 = got_object_commit_get_tree_id(pcommit);
3953 fprintf(outfile,
3954 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3955 fprintf(outfile, "commit - %s\n",
3956 id_str1 ? id_str1 : "/dev/null");
3957 fprintf(outfile, "commit + %s\n", id_str2);
3958 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3959 dsa, repo, outfile);
3961 done:
3962 free(id_str1);
3963 free(id_str2);
3964 if (pcommit)
3965 got_object_commit_close(pcommit);
3966 return err;
3969 static char *
3970 get_datestr(time_t *time, char *datebuf)
3972 struct tm mytm, *tm;
3973 char *p, *s;
3975 tm = gmtime_r(time, &mytm);
3976 if (tm == NULL)
3977 return NULL;
3978 s = asctime_r(tm, datebuf);
3979 if (s == NULL)
3980 return NULL;
3981 p = strchr(s, '\n');
3982 if (p)
3983 *p = '\0';
3984 return s;
3987 static const struct got_error *
3988 match_commit(int *have_match, struct got_object_id *id,
3989 struct got_commit_object *commit, regex_t *regex)
3991 const struct got_error *err = NULL;
3992 regmatch_t regmatch;
3993 char *id_str = NULL, *logmsg = NULL;
3995 *have_match = 0;
3997 err = got_object_id_str(&id_str, id);
3998 if (err)
3999 return err;
4001 err = got_object_commit_get_logmsg(&logmsg, commit);
4002 if (err)
4003 goto done;
4005 if (regexec(regex, got_object_commit_get_author(commit), 1,
4006 &regmatch, 0) == 0 ||
4007 regexec(regex, got_object_commit_get_committer(commit), 1,
4008 &regmatch, 0) == 0 ||
4009 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4010 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4011 *have_match = 1;
4012 done:
4013 free(id_str);
4014 free(logmsg);
4015 return err;
4018 static void
4019 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4020 regex_t *regex)
4022 regmatch_t regmatch;
4023 struct got_pathlist_entry *pe;
4025 *have_match = 0;
4027 TAILQ_FOREACH(pe, changed_paths, entry) {
4028 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4029 *have_match = 1;
4030 break;
4035 static const struct got_error *
4036 match_patch(int *have_match, struct got_commit_object *commit,
4037 struct got_object_id *id, const char *path, int diff_context,
4038 struct got_repository *repo, regex_t *regex, FILE *f)
4040 const struct got_error *err = NULL;
4041 char *line = NULL;
4042 size_t linesize = 0;
4043 regmatch_t regmatch;
4045 *have_match = 0;
4047 err = got_opentemp_truncate(f);
4048 if (err)
4049 return err;
4051 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4052 if (err)
4053 goto done;
4055 if (fseeko(f, 0L, SEEK_SET) == -1) {
4056 err = got_error_from_errno("fseeko");
4057 goto done;
4060 while (getline(&line, &linesize, f) != -1) {
4061 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4062 *have_match = 1;
4063 break;
4066 done:
4067 free(line);
4068 return err;
4071 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4073 static const struct got_error*
4074 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4075 struct got_object_id *id, struct got_repository *repo,
4076 int local_only)
4078 static const struct got_error *err = NULL;
4079 struct got_reflist_entry *re;
4080 char *s;
4081 const char *name;
4083 *refs_str = NULL;
4085 TAILQ_FOREACH(re, refs, entry) {
4086 struct got_tag_object *tag = NULL;
4087 struct got_object_id *ref_id;
4088 int cmp;
4090 name = got_ref_get_name(re->ref);
4091 if (strcmp(name, GOT_REF_HEAD) == 0)
4092 continue;
4093 if (strncmp(name, "refs/", 5) == 0)
4094 name += 5;
4095 if (strncmp(name, "got/", 4) == 0)
4096 continue;
4097 if (strncmp(name, "heads/", 6) == 0)
4098 name += 6;
4099 if (strncmp(name, "remotes/", 8) == 0) {
4100 if (local_only)
4101 continue;
4102 name += 8;
4103 s = strstr(name, "/" GOT_REF_HEAD);
4104 if (s != NULL && s[strlen(s)] == '\0')
4105 continue;
4107 err = got_ref_resolve(&ref_id, repo, re->ref);
4108 if (err)
4109 break;
4110 if (strncmp(name, "tags/", 5) == 0) {
4111 err = got_object_open_as_tag(&tag, repo, ref_id);
4112 if (err) {
4113 if (err->code != GOT_ERR_OBJ_TYPE) {
4114 free(ref_id);
4115 break;
4117 /* Ref points at something other than a tag. */
4118 err = NULL;
4119 tag = NULL;
4122 cmp = got_object_id_cmp(tag ?
4123 got_object_tag_get_object_id(tag) : ref_id, id);
4124 free(ref_id);
4125 if (tag)
4126 got_object_tag_close(tag);
4127 if (cmp != 0)
4128 continue;
4129 s = *refs_str;
4130 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4131 s ? ", " : "", name) == -1) {
4132 err = got_error_from_errno("asprintf");
4133 free(s);
4134 *refs_str = NULL;
4135 break;
4137 free(s);
4140 return err;
4143 static const struct got_error *
4144 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4145 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4147 const struct got_error *err = NULL;
4148 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4149 char *comma, *s, *nl;
4150 struct got_reflist_head *refs;
4151 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4152 struct tm tm;
4153 time_t committer_time;
4155 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4156 if (refs) {
4157 err = build_refs_str(&ref_str, refs, id, repo, 1);
4158 if (err)
4159 return err;
4161 /* Display the first matching ref only. */
4162 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4163 *comma = '\0';
4166 if (ref_str == NULL) {
4167 err = got_object_id_str(&id_str, id);
4168 if (err)
4169 return err;
4172 committer_time = got_object_commit_get_committer_time(commit);
4173 if (gmtime_r(&committer_time, &tm) == NULL) {
4174 err = got_error_from_errno("gmtime_r");
4175 goto done;
4177 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4178 err = got_error(GOT_ERR_NO_SPACE);
4179 goto done;
4182 err = got_object_commit_get_logmsg(&logmsg0, commit);
4183 if (err)
4184 goto done;
4186 s = logmsg0;
4187 while (isspace((unsigned char)s[0]))
4188 s++;
4190 nl = strchr(s, '\n');
4191 if (nl) {
4192 *nl = '\0';
4195 if (ref_str)
4196 printf("%s%-7s %s\n", datebuf, ref_str, s);
4197 else
4198 printf("%s%.7s %s\n", datebuf, id_str, s);
4200 if (fflush(stdout) != 0 && err == NULL)
4201 err = got_error_from_errno("fflush");
4202 done:
4203 free(id_str);
4204 free(ref_str);
4205 free(logmsg0);
4206 return err;
4209 static const struct got_error *
4210 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4212 struct got_pathlist_entry *pe;
4214 if (header != NULL)
4215 printf("%s\n", header);
4217 TAILQ_FOREACH(pe, dsa->paths, entry) {
4218 struct got_diff_changed_path *cp = pe->data;
4219 int pad = dsa->max_path_len - pe->path_len + 1;
4221 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4222 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4224 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4225 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4226 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4228 if (fflush(stdout) != 0)
4229 return got_error_from_errno("fflush");
4231 return NULL;
4234 static const struct got_error *
4235 printfile(FILE *f)
4237 char buf[8192];
4238 size_t r;
4240 if (fseeko(f, 0L, SEEK_SET) == -1)
4241 return got_error_from_errno("fseek");
4243 for (;;) {
4244 r = fread(buf, 1, sizeof(buf), f);
4245 if (r == 0) {
4246 if (ferror(f))
4247 return got_error_from_errno("fread");
4248 if (feof(f))
4249 break;
4251 if (fwrite(buf, 1, r, stdout) != r)
4252 return got_ferror(stdout, GOT_ERR_IO);
4255 return NULL;
4258 static const struct got_error *
4259 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4260 struct got_repository *repo, const char *path,
4261 struct got_pathlist_head *changed_paths,
4262 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4263 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4264 const char *prefix)
4266 const struct got_error *err = NULL;
4267 FILE *f = NULL;
4268 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4269 char datebuf[26];
4270 time_t committer_time;
4271 const char *author, *committer;
4272 char *refs_str = NULL;
4274 err = got_object_id_str(&id_str, id);
4275 if (err)
4276 return err;
4278 if (custom_refs_str == NULL) {
4279 struct got_reflist_head *refs;
4280 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4281 if (refs) {
4282 err = build_refs_str(&refs_str, refs, id, repo, 0);
4283 if (err)
4284 goto done;
4288 printf(GOT_COMMIT_SEP_STR);
4289 if (custom_refs_str)
4290 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4291 custom_refs_str);
4292 else
4293 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4294 refs_str ? " (" : "", refs_str ? refs_str : "",
4295 refs_str ? ")" : "");
4296 free(id_str);
4297 id_str = NULL;
4298 free(refs_str);
4299 refs_str = NULL;
4300 printf("from: %s\n", got_object_commit_get_author(commit));
4301 author = got_object_commit_get_author(commit);
4302 committer = got_object_commit_get_committer(commit);
4303 if (strcmp(author, committer) != 0)
4304 printf("via: %s\n", committer);
4305 committer_time = got_object_commit_get_committer_time(commit);
4306 datestr = get_datestr(&committer_time, datebuf);
4307 if (datestr)
4308 printf("date: %s UTC\n", datestr);
4309 if (got_object_commit_get_nparents(commit) > 1) {
4310 const struct got_object_id_queue *parent_ids;
4311 struct got_object_qid *qid;
4312 int n = 1;
4313 parent_ids = got_object_commit_get_parent_ids(commit);
4314 STAILQ_FOREACH(qid, parent_ids, entry) {
4315 err = got_object_id_str(&id_str, &qid->id);
4316 if (err)
4317 goto done;
4318 printf("parent %d: %s\n", n++, id_str);
4319 free(id_str);
4320 id_str = NULL;
4324 err = got_object_commit_get_logmsg(&logmsg0, commit);
4325 if (err)
4326 goto done;
4328 logmsg = logmsg0;
4329 do {
4330 line = strsep(&logmsg, "\n");
4331 if (line)
4332 printf(" %s\n", line);
4333 } while (line);
4334 free(logmsg0);
4336 if (changed_paths && diffstat == NULL) {
4337 struct got_pathlist_entry *pe;
4339 TAILQ_FOREACH(pe, changed_paths, entry) {
4340 struct got_diff_changed_path *cp = pe->data;
4342 printf(" %c %s\n", cp->status, pe->path);
4344 printf("\n");
4346 if (show_patch) {
4347 if (diffstat) {
4348 f = got_opentemp();
4349 if (f == NULL) {
4350 err = got_error_from_errno("got_opentemp");
4351 goto done;
4355 err = print_patch(commit, id, path, diff_context, diffstat,
4356 repo, diffstat == NULL ? stdout : f);
4357 if (err)
4358 goto done;
4360 if (diffstat) {
4361 err = print_diffstat(diffstat, NULL);
4362 if (err)
4363 goto done;
4364 if (show_patch) {
4365 err = printfile(f);
4366 if (err)
4367 goto done;
4370 if (show_patch)
4371 printf("\n");
4373 if (fflush(stdout) != 0 && err == NULL)
4374 err = got_error_from_errno("fflush");
4375 done:
4376 if (f && fclose(f) == EOF && err == NULL)
4377 err = got_error_from_errno("fclose");
4378 free(id_str);
4379 free(refs_str);
4380 return err;
4383 static const struct got_error *
4384 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4385 struct got_repository *repo, const char *path, int show_changed_paths,
4386 int show_diffstat, int show_patch, const char *search_pattern,
4387 int diff_context, int limit, int log_branches, int reverse_display_order,
4388 struct got_reflist_object_id_map *refs_idmap, int one_line,
4389 FILE *tmpfile)
4391 const struct got_error *err;
4392 struct got_commit_graph *graph;
4393 regex_t regex;
4394 int have_match;
4395 struct got_object_id_queue reversed_commits;
4396 struct got_object_qid *qid;
4397 struct got_commit_object *commit;
4398 struct got_pathlist_head changed_paths;
4400 STAILQ_INIT(&reversed_commits);
4401 TAILQ_INIT(&changed_paths);
4403 if (search_pattern && regcomp(&regex, search_pattern,
4404 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4405 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4407 err = got_commit_graph_open(&graph, path, !log_branches);
4408 if (err)
4409 return err;
4410 err = got_commit_graph_iter_start(graph, root_id, repo,
4411 check_cancelled, NULL);
4412 if (err)
4413 goto done;
4414 for (;;) {
4415 struct got_object_id id;
4416 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4417 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4419 if (sigint_received || sigpipe_received)
4420 break;
4422 err = got_commit_graph_iter_next(&id, graph, repo,
4423 check_cancelled, NULL);
4424 if (err) {
4425 if (err->code == GOT_ERR_ITER_COMPLETED)
4426 err = NULL;
4427 break;
4430 err = got_object_open_as_commit(&commit, repo, &id);
4431 if (err)
4432 break;
4434 if ((show_changed_paths || (show_diffstat && !show_patch))
4435 && !reverse_display_order) {
4436 err = get_changed_paths(&changed_paths, commit, repo,
4437 show_diffstat ? &dsa : NULL);
4438 if (err)
4439 break;
4442 if (search_pattern) {
4443 err = match_commit(&have_match, &id, commit, &regex);
4444 if (err) {
4445 got_object_commit_close(commit);
4446 break;
4448 if (have_match == 0 && show_changed_paths)
4449 match_changed_paths(&have_match,
4450 &changed_paths, &regex);
4451 if (have_match == 0 && show_patch) {
4452 err = match_patch(&have_match, commit, &id,
4453 path, diff_context, repo, &regex, tmpfile);
4454 if (err)
4455 break;
4457 if (have_match == 0) {
4458 got_object_commit_close(commit);
4459 got_pathlist_free(&changed_paths,
4460 GOT_PATHLIST_FREE_ALL);
4461 continue;
4465 if (reverse_display_order) {
4466 err = got_object_qid_alloc(&qid, &id);
4467 if (err)
4468 break;
4469 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4470 got_object_commit_close(commit);
4471 } else {
4472 if (one_line)
4473 err = print_commit_oneline(commit, &id,
4474 repo, refs_idmap);
4475 else
4476 err = print_commit(commit, &id, repo, path,
4477 (show_changed_paths || show_diffstat) ?
4478 &changed_paths : NULL,
4479 show_diffstat ? &dsa : NULL, show_patch,
4480 diff_context, refs_idmap, NULL, NULL);
4481 got_object_commit_close(commit);
4482 if (err)
4483 break;
4485 if ((limit && --limit == 0) ||
4486 (end_id && got_object_id_cmp(&id, end_id) == 0))
4487 break;
4489 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4491 if (reverse_display_order) {
4492 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4493 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4494 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4496 err = got_object_open_as_commit(&commit, repo,
4497 &qid->id);
4498 if (err)
4499 break;
4500 if (show_changed_paths ||
4501 (show_diffstat && !show_patch)) {
4502 err = get_changed_paths(&changed_paths, commit,
4503 repo, show_diffstat ? &dsa : NULL);
4504 if (err)
4505 break;
4507 if (one_line)
4508 err = print_commit_oneline(commit, &qid->id,
4509 repo, refs_idmap);
4510 else
4511 err = print_commit(commit, &qid->id, repo, path,
4512 (show_changed_paths || show_diffstat) ?
4513 &changed_paths : NULL,
4514 show_diffstat ? &dsa : NULL, show_patch,
4515 diff_context, refs_idmap, NULL, NULL);
4516 got_object_commit_close(commit);
4517 if (err)
4518 break;
4519 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4522 done:
4523 while (!STAILQ_EMPTY(&reversed_commits)) {
4524 qid = STAILQ_FIRST(&reversed_commits);
4525 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4526 got_object_qid_free(qid);
4528 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4529 if (search_pattern)
4530 regfree(&regex);
4531 got_commit_graph_close(graph);
4532 return err;
4535 __dead static void
4536 usage_log(void)
4538 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4539 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4540 "[path]\n", getprogname());
4541 exit(1);
4544 static int
4545 get_default_log_limit(void)
4547 const char *got_default_log_limit;
4548 long long n;
4549 const char *errstr;
4551 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4552 if (got_default_log_limit == NULL)
4553 return 0;
4554 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4555 if (errstr != NULL)
4556 return 0;
4557 return n;
4560 static const struct got_error *
4561 cmd_log(int argc, char *argv[])
4563 const struct got_error *error;
4564 struct got_repository *repo = NULL;
4565 struct got_worktree *worktree = NULL;
4566 struct got_object_id *start_id = NULL, *end_id = NULL;
4567 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4568 const char *start_commit = NULL, *end_commit = NULL;
4569 const char *search_pattern = NULL;
4570 int diff_context = -1, ch;
4571 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4572 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4573 const char *errstr;
4574 struct got_reflist_head refs;
4575 struct got_reflist_object_id_map *refs_idmap = NULL;
4576 FILE *tmpfile = NULL;
4577 int *pack_fds = NULL;
4579 TAILQ_INIT(&refs);
4581 #ifndef PROFILE
4582 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4583 NULL)
4584 == -1)
4585 err(1, "pledge");
4586 #endif
4588 limit = get_default_log_limit();
4590 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4591 switch (ch) {
4592 case 'b':
4593 log_branches = 1;
4594 break;
4595 case 'C':
4596 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4597 &errstr);
4598 if (errstr != NULL)
4599 errx(1, "number of context lines is %s: %s",
4600 errstr, optarg);
4601 break;
4602 case 'c':
4603 start_commit = optarg;
4604 break;
4605 case 'd':
4606 show_diffstat = 1;
4607 break;
4608 case 'l':
4609 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4610 if (errstr != NULL)
4611 errx(1, "number of commits is %s: %s",
4612 errstr, optarg);
4613 break;
4614 case 'P':
4615 show_changed_paths = 1;
4616 break;
4617 case 'p':
4618 show_patch = 1;
4619 break;
4620 case 'R':
4621 reverse_display_order = 1;
4622 break;
4623 case 'r':
4624 repo_path = realpath(optarg, NULL);
4625 if (repo_path == NULL)
4626 return got_error_from_errno2("realpath",
4627 optarg);
4628 got_path_strip_trailing_slashes(repo_path);
4629 break;
4630 case 'S':
4631 search_pattern = optarg;
4632 break;
4633 case 's':
4634 one_line = 1;
4635 break;
4636 case 'x':
4637 end_commit = optarg;
4638 break;
4639 default:
4640 usage_log();
4641 /* NOTREACHED */
4645 argc -= optind;
4646 argv += optind;
4648 if (diff_context == -1)
4649 diff_context = 3;
4650 else if (!show_patch)
4651 errx(1, "-C requires -p");
4653 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4654 errx(1, "cannot use -s with -d, -p or -P");
4656 cwd = getcwd(NULL, 0);
4657 if (cwd == NULL) {
4658 error = got_error_from_errno("getcwd");
4659 goto done;
4662 error = got_repo_pack_fds_open(&pack_fds);
4663 if (error != NULL)
4664 goto done;
4666 if (repo_path == NULL) {
4667 error = got_worktree_open(&worktree, cwd);
4668 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4669 goto done;
4670 error = NULL;
4673 if (argc == 1) {
4674 if (worktree) {
4675 error = got_worktree_resolve_path(&path, worktree,
4676 argv[0]);
4677 if (error)
4678 goto done;
4679 } else {
4680 path = strdup(argv[0]);
4681 if (path == NULL) {
4682 error = got_error_from_errno("strdup");
4683 goto done;
4686 } else if (argc != 0)
4687 usage_log();
4689 if (repo_path == NULL) {
4690 repo_path = worktree ?
4691 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4693 if (repo_path == NULL) {
4694 error = got_error_from_errno("strdup");
4695 goto done;
4698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4699 if (error != NULL)
4700 goto done;
4702 error = apply_unveil(got_repo_get_path(repo), 1,
4703 worktree ? got_worktree_get_root_path(worktree) : NULL);
4704 if (error)
4705 goto done;
4707 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4708 if (error)
4709 goto done;
4711 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4712 if (error)
4713 goto done;
4715 if (start_commit == NULL) {
4716 struct got_reference *head_ref;
4717 struct got_commit_object *commit = NULL;
4718 error = got_ref_open(&head_ref, repo,
4719 worktree ? got_worktree_get_head_ref_name(worktree)
4720 : GOT_REF_HEAD, 0);
4721 if (error != NULL)
4722 goto done;
4723 error = got_ref_resolve(&start_id, repo, head_ref);
4724 got_ref_close(head_ref);
4725 if (error != NULL)
4726 goto done;
4727 error = got_object_open_as_commit(&commit, repo,
4728 start_id);
4729 if (error != NULL)
4730 goto done;
4731 got_object_commit_close(commit);
4732 } else {
4733 error = got_repo_match_object_id(&start_id, NULL,
4734 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4735 if (error != NULL)
4736 goto done;
4738 if (end_commit != NULL) {
4739 error = got_repo_match_object_id(&end_id, NULL,
4740 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4741 if (error != NULL)
4742 goto done;
4745 if (worktree) {
4747 * If a path was specified on the command line it was resolved
4748 * to a path in the work tree above. Prepend the work tree's
4749 * path prefix to obtain the corresponding in-repository path.
4751 if (path) {
4752 const char *prefix;
4753 prefix = got_worktree_get_path_prefix(worktree);
4754 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4755 (path[0] != '\0') ? "/" : "", path) == -1) {
4756 error = got_error_from_errno("asprintf");
4757 goto done;
4760 } else
4761 error = got_repo_map_path(&in_repo_path, repo,
4762 path ? path : "");
4763 if (error != NULL)
4764 goto done;
4765 if (in_repo_path) {
4766 free(path);
4767 path = in_repo_path;
4770 if (worktree) {
4771 /* Release work tree lock. */
4772 got_worktree_close(worktree);
4773 worktree = NULL;
4776 if (search_pattern && show_patch) {
4777 tmpfile = got_opentemp();
4778 if (tmpfile == NULL) {
4779 error = got_error_from_errno("got_opentemp");
4780 goto done;
4784 error = print_commits(start_id, end_id, repo, path ? path : "",
4785 show_changed_paths, show_diffstat, show_patch, search_pattern,
4786 diff_context, limit, log_branches, reverse_display_order,
4787 refs_idmap, one_line, tmpfile);
4788 done:
4789 free(path);
4790 free(repo_path);
4791 free(cwd);
4792 if (worktree)
4793 got_worktree_close(worktree);
4794 if (repo) {
4795 const struct got_error *close_err = got_repo_close(repo);
4796 if (error == NULL)
4797 error = close_err;
4799 if (pack_fds) {
4800 const struct got_error *pack_err =
4801 got_repo_pack_fds_close(pack_fds);
4802 if (error == NULL)
4803 error = pack_err;
4805 if (refs_idmap)
4806 got_reflist_object_id_map_free(refs_idmap);
4807 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4808 error = got_error_from_errno("fclose");
4809 got_ref_list_free(&refs);
4810 return error;
4813 __dead static void
4814 usage_diff(void)
4816 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4817 "[-r repository-path] [object1 object2 | path ...]\n",
4818 getprogname());
4819 exit(1);
4822 struct print_diff_arg {
4823 struct got_repository *repo;
4824 struct got_worktree *worktree;
4825 struct got_diffstat_cb_arg *diffstat;
4826 int diff_context;
4827 const char *id_str;
4828 int header_shown;
4829 int diff_staged;
4830 enum got_diff_algorithm diff_algo;
4831 int ignore_whitespace;
4832 int force_text_diff;
4833 FILE *f1;
4834 FILE *f2;
4835 FILE *outfile;
4839 * Create a file which contains the target path of a symlink so we can feed
4840 * it as content to the diff engine.
4842 static const struct got_error *
4843 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4844 const char *abspath)
4846 const struct got_error *err = NULL;
4847 char target_path[PATH_MAX];
4848 ssize_t target_len, outlen;
4850 *fd = -1;
4852 if (dirfd != -1) {
4853 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4854 if (target_len == -1)
4855 return got_error_from_errno2("readlinkat", abspath);
4856 } else {
4857 target_len = readlink(abspath, target_path, PATH_MAX);
4858 if (target_len == -1)
4859 return got_error_from_errno2("readlink", abspath);
4862 *fd = got_opentempfd();
4863 if (*fd == -1)
4864 return got_error_from_errno("got_opentempfd");
4866 outlen = write(*fd, target_path, target_len);
4867 if (outlen == -1) {
4868 err = got_error_from_errno("got_opentempfd");
4869 goto done;
4872 if (lseek(*fd, 0, SEEK_SET) == -1) {
4873 err = got_error_from_errno2("lseek", abspath);
4874 goto done;
4876 done:
4877 if (err) {
4878 close(*fd);
4879 *fd = -1;
4881 return err;
4884 static const struct got_error *
4885 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4886 const char *path, struct got_object_id *blob_id,
4887 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4888 int dirfd, const char *de_name)
4890 struct print_diff_arg *a = arg;
4891 const struct got_error *err = NULL;
4892 struct got_blob_object *blob1 = NULL;
4893 int fd = -1, fd1 = -1, fd2 = -1;
4894 FILE *f2 = NULL;
4895 char *abspath = NULL, *label1 = NULL;
4896 struct stat sb;
4897 off_t size1 = 0;
4898 int f2_exists = 0;
4900 memset(&sb, 0, sizeof(sb));
4902 if (a->diff_staged) {
4903 if (staged_status != GOT_STATUS_MODIFY &&
4904 staged_status != GOT_STATUS_ADD &&
4905 staged_status != GOT_STATUS_DELETE)
4906 return NULL;
4907 } else {
4908 if (staged_status == GOT_STATUS_DELETE)
4909 return NULL;
4910 if (status == GOT_STATUS_NONEXISTENT)
4911 return got_error_set_errno(ENOENT, path);
4912 if (status != GOT_STATUS_MODIFY &&
4913 status != GOT_STATUS_ADD &&
4914 status != GOT_STATUS_DELETE &&
4915 status != GOT_STATUS_CONFLICT)
4916 return NULL;
4919 err = got_opentemp_truncate(a->f1);
4920 if (err)
4921 return got_error_from_errno("got_opentemp_truncate");
4922 err = got_opentemp_truncate(a->f2);
4923 if (err)
4924 return got_error_from_errno("got_opentemp_truncate");
4926 if (!a->header_shown) {
4927 if (fprintf(a->outfile, "diff %s%s\n",
4928 a->diff_staged ? "-s " : "",
4929 got_worktree_get_root_path(a->worktree)) < 0) {
4930 err = got_error_from_errno("fprintf");
4931 goto done;
4933 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4934 err = got_error_from_errno("fprintf");
4935 goto done;
4937 if (fprintf(a->outfile, "path + %s%s\n",
4938 got_worktree_get_root_path(a->worktree),
4939 a->diff_staged ? " (staged changes)" : "") < 0) {
4940 err = got_error_from_errno("fprintf");
4941 goto done;
4943 a->header_shown = 1;
4946 if (a->diff_staged) {
4947 const char *label1 = NULL, *label2 = NULL;
4948 switch (staged_status) {
4949 case GOT_STATUS_MODIFY:
4950 label1 = path;
4951 label2 = path;
4952 break;
4953 case GOT_STATUS_ADD:
4954 label2 = path;
4955 break;
4956 case GOT_STATUS_DELETE:
4957 label1 = path;
4958 break;
4959 default:
4960 return got_error(GOT_ERR_FILE_STATUS);
4962 fd1 = got_opentempfd();
4963 if (fd1 == -1) {
4964 err = got_error_from_errno("got_opentempfd");
4965 goto done;
4967 fd2 = got_opentempfd();
4968 if (fd2 == -1) {
4969 err = got_error_from_errno("got_opentempfd");
4970 goto done;
4972 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4973 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4974 a->diff_algo, a->diff_context, a->ignore_whitespace,
4975 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4976 goto done;
4979 fd1 = got_opentempfd();
4980 if (fd1 == -1) {
4981 err = got_error_from_errno("got_opentempfd");
4982 goto done;
4985 if (staged_status == GOT_STATUS_ADD ||
4986 staged_status == GOT_STATUS_MODIFY) {
4987 char *id_str;
4988 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4989 8192, fd1);
4990 if (err)
4991 goto done;
4992 err = got_object_id_str(&id_str, staged_blob_id);
4993 if (err)
4994 goto done;
4995 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4996 err = got_error_from_errno("asprintf");
4997 free(id_str);
4998 goto done;
5000 free(id_str);
5001 } else if (status != GOT_STATUS_ADD) {
5002 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5003 fd1);
5004 if (err)
5005 goto done;
5008 if (status != GOT_STATUS_DELETE) {
5009 if (asprintf(&abspath, "%s/%s",
5010 got_worktree_get_root_path(a->worktree), path) == -1) {
5011 err = got_error_from_errno("asprintf");
5012 goto done;
5015 if (dirfd != -1) {
5016 fd = openat(dirfd, de_name,
5017 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5018 if (fd == -1) {
5019 if (!got_err_open_nofollow_on_symlink()) {
5020 err = got_error_from_errno2("openat",
5021 abspath);
5022 goto done;
5024 err = get_symlink_target_file(&fd, dirfd,
5025 de_name, abspath);
5026 if (err)
5027 goto done;
5029 } else {
5030 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5031 if (fd == -1) {
5032 if (!got_err_open_nofollow_on_symlink()) {
5033 err = got_error_from_errno2("open",
5034 abspath);
5035 goto done;
5037 err = get_symlink_target_file(&fd, dirfd,
5038 de_name, abspath);
5039 if (err)
5040 goto done;
5043 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5044 err = got_error_from_errno2("fstatat", abspath);
5045 goto done;
5047 f2 = fdopen(fd, "r");
5048 if (f2 == NULL) {
5049 err = got_error_from_errno2("fdopen", abspath);
5050 goto done;
5052 fd = -1;
5053 f2_exists = 1;
5056 if (blob1) {
5057 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5058 a->f1, blob1);
5059 if (err)
5060 goto done;
5063 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5064 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5065 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5066 done:
5067 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5068 err = got_error_from_errno("close");
5069 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5070 err = got_error_from_errno("close");
5071 if (blob1)
5072 got_object_blob_close(blob1);
5073 if (fd != -1 && close(fd) == -1 && err == NULL)
5074 err = got_error_from_errno("close");
5075 if (f2 && fclose(f2) == EOF && err == NULL)
5076 err = got_error_from_errno("fclose");
5077 free(abspath);
5078 return err;
5081 static const struct got_error *
5082 cmd_diff(int argc, char *argv[])
5084 const struct got_error *error;
5085 struct got_repository *repo = NULL;
5086 struct got_worktree *worktree = NULL;
5087 char *cwd = NULL, *repo_path = NULL;
5088 const char *commit_args[2] = { NULL, NULL };
5089 int ncommit_args = 0;
5090 struct got_object_id *ids[2] = { NULL, NULL };
5091 char *labels[2] = { NULL, NULL };
5092 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5093 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5094 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5095 const char *errstr;
5096 struct got_reflist_head refs;
5097 struct got_pathlist_head diffstat_paths, paths;
5098 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5099 int fd1 = -1, fd2 = -1;
5100 int *pack_fds = NULL;
5101 struct got_diffstat_cb_arg dsa;
5103 memset(&dsa, 0, sizeof(dsa));
5105 TAILQ_INIT(&refs);
5106 TAILQ_INIT(&paths);
5107 TAILQ_INIT(&diffstat_paths);
5109 #ifndef PROFILE
5110 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5111 NULL) == -1)
5112 err(1, "pledge");
5113 #endif
5115 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5116 switch (ch) {
5117 case 'a':
5118 force_text_diff = 1;
5119 break;
5120 case 'C':
5121 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5122 &errstr);
5123 if (errstr != NULL)
5124 errx(1, "number of context lines is %s: %s",
5125 errstr, optarg);
5126 break;
5127 case 'c':
5128 if (ncommit_args >= 2)
5129 errx(1, "too many -c options used");
5130 commit_args[ncommit_args++] = optarg;
5131 break;
5132 case 'd':
5133 show_diffstat = 1;
5134 break;
5135 case 'P':
5136 force_path = 1;
5137 break;
5138 case 'r':
5139 repo_path = realpath(optarg, NULL);
5140 if (repo_path == NULL)
5141 return got_error_from_errno2("realpath",
5142 optarg);
5143 got_path_strip_trailing_slashes(repo_path);
5144 rflag = 1;
5145 break;
5146 case 's':
5147 diff_staged = 1;
5148 break;
5149 case 'w':
5150 ignore_whitespace = 1;
5151 break;
5152 default:
5153 usage_diff();
5154 /* NOTREACHED */
5158 argc -= optind;
5159 argv += optind;
5161 cwd = getcwd(NULL, 0);
5162 if (cwd == NULL) {
5163 error = got_error_from_errno("getcwd");
5164 goto done;
5167 error = got_repo_pack_fds_open(&pack_fds);
5168 if (error != NULL)
5169 goto done;
5171 if (repo_path == NULL) {
5172 error = got_worktree_open(&worktree, cwd);
5173 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5174 goto done;
5175 else
5176 error = NULL;
5177 if (worktree) {
5178 repo_path =
5179 strdup(got_worktree_get_repo_path(worktree));
5180 if (repo_path == NULL) {
5181 error = got_error_from_errno("strdup");
5182 goto done;
5184 } else {
5185 repo_path = strdup(cwd);
5186 if (repo_path == NULL) {
5187 error = got_error_from_errno("strdup");
5188 goto done;
5193 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5194 free(repo_path);
5195 if (error != NULL)
5196 goto done;
5198 if (show_diffstat) {
5199 dsa.paths = &diffstat_paths;
5200 dsa.force_text = force_text_diff;
5201 dsa.ignore_ws = ignore_whitespace;
5202 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5205 if (rflag || worktree == NULL || ncommit_args > 0) {
5206 if (force_path) {
5207 error = got_error_msg(GOT_ERR_NOT_IMPL,
5208 "-P option can only be used when diffing "
5209 "a work tree");
5210 goto done;
5212 if (diff_staged) {
5213 error = got_error_msg(GOT_ERR_NOT_IMPL,
5214 "-s option can only be used when diffing "
5215 "a work tree");
5216 goto done;
5220 error = apply_unveil(got_repo_get_path(repo), 1,
5221 worktree ? got_worktree_get_root_path(worktree) : NULL);
5222 if (error)
5223 goto done;
5225 if ((!force_path && argc == 2) || ncommit_args > 0) {
5226 int obj_type = (ncommit_args > 0 ?
5227 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5228 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5229 NULL);
5230 if (error)
5231 goto done;
5232 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5233 const char *arg;
5234 if (ncommit_args > 0)
5235 arg = commit_args[i];
5236 else
5237 arg = argv[i];
5238 error = got_repo_match_object_id(&ids[i], &labels[i],
5239 arg, obj_type, &refs, repo);
5240 if (error) {
5241 if (error->code != GOT_ERR_NOT_REF &&
5242 error->code != GOT_ERR_NO_OBJ)
5243 goto done;
5244 if (ncommit_args > 0)
5245 goto done;
5246 error = NULL;
5247 break;
5252 f1 = got_opentemp();
5253 if (f1 == NULL) {
5254 error = got_error_from_errno("got_opentemp");
5255 goto done;
5258 f2 = got_opentemp();
5259 if (f2 == NULL) {
5260 error = got_error_from_errno("got_opentemp");
5261 goto done;
5264 outfile = got_opentemp();
5265 if (outfile == NULL) {
5266 error = got_error_from_errno("got_opentemp");
5267 goto done;
5270 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5271 struct print_diff_arg arg;
5272 char *id_str;
5274 if (worktree == NULL) {
5275 if (argc == 2 && ids[0] == NULL) {
5276 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5277 goto done;
5278 } else if (argc == 2 && ids[1] == NULL) {
5279 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5280 goto done;
5281 } else if (argc > 0) {
5282 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5283 "%s", "specified paths cannot be resolved");
5284 goto done;
5285 } else {
5286 error = got_error(GOT_ERR_NOT_WORKTREE);
5287 goto done;
5291 error = get_worktree_paths_from_argv(&paths, argc, argv,
5292 worktree);
5293 if (error)
5294 goto done;
5296 error = got_object_id_str(&id_str,
5297 got_worktree_get_base_commit_id(worktree));
5298 if (error)
5299 goto done;
5300 arg.repo = repo;
5301 arg.worktree = worktree;
5302 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5303 arg.diff_context = diff_context;
5304 arg.id_str = id_str;
5305 arg.header_shown = 0;
5306 arg.diff_staged = diff_staged;
5307 arg.ignore_whitespace = ignore_whitespace;
5308 arg.force_text_diff = force_text_diff;
5309 arg.diffstat = show_diffstat ? &dsa : NULL;
5310 arg.f1 = f1;
5311 arg.f2 = f2;
5312 arg.outfile = outfile;
5314 error = got_worktree_status(worktree, &paths, repo, 0,
5315 print_diff, &arg, check_cancelled, NULL);
5316 free(id_str);
5317 if (error)
5318 goto done;
5320 if (show_diffstat && dsa.nfiles > 0) {
5321 char *header;
5323 if (asprintf(&header, "diffstat %s%s",
5324 diff_staged ? "-s " : "",
5325 got_worktree_get_root_path(worktree)) == -1) {
5326 error = got_error_from_errno("asprintf");
5327 goto done;
5330 error = print_diffstat(&dsa, header);
5331 free(header);
5332 if (error)
5333 goto done;
5336 error = printfile(outfile);
5337 goto done;
5340 if (ncommit_args == 1) {
5341 struct got_commit_object *commit;
5342 error = got_object_open_as_commit(&commit, repo, ids[0]);
5343 if (error)
5344 goto done;
5346 labels[1] = labels[0];
5347 ids[1] = ids[0];
5348 if (got_object_commit_get_nparents(commit) > 0) {
5349 const struct got_object_id_queue *pids;
5350 struct got_object_qid *pid;
5351 pids = got_object_commit_get_parent_ids(commit);
5352 pid = STAILQ_FIRST(pids);
5353 ids[0] = got_object_id_dup(&pid->id);
5354 if (ids[0] == NULL) {
5355 error = got_error_from_errno(
5356 "got_object_id_dup");
5357 got_object_commit_close(commit);
5358 goto done;
5360 error = got_object_id_str(&labels[0], ids[0]);
5361 if (error) {
5362 got_object_commit_close(commit);
5363 goto done;
5365 } else {
5366 ids[0] = NULL;
5367 labels[0] = strdup("/dev/null");
5368 if (labels[0] == NULL) {
5369 error = got_error_from_errno("strdup");
5370 got_object_commit_close(commit);
5371 goto done;
5375 got_object_commit_close(commit);
5378 if (ncommit_args == 0 && argc > 2) {
5379 error = got_error_msg(GOT_ERR_BAD_PATH,
5380 "path arguments cannot be used when diffing two objects");
5381 goto done;
5384 if (ids[0]) {
5385 error = got_object_get_type(&type1, repo, ids[0]);
5386 if (error)
5387 goto done;
5390 error = got_object_get_type(&type2, repo, ids[1]);
5391 if (error)
5392 goto done;
5393 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5394 error = got_error(GOT_ERR_OBJ_TYPE);
5395 goto done;
5397 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5398 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5399 "path arguments cannot be used when diffing blobs");
5400 goto done;
5403 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5404 char *in_repo_path;
5405 struct got_pathlist_entry *new;
5406 if (worktree) {
5407 const char *prefix;
5408 char *p;
5409 error = got_worktree_resolve_path(&p, worktree,
5410 argv[i]);
5411 if (error)
5412 goto done;
5413 prefix = got_worktree_get_path_prefix(worktree);
5414 while (prefix[0] == '/')
5415 prefix++;
5416 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5417 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5418 p) == -1) {
5419 error = got_error_from_errno("asprintf");
5420 free(p);
5421 goto done;
5423 free(p);
5424 } else {
5425 char *mapped_path, *s;
5426 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5427 if (error)
5428 goto done;
5429 s = mapped_path;
5430 while (s[0] == '/')
5431 s++;
5432 in_repo_path = strdup(s);
5433 if (in_repo_path == NULL) {
5434 error = got_error_from_errno("asprintf");
5435 free(mapped_path);
5436 goto done;
5438 free(mapped_path);
5441 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5442 if (error || new == NULL /* duplicate */)
5443 free(in_repo_path);
5444 if (error)
5445 goto done;
5448 if (worktree) {
5449 /* Release work tree lock. */
5450 got_worktree_close(worktree);
5451 worktree = NULL;
5454 fd1 = got_opentempfd();
5455 if (fd1 == -1) {
5456 error = got_error_from_errno("got_opentempfd");
5457 goto done;
5460 fd2 = got_opentempfd();
5461 if (fd2 == -1) {
5462 error = got_error_from_errno("got_opentempfd");
5463 goto done;
5466 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5467 case GOT_OBJ_TYPE_BLOB:
5468 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5469 fd1, fd2, ids[0], ids[1], NULL, NULL,
5470 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5471 ignore_whitespace, force_text_diff,
5472 show_diffstat ? &dsa : NULL, repo, outfile);
5473 break;
5474 case GOT_OBJ_TYPE_TREE:
5475 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5476 ids[0], ids[1], &paths, "", "",
5477 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5478 ignore_whitespace, force_text_diff,
5479 show_diffstat ? &dsa : NULL, repo, outfile);
5480 break;
5481 case GOT_OBJ_TYPE_COMMIT:
5482 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5483 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5484 fd1, fd2, ids[0], ids[1], &paths,
5485 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5486 ignore_whitespace, force_text_diff,
5487 show_diffstat ? &dsa : NULL, repo, outfile);
5488 break;
5489 default:
5490 error = got_error(GOT_ERR_OBJ_TYPE);
5492 if (error)
5493 goto done;
5495 if (show_diffstat && dsa.nfiles > 0) {
5496 char *header = NULL;
5498 if (asprintf(&header, "diffstat %s %s",
5499 labels[0], labels[1]) == -1) {
5500 error = got_error_from_errno("asprintf");
5501 goto done;
5504 error = print_diffstat(&dsa, header);
5505 free(header);
5506 if (error)
5507 goto done;
5510 error = printfile(outfile);
5512 done:
5513 free(labels[0]);
5514 free(labels[1]);
5515 free(ids[0]);
5516 free(ids[1]);
5517 if (worktree)
5518 got_worktree_close(worktree);
5519 if (repo) {
5520 const struct got_error *close_err = got_repo_close(repo);
5521 if (error == NULL)
5522 error = close_err;
5524 if (pack_fds) {
5525 const struct got_error *pack_err =
5526 got_repo_pack_fds_close(pack_fds);
5527 if (error == NULL)
5528 error = pack_err;
5530 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5531 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5532 got_ref_list_free(&refs);
5533 if (outfile && fclose(outfile) == EOF && error == NULL)
5534 error = got_error_from_errno("fclose");
5535 if (f1 && fclose(f1) == EOF && error == NULL)
5536 error = got_error_from_errno("fclose");
5537 if (f2 && fclose(f2) == EOF && error == NULL)
5538 error = got_error_from_errno("fclose");
5539 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5540 error = got_error_from_errno("close");
5541 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5542 error = got_error_from_errno("close");
5543 return error;
5546 __dead static void
5547 usage_blame(void)
5549 fprintf(stderr,
5550 "usage: %s blame [-c commit] [-r repository-path] path\n",
5551 getprogname());
5552 exit(1);
5555 struct blame_line {
5556 int annotated;
5557 char *id_str;
5558 char *committer;
5559 char datebuf[11]; /* YYYY-MM-DD + NUL */
5562 struct blame_cb_args {
5563 struct blame_line *lines;
5564 int nlines;
5565 int nlines_prec;
5566 int lineno_cur;
5567 off_t *line_offsets;
5568 FILE *f;
5569 struct got_repository *repo;
5572 static const struct got_error *
5573 blame_cb(void *arg, int nlines, int lineno,
5574 struct got_commit_object *commit, struct got_object_id *id)
5576 const struct got_error *err = NULL;
5577 struct blame_cb_args *a = arg;
5578 struct blame_line *bline;
5579 char *line = NULL;
5580 size_t linesize = 0;
5581 off_t offset;
5582 struct tm tm;
5583 time_t committer_time;
5585 if (nlines != a->nlines ||
5586 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5587 return got_error(GOT_ERR_RANGE);
5589 if (sigint_received)
5590 return got_error(GOT_ERR_ITER_COMPLETED);
5592 if (lineno == -1)
5593 return NULL; /* no change in this commit */
5595 /* Annotate this line. */
5596 bline = &a->lines[lineno - 1];
5597 if (bline->annotated)
5598 return NULL;
5599 err = got_object_id_str(&bline->id_str, id);
5600 if (err)
5601 return err;
5603 bline->committer = strdup(got_object_commit_get_committer(commit));
5604 if (bline->committer == NULL) {
5605 err = got_error_from_errno("strdup");
5606 goto done;
5609 committer_time = got_object_commit_get_committer_time(commit);
5610 if (gmtime_r(&committer_time, &tm) == NULL)
5611 return got_error_from_errno("gmtime_r");
5612 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5613 &tm) == 0) {
5614 err = got_error(GOT_ERR_NO_SPACE);
5615 goto done;
5617 bline->annotated = 1;
5619 /* Print lines annotated so far. */
5620 bline = &a->lines[a->lineno_cur - 1];
5621 if (!bline->annotated)
5622 goto done;
5624 offset = a->line_offsets[a->lineno_cur - 1];
5625 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5626 err = got_error_from_errno("fseeko");
5627 goto done;
5630 while (a->lineno_cur <= a->nlines && bline->annotated) {
5631 char *smallerthan, *at, *nl, *committer;
5632 size_t len;
5634 if (getline(&line, &linesize, a->f) == -1) {
5635 if (ferror(a->f))
5636 err = got_error_from_errno("getline");
5637 break;
5640 committer = bline->committer;
5641 smallerthan = strchr(committer, '<');
5642 if (smallerthan && smallerthan[1] != '\0')
5643 committer = smallerthan + 1;
5644 at = strchr(committer, '@');
5645 if (at)
5646 *at = '\0';
5647 len = strlen(committer);
5648 if (len >= 9)
5649 committer[8] = '\0';
5651 nl = strchr(line, '\n');
5652 if (nl)
5653 *nl = '\0';
5654 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5655 bline->id_str, bline->datebuf, committer, line);
5657 a->lineno_cur++;
5658 bline = &a->lines[a->lineno_cur - 1];
5660 done:
5661 free(line);
5662 return err;
5665 static const struct got_error *
5666 cmd_blame(int argc, char *argv[])
5668 const struct got_error *error;
5669 struct got_repository *repo = NULL;
5670 struct got_worktree *worktree = NULL;
5671 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5672 char *link_target = NULL;
5673 struct got_object_id *obj_id = NULL;
5674 struct got_object_id *commit_id = NULL;
5675 struct got_commit_object *commit = NULL;
5676 struct got_blob_object *blob = NULL;
5677 char *commit_id_str = NULL;
5678 struct blame_cb_args bca;
5679 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5680 off_t filesize;
5681 int *pack_fds = NULL;
5682 FILE *f1 = NULL, *f2 = NULL;
5684 fd1 = got_opentempfd();
5685 if (fd1 == -1)
5686 return got_error_from_errno("got_opentempfd");
5688 memset(&bca, 0, sizeof(bca));
5690 #ifndef PROFILE
5691 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5692 NULL) == -1)
5693 err(1, "pledge");
5694 #endif
5696 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5697 switch (ch) {
5698 case 'c':
5699 commit_id_str = optarg;
5700 break;
5701 case 'r':
5702 repo_path = realpath(optarg, NULL);
5703 if (repo_path == NULL)
5704 return got_error_from_errno2("realpath",
5705 optarg);
5706 got_path_strip_trailing_slashes(repo_path);
5707 break;
5708 default:
5709 usage_blame();
5710 /* NOTREACHED */
5714 argc -= optind;
5715 argv += optind;
5717 if (argc == 1)
5718 path = argv[0];
5719 else
5720 usage_blame();
5722 cwd = getcwd(NULL, 0);
5723 if (cwd == NULL) {
5724 error = got_error_from_errno("getcwd");
5725 goto done;
5728 error = got_repo_pack_fds_open(&pack_fds);
5729 if (error != NULL)
5730 goto done;
5732 if (repo_path == NULL) {
5733 error = got_worktree_open(&worktree, cwd);
5734 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5735 goto done;
5736 else
5737 error = NULL;
5738 if (worktree) {
5739 repo_path =
5740 strdup(got_worktree_get_repo_path(worktree));
5741 if (repo_path == NULL) {
5742 error = got_error_from_errno("strdup");
5743 if (error)
5744 goto done;
5746 } else {
5747 repo_path = strdup(cwd);
5748 if (repo_path == NULL) {
5749 error = got_error_from_errno("strdup");
5750 goto done;
5755 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5756 if (error != NULL)
5757 goto done;
5759 if (worktree) {
5760 const char *prefix = got_worktree_get_path_prefix(worktree);
5761 char *p;
5763 error = got_worktree_resolve_path(&p, worktree, path);
5764 if (error)
5765 goto done;
5766 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5767 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5768 p) == -1) {
5769 error = got_error_from_errno("asprintf");
5770 free(p);
5771 goto done;
5773 free(p);
5774 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5775 } else {
5776 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5777 if (error)
5778 goto done;
5779 error = got_repo_map_path(&in_repo_path, repo, path);
5781 if (error)
5782 goto done;
5784 if (commit_id_str == NULL) {
5785 struct got_reference *head_ref;
5786 error = got_ref_open(&head_ref, repo, worktree ?
5787 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5788 if (error != NULL)
5789 goto done;
5790 error = got_ref_resolve(&commit_id, repo, head_ref);
5791 got_ref_close(head_ref);
5792 if (error != NULL)
5793 goto done;
5794 } else {
5795 struct got_reflist_head refs;
5796 TAILQ_INIT(&refs);
5797 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5798 NULL);
5799 if (error)
5800 goto done;
5801 error = got_repo_match_object_id(&commit_id, NULL,
5802 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5803 got_ref_list_free(&refs);
5804 if (error)
5805 goto done;
5808 if (worktree) {
5809 /* Release work tree lock. */
5810 got_worktree_close(worktree);
5811 worktree = NULL;
5814 error = got_object_open_as_commit(&commit, repo, commit_id);
5815 if (error)
5816 goto done;
5818 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5819 commit, repo);
5820 if (error)
5821 goto done;
5823 error = got_object_id_by_path(&obj_id, repo, commit,
5824 link_target ? link_target : in_repo_path);
5825 if (error)
5826 goto done;
5828 error = got_object_get_type(&obj_type, repo, obj_id);
5829 if (error)
5830 goto done;
5832 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5833 error = got_error_path(link_target ? link_target : in_repo_path,
5834 GOT_ERR_OBJ_TYPE);
5835 goto done;
5838 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5839 if (error)
5840 goto done;
5841 bca.f = got_opentemp();
5842 if (bca.f == NULL) {
5843 error = got_error_from_errno("got_opentemp");
5844 goto done;
5846 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5847 &bca.line_offsets, bca.f, blob);
5848 if (error || bca.nlines == 0)
5849 goto done;
5851 /* Don't include \n at EOF in the blame line count. */
5852 if (bca.line_offsets[bca.nlines - 1] == filesize)
5853 bca.nlines--;
5855 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5856 if (bca.lines == NULL) {
5857 error = got_error_from_errno("calloc");
5858 goto done;
5860 bca.lineno_cur = 1;
5861 bca.nlines_prec = 0;
5862 i = bca.nlines;
5863 while (i > 0) {
5864 i /= 10;
5865 bca.nlines_prec++;
5867 bca.repo = repo;
5869 fd2 = got_opentempfd();
5870 if (fd2 == -1) {
5871 error = got_error_from_errno("got_opentempfd");
5872 goto done;
5874 fd3 = got_opentempfd();
5875 if (fd3 == -1) {
5876 error = got_error_from_errno("got_opentempfd");
5877 goto done;
5879 f1 = got_opentemp();
5880 if (f1 == NULL) {
5881 error = got_error_from_errno("got_opentemp");
5882 goto done;
5884 f2 = got_opentemp();
5885 if (f2 == NULL) {
5886 error = got_error_from_errno("got_opentemp");
5887 goto done;
5889 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5890 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5891 check_cancelled, NULL, fd2, fd3, f1, f2);
5892 done:
5893 free(in_repo_path);
5894 free(link_target);
5895 free(repo_path);
5896 free(cwd);
5897 free(commit_id);
5898 free(obj_id);
5899 if (commit)
5900 got_object_commit_close(commit);
5902 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5903 error = got_error_from_errno("close");
5904 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5905 error = got_error_from_errno("close");
5906 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5907 error = got_error_from_errno("close");
5908 if (f1 && fclose(f1) == EOF && error == NULL)
5909 error = got_error_from_errno("fclose");
5910 if (f2 && fclose(f2) == EOF && error == NULL)
5911 error = got_error_from_errno("fclose");
5913 if (blob)
5914 got_object_blob_close(blob);
5915 if (worktree)
5916 got_worktree_close(worktree);
5917 if (repo) {
5918 const struct got_error *close_err = got_repo_close(repo);
5919 if (error == NULL)
5920 error = close_err;
5922 if (pack_fds) {
5923 const struct got_error *pack_err =
5924 got_repo_pack_fds_close(pack_fds);
5925 if (error == NULL)
5926 error = pack_err;
5928 if (bca.lines) {
5929 for (i = 0; i < bca.nlines; i++) {
5930 struct blame_line *bline = &bca.lines[i];
5931 free(bline->id_str);
5932 free(bline->committer);
5934 free(bca.lines);
5936 free(bca.line_offsets);
5937 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5938 error = got_error_from_errno("fclose");
5939 return error;
5942 __dead static void
5943 usage_tree(void)
5945 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5946 "[path]\n", getprogname());
5947 exit(1);
5950 static const struct got_error *
5951 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5952 const char *root_path, struct got_repository *repo)
5954 const struct got_error *err = NULL;
5955 int is_root_path = (strcmp(path, root_path) == 0);
5956 const char *modestr = "";
5957 mode_t mode = got_tree_entry_get_mode(te);
5958 char *link_target = NULL;
5960 path += strlen(root_path);
5961 while (path[0] == '/')
5962 path++;
5964 if (got_object_tree_entry_is_submodule(te))
5965 modestr = "$";
5966 else if (S_ISLNK(mode)) {
5967 int i;
5969 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5970 if (err)
5971 return err;
5972 for (i = 0; i < strlen(link_target); i++) {
5973 if (!isprint((unsigned char)link_target[i]))
5974 link_target[i] = '?';
5977 modestr = "@";
5979 else if (S_ISDIR(mode))
5980 modestr = "/";
5981 else if (mode & S_IXUSR)
5982 modestr = "*";
5984 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5985 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5986 link_target ? " -> ": "", link_target ? link_target : "");
5988 free(link_target);
5989 return NULL;
5992 static const struct got_error *
5993 print_tree(const char *path, struct got_commit_object *commit,
5994 int show_ids, int recurse, const char *root_path,
5995 struct got_repository *repo)
5997 const struct got_error *err = NULL;
5998 struct got_object_id *tree_id = NULL;
5999 struct got_tree_object *tree = NULL;
6000 int nentries, i;
6002 err = got_object_id_by_path(&tree_id, repo, commit, path);
6003 if (err)
6004 goto done;
6006 err = got_object_open_as_tree(&tree, repo, tree_id);
6007 if (err)
6008 goto done;
6009 nentries = got_object_tree_get_nentries(tree);
6010 for (i = 0; i < nentries; i++) {
6011 struct got_tree_entry *te;
6012 char *id = NULL;
6014 if (sigint_received || sigpipe_received)
6015 break;
6017 te = got_object_tree_get_entry(tree, i);
6018 if (show_ids) {
6019 char *id_str;
6020 err = got_object_id_str(&id_str,
6021 got_tree_entry_get_id(te));
6022 if (err)
6023 goto done;
6024 if (asprintf(&id, "%s ", id_str) == -1) {
6025 err = got_error_from_errno("asprintf");
6026 free(id_str);
6027 goto done;
6029 free(id_str);
6031 err = print_entry(te, id, path, root_path, repo);
6032 free(id);
6033 if (err)
6034 goto done;
6036 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6037 char *child_path;
6038 if (asprintf(&child_path, "%s%s%s", path,
6039 path[0] == '/' && path[1] == '\0' ? "" : "/",
6040 got_tree_entry_get_name(te)) == -1) {
6041 err = got_error_from_errno("asprintf");
6042 goto done;
6044 err = print_tree(child_path, commit, show_ids, 1,
6045 root_path, repo);
6046 free(child_path);
6047 if (err)
6048 goto done;
6051 done:
6052 if (tree)
6053 got_object_tree_close(tree);
6054 free(tree_id);
6055 return err;
6058 static const struct got_error *
6059 cmd_tree(int argc, char *argv[])
6061 const struct got_error *error;
6062 struct got_repository *repo = NULL;
6063 struct got_worktree *worktree = NULL;
6064 const char *path, *refname = NULL;
6065 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6066 struct got_object_id *commit_id = NULL;
6067 struct got_commit_object *commit = NULL;
6068 char *commit_id_str = NULL;
6069 int show_ids = 0, recurse = 0;
6070 int ch;
6071 int *pack_fds = NULL;
6073 #ifndef PROFILE
6074 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6075 NULL) == -1)
6076 err(1, "pledge");
6077 #endif
6079 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6080 switch (ch) {
6081 case 'c':
6082 commit_id_str = optarg;
6083 break;
6084 case 'i':
6085 show_ids = 1;
6086 break;
6087 case 'R':
6088 recurse = 1;
6089 break;
6090 case 'r':
6091 repo_path = realpath(optarg, NULL);
6092 if (repo_path == NULL)
6093 return got_error_from_errno2("realpath",
6094 optarg);
6095 got_path_strip_trailing_slashes(repo_path);
6096 break;
6097 default:
6098 usage_tree();
6099 /* NOTREACHED */
6103 argc -= optind;
6104 argv += optind;
6106 if (argc == 1)
6107 path = argv[0];
6108 else if (argc > 1)
6109 usage_tree();
6110 else
6111 path = NULL;
6113 cwd = getcwd(NULL, 0);
6114 if (cwd == NULL) {
6115 error = got_error_from_errno("getcwd");
6116 goto done;
6119 error = got_repo_pack_fds_open(&pack_fds);
6120 if (error != NULL)
6121 goto done;
6123 if (repo_path == NULL) {
6124 error = got_worktree_open(&worktree, cwd);
6125 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6126 goto done;
6127 else
6128 error = NULL;
6129 if (worktree) {
6130 repo_path =
6131 strdup(got_worktree_get_repo_path(worktree));
6132 if (repo_path == NULL)
6133 error = got_error_from_errno("strdup");
6134 if (error)
6135 goto done;
6136 } else {
6137 repo_path = strdup(cwd);
6138 if (repo_path == NULL) {
6139 error = got_error_from_errno("strdup");
6140 goto done;
6145 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6146 if (error != NULL)
6147 goto done;
6149 if (worktree) {
6150 const char *prefix = got_worktree_get_path_prefix(worktree);
6151 char *p;
6153 if (path == NULL)
6154 path = "";
6155 error = got_worktree_resolve_path(&p, worktree, path);
6156 if (error)
6157 goto done;
6158 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6159 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6160 p) == -1) {
6161 error = got_error_from_errno("asprintf");
6162 free(p);
6163 goto done;
6165 free(p);
6166 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6167 if (error)
6168 goto done;
6169 } else {
6170 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6171 if (error)
6172 goto done;
6173 if (path == NULL)
6174 path = "/";
6175 error = got_repo_map_path(&in_repo_path, repo, path);
6176 if (error != NULL)
6177 goto done;
6180 if (commit_id_str == NULL) {
6181 struct got_reference *head_ref;
6182 if (worktree)
6183 refname = got_worktree_get_head_ref_name(worktree);
6184 else
6185 refname = GOT_REF_HEAD;
6186 error = got_ref_open(&head_ref, repo, refname, 0);
6187 if (error != NULL)
6188 goto done;
6189 error = got_ref_resolve(&commit_id, repo, head_ref);
6190 got_ref_close(head_ref);
6191 if (error != NULL)
6192 goto done;
6193 } else {
6194 struct got_reflist_head refs;
6195 TAILQ_INIT(&refs);
6196 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6197 NULL);
6198 if (error)
6199 goto done;
6200 error = got_repo_match_object_id(&commit_id, NULL,
6201 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6202 got_ref_list_free(&refs);
6203 if (error)
6204 goto done;
6207 if (worktree) {
6208 /* Release work tree lock. */
6209 got_worktree_close(worktree);
6210 worktree = NULL;
6213 error = got_object_open_as_commit(&commit, repo, commit_id);
6214 if (error)
6215 goto done;
6217 error = print_tree(in_repo_path, commit, show_ids, recurse,
6218 in_repo_path, repo);
6219 done:
6220 free(in_repo_path);
6221 free(repo_path);
6222 free(cwd);
6223 free(commit_id);
6224 if (commit)
6225 got_object_commit_close(commit);
6226 if (worktree)
6227 got_worktree_close(worktree);
6228 if (repo) {
6229 const struct got_error *close_err = got_repo_close(repo);
6230 if (error == NULL)
6231 error = close_err;
6233 if (pack_fds) {
6234 const struct got_error *pack_err =
6235 got_repo_pack_fds_close(pack_fds);
6236 if (error == NULL)
6237 error = pack_err;
6239 return error;
6242 __dead static void
6243 usage_status(void)
6245 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6246 "[-s status-codes] [path ...]\n", getprogname());
6247 exit(1);
6250 struct got_status_arg {
6251 char *status_codes;
6252 int suppress;
6255 static const struct got_error *
6256 print_status(void *arg, unsigned char status, unsigned char staged_status,
6257 const char *path, struct got_object_id *blob_id,
6258 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6259 int dirfd, const char *de_name)
6261 struct got_status_arg *st = arg;
6263 if (status == staged_status && (status == GOT_STATUS_DELETE))
6264 status = GOT_STATUS_NO_CHANGE;
6265 if (st != NULL && st->status_codes) {
6266 size_t ncodes = strlen(st->status_codes);
6267 int i, j = 0;
6269 for (i = 0; i < ncodes ; i++) {
6270 if (st->suppress) {
6271 if (status == st->status_codes[i] ||
6272 staged_status == st->status_codes[i]) {
6273 j++;
6274 continue;
6276 } else {
6277 if (status == st->status_codes[i] ||
6278 staged_status == st->status_codes[i])
6279 break;
6283 if (st->suppress && j == 0)
6284 goto print;
6286 if (i == ncodes)
6287 return NULL;
6289 print:
6290 printf("%c%c %s\n", status, staged_status, path);
6291 return NULL;
6294 static const struct got_error *
6295 cmd_status(int argc, char *argv[])
6297 const struct got_error *error = NULL;
6298 struct got_repository *repo = NULL;
6299 struct got_worktree *worktree = NULL;
6300 struct got_status_arg st;
6301 char *cwd = NULL;
6302 struct got_pathlist_head paths;
6303 int ch, i, no_ignores = 0;
6304 int *pack_fds = NULL;
6306 TAILQ_INIT(&paths);
6308 memset(&st, 0, sizeof(st));
6309 st.status_codes = NULL;
6310 st.suppress = 0;
6312 #ifndef PROFILE
6313 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6314 NULL) == -1)
6315 err(1, "pledge");
6316 #endif
6318 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6319 switch (ch) {
6320 case 'I':
6321 no_ignores = 1;
6322 break;
6323 case 'S':
6324 if (st.status_codes != NULL && st.suppress == 0)
6325 option_conflict('S', 's');
6326 st.suppress = 1;
6327 /* fallthrough */
6328 case 's':
6329 for (i = 0; i < strlen(optarg); i++) {
6330 switch (optarg[i]) {
6331 case GOT_STATUS_MODIFY:
6332 case GOT_STATUS_ADD:
6333 case GOT_STATUS_DELETE:
6334 case GOT_STATUS_CONFLICT:
6335 case GOT_STATUS_MISSING:
6336 case GOT_STATUS_OBSTRUCTED:
6337 case GOT_STATUS_UNVERSIONED:
6338 case GOT_STATUS_MODE_CHANGE:
6339 case GOT_STATUS_NONEXISTENT:
6340 break;
6341 default:
6342 errx(1, "invalid status code '%c'",
6343 optarg[i]);
6346 if (ch == 's' && st.suppress)
6347 option_conflict('s', 'S');
6348 st.status_codes = optarg;
6349 break;
6350 default:
6351 usage_status();
6352 /* NOTREACHED */
6356 argc -= optind;
6357 argv += optind;
6359 cwd = getcwd(NULL, 0);
6360 if (cwd == NULL) {
6361 error = got_error_from_errno("getcwd");
6362 goto done;
6365 error = got_repo_pack_fds_open(&pack_fds);
6366 if (error != NULL)
6367 goto done;
6369 error = got_worktree_open(&worktree, cwd);
6370 if (error) {
6371 if (error->code == GOT_ERR_NOT_WORKTREE)
6372 error = wrap_not_worktree_error(error, "status", cwd);
6373 goto done;
6376 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6377 NULL, pack_fds);
6378 if (error != NULL)
6379 goto done;
6381 error = apply_unveil(got_repo_get_path(repo), 1,
6382 got_worktree_get_root_path(worktree));
6383 if (error)
6384 goto done;
6386 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6387 if (error)
6388 goto done;
6390 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6391 print_status, &st, check_cancelled, NULL);
6392 done:
6393 if (pack_fds) {
6394 const struct got_error *pack_err =
6395 got_repo_pack_fds_close(pack_fds);
6396 if (error == NULL)
6397 error = pack_err;
6399 if (repo) {
6400 const struct got_error *close_err = got_repo_close(repo);
6401 if (error == NULL)
6402 error = close_err;
6405 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6406 free(cwd);
6407 return error;
6410 __dead static void
6411 usage_ref(void)
6413 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6414 "[-s reference] [name]\n", getprogname());
6415 exit(1);
6418 static const struct got_error *
6419 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6421 static const struct got_error *err = NULL;
6422 struct got_reflist_head refs;
6423 struct got_reflist_entry *re;
6425 TAILQ_INIT(&refs);
6426 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6427 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6428 repo);
6429 if (err)
6430 return err;
6432 TAILQ_FOREACH(re, &refs, entry) {
6433 char *refstr;
6434 refstr = got_ref_to_str(re->ref);
6435 if (refstr == NULL) {
6436 err = got_error_from_errno("got_ref_to_str");
6437 break;
6439 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6440 free(refstr);
6443 got_ref_list_free(&refs);
6444 return err;
6447 static const struct got_error *
6448 delete_ref_by_name(struct got_repository *repo, const char *refname)
6450 const struct got_error *err;
6451 struct got_reference *ref;
6453 err = got_ref_open(&ref, repo, refname, 0);
6454 if (err)
6455 return err;
6457 err = delete_ref(repo, ref);
6458 got_ref_close(ref);
6459 return err;
6462 static const struct got_error *
6463 add_ref(struct got_repository *repo, const char *refname, const char *target)
6465 const struct got_error *err = NULL;
6466 struct got_object_id *id = NULL;
6467 struct got_reference *ref = NULL;
6468 struct got_reflist_head refs;
6471 * Don't let the user create a reference name with a leading '-'.
6472 * While technically a valid reference name, this case is usually
6473 * an unintended typo.
6475 if (refname[0] == '-')
6476 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6478 TAILQ_INIT(&refs);
6479 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6480 if (err)
6481 goto done;
6482 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6483 &refs, repo);
6484 got_ref_list_free(&refs);
6485 if (err)
6486 goto done;
6488 err = got_ref_alloc(&ref, refname, id);
6489 if (err)
6490 goto done;
6492 err = got_ref_write(ref, repo);
6493 done:
6494 if (ref)
6495 got_ref_close(ref);
6496 free(id);
6497 return err;
6500 static const struct got_error *
6501 add_symref(struct got_repository *repo, const char *refname, const char *target)
6503 const struct got_error *err = NULL;
6504 struct got_reference *ref = NULL;
6505 struct got_reference *target_ref = NULL;
6508 * Don't let the user create a reference name with a leading '-'.
6509 * While technically a valid reference name, this case is usually
6510 * an unintended typo.
6512 if (refname[0] == '-')
6513 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6515 err = got_ref_open(&target_ref, repo, target, 0);
6516 if (err)
6517 return err;
6519 err = got_ref_alloc_symref(&ref, refname, target_ref);
6520 if (err)
6521 goto done;
6523 err = got_ref_write(ref, repo);
6524 done:
6525 if (target_ref)
6526 got_ref_close(target_ref);
6527 if (ref)
6528 got_ref_close(ref);
6529 return err;
6532 static const struct got_error *
6533 cmd_ref(int argc, char *argv[])
6535 const struct got_error *error = NULL;
6536 struct got_repository *repo = NULL;
6537 struct got_worktree *worktree = NULL;
6538 char *cwd = NULL, *repo_path = NULL;
6539 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6540 const char *obj_arg = NULL, *symref_target= NULL;
6541 char *refname = NULL;
6542 int *pack_fds = NULL;
6544 #ifndef PROFILE
6545 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6546 "sendfd unveil", NULL) == -1)
6547 err(1, "pledge");
6548 #endif
6550 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6551 switch (ch) {
6552 case 'c':
6553 obj_arg = optarg;
6554 break;
6555 case 'd':
6556 do_delete = 1;
6557 break;
6558 case 'l':
6559 do_list = 1;
6560 break;
6561 case 'r':
6562 repo_path = realpath(optarg, NULL);
6563 if (repo_path == NULL)
6564 return got_error_from_errno2("realpath",
6565 optarg);
6566 got_path_strip_trailing_slashes(repo_path);
6567 break;
6568 case 's':
6569 symref_target = optarg;
6570 break;
6571 case 't':
6572 sort_by_time = 1;
6573 break;
6574 default:
6575 usage_ref();
6576 /* NOTREACHED */
6580 if (obj_arg && do_list)
6581 option_conflict('c', 'l');
6582 if (obj_arg && do_delete)
6583 option_conflict('c', 'd');
6584 if (obj_arg && symref_target)
6585 option_conflict('c', 's');
6586 if (symref_target && do_delete)
6587 option_conflict('s', 'd');
6588 if (symref_target && do_list)
6589 option_conflict('s', 'l');
6590 if (do_delete && do_list)
6591 option_conflict('d', 'l');
6592 if (sort_by_time && !do_list)
6593 errx(1, "-t option requires -l option");
6595 argc -= optind;
6596 argv += optind;
6598 if (do_list) {
6599 if (argc != 0 && argc != 1)
6600 usage_ref();
6601 if (argc == 1) {
6602 refname = strdup(argv[0]);
6603 if (refname == NULL) {
6604 error = got_error_from_errno("strdup");
6605 goto done;
6608 } else {
6609 if (argc != 1)
6610 usage_ref();
6611 refname = strdup(argv[0]);
6612 if (refname == NULL) {
6613 error = got_error_from_errno("strdup");
6614 goto done;
6618 if (refname)
6619 got_path_strip_trailing_slashes(refname);
6621 cwd = getcwd(NULL, 0);
6622 if (cwd == NULL) {
6623 error = got_error_from_errno("getcwd");
6624 goto done;
6627 error = got_repo_pack_fds_open(&pack_fds);
6628 if (error != NULL)
6629 goto done;
6631 if (repo_path == NULL) {
6632 error = got_worktree_open(&worktree, cwd);
6633 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6634 goto done;
6635 else
6636 error = NULL;
6637 if (worktree) {
6638 repo_path =
6639 strdup(got_worktree_get_repo_path(worktree));
6640 if (repo_path == NULL)
6641 error = got_error_from_errno("strdup");
6642 if (error)
6643 goto done;
6644 } else {
6645 repo_path = strdup(cwd);
6646 if (repo_path == NULL) {
6647 error = got_error_from_errno("strdup");
6648 goto done;
6653 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6654 if (error != NULL)
6655 goto done;
6657 #ifndef PROFILE
6658 if (do_list) {
6659 /* Remove "cpath" promise. */
6660 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6661 NULL) == -1)
6662 err(1, "pledge");
6664 #endif
6666 error = apply_unveil(got_repo_get_path(repo), do_list,
6667 worktree ? got_worktree_get_root_path(worktree) : NULL);
6668 if (error)
6669 goto done;
6671 if (do_list)
6672 error = list_refs(repo, refname, sort_by_time);
6673 else if (do_delete)
6674 error = delete_ref_by_name(repo, refname);
6675 else if (symref_target)
6676 error = add_symref(repo, refname, symref_target);
6677 else {
6678 if (obj_arg == NULL)
6679 usage_ref();
6680 error = add_ref(repo, refname, obj_arg);
6682 done:
6683 free(refname);
6684 if (repo) {
6685 const struct got_error *close_err = got_repo_close(repo);
6686 if (error == NULL)
6687 error = close_err;
6689 if (worktree)
6690 got_worktree_close(worktree);
6691 if (pack_fds) {
6692 const struct got_error *pack_err =
6693 got_repo_pack_fds_close(pack_fds);
6694 if (error == NULL)
6695 error = pack_err;
6697 free(cwd);
6698 free(repo_path);
6699 return error;
6702 __dead static void
6703 usage_branch(void)
6705 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6706 "[-r repository-path] [name]\n", getprogname());
6707 exit(1);
6710 static const struct got_error *
6711 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6712 struct got_reference *ref)
6714 const struct got_error *err = NULL;
6715 const char *refname, *marker = " ";
6716 char *refstr;
6718 refname = got_ref_get_name(ref);
6719 if (worktree && strcmp(refname,
6720 got_worktree_get_head_ref_name(worktree)) == 0) {
6721 struct got_object_id *id = NULL;
6723 err = got_ref_resolve(&id, repo, ref);
6724 if (err)
6725 return err;
6726 if (got_object_id_cmp(id,
6727 got_worktree_get_base_commit_id(worktree)) == 0)
6728 marker = "* ";
6729 else
6730 marker = "~ ";
6731 free(id);
6734 if (strncmp(refname, "refs/heads/", 11) == 0)
6735 refname += 11;
6736 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6737 refname += 18;
6738 if (strncmp(refname, "refs/remotes/", 13) == 0)
6739 refname += 13;
6741 refstr = got_ref_to_str(ref);
6742 if (refstr == NULL)
6743 return got_error_from_errno("got_ref_to_str");
6745 printf("%s%s: %s\n", marker, refname, refstr);
6746 free(refstr);
6747 return NULL;
6750 static const struct got_error *
6751 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6753 const char *refname;
6755 if (worktree == NULL)
6756 return got_error(GOT_ERR_NOT_WORKTREE);
6758 refname = got_worktree_get_head_ref_name(worktree);
6760 if (strncmp(refname, "refs/heads/", 11) == 0)
6761 refname += 11;
6762 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6763 refname += 18;
6765 printf("%s\n", refname);
6767 return NULL;
6770 static const struct got_error *
6771 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6772 int sort_by_time)
6774 static const struct got_error *err = NULL;
6775 struct got_reflist_head refs;
6776 struct got_reflist_entry *re;
6777 struct got_reference *temp_ref = NULL;
6778 int rebase_in_progress, histedit_in_progress;
6780 TAILQ_INIT(&refs);
6782 if (worktree) {
6783 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6784 worktree);
6785 if (err)
6786 return err;
6788 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6789 worktree);
6790 if (err)
6791 return err;
6793 if (rebase_in_progress || histedit_in_progress) {
6794 err = got_ref_open(&temp_ref, repo,
6795 got_worktree_get_head_ref_name(worktree), 0);
6796 if (err)
6797 return err;
6798 list_branch(repo, worktree, temp_ref);
6799 got_ref_close(temp_ref);
6803 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6804 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6805 repo);
6806 if (err)
6807 return err;
6809 TAILQ_FOREACH(re, &refs, entry)
6810 list_branch(repo, worktree, re->ref);
6812 got_ref_list_free(&refs);
6814 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6815 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6816 repo);
6817 if (err)
6818 return err;
6820 TAILQ_FOREACH(re, &refs, entry)
6821 list_branch(repo, worktree, re->ref);
6823 got_ref_list_free(&refs);
6825 return NULL;
6828 static const struct got_error *
6829 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6830 const char *branch_name)
6832 const struct got_error *err = NULL;
6833 struct got_reference *ref = NULL;
6834 char *refname, *remote_refname = NULL;
6836 if (strncmp(branch_name, "refs/", 5) == 0)
6837 branch_name += 5;
6838 if (strncmp(branch_name, "heads/", 6) == 0)
6839 branch_name += 6;
6840 else if (strncmp(branch_name, "remotes/", 8) == 0)
6841 branch_name += 8;
6843 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6844 return got_error_from_errno("asprintf");
6846 if (asprintf(&remote_refname, "refs/remotes/%s",
6847 branch_name) == -1) {
6848 err = got_error_from_errno("asprintf");
6849 goto done;
6852 err = got_ref_open(&ref, repo, refname, 0);
6853 if (err) {
6854 const struct got_error *err2;
6855 if (err->code != GOT_ERR_NOT_REF)
6856 goto done;
6858 * Keep 'err' intact such that if neither branch exists
6859 * we report "refs/heads" rather than "refs/remotes" in
6860 * our error message.
6862 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6863 if (err2)
6864 goto done;
6865 err = NULL;
6868 if (worktree &&
6869 strcmp(got_worktree_get_head_ref_name(worktree),
6870 got_ref_get_name(ref)) == 0) {
6871 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6872 "will not delete this work tree's current branch");
6873 goto done;
6876 err = delete_ref(repo, ref);
6877 done:
6878 if (ref)
6879 got_ref_close(ref);
6880 free(refname);
6881 free(remote_refname);
6882 return err;
6885 static const struct got_error *
6886 add_branch(struct got_repository *repo, const char *branch_name,
6887 struct got_object_id *base_commit_id)
6889 const struct got_error *err = NULL;
6890 struct got_reference *ref = NULL;
6891 char *refname = NULL;
6894 * Don't let the user create a branch name with a leading '-'.
6895 * While technically a valid reference name, this case is usually
6896 * an unintended typo.
6898 if (branch_name[0] == '-')
6899 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6901 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6902 branch_name += 11;
6904 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6905 err = got_error_from_errno("asprintf");
6906 goto done;
6909 err = got_ref_open(&ref, repo, refname, 0);
6910 if (err == NULL) {
6911 err = got_error(GOT_ERR_BRANCH_EXISTS);
6912 goto done;
6913 } else if (err->code != GOT_ERR_NOT_REF)
6914 goto done;
6916 err = got_ref_alloc(&ref, refname, base_commit_id);
6917 if (err)
6918 goto done;
6920 err = got_ref_write(ref, repo);
6921 done:
6922 if (ref)
6923 got_ref_close(ref);
6924 free(refname);
6925 return err;
6928 static const struct got_error *
6929 cmd_branch(int argc, char *argv[])
6931 const struct got_error *error = NULL;
6932 struct got_repository *repo = NULL;
6933 struct got_worktree *worktree = NULL;
6934 char *cwd = NULL, *repo_path = NULL;
6935 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6936 const char *delref = NULL, *commit_id_arg = NULL;
6937 struct got_reference *ref = NULL;
6938 struct got_pathlist_head paths;
6939 struct got_object_id *commit_id = NULL;
6940 char *commit_id_str = NULL;
6941 int *pack_fds = NULL;
6943 TAILQ_INIT(&paths);
6945 #ifndef PROFILE
6946 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6947 "sendfd unveil", NULL) == -1)
6948 err(1, "pledge");
6949 #endif
6951 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6952 switch (ch) {
6953 case 'c':
6954 commit_id_arg = optarg;
6955 break;
6956 case 'd':
6957 delref = optarg;
6958 break;
6959 case 'l':
6960 do_list = 1;
6961 break;
6962 case 'n':
6963 do_update = 0;
6964 break;
6965 case 'r':
6966 repo_path = realpath(optarg, NULL);
6967 if (repo_path == NULL)
6968 return got_error_from_errno2("realpath",
6969 optarg);
6970 got_path_strip_trailing_slashes(repo_path);
6971 break;
6972 case 't':
6973 sort_by_time = 1;
6974 break;
6975 default:
6976 usage_branch();
6977 /* NOTREACHED */
6981 if (do_list && delref)
6982 option_conflict('l', 'd');
6983 if (sort_by_time && !do_list)
6984 errx(1, "-t option requires -l option");
6986 argc -= optind;
6987 argv += optind;
6989 if (!do_list && !delref && argc == 0)
6990 do_show = 1;
6992 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6993 errx(1, "-c option can only be used when creating a branch");
6995 if (do_list || delref) {
6996 if (argc > 0)
6997 usage_branch();
6998 } else if (!do_show && argc != 1)
6999 usage_branch();
7001 cwd = getcwd(NULL, 0);
7002 if (cwd == NULL) {
7003 error = got_error_from_errno("getcwd");
7004 goto done;
7007 error = got_repo_pack_fds_open(&pack_fds);
7008 if (error != NULL)
7009 goto done;
7011 if (repo_path == NULL) {
7012 error = got_worktree_open(&worktree, cwd);
7013 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7014 goto done;
7015 else
7016 error = NULL;
7017 if (worktree) {
7018 repo_path =
7019 strdup(got_worktree_get_repo_path(worktree));
7020 if (repo_path == NULL)
7021 error = got_error_from_errno("strdup");
7022 if (error)
7023 goto done;
7024 } else {
7025 repo_path = strdup(cwd);
7026 if (repo_path == NULL) {
7027 error = got_error_from_errno("strdup");
7028 goto done;
7033 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7034 if (error != NULL)
7035 goto done;
7037 #ifndef PROFILE
7038 if (do_list || do_show) {
7039 /* Remove "cpath" promise. */
7040 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7041 NULL) == -1)
7042 err(1, "pledge");
7044 #endif
7046 error = apply_unveil(got_repo_get_path(repo), do_list,
7047 worktree ? got_worktree_get_root_path(worktree) : NULL);
7048 if (error)
7049 goto done;
7051 if (do_show)
7052 error = show_current_branch(repo, worktree);
7053 else if (do_list)
7054 error = list_branches(repo, worktree, sort_by_time);
7055 else if (delref)
7056 error = delete_branch(repo, worktree, delref);
7057 else {
7058 struct got_reflist_head refs;
7059 TAILQ_INIT(&refs);
7060 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7061 NULL);
7062 if (error)
7063 goto done;
7064 if (commit_id_arg == NULL)
7065 commit_id_arg = worktree ?
7066 got_worktree_get_head_ref_name(worktree) :
7067 GOT_REF_HEAD;
7068 error = got_repo_match_object_id(&commit_id, NULL,
7069 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7070 got_ref_list_free(&refs);
7071 if (error)
7072 goto done;
7073 error = add_branch(repo, argv[0], commit_id);
7074 if (error)
7075 goto done;
7076 if (worktree && do_update) {
7077 struct got_update_progress_arg upa;
7078 char *branch_refname = NULL;
7080 error = got_object_id_str(&commit_id_str, commit_id);
7081 if (error)
7082 goto done;
7083 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7084 worktree);
7085 if (error)
7086 goto done;
7087 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7088 == -1) {
7089 error = got_error_from_errno("asprintf");
7090 goto done;
7092 error = got_ref_open(&ref, repo, branch_refname, 0);
7093 free(branch_refname);
7094 if (error)
7095 goto done;
7096 error = switch_head_ref(ref, commit_id, worktree,
7097 repo);
7098 if (error)
7099 goto done;
7100 error = got_worktree_set_base_commit_id(worktree, repo,
7101 commit_id);
7102 if (error)
7103 goto done;
7104 memset(&upa, 0, sizeof(upa));
7105 error = got_worktree_checkout_files(worktree, &paths,
7106 repo, update_progress, &upa, check_cancelled,
7107 NULL);
7108 if (error)
7109 goto done;
7110 if (upa.did_something) {
7111 printf("Updated to %s: %s\n",
7112 got_worktree_get_head_ref_name(worktree),
7113 commit_id_str);
7115 print_update_progress_stats(&upa);
7118 done:
7119 if (ref)
7120 got_ref_close(ref);
7121 if (repo) {
7122 const struct got_error *close_err = got_repo_close(repo);
7123 if (error == NULL)
7124 error = close_err;
7126 if (worktree)
7127 got_worktree_close(worktree);
7128 if (pack_fds) {
7129 const struct got_error *pack_err =
7130 got_repo_pack_fds_close(pack_fds);
7131 if (error == NULL)
7132 error = pack_err;
7134 free(cwd);
7135 free(repo_path);
7136 free(commit_id);
7137 free(commit_id_str);
7138 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7139 return error;
7143 __dead static void
7144 usage_tag(void)
7146 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7147 "[-r repository-path] [-s signer-id] name\n", getprogname());
7148 exit(1);
7151 #if 0
7152 static const struct got_error *
7153 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7155 const struct got_error *err = NULL;
7156 struct got_reflist_entry *re, *se, *new;
7157 struct got_object_id *re_id, *se_id;
7158 struct got_tag_object *re_tag, *se_tag;
7159 time_t re_time, se_time;
7161 STAILQ_FOREACH(re, tags, entry) {
7162 se = STAILQ_FIRST(sorted);
7163 if (se == NULL) {
7164 err = got_reflist_entry_dup(&new, re);
7165 if (err)
7166 return err;
7167 STAILQ_INSERT_HEAD(sorted, new, entry);
7168 continue;
7169 } else {
7170 err = got_ref_resolve(&re_id, repo, re->ref);
7171 if (err)
7172 break;
7173 err = got_object_open_as_tag(&re_tag, repo, re_id);
7174 free(re_id);
7175 if (err)
7176 break;
7177 re_time = got_object_tag_get_tagger_time(re_tag);
7178 got_object_tag_close(re_tag);
7181 while (se) {
7182 err = got_ref_resolve(&se_id, repo, re->ref);
7183 if (err)
7184 break;
7185 err = got_object_open_as_tag(&se_tag, repo, se_id);
7186 free(se_id);
7187 if (err)
7188 break;
7189 se_time = got_object_tag_get_tagger_time(se_tag);
7190 got_object_tag_close(se_tag);
7192 if (se_time > re_time) {
7193 err = got_reflist_entry_dup(&new, re);
7194 if (err)
7195 return err;
7196 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7197 break;
7199 se = STAILQ_NEXT(se, entry);
7200 continue;
7203 done:
7204 return err;
7206 #endif
7208 static const struct got_error *
7209 get_tag_refname(char **refname, const char *tag_name)
7211 const struct got_error *err;
7213 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7214 *refname = strdup(tag_name);
7215 if (*refname == NULL)
7216 return got_error_from_errno("strdup");
7217 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7218 err = got_error_from_errno("asprintf");
7219 *refname = NULL;
7220 return err;
7223 return NULL;
7226 static const struct got_error *
7227 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7228 const char *allowed_signers, const char *revoked_signers, int verbosity)
7230 static const struct got_error *err = NULL;
7231 struct got_reflist_head refs;
7232 struct got_reflist_entry *re;
7233 char *wanted_refname = NULL;
7234 int bad_sigs = 0;
7236 TAILQ_INIT(&refs);
7238 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7239 if (err)
7240 return err;
7242 if (tag_name) {
7243 struct got_reference *ref;
7244 err = get_tag_refname(&wanted_refname, tag_name);
7245 if (err)
7246 goto done;
7247 /* Wanted tag reference should exist. */
7248 err = got_ref_open(&ref, repo, wanted_refname, 0);
7249 if (err)
7250 goto done;
7251 got_ref_close(ref);
7254 TAILQ_FOREACH(re, &refs, entry) {
7255 const char *refname;
7256 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7257 char datebuf[26];
7258 const char *tagger, *ssh_sig = NULL;
7259 char *sig_msg = NULL;
7260 time_t tagger_time;
7261 struct got_object_id *id;
7262 struct got_tag_object *tag;
7263 struct got_commit_object *commit = NULL;
7265 refname = got_ref_get_name(re->ref);
7266 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7267 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7268 continue;
7269 refname += 10;
7270 refstr = got_ref_to_str(re->ref);
7271 if (refstr == NULL) {
7272 err = got_error_from_errno("got_ref_to_str");
7273 break;
7276 err = got_ref_resolve(&id, repo, re->ref);
7277 if (err)
7278 break;
7279 err = got_object_open_as_tag(&tag, repo, id);
7280 if (err) {
7281 if (err->code != GOT_ERR_OBJ_TYPE) {
7282 free(id);
7283 break;
7285 /* "lightweight" tag */
7286 err = got_object_open_as_commit(&commit, repo, id);
7287 if (err) {
7288 free(id);
7289 break;
7291 tagger = got_object_commit_get_committer(commit);
7292 tagger_time =
7293 got_object_commit_get_committer_time(commit);
7294 err = got_object_id_str(&id_str, id);
7295 free(id);
7296 if (err)
7297 break;
7298 } else {
7299 free(id);
7300 tagger = got_object_tag_get_tagger(tag);
7301 tagger_time = got_object_tag_get_tagger_time(tag);
7302 err = got_object_id_str(&id_str,
7303 got_object_tag_get_object_id(tag));
7304 if (err)
7305 break;
7308 if (tag && verify_tags) {
7309 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7310 got_object_tag_get_message(tag));
7311 if (ssh_sig && allowed_signers == NULL) {
7312 err = got_error_msg(
7313 GOT_ERR_VERIFY_TAG_SIGNATURE,
7314 "SSH signature verification requires "
7315 "setting allowed_signers in "
7316 "got.conf(5)");
7317 break;
7321 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7322 free(refstr);
7323 printf("from: %s\n", tagger);
7324 datestr = get_datestr(&tagger_time, datebuf);
7325 if (datestr)
7326 printf("date: %s UTC\n", datestr);
7327 if (commit)
7328 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7329 else {
7330 switch (got_object_tag_get_object_type(tag)) {
7331 case GOT_OBJ_TYPE_BLOB:
7332 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7333 id_str);
7334 break;
7335 case GOT_OBJ_TYPE_TREE:
7336 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7337 id_str);
7338 break;
7339 case GOT_OBJ_TYPE_COMMIT:
7340 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7341 id_str);
7342 break;
7343 case GOT_OBJ_TYPE_TAG:
7344 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7345 id_str);
7346 break;
7347 default:
7348 break;
7351 free(id_str);
7353 if (ssh_sig) {
7354 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7355 allowed_signers, revoked_signers, verbosity);
7356 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7357 bad_sigs = 1;
7358 else if (err)
7359 break;
7360 printf("signature: %s", sig_msg);
7361 free(sig_msg);
7362 sig_msg = NULL;
7365 if (commit) {
7366 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7367 if (err)
7368 break;
7369 got_object_commit_close(commit);
7370 } else {
7371 tagmsg0 = strdup(got_object_tag_get_message(tag));
7372 got_object_tag_close(tag);
7373 if (tagmsg0 == NULL) {
7374 err = got_error_from_errno("strdup");
7375 break;
7379 tagmsg = tagmsg0;
7380 do {
7381 line = strsep(&tagmsg, "\n");
7382 if (line)
7383 printf(" %s\n", line);
7384 } while (line);
7385 free(tagmsg0);
7387 done:
7388 got_ref_list_free(&refs);
7389 free(wanted_refname);
7391 if (err == NULL && bad_sigs)
7392 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7393 return err;
7396 static const struct got_error *
7397 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7398 const char *tag_name, const char *repo_path)
7400 const struct got_error *err = NULL;
7401 char *template = NULL, *initial_content = NULL;
7402 char *editor = NULL;
7403 int initial_content_len;
7404 int fd = -1;
7406 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7407 err = got_error_from_errno("asprintf");
7408 goto done;
7411 initial_content_len = asprintf(&initial_content,
7412 "\n# tagging commit %s as %s\n",
7413 commit_id_str, tag_name);
7414 if (initial_content_len == -1) {
7415 err = got_error_from_errno("asprintf");
7416 goto done;
7419 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7420 if (err)
7421 goto done;
7423 if (write(fd, initial_content, initial_content_len) == -1) {
7424 err = got_error_from_errno2("write", *tagmsg_path);
7425 goto done;
7427 if (close(fd) == -1) {
7428 err = got_error_from_errno2("close", *tagmsg_path);
7429 goto done;
7431 fd = -1;
7433 err = get_editor(&editor);
7434 if (err)
7435 goto done;
7436 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7437 initial_content_len, 1);
7438 done:
7439 free(initial_content);
7440 free(template);
7441 free(editor);
7443 if (fd != -1 && close(fd) == -1 && err == NULL)
7444 err = got_error_from_errno2("close", *tagmsg_path);
7446 if (err) {
7447 free(*tagmsg);
7448 *tagmsg = NULL;
7450 return err;
7453 static const struct got_error *
7454 add_tag(struct got_repository *repo, const char *tagger,
7455 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7456 const char *signer_id, int verbosity)
7458 const struct got_error *err = NULL;
7459 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7460 char *label = NULL, *commit_id_str = NULL;
7461 struct got_reference *ref = NULL;
7462 char *refname = NULL, *tagmsg = NULL;
7463 char *tagmsg_path = NULL, *tag_id_str = NULL;
7464 int preserve_tagmsg = 0;
7465 struct got_reflist_head refs;
7467 TAILQ_INIT(&refs);
7470 * Don't let the user create a tag name with a leading '-'.
7471 * While technically a valid reference name, this case is usually
7472 * an unintended typo.
7474 if (tag_name[0] == '-')
7475 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7477 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7478 if (err)
7479 goto done;
7481 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7482 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7483 if (err)
7484 goto done;
7486 err = got_object_id_str(&commit_id_str, commit_id);
7487 if (err)
7488 goto done;
7490 err = get_tag_refname(&refname, tag_name);
7491 if (err)
7492 goto done;
7493 if (strncmp("refs/tags/", tag_name, 10) == 0)
7494 tag_name += 10;
7496 err = got_ref_open(&ref, repo, refname, 0);
7497 if (err == NULL) {
7498 err = got_error(GOT_ERR_TAG_EXISTS);
7499 goto done;
7500 } else if (err->code != GOT_ERR_NOT_REF)
7501 goto done;
7503 if (tagmsg_arg == NULL) {
7504 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7505 tag_name, got_repo_get_path(repo));
7506 if (err) {
7507 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7508 tagmsg_path != NULL)
7509 preserve_tagmsg = 1;
7510 goto done;
7512 /* Editor is done; we can now apply unveil(2) */
7513 err = got_sigs_apply_unveil();
7514 if (err)
7515 goto done;
7516 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7517 if (err)
7518 goto done;
7521 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7522 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7523 verbosity);
7524 if (err) {
7525 if (tagmsg_path)
7526 preserve_tagmsg = 1;
7527 goto done;
7530 err = got_ref_alloc(&ref, refname, tag_id);
7531 if (err) {
7532 if (tagmsg_path)
7533 preserve_tagmsg = 1;
7534 goto done;
7537 err = got_ref_write(ref, repo);
7538 if (err) {
7539 if (tagmsg_path)
7540 preserve_tagmsg = 1;
7541 goto done;
7544 err = got_object_id_str(&tag_id_str, tag_id);
7545 if (err) {
7546 if (tagmsg_path)
7547 preserve_tagmsg = 1;
7548 goto done;
7550 printf("Created tag %s\n", tag_id_str);
7551 done:
7552 if (preserve_tagmsg) {
7553 fprintf(stderr, "%s: tag message preserved in %s\n",
7554 getprogname(), tagmsg_path);
7555 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7556 err = got_error_from_errno2("unlink", tagmsg_path);
7557 free(tag_id_str);
7558 if (ref)
7559 got_ref_close(ref);
7560 free(commit_id);
7561 free(commit_id_str);
7562 free(refname);
7563 free(tagmsg);
7564 free(tagmsg_path);
7565 got_ref_list_free(&refs);
7566 return err;
7569 static const struct got_error *
7570 cmd_tag(int argc, char *argv[])
7572 const struct got_error *error = NULL;
7573 struct got_repository *repo = NULL;
7574 struct got_worktree *worktree = NULL;
7575 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7576 char *gitconfig_path = NULL, *tagger = NULL;
7577 char *allowed_signers = NULL, *revoked_signers = NULL;
7578 const char *signer_id = NULL;
7579 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7580 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7581 int *pack_fds = NULL;
7583 #ifndef PROFILE
7584 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7585 "sendfd unveil", NULL) == -1)
7586 err(1, "pledge");
7587 #endif
7589 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7590 switch (ch) {
7591 case 'c':
7592 commit_id_arg = optarg;
7593 break;
7594 case 'l':
7595 do_list = 1;
7596 break;
7597 case 'm':
7598 tagmsg = optarg;
7599 break;
7600 case 'r':
7601 repo_path = realpath(optarg, NULL);
7602 if (repo_path == NULL) {
7603 error = got_error_from_errno2("realpath",
7604 optarg);
7605 goto done;
7607 got_path_strip_trailing_slashes(repo_path);
7608 break;
7609 case 's':
7610 signer_id = optarg;
7611 break;
7612 case 'V':
7613 verify_tags = 1;
7614 break;
7615 case 'v':
7616 if (verbosity < 0)
7617 verbosity = 0;
7618 else if (verbosity < 3)
7619 verbosity++;
7620 break;
7621 default:
7622 usage_tag();
7623 /* NOTREACHED */
7627 argc -= optind;
7628 argv += optind;
7630 if (do_list || verify_tags) {
7631 if (commit_id_arg != NULL)
7632 errx(1,
7633 "-c option can only be used when creating a tag");
7634 if (tagmsg) {
7635 if (do_list)
7636 option_conflict('l', 'm');
7637 else
7638 option_conflict('V', 'm');
7640 if (signer_id) {
7641 if (do_list)
7642 option_conflict('l', 's');
7643 else
7644 option_conflict('V', 's');
7646 if (argc > 1)
7647 usage_tag();
7648 } else if (argc != 1)
7649 usage_tag();
7651 if (argc == 1)
7652 tag_name = argv[0];
7654 cwd = getcwd(NULL, 0);
7655 if (cwd == NULL) {
7656 error = got_error_from_errno("getcwd");
7657 goto done;
7660 error = got_repo_pack_fds_open(&pack_fds);
7661 if (error != NULL)
7662 goto done;
7664 if (repo_path == NULL) {
7665 error = got_worktree_open(&worktree, cwd);
7666 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7667 goto done;
7668 else
7669 error = NULL;
7670 if (worktree) {
7671 repo_path =
7672 strdup(got_worktree_get_repo_path(worktree));
7673 if (repo_path == NULL)
7674 error = got_error_from_errno("strdup");
7675 if (error)
7676 goto done;
7677 } else {
7678 repo_path = strdup(cwd);
7679 if (repo_path == NULL) {
7680 error = got_error_from_errno("strdup");
7681 goto done;
7686 if (do_list || verify_tags) {
7687 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7688 if (error != NULL)
7689 goto done;
7690 error = get_allowed_signers(&allowed_signers, repo, worktree);
7691 if (error)
7692 goto done;
7693 error = get_revoked_signers(&revoked_signers, repo, worktree);
7694 if (error)
7695 goto done;
7696 if (worktree) {
7697 /* Release work tree lock. */
7698 got_worktree_close(worktree);
7699 worktree = NULL;
7703 * Remove "cpath" promise unless needed for signature tmpfile
7704 * creation.
7706 if (verify_tags)
7707 got_sigs_apply_unveil();
7708 else {
7709 #ifndef PROFILE
7710 if (pledge("stdio rpath wpath flock proc exec sendfd "
7711 "unveil", NULL) == -1)
7712 err(1, "pledge");
7713 #endif
7715 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7716 if (error)
7717 goto done;
7718 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7719 revoked_signers, verbosity);
7720 } else {
7721 error = get_gitconfig_path(&gitconfig_path);
7722 if (error)
7723 goto done;
7724 error = got_repo_open(&repo, repo_path, gitconfig_path,
7725 pack_fds);
7726 if (error != NULL)
7727 goto done;
7729 error = get_author(&tagger, repo, worktree);
7730 if (error)
7731 goto done;
7732 if (signer_id == NULL)
7733 signer_id = get_signer_id(repo, worktree);
7735 if (tagmsg) {
7736 if (signer_id) {
7737 error = got_sigs_apply_unveil();
7738 if (error)
7739 goto done;
7741 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7742 if (error)
7743 goto done;
7746 if (commit_id_arg == NULL) {
7747 struct got_reference *head_ref;
7748 struct got_object_id *commit_id;
7749 error = got_ref_open(&head_ref, repo,
7750 worktree ? got_worktree_get_head_ref_name(worktree)
7751 : GOT_REF_HEAD, 0);
7752 if (error)
7753 goto done;
7754 error = got_ref_resolve(&commit_id, repo, head_ref);
7755 got_ref_close(head_ref);
7756 if (error)
7757 goto done;
7758 error = got_object_id_str(&commit_id_str, commit_id);
7759 free(commit_id);
7760 if (error)
7761 goto done;
7764 if (worktree) {
7765 /* Release work tree lock. */
7766 got_worktree_close(worktree);
7767 worktree = NULL;
7770 error = add_tag(repo, tagger, tag_name,
7771 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7772 signer_id, verbosity);
7774 done:
7775 if (repo) {
7776 const struct got_error *close_err = got_repo_close(repo);
7777 if (error == NULL)
7778 error = close_err;
7780 if (worktree)
7781 got_worktree_close(worktree);
7782 if (pack_fds) {
7783 const struct got_error *pack_err =
7784 got_repo_pack_fds_close(pack_fds);
7785 if (error == NULL)
7786 error = pack_err;
7788 free(cwd);
7789 free(repo_path);
7790 free(gitconfig_path);
7791 free(commit_id_str);
7792 free(tagger);
7793 free(allowed_signers);
7794 free(revoked_signers);
7795 return error;
7798 __dead static void
7799 usage_add(void)
7801 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7802 exit(1);
7805 static const struct got_error *
7806 add_progress(void *arg, unsigned char status, const char *path)
7808 while (path[0] == '/')
7809 path++;
7810 printf("%c %s\n", status, path);
7811 return NULL;
7814 static const struct got_error *
7815 cmd_add(int argc, char *argv[])
7817 const struct got_error *error = NULL;
7818 struct got_repository *repo = NULL;
7819 struct got_worktree *worktree = NULL;
7820 char *cwd = NULL;
7821 struct got_pathlist_head paths;
7822 struct got_pathlist_entry *pe;
7823 int ch, can_recurse = 0, no_ignores = 0;
7824 int *pack_fds = NULL;
7826 TAILQ_INIT(&paths);
7828 #ifndef PROFILE
7829 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7830 NULL) == -1)
7831 err(1, "pledge");
7832 #endif
7834 while ((ch = getopt(argc, argv, "IR")) != -1) {
7835 switch (ch) {
7836 case 'I':
7837 no_ignores = 1;
7838 break;
7839 case 'R':
7840 can_recurse = 1;
7841 break;
7842 default:
7843 usage_add();
7844 /* NOTREACHED */
7848 argc -= optind;
7849 argv += optind;
7851 if (argc < 1)
7852 usage_add();
7854 cwd = getcwd(NULL, 0);
7855 if (cwd == NULL) {
7856 error = got_error_from_errno("getcwd");
7857 goto done;
7860 error = got_repo_pack_fds_open(&pack_fds);
7861 if (error != NULL)
7862 goto done;
7864 error = got_worktree_open(&worktree, cwd);
7865 if (error) {
7866 if (error->code == GOT_ERR_NOT_WORKTREE)
7867 error = wrap_not_worktree_error(error, "add", cwd);
7868 goto done;
7871 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7872 NULL, pack_fds);
7873 if (error != NULL)
7874 goto done;
7876 error = apply_unveil(got_repo_get_path(repo), 1,
7877 got_worktree_get_root_path(worktree));
7878 if (error)
7879 goto done;
7881 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7882 if (error)
7883 goto done;
7885 if (!can_recurse) {
7886 char *ondisk_path;
7887 struct stat sb;
7888 TAILQ_FOREACH(pe, &paths, entry) {
7889 if (asprintf(&ondisk_path, "%s/%s",
7890 got_worktree_get_root_path(worktree),
7891 pe->path) == -1) {
7892 error = got_error_from_errno("asprintf");
7893 goto done;
7895 if (lstat(ondisk_path, &sb) == -1) {
7896 if (errno == ENOENT) {
7897 free(ondisk_path);
7898 continue;
7900 error = got_error_from_errno2("lstat",
7901 ondisk_path);
7902 free(ondisk_path);
7903 goto done;
7905 free(ondisk_path);
7906 if (S_ISDIR(sb.st_mode)) {
7907 error = got_error_msg(GOT_ERR_BAD_PATH,
7908 "adding directories requires -R option");
7909 goto done;
7914 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7915 NULL, repo, no_ignores);
7916 done:
7917 if (repo) {
7918 const struct got_error *close_err = got_repo_close(repo);
7919 if (error == NULL)
7920 error = close_err;
7922 if (worktree)
7923 got_worktree_close(worktree);
7924 if (pack_fds) {
7925 const struct got_error *pack_err =
7926 got_repo_pack_fds_close(pack_fds);
7927 if (error == NULL)
7928 error = pack_err;
7930 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7931 free(cwd);
7932 return error;
7935 __dead static void
7936 usage_remove(void)
7938 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7939 getprogname());
7940 exit(1);
7943 static const struct got_error *
7944 print_remove_status(void *arg, unsigned char status,
7945 unsigned char staged_status, const char *path)
7947 while (path[0] == '/')
7948 path++;
7949 if (status == GOT_STATUS_NONEXISTENT)
7950 return NULL;
7951 if (status == staged_status && (status == GOT_STATUS_DELETE))
7952 status = GOT_STATUS_NO_CHANGE;
7953 printf("%c%c %s\n", status, staged_status, path);
7954 return NULL;
7957 static const struct got_error *
7958 cmd_remove(int argc, char *argv[])
7960 const struct got_error *error = NULL;
7961 struct got_worktree *worktree = NULL;
7962 struct got_repository *repo = NULL;
7963 const char *status_codes = NULL;
7964 char *cwd = NULL;
7965 struct got_pathlist_head paths;
7966 struct got_pathlist_entry *pe;
7967 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7968 int ignore_missing_paths = 0;
7969 int *pack_fds = NULL;
7971 TAILQ_INIT(&paths);
7973 #ifndef PROFILE
7974 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7975 NULL) == -1)
7976 err(1, "pledge");
7977 #endif
7979 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7980 switch (ch) {
7981 case 'f':
7982 delete_local_mods = 1;
7983 ignore_missing_paths = 1;
7984 break;
7985 case 'k':
7986 keep_on_disk = 1;
7987 break;
7988 case 'R':
7989 can_recurse = 1;
7990 break;
7991 case 's':
7992 for (i = 0; i < strlen(optarg); i++) {
7993 switch (optarg[i]) {
7994 case GOT_STATUS_MODIFY:
7995 delete_local_mods = 1;
7996 break;
7997 case GOT_STATUS_MISSING:
7998 ignore_missing_paths = 1;
7999 break;
8000 default:
8001 errx(1, "invalid status code '%c'",
8002 optarg[i]);
8005 status_codes = optarg;
8006 break;
8007 default:
8008 usage_remove();
8009 /* NOTREACHED */
8013 argc -= optind;
8014 argv += optind;
8016 if (argc < 1)
8017 usage_remove();
8019 cwd = getcwd(NULL, 0);
8020 if (cwd == NULL) {
8021 error = got_error_from_errno("getcwd");
8022 goto done;
8025 error = got_repo_pack_fds_open(&pack_fds);
8026 if (error != NULL)
8027 goto done;
8029 error = got_worktree_open(&worktree, cwd);
8030 if (error) {
8031 if (error->code == GOT_ERR_NOT_WORKTREE)
8032 error = wrap_not_worktree_error(error, "remove", cwd);
8033 goto done;
8036 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8037 NULL, pack_fds);
8038 if (error)
8039 goto done;
8041 error = apply_unveil(got_repo_get_path(repo), 1,
8042 got_worktree_get_root_path(worktree));
8043 if (error)
8044 goto done;
8046 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8047 if (error)
8048 goto done;
8050 if (!can_recurse) {
8051 char *ondisk_path;
8052 struct stat sb;
8053 TAILQ_FOREACH(pe, &paths, entry) {
8054 if (asprintf(&ondisk_path, "%s/%s",
8055 got_worktree_get_root_path(worktree),
8056 pe->path) == -1) {
8057 error = got_error_from_errno("asprintf");
8058 goto done;
8060 if (lstat(ondisk_path, &sb) == -1) {
8061 if (errno == ENOENT) {
8062 free(ondisk_path);
8063 continue;
8065 error = got_error_from_errno2("lstat",
8066 ondisk_path);
8067 free(ondisk_path);
8068 goto done;
8070 free(ondisk_path);
8071 if (S_ISDIR(sb.st_mode)) {
8072 error = got_error_msg(GOT_ERR_BAD_PATH,
8073 "removing directories requires -R option");
8074 goto done;
8079 error = got_worktree_schedule_delete(worktree, &paths,
8080 delete_local_mods, status_codes, print_remove_status, NULL,
8081 repo, keep_on_disk, ignore_missing_paths);
8082 done:
8083 if (repo) {
8084 const struct got_error *close_err = got_repo_close(repo);
8085 if (error == NULL)
8086 error = close_err;
8088 if (worktree)
8089 got_worktree_close(worktree);
8090 if (pack_fds) {
8091 const struct got_error *pack_err =
8092 got_repo_pack_fds_close(pack_fds);
8093 if (error == NULL)
8094 error = pack_err;
8096 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8097 free(cwd);
8098 return error;
8101 __dead static void
8102 usage_patch(void)
8104 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8105 "[patchfile]\n", getprogname());
8106 exit(1);
8109 static const struct got_error *
8110 patch_from_stdin(int *patchfd)
8112 const struct got_error *err = NULL;
8113 ssize_t r;
8114 char buf[BUFSIZ];
8115 sig_t sighup, sigint, sigquit;
8117 *patchfd = got_opentempfd();
8118 if (*patchfd == -1)
8119 return got_error_from_errno("got_opentempfd");
8121 sighup = signal(SIGHUP, SIG_DFL);
8122 sigint = signal(SIGINT, SIG_DFL);
8123 sigquit = signal(SIGQUIT, SIG_DFL);
8125 for (;;) {
8126 r = read(0, buf, sizeof(buf));
8127 if (r == -1) {
8128 err = got_error_from_errno("read");
8129 break;
8131 if (r == 0)
8132 break;
8133 if (write(*patchfd, buf, r) == -1) {
8134 err = got_error_from_errno("write");
8135 break;
8139 signal(SIGHUP, sighup);
8140 signal(SIGINT, sigint);
8141 signal(SIGQUIT, sigquit);
8143 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8144 err = got_error_from_errno("lseek");
8146 if (err != NULL) {
8147 close(*patchfd);
8148 *patchfd = -1;
8151 return err;
8154 struct got_patch_progress_arg {
8155 int did_something;
8156 int conflicts;
8157 int rejects;
8160 static const struct got_error *
8161 patch_progress(void *arg, const char *old, const char *new,
8162 unsigned char status, const struct got_error *error, int old_from,
8163 int old_lines, int new_from, int new_lines, int offset,
8164 int ws_mangled, const struct got_error *hunk_err)
8166 const char *path = new == NULL ? old : new;
8167 struct got_patch_progress_arg *a = arg;
8169 while (*path == '/')
8170 path++;
8172 if (status != GOT_STATUS_NO_CHANGE &&
8173 status != 0 /* per-hunk progress */) {
8174 printf("%c %s\n", status, path);
8175 a->did_something = 1;
8178 if (hunk_err == NULL) {
8179 if (status == GOT_STATUS_CANNOT_UPDATE)
8180 a->rejects++;
8181 else if (status == GOT_STATUS_CONFLICT)
8182 a->conflicts++;
8185 if (error != NULL)
8186 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8188 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8189 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8190 old_lines, new_from, new_lines);
8191 if (hunk_err != NULL)
8192 printf("%s\n", hunk_err->msg);
8193 else if (offset != 0)
8194 printf("applied with offset %d\n", offset);
8195 else
8196 printf("hunk contains mangled whitespace\n");
8199 return NULL;
8202 static void
8203 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8205 if (!ppa->did_something)
8206 return;
8208 if (ppa->conflicts > 0)
8209 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8211 if (ppa->rejects > 0) {
8212 printf("Files where patch failed to apply: %d\n",
8213 ppa->rejects);
8217 static const struct got_error *
8218 cmd_patch(int argc, char *argv[])
8220 const struct got_error *error = NULL, *close_error = NULL;
8221 struct got_worktree *worktree = NULL;
8222 struct got_repository *repo = NULL;
8223 struct got_reflist_head refs;
8224 struct got_object_id *commit_id = NULL;
8225 const char *commit_id_str = NULL;
8226 struct stat sb;
8227 const char *errstr;
8228 char *cwd = NULL;
8229 int ch, nop = 0, strip = -1, reverse = 0;
8230 int patchfd;
8231 int *pack_fds = NULL;
8232 struct got_patch_progress_arg ppa;
8234 TAILQ_INIT(&refs);
8236 #ifndef PROFILE
8237 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8238 "unveil", NULL) == -1)
8239 err(1, "pledge");
8240 #endif
8242 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8243 switch (ch) {
8244 case 'c':
8245 commit_id_str = optarg;
8246 break;
8247 case 'n':
8248 nop = 1;
8249 break;
8250 case 'p':
8251 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8252 if (errstr != NULL)
8253 errx(1, "pathname strip count is %s: %s",
8254 errstr, optarg);
8255 break;
8256 case 'R':
8257 reverse = 1;
8258 break;
8259 default:
8260 usage_patch();
8261 /* NOTREACHED */
8265 argc -= optind;
8266 argv += optind;
8268 if (argc == 0) {
8269 error = patch_from_stdin(&patchfd);
8270 if (error)
8271 return error;
8272 } else if (argc == 1) {
8273 patchfd = open(argv[0], O_RDONLY);
8274 if (patchfd == -1) {
8275 error = got_error_from_errno2("open", argv[0]);
8276 return error;
8278 if (fstat(patchfd, &sb) == -1) {
8279 error = got_error_from_errno2("fstat", argv[0]);
8280 goto done;
8282 if (!S_ISREG(sb.st_mode)) {
8283 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8284 goto done;
8286 } else
8287 usage_patch();
8289 if ((cwd = getcwd(NULL, 0)) == NULL) {
8290 error = got_error_from_errno("getcwd");
8291 goto done;
8294 error = got_repo_pack_fds_open(&pack_fds);
8295 if (error != NULL)
8296 goto done;
8298 error = got_worktree_open(&worktree, cwd);
8299 if (error != NULL)
8300 goto done;
8302 const char *repo_path = got_worktree_get_repo_path(worktree);
8303 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8304 if (error != NULL)
8305 goto done;
8307 error = apply_unveil(got_repo_get_path(repo), 0,
8308 got_worktree_get_root_path(worktree));
8309 if (error != NULL)
8310 goto done;
8312 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8313 if (error)
8314 goto done;
8316 if (commit_id_str != NULL) {
8317 error = got_repo_match_object_id(&commit_id, NULL,
8318 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8319 if (error)
8320 goto done;
8323 memset(&ppa, 0, sizeof(ppa));
8324 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8325 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8326 print_patch_progress_stats(&ppa);
8327 done:
8328 got_ref_list_free(&refs);
8329 free(commit_id);
8330 if (repo) {
8331 close_error = got_repo_close(repo);
8332 if (error == NULL)
8333 error = close_error;
8335 if (worktree != NULL) {
8336 close_error = got_worktree_close(worktree);
8337 if (error == NULL)
8338 error = close_error;
8340 if (pack_fds) {
8341 const struct got_error *pack_err =
8342 got_repo_pack_fds_close(pack_fds);
8343 if (error == NULL)
8344 error = pack_err;
8346 free(cwd);
8347 return error;
8350 __dead static void
8351 usage_revert(void)
8353 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8354 getprogname());
8355 exit(1);
8358 static const struct got_error *
8359 revert_progress(void *arg, unsigned char status, const char *path)
8361 if (status == GOT_STATUS_UNVERSIONED)
8362 return NULL;
8364 while (path[0] == '/')
8365 path++;
8366 printf("%c %s\n", status, path);
8367 return NULL;
8370 struct choose_patch_arg {
8371 FILE *patch_script_file;
8372 const char *action;
8375 static const struct got_error *
8376 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8377 int nchanges, const char *action)
8379 const struct got_error *err;
8380 char *line = NULL;
8381 size_t linesize = 0;
8382 ssize_t linelen;
8384 switch (status) {
8385 case GOT_STATUS_ADD:
8386 printf("A %s\n%s this addition? [y/n] ", path, action);
8387 break;
8388 case GOT_STATUS_DELETE:
8389 printf("D %s\n%s this deletion? [y/n] ", path, action);
8390 break;
8391 case GOT_STATUS_MODIFY:
8392 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8393 return got_error_from_errno("fseek");
8394 printf(GOT_COMMIT_SEP_STR);
8395 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8396 printf("%s", line);
8397 if (linelen == -1 && ferror(patch_file)) {
8398 err = got_error_from_errno("getline");
8399 free(line);
8400 return err;
8402 free(line);
8403 printf(GOT_COMMIT_SEP_STR);
8404 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8405 path, n, nchanges, action);
8406 break;
8407 default:
8408 return got_error_path(path, GOT_ERR_FILE_STATUS);
8411 fflush(stdout);
8412 return NULL;
8415 static const struct got_error *
8416 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8417 FILE *patch_file, int n, int nchanges)
8419 const struct got_error *err = NULL;
8420 char *line = NULL;
8421 size_t linesize = 0;
8422 ssize_t linelen;
8423 int resp = ' ';
8424 struct choose_patch_arg *a = arg;
8426 *choice = GOT_PATCH_CHOICE_NONE;
8428 if (a->patch_script_file) {
8429 char *nl;
8430 err = show_change(status, path, patch_file, n, nchanges,
8431 a->action);
8432 if (err)
8433 return err;
8434 linelen = getline(&line, &linesize, a->patch_script_file);
8435 if (linelen == -1) {
8436 if (ferror(a->patch_script_file))
8437 return got_error_from_errno("getline");
8438 return NULL;
8440 nl = strchr(line, '\n');
8441 if (nl)
8442 *nl = '\0';
8443 if (strcmp(line, "y") == 0) {
8444 *choice = GOT_PATCH_CHOICE_YES;
8445 printf("y\n");
8446 } else if (strcmp(line, "n") == 0) {
8447 *choice = GOT_PATCH_CHOICE_NO;
8448 printf("n\n");
8449 } else if (strcmp(line, "q") == 0 &&
8450 status == GOT_STATUS_MODIFY) {
8451 *choice = GOT_PATCH_CHOICE_QUIT;
8452 printf("q\n");
8453 } else
8454 printf("invalid response '%s'\n", line);
8455 free(line);
8456 return NULL;
8459 while (resp != 'y' && resp != 'n' && resp != 'q') {
8460 err = show_change(status, path, patch_file, n, nchanges,
8461 a->action);
8462 if (err)
8463 return err;
8464 resp = getchar();
8465 if (resp == '\n')
8466 resp = getchar();
8467 if (status == GOT_STATUS_MODIFY) {
8468 if (resp != 'y' && resp != 'n' && resp != 'q') {
8469 printf("invalid response '%c'\n", resp);
8470 resp = ' ';
8472 } else if (resp != 'y' && resp != 'n') {
8473 printf("invalid response '%c'\n", resp);
8474 resp = ' ';
8478 if (resp == 'y')
8479 *choice = GOT_PATCH_CHOICE_YES;
8480 else if (resp == 'n')
8481 *choice = GOT_PATCH_CHOICE_NO;
8482 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8483 *choice = GOT_PATCH_CHOICE_QUIT;
8485 return NULL;
8488 struct wt_commitable_path_arg {
8489 struct got_pathlist_head *commit_paths;
8490 int *has_changes;
8494 * Shortcut work tree status callback to determine if the set of paths scanned
8495 * has at least one versioned path that is being modified and, if not NULL, is
8496 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8497 * soon as a path is passed with a status that satisfies this criteria.
8499 static const struct got_error *
8500 worktree_has_commitable_path(void *arg, unsigned char status,
8501 unsigned char staged_status, const char *path,
8502 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8503 struct got_object_id *commit_id, int dirfd, const char *de_name)
8505 struct wt_commitable_path_arg *a = arg;
8507 if (status == staged_status && (status == GOT_STATUS_DELETE))
8508 status = GOT_STATUS_NO_CHANGE;
8510 if (!(status == GOT_STATUS_NO_CHANGE ||
8511 status == GOT_STATUS_UNVERSIONED) ||
8512 staged_status != GOT_STATUS_NO_CHANGE) {
8513 if (a->commit_paths != NULL) {
8514 struct got_pathlist_entry *pe;
8516 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8517 if (strncmp(path, pe->path,
8518 pe->path_len) == 0) {
8519 *a->has_changes = 1;
8520 break;
8523 } else
8524 *a->has_changes = 1;
8526 if (*a->has_changes)
8527 return got_error(GOT_ERR_FILE_MODIFIED);
8530 return NULL;
8534 * Check that the changeset of the commit identified by id is
8535 * comprised of at least one modified path that is being committed.
8537 static const struct got_error *
8538 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8539 struct got_object_id *id, struct got_worktree *worktree,
8540 struct got_repository *repo)
8542 const struct got_error *err;
8543 struct got_pathlist_head paths;
8544 struct got_commit_object *commit = NULL, *pcommit = NULL;
8545 struct got_tree_object *tree = NULL, *ptree = NULL;
8546 struct got_object_qid *pid;
8548 TAILQ_INIT(&paths);
8550 err = got_object_open_as_commit(&commit, repo, id);
8551 if (err)
8552 goto done;
8554 err = got_object_open_as_tree(&tree, repo,
8555 got_object_commit_get_tree_id(commit));
8556 if (err)
8557 goto done;
8559 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8560 if (pid != NULL) {
8561 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8562 if (err)
8563 goto done;
8565 err = got_object_open_as_tree(&ptree, repo,
8566 got_object_commit_get_tree_id(pcommit));
8567 if (err)
8568 goto done;
8571 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8572 got_diff_tree_collect_changed_paths, &paths, 0);
8573 if (err)
8574 goto done;
8576 err = got_worktree_status(worktree, &paths, repo, 0,
8577 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8578 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8580 * At least one changed path in the referenced commit is
8581 * modified in the work tree, that's all we need to know!
8583 err = NULL;
8586 done:
8587 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8588 if (commit)
8589 got_object_commit_close(commit);
8590 if (pcommit)
8591 got_object_commit_close(pcommit);
8592 if (tree)
8593 got_object_tree_close(tree);
8594 if (ptree)
8595 got_object_tree_close(ptree);
8596 return err;
8600 * Remove any "logmsg" reference comprised entirely of paths that have
8601 * been reverted in this work tree. If any path in the logmsg ref changeset
8602 * remains in a changed state in the worktree, do not remove the reference.
8604 static const struct got_error *
8605 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8607 const struct got_error *err;
8608 struct got_reflist_head refs;
8609 struct got_reflist_entry *re;
8610 struct got_commit_object *commit = NULL;
8611 struct got_object_id *commit_id = NULL;
8612 struct wt_commitable_path_arg wcpa;
8613 char *uuidstr = NULL;
8615 TAILQ_INIT(&refs);
8617 err = got_worktree_get_uuid(&uuidstr, worktree);
8618 if (err)
8619 goto done;
8621 err = got_ref_list(&refs, repo, "refs/got/worktree",
8622 got_ref_cmp_by_name, repo);
8623 if (err)
8624 goto done;
8626 TAILQ_FOREACH(re, &refs, entry) {
8627 const char *refname;
8628 int has_changes = 0;
8630 refname = got_ref_get_name(re->ref);
8632 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8633 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8634 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8635 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8636 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8637 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8638 else
8639 continue;
8641 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8642 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8643 else
8644 continue;
8646 err = got_repo_match_object_id(&commit_id, NULL, refname,
8647 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8648 if (err)
8649 goto done;
8651 err = got_object_open_as_commit(&commit, repo, commit_id);
8652 if (err)
8653 goto done;
8655 wcpa.commit_paths = NULL;
8656 wcpa.has_changes = &has_changes;
8658 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8659 worktree, repo);
8660 if (err)
8661 goto done;
8663 if (!has_changes) {
8664 err = got_ref_delete(re->ref, repo);
8665 if (err)
8666 goto done;
8669 got_object_commit_close(commit);
8670 commit = NULL;
8671 free(commit_id);
8672 commit_id = NULL;
8675 done:
8676 free(uuidstr);
8677 free(commit_id);
8678 got_ref_list_free(&refs);
8679 if (commit)
8680 got_object_commit_close(commit);
8681 return err;
8684 static const struct got_error *
8685 cmd_revert(int argc, char *argv[])
8687 const struct got_error *error = NULL;
8688 struct got_worktree *worktree = NULL;
8689 struct got_repository *repo = NULL;
8690 char *cwd = NULL, *path = NULL;
8691 struct got_pathlist_head paths;
8692 struct got_pathlist_entry *pe;
8693 int ch, can_recurse = 0, pflag = 0;
8694 FILE *patch_script_file = NULL;
8695 const char *patch_script_path = NULL;
8696 struct choose_patch_arg cpa;
8697 int *pack_fds = NULL;
8699 TAILQ_INIT(&paths);
8701 #ifndef PROFILE
8702 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8703 "unveil", NULL) == -1)
8704 err(1, "pledge");
8705 #endif
8707 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8708 switch (ch) {
8709 case 'F':
8710 patch_script_path = optarg;
8711 break;
8712 case 'p':
8713 pflag = 1;
8714 break;
8715 case 'R':
8716 can_recurse = 1;
8717 break;
8718 default:
8719 usage_revert();
8720 /* NOTREACHED */
8724 argc -= optind;
8725 argv += optind;
8727 if (argc < 1)
8728 usage_revert();
8729 if (patch_script_path && !pflag)
8730 errx(1, "-F option can only be used together with -p option");
8732 cwd = getcwd(NULL, 0);
8733 if (cwd == NULL) {
8734 error = got_error_from_errno("getcwd");
8735 goto done;
8738 error = got_repo_pack_fds_open(&pack_fds);
8739 if (error != NULL)
8740 goto done;
8742 error = got_worktree_open(&worktree, cwd);
8743 if (error) {
8744 if (error->code == GOT_ERR_NOT_WORKTREE)
8745 error = wrap_not_worktree_error(error, "revert", cwd);
8746 goto done;
8749 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8750 NULL, pack_fds);
8751 if (error != NULL)
8752 goto done;
8754 if (patch_script_path) {
8755 patch_script_file = fopen(patch_script_path, "re");
8756 if (patch_script_file == NULL) {
8757 error = got_error_from_errno2("fopen",
8758 patch_script_path);
8759 goto done;
8764 * XXX "c" perm needed on repo dir to delete merge references.
8766 error = apply_unveil(got_repo_get_path(repo), 0,
8767 got_worktree_get_root_path(worktree));
8768 if (error)
8769 goto done;
8771 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8772 if (error)
8773 goto done;
8775 if (!can_recurse) {
8776 char *ondisk_path;
8777 struct stat sb;
8778 TAILQ_FOREACH(pe, &paths, entry) {
8779 if (asprintf(&ondisk_path, "%s/%s",
8780 got_worktree_get_root_path(worktree),
8781 pe->path) == -1) {
8782 error = got_error_from_errno("asprintf");
8783 goto done;
8785 if (lstat(ondisk_path, &sb) == -1) {
8786 if (errno == ENOENT) {
8787 free(ondisk_path);
8788 continue;
8790 error = got_error_from_errno2("lstat",
8791 ondisk_path);
8792 free(ondisk_path);
8793 goto done;
8795 free(ondisk_path);
8796 if (S_ISDIR(sb.st_mode)) {
8797 error = got_error_msg(GOT_ERR_BAD_PATH,
8798 "reverting directories requires -R option");
8799 goto done;
8804 cpa.patch_script_file = patch_script_file;
8805 cpa.action = "revert";
8806 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8807 pflag ? choose_patch : NULL, &cpa, repo);
8809 error = rm_logmsg_ref(worktree, repo);
8810 done:
8811 if (patch_script_file && fclose(patch_script_file) == EOF &&
8812 error == NULL)
8813 error = got_error_from_errno2("fclose", patch_script_path);
8814 if (repo) {
8815 const struct got_error *close_err = got_repo_close(repo);
8816 if (error == NULL)
8817 error = close_err;
8819 if (worktree)
8820 got_worktree_close(worktree);
8821 if (pack_fds) {
8822 const struct got_error *pack_err =
8823 got_repo_pack_fds_close(pack_fds);
8824 if (error == NULL)
8825 error = pack_err;
8827 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8828 free(path);
8829 free(cwd);
8830 return error;
8833 __dead static void
8834 usage_commit(void)
8836 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8837 "[-m message] [path ...]\n", getprogname());
8838 exit(1);
8841 struct collect_commit_logmsg_arg {
8842 const char *cmdline_log;
8843 const char *prepared_log;
8844 const char *merged_log;
8845 int non_interactive;
8846 const char *editor;
8847 const char *worktree_path;
8848 const char *branch_name;
8849 const char *repo_path;
8850 char *logmsg_path;
8854 static const struct got_error *
8855 read_prepared_logmsg(char **logmsg, const char *path)
8857 const struct got_error *err = NULL;
8858 FILE *f = NULL;
8859 struct stat sb;
8860 size_t r;
8862 *logmsg = NULL;
8863 memset(&sb, 0, sizeof(sb));
8865 f = fopen(path, "re");
8866 if (f == NULL)
8867 return got_error_from_errno2("fopen", path);
8869 if (fstat(fileno(f), &sb) == -1) {
8870 err = got_error_from_errno2("fstat", path);
8871 goto done;
8873 if (sb.st_size == 0) {
8874 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8875 goto done;
8878 *logmsg = malloc(sb.st_size + 1);
8879 if (*logmsg == NULL) {
8880 err = got_error_from_errno("malloc");
8881 goto done;
8884 r = fread(*logmsg, 1, sb.st_size, f);
8885 if (r != sb.st_size) {
8886 if (ferror(f))
8887 err = got_error_from_errno2("fread", path);
8888 else
8889 err = got_error(GOT_ERR_IO);
8890 goto done;
8892 (*logmsg)[sb.st_size] = '\0';
8893 done:
8894 if (fclose(f) == EOF && err == NULL)
8895 err = got_error_from_errno2("fclose", path);
8896 if (err) {
8897 free(*logmsg);
8898 *logmsg = NULL;
8900 return err;
8903 static const struct got_error *
8904 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8905 const char *diff_path, char **logmsg, void *arg)
8907 char *initial_content = NULL;
8908 struct got_pathlist_entry *pe;
8909 const struct got_error *err = NULL;
8910 char *template = NULL;
8911 char *prepared_msg = NULL, *merged_msg = NULL;
8912 struct collect_commit_logmsg_arg *a = arg;
8913 int initial_content_len;
8914 int fd = -1;
8915 size_t len;
8917 /* if a message was specified on the command line, just use it */
8918 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8919 len = strlen(a->cmdline_log) + 1;
8920 *logmsg = malloc(len + 1);
8921 if (*logmsg == NULL)
8922 return got_error_from_errno("malloc");
8923 strlcpy(*logmsg, a->cmdline_log, len);
8924 return NULL;
8925 } else if (a->prepared_log != NULL && a->non_interactive)
8926 return read_prepared_logmsg(logmsg, a->prepared_log);
8928 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8929 return got_error_from_errno("asprintf");
8931 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8932 if (err)
8933 goto done;
8935 if (a->prepared_log) {
8936 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8937 if (err)
8938 goto done;
8939 } else if (a->merged_log) {
8940 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8941 if (err)
8942 goto done;
8945 initial_content_len = asprintf(&initial_content,
8946 "%s%s\n# changes to be committed on branch %s:\n",
8947 prepared_msg ? prepared_msg : "",
8948 merged_msg ? merged_msg : "", a->branch_name);
8949 if (initial_content_len == -1) {
8950 err = got_error_from_errno("asprintf");
8951 goto done;
8954 if (write(fd, initial_content, initial_content_len) == -1) {
8955 err = got_error_from_errno2("write", a->logmsg_path);
8956 goto done;
8959 TAILQ_FOREACH(pe, commitable_paths, entry) {
8960 struct got_commitable *ct = pe->data;
8961 dprintf(fd, "# %c %s\n",
8962 got_commitable_get_status(ct),
8963 got_commitable_get_path(ct));
8966 if (diff_path) {
8967 dprintf(fd, "# detailed changes can be viewed in %s\n",
8968 diff_path);
8971 if (close(fd) == -1) {
8972 err = got_error_from_errno2("close", a->logmsg_path);
8973 goto done;
8975 fd = -1;
8977 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8978 initial_content_len, a->prepared_log ? 0 : 1);
8979 done:
8980 free(initial_content);
8981 free(template);
8982 free(prepared_msg);
8983 free(merged_msg);
8985 if (fd != -1 && close(fd) == -1 && err == NULL)
8986 err = got_error_from_errno2("close", a->logmsg_path);
8988 /* Editor is done; we can now apply unveil(2) */
8989 if (err == NULL)
8990 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8991 if (err) {
8992 free(*logmsg);
8993 *logmsg = NULL;
8995 return err;
8998 static const struct got_error *
8999 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9000 const char *type, int has_content)
9002 const struct got_error *err = NULL;
9003 char *logmsg = NULL;
9005 err = got_object_commit_get_logmsg(&logmsg, commit);
9006 if (err)
9007 return err;
9009 if (fprintf(f, "%s# log message of %s commit %s:%s",
9010 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9011 err = got_ferror(f, GOT_ERR_IO);
9013 free(logmsg);
9014 return err;
9018 * Lookup "logmsg" references of backed-out and cherrypicked commits
9019 * belonging to the current work tree. If found, and the worktree has
9020 * at least one modified file that was changed in the referenced commit,
9021 * add its log message to a new temporary file at *logmsg_path.
9022 * Add all refs found to matched_refs to be scheduled for removal on
9023 * successful commit.
9025 static const struct got_error *
9026 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9027 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9028 struct got_repository *repo)
9030 const struct got_error *err;
9031 struct got_commit_object *commit = NULL;
9032 struct got_object_id *id = NULL;
9033 struct got_reflist_head refs;
9034 struct got_reflist_entry *re, *re_match;
9035 FILE *f = NULL;
9036 char *uuidstr = NULL;
9037 int added_logmsg = 0;
9039 TAILQ_INIT(&refs);
9041 *logmsg_path = NULL;
9043 err = got_worktree_get_uuid(&uuidstr, worktree);
9044 if (err)
9045 goto done;
9047 err = got_ref_list(&refs, repo, "refs/got/worktree",
9048 got_ref_cmp_by_name, repo);
9049 if (err)
9050 goto done;
9052 TAILQ_FOREACH(re, &refs, entry) {
9053 const char *refname, *type;
9054 struct wt_commitable_path_arg wcpa;
9055 int add_logmsg = 0;
9057 refname = got_ref_get_name(re->ref);
9059 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9060 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9061 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9062 type = "cherrypicked";
9063 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9064 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9065 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9066 type = "backed-out";
9067 } else
9068 continue;
9070 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9071 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9072 else
9073 continue;
9075 err = got_repo_match_object_id(&id, NULL, refname,
9076 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9077 if (err)
9078 goto done;
9080 err = got_object_open_as_commit(&commit, repo, id);
9081 if (err)
9082 goto done;
9084 wcpa.commit_paths = paths;
9085 wcpa.has_changes = &add_logmsg;
9087 err = commit_path_changed_in_worktree(&wcpa, id,
9088 worktree, repo);
9089 if (err)
9090 goto done;
9092 if (add_logmsg) {
9093 if (f == NULL) {
9094 err = got_opentemp_named(logmsg_path, &f,
9095 "got-commit-logmsg", "");
9096 if (err)
9097 goto done;
9099 err = cat_logmsg(f, commit, refname, type,
9100 added_logmsg);
9101 if (err)
9102 goto done;
9103 if (!added_logmsg)
9104 ++added_logmsg;
9106 err = got_reflist_entry_dup(&re_match, re);
9107 if (err)
9108 goto done;
9109 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9112 got_object_commit_close(commit);
9113 commit = NULL;
9114 free(id);
9115 id = NULL;
9118 done:
9119 free(id);
9120 free(uuidstr);
9121 got_ref_list_free(&refs);
9122 if (commit)
9123 got_object_commit_close(commit);
9124 if (f && fclose(f) == EOF && err == NULL)
9125 err = got_error_from_errno("fclose");
9126 if (!added_logmsg) {
9127 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9128 err = got_error_from_errno2("unlink", *logmsg_path);
9129 *logmsg_path = NULL;
9131 return err;
9134 static const struct got_error *
9135 cmd_commit(int argc, char *argv[])
9137 const struct got_error *error = NULL;
9138 struct got_worktree *worktree = NULL;
9139 struct got_repository *repo = NULL;
9140 char *cwd = NULL, *id_str = NULL;
9141 struct got_object_id *id = NULL;
9142 const char *logmsg = NULL;
9143 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9144 struct collect_commit_logmsg_arg cl_arg;
9145 const char *author = NULL;
9146 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9147 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9148 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9149 int show_diff = 1, commit_conflicts = 0;
9150 struct got_pathlist_head paths;
9151 struct got_reflist_head refs;
9152 struct got_reflist_entry *re;
9153 int *pack_fds = NULL;
9155 TAILQ_INIT(&refs);
9156 TAILQ_INIT(&paths);
9157 cl_arg.logmsg_path = NULL;
9159 #ifndef PROFILE
9160 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9161 "unveil", NULL) == -1)
9162 err(1, "pledge");
9163 #endif
9165 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9166 switch (ch) {
9167 case 'A':
9168 author = optarg;
9169 error = valid_author(author);
9170 if (error)
9171 return error;
9172 break;
9173 case 'C':
9174 commit_conflicts = 1;
9175 break;
9176 case 'F':
9177 if (logmsg != NULL)
9178 option_conflict('F', 'm');
9179 prepared_logmsg = realpath(optarg, NULL);
9180 if (prepared_logmsg == NULL)
9181 return got_error_from_errno2("realpath",
9182 optarg);
9183 break;
9184 case 'm':
9185 if (prepared_logmsg)
9186 option_conflict('m', 'F');
9187 logmsg = optarg;
9188 break;
9189 case 'N':
9190 non_interactive = 1;
9191 break;
9192 case 'n':
9193 show_diff = 0;
9194 break;
9195 case 'S':
9196 allow_bad_symlinks = 1;
9197 break;
9198 default:
9199 usage_commit();
9200 /* NOTREACHED */
9204 argc -= optind;
9205 argv += optind;
9207 cwd = getcwd(NULL, 0);
9208 if (cwd == NULL) {
9209 error = got_error_from_errno("getcwd");
9210 goto done;
9213 error = got_repo_pack_fds_open(&pack_fds);
9214 if (error != NULL)
9215 goto done;
9217 error = got_worktree_open(&worktree, cwd);
9218 if (error) {
9219 if (error->code == GOT_ERR_NOT_WORKTREE)
9220 error = wrap_not_worktree_error(error, "commit", cwd);
9221 goto done;
9224 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9225 if (error)
9226 goto done;
9227 if (rebase_in_progress) {
9228 error = got_error(GOT_ERR_REBASING);
9229 goto done;
9232 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9233 worktree);
9234 if (error)
9235 goto done;
9237 error = get_gitconfig_path(&gitconfig_path);
9238 if (error)
9239 goto done;
9240 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9241 gitconfig_path, pack_fds);
9242 if (error != NULL)
9243 goto done;
9245 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9246 if (error)
9247 goto done;
9248 if (merge_in_progress) {
9249 error = got_error(GOT_ERR_MERGE_BUSY);
9250 goto done;
9253 error = get_author(&committer, repo, worktree);
9254 if (error)
9255 goto done;
9257 if (author == NULL)
9258 author = committer;
9261 * unveil(2) traverses exec(2); if an editor is used we have
9262 * to apply unveil after the log message has been written.
9264 if (logmsg == NULL || strlen(logmsg) == 0)
9265 error = get_editor(&editor);
9266 else
9267 error = apply_unveil(got_repo_get_path(repo), 0,
9268 got_worktree_get_root_path(worktree));
9269 if (error)
9270 goto done;
9272 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9273 if (error)
9274 goto done;
9276 if (prepared_logmsg == NULL) {
9277 error = lookup_logmsg_ref(&merged_logmsg,
9278 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9279 if (error)
9280 goto done;
9283 cl_arg.editor = editor;
9284 cl_arg.cmdline_log = logmsg;
9285 cl_arg.prepared_log = prepared_logmsg;
9286 cl_arg.merged_log = merged_logmsg;
9287 cl_arg.non_interactive = non_interactive;
9288 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9289 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9290 if (!histedit_in_progress) {
9291 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9292 error = got_error(GOT_ERR_COMMIT_BRANCH);
9293 goto done;
9295 cl_arg.branch_name += 11;
9297 cl_arg.repo_path = got_repo_get_path(repo);
9298 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9299 allow_bad_symlinks, show_diff, commit_conflicts,
9300 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9301 if (error) {
9302 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9303 cl_arg.logmsg_path != NULL)
9304 preserve_logmsg = 1;
9305 goto done;
9308 error = got_object_id_str(&id_str, id);
9309 if (error)
9310 goto done;
9311 printf("Created commit %s\n", id_str);
9313 TAILQ_FOREACH(re, &refs, entry) {
9314 error = got_ref_delete(re->ref, repo);
9315 if (error)
9316 goto done;
9319 done:
9320 if (preserve_logmsg) {
9321 fprintf(stderr, "%s: log message preserved in %s\n",
9322 getprogname(), cl_arg.logmsg_path);
9323 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9324 error == NULL)
9325 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9326 free(cl_arg.logmsg_path);
9327 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9328 error = got_error_from_errno2("unlink", merged_logmsg);
9329 free(merged_logmsg);
9330 if (repo) {
9331 const struct got_error *close_err = got_repo_close(repo);
9332 if (error == NULL)
9333 error = close_err;
9335 if (worktree)
9336 got_worktree_close(worktree);
9337 if (pack_fds) {
9338 const struct got_error *pack_err =
9339 got_repo_pack_fds_close(pack_fds);
9340 if (error == NULL)
9341 error = pack_err;
9343 got_ref_list_free(&refs);
9344 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9345 free(cwd);
9346 free(id_str);
9347 free(gitconfig_path);
9348 free(editor);
9349 free(committer);
9350 free(prepared_logmsg);
9351 return error;
9354 __dead static void
9355 usage_send(void)
9357 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9358 "[-r repository-path] [-t tag] [remote-repository]\n",
9359 getprogname());
9360 exit(1);
9363 static void
9364 print_load_info(int print_colored, int print_found, int print_trees,
9365 int ncolored, int nfound, int ntrees)
9367 if (print_colored) {
9368 printf("%d commit%s colored", ncolored,
9369 ncolored == 1 ? "" : "s");
9371 if (print_found) {
9372 printf("%s%d object%s found",
9373 ncolored > 0 ? "; " : "",
9374 nfound, nfound == 1 ? "" : "s");
9376 if (print_trees) {
9377 printf("; %d tree%s scanned", ntrees,
9378 ntrees == 1 ? "" : "s");
9382 struct got_send_progress_arg {
9383 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9384 int verbosity;
9385 int last_ncolored;
9386 int last_nfound;
9387 int last_ntrees;
9388 int loading_done;
9389 int last_ncommits;
9390 int last_nobj_total;
9391 int last_p_deltify;
9392 int last_p_written;
9393 int last_p_sent;
9394 int printed_something;
9395 int sent_something;
9396 struct got_pathlist_head *delete_branches;
9399 static const struct got_error *
9400 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9401 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9402 int nobj_written, off_t bytes_sent, const char *refname,
9403 const char *errmsg, int success)
9405 struct got_send_progress_arg *a = arg;
9406 char scaled_packsize[FMT_SCALED_STRSIZE];
9407 char scaled_sent[FMT_SCALED_STRSIZE];
9408 int p_deltify = 0, p_written = 0, p_sent = 0;
9409 int print_colored = 0, print_found = 0, print_trees = 0;
9410 int print_searching = 0, print_total = 0;
9411 int print_deltify = 0, print_written = 0, print_sent = 0;
9413 if (a->verbosity < 0)
9414 return NULL;
9416 if (refname) {
9417 const char *status = success ? "accepted" : "rejected";
9419 if (success) {
9420 struct got_pathlist_entry *pe;
9421 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9422 const char *branchname = pe->path;
9423 if (got_path_cmp(branchname, refname,
9424 strlen(branchname), strlen(refname)) == 0) {
9425 status = "deleted";
9426 a->sent_something = 1;
9427 break;
9432 if (a->printed_something)
9433 putchar('\n');
9434 printf("Server has %s %s", status, refname);
9435 if (errmsg)
9436 printf(": %s", errmsg);
9437 a->printed_something = 1;
9438 return NULL;
9441 if (a->last_ncolored != ncolored) {
9442 print_colored = 1;
9443 a->last_ncolored = ncolored;
9446 if (a->last_nfound != nfound) {
9447 print_colored = 1;
9448 print_found = 1;
9449 a->last_nfound = nfound;
9452 if (a->last_ntrees != ntrees) {
9453 print_colored = 1;
9454 print_found = 1;
9455 print_trees = 1;
9456 a->last_ntrees = ntrees;
9459 if ((print_colored || print_found || print_trees) &&
9460 !a->loading_done) {
9461 printf("\r");
9462 print_load_info(print_colored, print_found, print_trees,
9463 ncolored, nfound, ntrees);
9464 a->printed_something = 1;
9465 fflush(stdout);
9466 return NULL;
9467 } else if (!a->loading_done) {
9468 printf("\r");
9469 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9470 printf("\n");
9471 a->loading_done = 1;
9474 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9475 return got_error_from_errno("fmt_scaled");
9476 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9477 return got_error_from_errno("fmt_scaled");
9479 if (a->last_ncommits != ncommits) {
9480 print_searching = 1;
9481 a->last_ncommits = ncommits;
9484 if (a->last_nobj_total != nobj_total) {
9485 print_searching = 1;
9486 print_total = 1;
9487 a->last_nobj_total = nobj_total;
9490 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9491 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9492 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9493 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9494 return got_error(GOT_ERR_NO_SPACE);
9497 if (nobj_deltify > 0 || nobj_written > 0) {
9498 if (nobj_deltify > 0) {
9499 p_deltify = (nobj_deltify * 100) / nobj_total;
9500 if (p_deltify != a->last_p_deltify) {
9501 a->last_p_deltify = p_deltify;
9502 print_searching = 1;
9503 print_total = 1;
9504 print_deltify = 1;
9507 if (nobj_written > 0) {
9508 p_written = (nobj_written * 100) / nobj_total;
9509 if (p_written != a->last_p_written) {
9510 a->last_p_written = p_written;
9511 print_searching = 1;
9512 print_total = 1;
9513 print_deltify = 1;
9514 print_written = 1;
9519 if (bytes_sent > 0) {
9520 p_sent = (bytes_sent * 100) / packfile_size;
9521 if (p_sent != a->last_p_sent) {
9522 a->last_p_sent = p_sent;
9523 print_searching = 1;
9524 print_total = 1;
9525 print_deltify = 1;
9526 print_written = 1;
9527 print_sent = 1;
9529 a->sent_something = 1;
9532 if (print_searching || print_total || print_deltify || print_written ||
9533 print_sent)
9534 printf("\r");
9535 if (print_searching)
9536 printf("packing %d reference%s", ncommits,
9537 ncommits == 1 ? "" : "s");
9538 if (print_total)
9539 printf("; %d object%s", nobj_total,
9540 nobj_total == 1 ? "" : "s");
9541 if (print_deltify)
9542 printf("; deltify: %d%%", p_deltify);
9543 if (print_sent)
9544 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9545 scaled_packsize, p_sent);
9546 else if (print_written)
9547 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9548 scaled_packsize, p_written);
9549 if (print_searching || print_total || print_deltify ||
9550 print_written || print_sent) {
9551 a->printed_something = 1;
9552 fflush(stdout);
9554 return NULL;
9557 static const struct got_error *
9558 cmd_send(int argc, char *argv[])
9560 const struct got_error *error = NULL;
9561 char *cwd = NULL, *repo_path = NULL;
9562 const char *remote_name;
9563 char *proto = NULL, *host = NULL, *port = NULL;
9564 char *repo_name = NULL, *server_path = NULL;
9565 const struct got_remote_repo *remotes, *remote = NULL;
9566 int nremotes, nbranches = 0, ndelete_branches = 0;
9567 struct got_repository *repo = NULL;
9568 struct got_worktree *worktree = NULL;
9569 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9570 struct got_pathlist_head branches;
9571 struct got_pathlist_head tags;
9572 struct got_reflist_head all_branches;
9573 struct got_reflist_head all_tags;
9574 struct got_pathlist_head delete_args;
9575 struct got_pathlist_head delete_branches;
9576 struct got_reflist_entry *re;
9577 struct got_pathlist_entry *pe;
9578 int i, ch, sendfd = -1, sendstatus;
9579 pid_t sendpid = -1;
9580 struct got_send_progress_arg spa;
9581 int verbosity = 0, overwrite_refs = 0;
9582 int send_all_branches = 0, send_all_tags = 0;
9583 struct got_reference *ref = NULL;
9584 int *pack_fds = NULL;
9586 TAILQ_INIT(&branches);
9587 TAILQ_INIT(&tags);
9588 TAILQ_INIT(&all_branches);
9589 TAILQ_INIT(&all_tags);
9590 TAILQ_INIT(&delete_args);
9591 TAILQ_INIT(&delete_branches);
9593 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9594 switch (ch) {
9595 case 'a':
9596 send_all_branches = 1;
9597 break;
9598 case 'b':
9599 error = got_pathlist_append(&branches, optarg, NULL);
9600 if (error)
9601 return error;
9602 nbranches++;
9603 break;
9604 case 'd':
9605 error = got_pathlist_append(&delete_args, optarg, NULL);
9606 if (error)
9607 return error;
9608 break;
9609 case 'f':
9610 overwrite_refs = 1;
9611 break;
9612 case 'q':
9613 verbosity = -1;
9614 break;
9615 case 'r':
9616 repo_path = realpath(optarg, NULL);
9617 if (repo_path == NULL)
9618 return got_error_from_errno2("realpath",
9619 optarg);
9620 got_path_strip_trailing_slashes(repo_path);
9621 break;
9622 case 'T':
9623 send_all_tags = 1;
9624 break;
9625 case 't':
9626 error = got_pathlist_append(&tags, optarg, NULL);
9627 if (error)
9628 return error;
9629 break;
9630 case 'v':
9631 if (verbosity < 0)
9632 verbosity = 0;
9633 else if (verbosity < 3)
9634 verbosity++;
9635 break;
9636 default:
9637 usage_send();
9638 /* NOTREACHED */
9641 argc -= optind;
9642 argv += optind;
9644 if (send_all_branches && !TAILQ_EMPTY(&branches))
9645 option_conflict('a', 'b');
9646 if (send_all_tags && !TAILQ_EMPTY(&tags))
9647 option_conflict('T', 't');
9650 if (argc == 0)
9651 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9652 else if (argc == 1)
9653 remote_name = argv[0];
9654 else
9655 usage_send();
9657 cwd = getcwd(NULL, 0);
9658 if (cwd == NULL) {
9659 error = got_error_from_errno("getcwd");
9660 goto done;
9663 error = got_repo_pack_fds_open(&pack_fds);
9664 if (error != NULL)
9665 goto done;
9667 if (repo_path == NULL) {
9668 error = got_worktree_open(&worktree, cwd);
9669 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9670 goto done;
9671 else
9672 error = NULL;
9673 if (worktree) {
9674 repo_path =
9675 strdup(got_worktree_get_repo_path(worktree));
9676 if (repo_path == NULL)
9677 error = got_error_from_errno("strdup");
9678 if (error)
9679 goto done;
9680 } else {
9681 repo_path = strdup(cwd);
9682 if (repo_path == NULL) {
9683 error = got_error_from_errno("strdup");
9684 goto done;
9689 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9690 if (error)
9691 goto done;
9693 if (worktree) {
9694 worktree_conf = got_worktree_get_gotconfig(worktree);
9695 if (worktree_conf) {
9696 got_gotconfig_get_remotes(&nremotes, &remotes,
9697 worktree_conf);
9698 for (i = 0; i < nremotes; i++) {
9699 if (strcmp(remotes[i].name, remote_name) == 0) {
9700 remote = &remotes[i];
9701 break;
9706 if (remote == NULL) {
9707 repo_conf = got_repo_get_gotconfig(repo);
9708 if (repo_conf) {
9709 got_gotconfig_get_remotes(&nremotes, &remotes,
9710 repo_conf);
9711 for (i = 0; i < nremotes; i++) {
9712 if (strcmp(remotes[i].name, remote_name) == 0) {
9713 remote = &remotes[i];
9714 break;
9719 if (remote == NULL) {
9720 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9721 for (i = 0; i < nremotes; i++) {
9722 if (strcmp(remotes[i].name, remote_name) == 0) {
9723 remote = &remotes[i];
9724 break;
9728 if (remote == NULL) {
9729 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9730 goto done;
9733 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9734 &repo_name, remote->send_url);
9735 if (error)
9736 goto done;
9738 if (strcmp(proto, "git") == 0) {
9739 #ifndef PROFILE
9740 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9741 "sendfd dns inet unveil", NULL) == -1)
9742 err(1, "pledge");
9743 #endif
9744 } else if (strcmp(proto, "git+ssh") == 0 ||
9745 strcmp(proto, "ssh") == 0) {
9746 #ifndef PROFILE
9747 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9748 "sendfd unveil", NULL) == -1)
9749 err(1, "pledge");
9750 #endif
9751 } else if (strcmp(proto, "http") == 0 ||
9752 strcmp(proto, "git+http") == 0) {
9753 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9754 goto done;
9755 } else {
9756 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9757 goto done;
9760 error = got_dial_apply_unveil(proto);
9761 if (error)
9762 goto done;
9764 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9765 if (error)
9766 goto done;
9768 if (send_all_branches) {
9769 error = got_ref_list(&all_branches, repo, "refs/heads",
9770 got_ref_cmp_by_name, NULL);
9771 if (error)
9772 goto done;
9773 TAILQ_FOREACH(re, &all_branches, entry) {
9774 const char *branchname = got_ref_get_name(re->ref);
9775 error = got_pathlist_append(&branches,
9776 branchname, NULL);
9777 if (error)
9778 goto done;
9779 nbranches++;
9781 } else if (nbranches == 0) {
9782 for (i = 0; i < remote->nsend_branches; i++) {
9783 error = got_pathlist_append(&branches,
9784 remote->send_branches[i], NULL);
9785 if (error)
9786 goto done;
9790 if (send_all_tags) {
9791 error = got_ref_list(&all_tags, repo, "refs/tags",
9792 got_ref_cmp_by_name, NULL);
9793 if (error)
9794 goto done;
9795 TAILQ_FOREACH(re, &all_tags, entry) {
9796 const char *tagname = got_ref_get_name(re->ref);
9797 error = got_pathlist_append(&tags,
9798 tagname, NULL);
9799 if (error)
9800 goto done;
9805 * To prevent accidents only branches in refs/heads/ can be deleted
9806 * with 'got send -d'.
9807 * Deleting anything else requires local repository access or Git.
9809 TAILQ_FOREACH(pe, &delete_args, entry) {
9810 const char *branchname = pe->path;
9811 char *s;
9812 struct got_pathlist_entry *new;
9813 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9814 s = strdup(branchname);
9815 if (s == NULL) {
9816 error = got_error_from_errno("strdup");
9817 goto done;
9819 } else {
9820 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9821 error = got_error_from_errno("asprintf");
9822 goto done;
9825 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9826 if (error || new == NULL /* duplicate */)
9827 free(s);
9828 if (error)
9829 goto done;
9830 ndelete_branches++;
9833 if (nbranches == 0 && ndelete_branches == 0) {
9834 struct got_reference *head_ref;
9835 if (worktree)
9836 error = got_ref_open(&head_ref, repo,
9837 got_worktree_get_head_ref_name(worktree), 0);
9838 else
9839 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9840 if (error)
9841 goto done;
9842 if (got_ref_is_symbolic(head_ref)) {
9843 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9844 got_ref_close(head_ref);
9845 if (error)
9846 goto done;
9847 } else
9848 ref = head_ref;
9849 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9850 NULL);
9851 if (error)
9852 goto done;
9853 nbranches++;
9856 if (verbosity >= 0) {
9857 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9858 remote->name, proto, host,
9859 port ? ":" : "", port ? port : "",
9860 *server_path == '/' ? "" : "/", server_path);
9863 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9864 server_path, verbosity);
9865 if (error)
9866 goto done;
9868 memset(&spa, 0, sizeof(spa));
9869 spa.last_scaled_packsize[0] = '\0';
9870 spa.last_p_deltify = -1;
9871 spa.last_p_written = -1;
9872 spa.verbosity = verbosity;
9873 spa.delete_branches = &delete_branches;
9874 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9875 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9876 check_cancelled, NULL);
9877 if (spa.printed_something)
9878 putchar('\n');
9879 if (error)
9880 goto done;
9881 if (!spa.sent_something && verbosity >= 0)
9882 printf("Already up-to-date\n");
9883 done:
9884 if (sendpid > 0) {
9885 if (kill(sendpid, SIGTERM) == -1)
9886 error = got_error_from_errno("kill");
9887 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9888 error = got_error_from_errno("waitpid");
9890 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9891 error = got_error_from_errno("close");
9892 if (repo) {
9893 const struct got_error *close_err = got_repo_close(repo);
9894 if (error == NULL)
9895 error = close_err;
9897 if (worktree)
9898 got_worktree_close(worktree);
9899 if (pack_fds) {
9900 const struct got_error *pack_err =
9901 got_repo_pack_fds_close(pack_fds);
9902 if (error == NULL)
9903 error = pack_err;
9905 if (ref)
9906 got_ref_close(ref);
9907 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9908 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9909 got_ref_list_free(&all_branches);
9910 got_ref_list_free(&all_tags);
9911 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9912 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9913 free(cwd);
9914 free(repo_path);
9915 free(proto);
9916 free(host);
9917 free(port);
9918 free(server_path);
9919 free(repo_name);
9920 return error;
9924 * Print and if delete is set delete all ref_prefix references.
9925 * If wanted_ref is not NULL, only print or delete this reference.
9927 static const struct got_error *
9928 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9929 const char *wanted_ref, int delete, struct got_worktree *worktree,
9930 struct got_repository *repo)
9932 const struct got_error *err;
9933 struct got_pathlist_head paths;
9934 struct got_reflist_head refs;
9935 struct got_reflist_entry *re;
9936 struct got_reflist_object_id_map *refs_idmap = NULL;
9937 struct got_commit_object *commit = NULL;
9938 struct got_object_id *id = NULL;
9939 const char *header_prefix;
9940 char *uuidstr = NULL;
9941 int found = 0;
9943 TAILQ_INIT(&refs);
9944 TAILQ_INIT(&paths);
9946 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9947 if (err)
9948 goto done;
9950 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9951 if (err)
9952 goto done;
9954 if (worktree != NULL) {
9955 err = got_worktree_get_uuid(&uuidstr, worktree);
9956 if (err)
9957 goto done;
9960 if (wanted_ref) {
9961 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9962 wanted_ref += 11;
9965 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9966 header_prefix = "backout";
9967 else
9968 header_prefix = "cherrypick";
9970 TAILQ_FOREACH(re, &refs, entry) {
9971 const char *refname, *wt;
9973 refname = got_ref_get_name(re->ref);
9975 err = check_cancelled(NULL);
9976 if (err)
9977 goto done;
9979 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9980 refname += prefix_len + 1; /* skip '-' delimiter */
9981 else
9982 continue;
9984 wt = refname;
9986 if (worktree == NULL || strncmp(refname, uuidstr,
9987 GOT_WORKTREE_UUID_STRLEN) == 0)
9988 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9989 else
9990 continue;
9992 err = got_repo_match_object_id(&id, NULL, refname,
9993 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9994 if (err)
9995 goto done;
9997 err = got_object_open_as_commit(&commit, repo, id);
9998 if (err)
9999 goto done;
10001 if (wanted_ref)
10002 found = strncmp(wanted_ref, refname,
10003 strlen(wanted_ref)) == 0;
10004 if (wanted_ref && !found) {
10005 struct got_reflist_head *ci_refs;
10007 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10008 id);
10010 if (ci_refs) {
10011 char *refs_str = NULL;
10012 char const *r = NULL;
10014 err = build_refs_str(&refs_str, ci_refs, id,
10015 repo, 1);
10016 if (err)
10017 goto done;
10019 r = refs_str;
10020 while (r) {
10021 if (strncmp(r, wanted_ref,
10022 strlen(wanted_ref)) == 0) {
10023 found = 1;
10024 break;
10026 r = strchr(r, ' ');
10027 if (r)
10028 ++r;
10030 free(refs_str);
10034 if (wanted_ref == NULL || found) {
10035 if (delete) {
10036 err = got_ref_delete(re->ref, repo);
10037 if (err)
10038 goto done;
10039 printf("Deleted: ");
10040 err = print_commit_oneline(commit, id, repo,
10041 refs_idmap);
10042 } else {
10044 * Print paths modified by commit to help
10045 * associate commits with worktree changes.
10047 err = get_changed_paths(&paths, commit,
10048 repo, NULL);
10049 if (err)
10050 goto done;
10052 err = print_commit(commit, id, repo, NULL,
10053 &paths, NULL, 0, 0, refs_idmap, NULL,
10054 header_prefix);
10055 got_pathlist_free(&paths,
10056 GOT_PATHLIST_FREE_ALL);
10058 if (worktree == NULL)
10059 printf("work tree: %.*s\n\n",
10060 GOT_WORKTREE_UUID_STRLEN, wt);
10062 if (err || found)
10063 goto done;
10066 got_object_commit_close(commit);
10067 commit = NULL;
10068 free(id);
10069 id = NULL;
10072 if (wanted_ref != NULL && !found)
10073 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10075 done:
10076 free(id);
10077 free(uuidstr);
10078 got_ref_list_free(&refs);
10079 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10080 if (refs_idmap)
10081 got_reflist_object_id_map_free(refs_idmap);
10082 if (commit)
10083 got_object_commit_close(commit);
10084 return err;
10088 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10089 * identified by id for log messages to prepopulate the editor on commit.
10091 static const struct got_error *
10092 logmsg_ref(struct got_object_id *id, const char *prefix,
10093 struct got_worktree *worktree, struct got_repository *repo)
10095 const struct got_error *err = NULL;
10096 char *idstr, *ref = NULL, *refname = NULL;
10097 int histedit_in_progress;
10098 int rebase_in_progress, merge_in_progress;
10101 * Silenty refuse to create merge reference if any histedit, merge,
10102 * or rebase operation is in progress.
10104 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10105 worktree);
10106 if (err)
10107 return err;
10108 if (histedit_in_progress)
10109 return NULL;
10111 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10112 if (err)
10113 return err;
10114 if (rebase_in_progress)
10115 return NULL;
10117 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10118 repo);
10119 if (err)
10120 return err;
10121 if (merge_in_progress)
10122 return NULL;
10124 err = got_object_id_str(&idstr, id);
10125 if (err)
10126 return err;
10128 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10129 if (err)
10130 goto done;
10132 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10133 err = got_error_from_errno("asprintf");
10134 goto done;
10137 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10138 -1, repo);
10139 done:
10140 free(ref);
10141 free(idstr);
10142 free(refname);
10143 return err;
10146 __dead static void
10147 usage_cherrypick(void)
10149 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10150 getprogname());
10151 exit(1);
10154 static const struct got_error *
10155 cmd_cherrypick(int argc, char *argv[])
10157 const struct got_error *error = NULL;
10158 struct got_worktree *worktree = NULL;
10159 struct got_repository *repo = NULL;
10160 char *cwd = NULL, *commit_id_str = NULL;
10161 struct got_object_id *commit_id = NULL;
10162 struct got_commit_object *commit = NULL;
10163 struct got_object_qid *pid;
10164 int ch, list_refs = 0, remove_refs = 0;
10165 struct got_update_progress_arg upa;
10166 int *pack_fds = NULL;
10168 #ifndef PROFILE
10169 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10170 "unveil", NULL) == -1)
10171 err(1, "pledge");
10172 #endif
10174 while ((ch = getopt(argc, argv, "lX")) != -1) {
10175 switch (ch) {
10176 case 'l':
10177 list_refs = 1;
10178 break;
10179 case 'X':
10180 remove_refs = 1;
10181 break;
10182 default:
10183 usage_cherrypick();
10184 /* NOTREACHED */
10188 argc -= optind;
10189 argv += optind;
10191 if (list_refs || remove_refs) {
10192 if (argc != 0 && argc != 1)
10193 usage_cherrypick();
10194 } else if (argc != 1)
10195 usage_cherrypick();
10196 if (list_refs && remove_refs)
10197 option_conflict('l', 'X');
10199 cwd = getcwd(NULL, 0);
10200 if (cwd == NULL) {
10201 error = got_error_from_errno("getcwd");
10202 goto done;
10205 error = got_repo_pack_fds_open(&pack_fds);
10206 if (error != NULL)
10207 goto done;
10209 error = got_worktree_open(&worktree, cwd);
10210 if (error) {
10211 if (list_refs || remove_refs) {
10212 if (error->code != GOT_ERR_NOT_WORKTREE)
10213 goto done;
10214 } else {
10215 if (error->code == GOT_ERR_NOT_WORKTREE)
10216 error = wrap_not_worktree_error(error,
10217 "cherrypick", cwd);
10218 goto done;
10222 error = got_repo_open(&repo,
10223 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10224 NULL, pack_fds);
10225 if (error != NULL)
10226 goto done;
10228 error = apply_unveil(got_repo_get_path(repo), 0,
10229 worktree ? got_worktree_get_root_path(worktree) : NULL);
10230 if (error)
10231 goto done;
10233 if (list_refs || remove_refs) {
10234 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10235 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10236 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10237 goto done;
10240 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10241 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10242 if (error)
10243 goto done;
10244 error = got_object_id_str(&commit_id_str, commit_id);
10245 if (error)
10246 goto done;
10248 error = got_object_open_as_commit(&commit, repo, commit_id);
10249 if (error)
10250 goto done;
10251 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10252 memset(&upa, 0, sizeof(upa));
10253 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10254 commit_id, repo, update_progress, &upa, check_cancelled,
10255 NULL);
10256 if (error != NULL)
10257 goto done;
10259 if (upa.did_something) {
10260 error = logmsg_ref(commit_id,
10261 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10262 if (error)
10263 goto done;
10264 printf("Merged commit %s\n", commit_id_str);
10266 print_merge_progress_stats(&upa);
10267 done:
10268 free(cwd);
10269 if (commit)
10270 got_object_commit_close(commit);
10271 free(commit_id_str);
10272 if (worktree)
10273 got_worktree_close(worktree);
10274 if (repo) {
10275 const struct got_error *close_err = got_repo_close(repo);
10276 if (error == NULL)
10277 error = close_err;
10279 if (pack_fds) {
10280 const struct got_error *pack_err =
10281 got_repo_pack_fds_close(pack_fds);
10282 if (error == NULL)
10283 error = pack_err;
10286 return error;
10289 __dead static void
10290 usage_backout(void)
10292 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10293 exit(1);
10296 static const struct got_error *
10297 cmd_backout(int argc, char *argv[])
10299 const struct got_error *error = NULL;
10300 struct got_worktree *worktree = NULL;
10301 struct got_repository *repo = NULL;
10302 char *cwd = NULL, *commit_id_str = NULL;
10303 struct got_object_id *commit_id = NULL;
10304 struct got_commit_object *commit = NULL;
10305 struct got_object_qid *pid;
10306 int ch, list_refs = 0, remove_refs = 0;
10307 struct got_update_progress_arg upa;
10308 int *pack_fds = NULL;
10310 #ifndef PROFILE
10311 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10312 "unveil", NULL) == -1)
10313 err(1, "pledge");
10314 #endif
10316 while ((ch = getopt(argc, argv, "lX")) != -1) {
10317 switch (ch) {
10318 case 'l':
10319 list_refs = 1;
10320 break;
10321 case 'X':
10322 remove_refs = 1;
10323 break;
10324 default:
10325 usage_backout();
10326 /* NOTREACHED */
10330 argc -= optind;
10331 argv += optind;
10333 if (list_refs || remove_refs) {
10334 if (argc != 0 && argc != 1)
10335 usage_backout();
10336 } else if (argc != 1)
10337 usage_backout();
10338 if (list_refs && remove_refs)
10339 option_conflict('l', 'X');
10341 cwd = getcwd(NULL, 0);
10342 if (cwd == NULL) {
10343 error = got_error_from_errno("getcwd");
10344 goto done;
10347 error = got_repo_pack_fds_open(&pack_fds);
10348 if (error != NULL)
10349 goto done;
10351 error = got_worktree_open(&worktree, cwd);
10352 if (error) {
10353 if (list_refs || remove_refs) {
10354 if (error->code != GOT_ERR_NOT_WORKTREE)
10355 goto done;
10356 } else {
10357 if (error->code == GOT_ERR_NOT_WORKTREE)
10358 error = wrap_not_worktree_error(error,
10359 "backout", cwd);
10360 goto done;
10364 error = got_repo_open(&repo,
10365 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10366 NULL, pack_fds);
10367 if (error != NULL)
10368 goto done;
10370 error = apply_unveil(got_repo_get_path(repo), 0,
10371 worktree ? got_worktree_get_root_path(worktree) : NULL);
10372 if (error)
10373 goto done;
10375 if (list_refs || remove_refs) {
10376 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10377 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10378 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10379 goto done;
10382 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10383 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10384 if (error)
10385 goto done;
10386 error = got_object_id_str(&commit_id_str, commit_id);
10387 if (error)
10388 goto done;
10390 error = got_object_open_as_commit(&commit, repo, commit_id);
10391 if (error)
10392 goto done;
10393 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10394 if (pid == NULL) {
10395 error = got_error(GOT_ERR_ROOT_COMMIT);
10396 goto done;
10399 memset(&upa, 0, sizeof(upa));
10400 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10401 repo, update_progress, &upa, check_cancelled, NULL);
10402 if (error != NULL)
10403 goto done;
10405 if (upa.did_something) {
10406 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10407 worktree, repo);
10408 if (error)
10409 goto done;
10410 printf("Backed out commit %s\n", commit_id_str);
10412 print_merge_progress_stats(&upa);
10413 done:
10414 free(cwd);
10415 if (commit)
10416 got_object_commit_close(commit);
10417 free(commit_id_str);
10418 if (worktree)
10419 got_worktree_close(worktree);
10420 if (repo) {
10421 const struct got_error *close_err = got_repo_close(repo);
10422 if (error == NULL)
10423 error = close_err;
10425 if (pack_fds) {
10426 const struct got_error *pack_err =
10427 got_repo_pack_fds_close(pack_fds);
10428 if (error == NULL)
10429 error = pack_err;
10431 return error;
10434 __dead static void
10435 usage_rebase(void)
10437 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10438 exit(1);
10441 static void
10442 trim_logmsg(char *logmsg, int limit)
10444 char *nl;
10445 size_t len;
10447 len = strlen(logmsg);
10448 if (len > limit)
10449 len = limit;
10450 logmsg[len] = '\0';
10451 nl = strchr(logmsg, '\n');
10452 if (nl)
10453 *nl = '\0';
10456 static const struct got_error *
10457 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10459 const struct got_error *err;
10460 char *logmsg0 = NULL;
10461 const char *s;
10463 err = got_object_commit_get_logmsg(&logmsg0, commit);
10464 if (err)
10465 return err;
10467 s = logmsg0;
10468 while (isspace((unsigned char)s[0]))
10469 s++;
10471 *logmsg = strdup(s);
10472 if (*logmsg == NULL) {
10473 err = got_error_from_errno("strdup");
10474 goto done;
10477 trim_logmsg(*logmsg, limit);
10478 done:
10479 free(logmsg0);
10480 return err;
10483 static const struct got_error *
10484 show_rebase_merge_conflict(struct got_object_id *id,
10485 struct got_repository *repo)
10487 const struct got_error *err;
10488 struct got_commit_object *commit = NULL;
10489 char *id_str = NULL, *logmsg = NULL;
10491 err = got_object_open_as_commit(&commit, repo, id);
10492 if (err)
10493 return err;
10495 err = got_object_id_str(&id_str, id);
10496 if (err)
10497 goto done;
10499 id_str[12] = '\0';
10501 err = get_short_logmsg(&logmsg, 42, commit);
10502 if (err)
10503 goto done;
10505 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10506 done:
10507 free(id_str);
10508 got_object_commit_close(commit);
10509 free(logmsg);
10510 return err;
10513 static const struct got_error *
10514 show_rebase_progress(struct got_commit_object *commit,
10515 struct got_object_id *old_id, struct got_object_id *new_id)
10517 const struct got_error *err;
10518 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10520 err = got_object_id_str(&old_id_str, old_id);
10521 if (err)
10522 goto done;
10524 if (new_id) {
10525 err = got_object_id_str(&new_id_str, new_id);
10526 if (err)
10527 goto done;
10530 old_id_str[12] = '\0';
10531 if (new_id_str)
10532 new_id_str[12] = '\0';
10534 err = get_short_logmsg(&logmsg, 42, commit);
10535 if (err)
10536 goto done;
10538 printf("%s -> %s: %s\n", old_id_str,
10539 new_id_str ? new_id_str : "no-op change", logmsg);
10540 done:
10541 free(old_id_str);
10542 free(new_id_str);
10543 free(logmsg);
10544 return err;
10547 static const struct got_error *
10548 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10549 struct got_reference *branch, struct got_reference *tmp_branch,
10550 struct got_repository *repo, int create_backup)
10552 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10553 return got_worktree_rebase_complete(worktree, fileindex,
10554 tmp_branch, branch, repo, create_backup);
10557 static const struct got_error *
10558 rebase_commit(struct got_pathlist_head *merged_paths,
10559 struct got_worktree *worktree, struct got_fileindex *fileindex,
10560 struct got_reference *tmp_branch, const char *committer,
10561 struct got_object_id *commit_id, int allow_conflict,
10562 struct got_repository *repo)
10564 const struct got_error *error;
10565 struct got_commit_object *commit;
10566 struct got_object_id *new_commit_id;
10568 error = got_object_open_as_commit(&commit, repo, commit_id);
10569 if (error)
10570 return error;
10572 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10573 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10574 allow_conflict, repo);
10575 if (error) {
10576 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10577 goto done;
10578 error = show_rebase_progress(commit, commit_id, NULL);
10579 } else {
10580 error = show_rebase_progress(commit, commit_id, new_commit_id);
10581 free(new_commit_id);
10583 done:
10584 got_object_commit_close(commit);
10585 return error;
10588 struct check_path_prefix_arg {
10589 const char *path_prefix;
10590 size_t len;
10591 int errcode;
10594 static const struct got_error *
10595 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10596 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10597 struct got_object_id *id1, struct got_object_id *id2,
10598 const char *path1, const char *path2,
10599 mode_t mode1, mode_t mode2, struct got_repository *repo)
10601 struct check_path_prefix_arg *a = arg;
10603 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10604 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10605 return got_error(a->errcode);
10607 return NULL;
10610 static const struct got_error *
10611 check_path_prefix(struct got_object_id *parent_id,
10612 struct got_object_id *commit_id, const char *path_prefix,
10613 int errcode, struct got_repository *repo)
10615 const struct got_error *err;
10616 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10617 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10618 struct check_path_prefix_arg cpp_arg;
10620 if (got_path_is_root_dir(path_prefix))
10621 return NULL;
10623 err = got_object_open_as_commit(&commit, repo, commit_id);
10624 if (err)
10625 goto done;
10627 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10628 if (err)
10629 goto done;
10631 err = got_object_open_as_tree(&tree1, repo,
10632 got_object_commit_get_tree_id(parent_commit));
10633 if (err)
10634 goto done;
10636 err = got_object_open_as_tree(&tree2, repo,
10637 got_object_commit_get_tree_id(commit));
10638 if (err)
10639 goto done;
10641 cpp_arg.path_prefix = path_prefix;
10642 while (cpp_arg.path_prefix[0] == '/')
10643 cpp_arg.path_prefix++;
10644 cpp_arg.len = strlen(cpp_arg.path_prefix);
10645 cpp_arg.errcode = errcode;
10646 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10647 check_path_prefix_in_diff, &cpp_arg, 0);
10648 done:
10649 if (tree1)
10650 got_object_tree_close(tree1);
10651 if (tree2)
10652 got_object_tree_close(tree2);
10653 if (commit)
10654 got_object_commit_close(commit);
10655 if (parent_commit)
10656 got_object_commit_close(parent_commit);
10657 return err;
10660 static const struct got_error *
10661 collect_commits(struct got_object_id_queue *commits,
10662 struct got_object_id *initial_commit_id,
10663 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10664 const char *path_prefix, int path_prefix_errcode,
10665 struct got_repository *repo)
10667 const struct got_error *err = NULL;
10668 struct got_commit_graph *graph = NULL;
10669 struct got_object_id parent_id, commit_id;
10670 struct got_object_qid *qid;
10672 err = got_commit_graph_open(&graph, "/", 1);
10673 if (err)
10674 return err;
10676 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10677 check_cancelled, NULL);
10678 if (err)
10679 goto done;
10681 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10682 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10683 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10684 check_cancelled, NULL);
10685 if (err) {
10686 if (err->code == GOT_ERR_ITER_COMPLETED) {
10687 err = got_error_msg(GOT_ERR_ANCESTRY,
10688 "ran out of commits to rebase before "
10689 "youngest common ancestor commit has "
10690 "been reached?!?");
10692 goto done;
10693 } else {
10694 err = check_path_prefix(&parent_id, &commit_id,
10695 path_prefix, path_prefix_errcode, repo);
10696 if (err)
10697 goto done;
10699 err = got_object_qid_alloc(&qid, &commit_id);
10700 if (err)
10701 goto done;
10702 STAILQ_INSERT_HEAD(commits, qid, entry);
10704 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10707 done:
10708 got_commit_graph_close(graph);
10709 return err;
10712 static const struct got_error *
10713 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10715 const struct got_error *err = NULL;
10716 time_t committer_time;
10717 struct tm tm;
10718 char datebuf[11]; /* YYYY-MM-DD + NUL */
10719 char *author0 = NULL, *author, *smallerthan;
10720 char *logmsg0 = NULL, *logmsg, *newline;
10722 committer_time = got_object_commit_get_committer_time(commit);
10723 if (gmtime_r(&committer_time, &tm) == NULL)
10724 return got_error_from_errno("gmtime_r");
10725 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10726 return got_error(GOT_ERR_NO_SPACE);
10728 author0 = strdup(got_object_commit_get_author(commit));
10729 if (author0 == NULL)
10730 return got_error_from_errno("strdup");
10731 author = author0;
10732 smallerthan = strchr(author, '<');
10733 if (smallerthan && smallerthan[1] != '\0')
10734 author = smallerthan + 1;
10735 author[strcspn(author, "@>")] = '\0';
10737 err = got_object_commit_get_logmsg(&logmsg0, commit);
10738 if (err)
10739 goto done;
10740 logmsg = logmsg0;
10741 while (*logmsg == '\n')
10742 logmsg++;
10743 newline = strchr(logmsg, '\n');
10744 if (newline)
10745 *newline = '\0';
10747 if (asprintf(brief_str, "%s %s %s",
10748 datebuf, author, logmsg) == -1)
10749 err = got_error_from_errno("asprintf");
10750 done:
10751 free(author0);
10752 free(logmsg0);
10753 return err;
10756 static const struct got_error *
10757 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10758 struct got_repository *repo)
10760 const struct got_error *err;
10761 char *id_str;
10763 err = got_object_id_str(&id_str, id);
10764 if (err)
10765 return err;
10767 err = got_ref_delete(ref, repo);
10768 if (err)
10769 goto done;
10771 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10772 done:
10773 free(id_str);
10774 return err;
10777 static const struct got_error *
10778 print_backup_ref(const char *branch_name, const char *new_id_str,
10779 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10780 struct got_reflist_object_id_map *refs_idmap,
10781 struct got_repository *repo)
10783 const struct got_error *err = NULL;
10784 struct got_reflist_head *refs;
10785 char *refs_str = NULL;
10786 struct got_object_id *new_commit_id = NULL;
10787 struct got_commit_object *new_commit = NULL;
10788 char *new_commit_brief_str = NULL;
10789 struct got_object_id *yca_id = NULL;
10790 struct got_commit_object *yca_commit = NULL;
10791 char *yca_id_str = NULL, *yca_brief_str = NULL;
10792 char *custom_refs_str;
10794 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10795 return got_error_from_errno("asprintf");
10797 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10798 0, 0, refs_idmap, custom_refs_str, NULL);
10799 if (err)
10800 goto done;
10802 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10803 if (err)
10804 goto done;
10806 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10807 if (refs) {
10808 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10809 if (err)
10810 goto done;
10813 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10814 if (err)
10815 goto done;
10817 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10818 if (err)
10819 goto done;
10821 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10822 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10823 if (err)
10824 goto done;
10826 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10827 refs_str ? " (" : "", refs_str ? refs_str : "",
10828 refs_str ? ")" : "", new_commit_brief_str);
10829 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10830 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10831 free(refs_str);
10832 refs_str = NULL;
10834 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10835 if (err)
10836 goto done;
10838 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10839 if (err)
10840 goto done;
10842 err = got_object_id_str(&yca_id_str, yca_id);
10843 if (err)
10844 goto done;
10846 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10847 if (refs) {
10848 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10849 if (err)
10850 goto done;
10852 printf("history forked at %s%s%s%s\n %s\n",
10853 yca_id_str,
10854 refs_str ? " (" : "", refs_str ? refs_str : "",
10855 refs_str ? ")" : "", yca_brief_str);
10857 done:
10858 free(custom_refs_str);
10859 free(new_commit_id);
10860 free(refs_str);
10861 free(yca_id);
10862 free(yca_id_str);
10863 free(yca_brief_str);
10864 if (new_commit)
10865 got_object_commit_close(new_commit);
10866 if (yca_commit)
10867 got_object_commit_close(yca_commit);
10869 return err;
10872 static const struct got_error *
10873 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10874 struct got_repository *repo)
10876 const struct got_error *err;
10877 struct got_reflist_head refs;
10878 struct got_reflist_entry *re;
10879 char *uuidstr = NULL;
10880 static char msg[160];
10882 TAILQ_INIT(&refs);
10884 err = got_worktree_get_uuid(&uuidstr, worktree);
10885 if (err)
10886 goto done;
10888 err = got_ref_list(&refs, repo, "refs/got/worktree",
10889 got_ref_cmp_by_name, repo);
10890 if (err)
10891 goto done;
10893 TAILQ_FOREACH(re, &refs, entry) {
10894 const char *cmd, *refname, *type;
10896 refname = got_ref_get_name(re->ref);
10898 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10899 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10900 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10901 cmd = "cherrypick";
10902 type = "cherrypicked";
10903 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10904 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10905 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10906 cmd = "backout";
10907 type = "backed-out";
10908 } else
10909 continue;
10911 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10912 continue;
10914 snprintf(msg, sizeof(msg),
10915 "work tree has references created by %s commits which "
10916 "must be removed with 'got %s -X' before running the %s "
10917 "command", type, cmd, caller);
10918 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10919 goto done;
10922 done:
10923 free(uuidstr);
10924 got_ref_list_free(&refs);
10925 return err;
10928 static const struct got_error *
10929 process_backup_refs(const char *backup_ref_prefix,
10930 const char *wanted_branch_name,
10931 int delete, struct got_repository *repo)
10933 const struct got_error *err;
10934 struct got_reflist_head refs, backup_refs;
10935 struct got_reflist_entry *re;
10936 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10937 struct got_object_id *old_commit_id = NULL;
10938 char *branch_name = NULL;
10939 struct got_commit_object *old_commit = NULL;
10940 struct got_reflist_object_id_map *refs_idmap = NULL;
10941 int wanted_branch_found = 0;
10943 TAILQ_INIT(&refs);
10944 TAILQ_INIT(&backup_refs);
10946 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10947 if (err)
10948 return err;
10950 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10951 if (err)
10952 goto done;
10954 if (wanted_branch_name) {
10955 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10956 wanted_branch_name += 11;
10959 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10960 got_ref_cmp_by_commit_timestamp_descending, repo);
10961 if (err)
10962 goto done;
10964 TAILQ_FOREACH(re, &backup_refs, entry) {
10965 const char *refname = got_ref_get_name(re->ref);
10966 char *slash;
10968 err = check_cancelled(NULL);
10969 if (err)
10970 break;
10972 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10973 if (err)
10974 break;
10976 err = got_object_open_as_commit(&old_commit, repo,
10977 old_commit_id);
10978 if (err)
10979 break;
10981 if (strncmp(backup_ref_prefix, refname,
10982 backup_ref_prefix_len) == 0)
10983 refname += backup_ref_prefix_len;
10985 while (refname[0] == '/')
10986 refname++;
10988 branch_name = strdup(refname);
10989 if (branch_name == NULL) {
10990 err = got_error_from_errno("strdup");
10991 break;
10993 slash = strrchr(branch_name, '/');
10994 if (slash) {
10995 *slash = '\0';
10996 refname += strlen(branch_name) + 1;
10999 if (wanted_branch_name == NULL ||
11000 strcmp(wanted_branch_name, branch_name) == 0) {
11001 wanted_branch_found = 1;
11002 if (delete) {
11003 err = delete_backup_ref(re->ref,
11004 old_commit_id, repo);
11005 } else {
11006 err = print_backup_ref(branch_name, refname,
11007 old_commit_id, old_commit, refs_idmap,
11008 repo);
11010 if (err)
11011 break;
11014 free(old_commit_id);
11015 old_commit_id = NULL;
11016 free(branch_name);
11017 branch_name = NULL;
11018 got_object_commit_close(old_commit);
11019 old_commit = NULL;
11022 if (wanted_branch_name && !wanted_branch_found) {
11023 err = got_error_fmt(GOT_ERR_NOT_REF,
11024 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11026 done:
11027 if (refs_idmap)
11028 got_reflist_object_id_map_free(refs_idmap);
11029 got_ref_list_free(&refs);
11030 got_ref_list_free(&backup_refs);
11031 free(old_commit_id);
11032 free(branch_name);
11033 if (old_commit)
11034 got_object_commit_close(old_commit);
11035 return err;
11038 static const struct got_error *
11039 abort_progress(void *arg, unsigned char status, const char *path)
11042 * Unversioned files should not clutter progress output when
11043 * an operation is aborted.
11045 if (status == GOT_STATUS_UNVERSIONED)
11046 return NULL;
11048 return update_progress(arg, status, path);
11051 static const struct got_error *
11052 cmd_rebase(int argc, char *argv[])
11054 const struct got_error *error = NULL;
11055 struct got_worktree *worktree = NULL;
11056 struct got_repository *repo = NULL;
11057 struct got_fileindex *fileindex = NULL;
11058 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11059 struct got_reference *branch = NULL;
11060 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11061 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11062 struct got_object_id *resume_commit_id = NULL;
11063 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11064 struct got_object_id *head_commit_id = NULL;
11065 struct got_reference *head_ref = NULL;
11066 struct got_commit_object *commit = NULL;
11067 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11068 int histedit_in_progress = 0, merge_in_progress = 0;
11069 int create_backup = 1, list_backups = 0, delete_backups = 0;
11070 int allow_conflict = 0;
11071 struct got_object_id_queue commits;
11072 struct got_pathlist_head merged_paths;
11073 const struct got_object_id_queue *parent_ids;
11074 struct got_object_qid *qid, *pid;
11075 struct got_update_progress_arg upa;
11076 int *pack_fds = NULL;
11078 STAILQ_INIT(&commits);
11079 TAILQ_INIT(&merged_paths);
11080 memset(&upa, 0, sizeof(upa));
11082 #ifndef PROFILE
11083 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11084 "unveil", NULL) == -1)
11085 err(1, "pledge");
11086 #endif
11088 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11089 switch (ch) {
11090 case 'a':
11091 abort_rebase = 1;
11092 break;
11093 case 'C':
11094 allow_conflict = 1;
11095 break;
11096 case 'c':
11097 continue_rebase = 1;
11098 break;
11099 case 'l':
11100 list_backups = 1;
11101 break;
11102 case 'X':
11103 delete_backups = 1;
11104 break;
11105 default:
11106 usage_rebase();
11107 /* NOTREACHED */
11111 argc -= optind;
11112 argv += optind;
11114 if (list_backups) {
11115 if (abort_rebase)
11116 option_conflict('l', 'a');
11117 if (allow_conflict)
11118 option_conflict('l', 'C');
11119 if (continue_rebase)
11120 option_conflict('l', 'c');
11121 if (delete_backups)
11122 option_conflict('l', 'X');
11123 if (argc != 0 && argc != 1)
11124 usage_rebase();
11125 } else if (delete_backups) {
11126 if (abort_rebase)
11127 option_conflict('X', 'a');
11128 if (allow_conflict)
11129 option_conflict('X', 'C');
11130 if (continue_rebase)
11131 option_conflict('X', 'c');
11132 if (list_backups)
11133 option_conflict('l', 'X');
11134 if (argc != 0 && argc != 1)
11135 usage_rebase();
11136 } else if (allow_conflict) {
11137 if (abort_rebase)
11138 option_conflict('C', 'a');
11139 if (!continue_rebase)
11140 errx(1, "-C option requires -c");
11141 } else {
11142 if (abort_rebase && continue_rebase)
11143 usage_rebase();
11144 else if (abort_rebase || continue_rebase) {
11145 if (argc != 0)
11146 usage_rebase();
11147 } else if (argc != 1)
11148 usage_rebase();
11151 cwd = getcwd(NULL, 0);
11152 if (cwd == NULL) {
11153 error = got_error_from_errno("getcwd");
11154 goto done;
11157 error = got_repo_pack_fds_open(&pack_fds);
11158 if (error != NULL)
11159 goto done;
11161 error = got_worktree_open(&worktree, cwd);
11162 if (error) {
11163 if (list_backups || delete_backups) {
11164 if (error->code != GOT_ERR_NOT_WORKTREE)
11165 goto done;
11166 } else {
11167 if (error->code == GOT_ERR_NOT_WORKTREE)
11168 error = wrap_not_worktree_error(error,
11169 "rebase", cwd);
11170 goto done;
11174 error = get_gitconfig_path(&gitconfig_path);
11175 if (error)
11176 goto done;
11177 error = got_repo_open(&repo,
11178 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11179 gitconfig_path, pack_fds);
11180 if (error != NULL)
11181 goto done;
11183 if (worktree != NULL && !list_backups && !delete_backups) {
11184 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11185 if (error)
11186 goto done;
11189 error = get_author(&committer, repo, worktree);
11190 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11191 goto done;
11193 error = apply_unveil(got_repo_get_path(repo), 0,
11194 worktree ? got_worktree_get_root_path(worktree) : NULL);
11195 if (error)
11196 goto done;
11198 if (list_backups || delete_backups) {
11199 error = process_backup_refs(
11200 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11201 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11202 goto done; /* nothing else to do */
11205 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11206 worktree);
11207 if (error)
11208 goto done;
11209 if (histedit_in_progress) {
11210 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11211 goto done;
11214 error = got_worktree_merge_in_progress(&merge_in_progress,
11215 worktree, repo);
11216 if (error)
11217 goto done;
11218 if (merge_in_progress) {
11219 error = got_error(GOT_ERR_MERGE_BUSY);
11220 goto done;
11223 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11224 if (error)
11225 goto done;
11227 if (abort_rebase) {
11228 if (!rebase_in_progress) {
11229 error = got_error(GOT_ERR_NOT_REBASING);
11230 goto done;
11232 error = got_worktree_rebase_continue(&resume_commit_id,
11233 &new_base_branch, &tmp_branch, &branch, &fileindex,
11234 worktree, repo);
11235 if (error)
11236 goto done;
11237 printf("Switching work tree to %s\n",
11238 got_ref_get_symref_target(new_base_branch));
11239 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11240 new_base_branch, abort_progress, &upa);
11241 if (error)
11242 goto done;
11243 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11244 print_merge_progress_stats(&upa);
11245 goto done; /* nothing else to do */
11248 if (continue_rebase) {
11249 if (!rebase_in_progress) {
11250 error = got_error(GOT_ERR_NOT_REBASING);
11251 goto done;
11253 error = got_worktree_rebase_continue(&resume_commit_id,
11254 &new_base_branch, &tmp_branch, &branch, &fileindex,
11255 worktree, repo);
11256 if (error)
11257 goto done;
11259 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11260 committer, resume_commit_id, allow_conflict, repo);
11261 if (error)
11262 goto done;
11264 yca_id = got_object_id_dup(resume_commit_id);
11265 if (yca_id == NULL) {
11266 error = got_error_from_errno("got_object_id_dup");
11267 goto done;
11269 } else {
11270 error = got_ref_open(&branch, repo, argv[0], 0);
11271 if (error != NULL)
11272 goto done;
11273 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11274 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11275 "will not rebase a branch which lives outside "
11276 "the \"refs/heads/\" reference namespace");
11277 goto done;
11281 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11282 if (error)
11283 goto done;
11285 if (!continue_rebase) {
11286 struct got_object_id *base_commit_id;
11288 error = got_ref_open(&head_ref, repo,
11289 got_worktree_get_head_ref_name(worktree), 0);
11290 if (error)
11291 goto done;
11292 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11293 if (error)
11294 goto done;
11295 base_commit_id = got_worktree_get_base_commit_id(worktree);
11296 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11297 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11298 goto done;
11301 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11302 base_commit_id, branch_head_commit_id, 1, repo,
11303 check_cancelled, NULL);
11304 if (error) {
11305 if (error->code == GOT_ERR_ANCESTRY) {
11306 error = got_error_msg(GOT_ERR_ANCESTRY,
11307 "specified branch shares no common "
11308 "ancestry with work tree's branch");
11310 goto done;
11313 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11314 struct got_pathlist_head paths;
11315 printf("%s is already based on %s\n",
11316 got_ref_get_name(branch),
11317 got_worktree_get_head_ref_name(worktree));
11318 error = switch_head_ref(branch, branch_head_commit_id,
11319 worktree, repo);
11320 if (error)
11321 goto done;
11322 error = got_worktree_set_base_commit_id(worktree, repo,
11323 branch_head_commit_id);
11324 if (error)
11325 goto done;
11326 TAILQ_INIT(&paths);
11327 error = got_pathlist_append(&paths, "", NULL);
11328 if (error)
11329 goto done;
11330 error = got_worktree_checkout_files(worktree,
11331 &paths, repo, update_progress, &upa,
11332 check_cancelled, NULL);
11333 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11334 if (error)
11335 goto done;
11336 if (upa.did_something) {
11337 char *id_str;
11338 error = got_object_id_str(&id_str,
11339 branch_head_commit_id);
11340 if (error)
11341 goto done;
11342 printf("Updated to %s: %s\n",
11343 got_worktree_get_head_ref_name(worktree),
11344 id_str);
11345 free(id_str);
11346 } else
11347 printf("Already up-to-date\n");
11348 print_update_progress_stats(&upa);
11349 goto done;
11353 commit_id = branch_head_commit_id;
11354 error = got_object_open_as_commit(&commit, repo, commit_id);
11355 if (error)
11356 goto done;
11358 parent_ids = got_object_commit_get_parent_ids(commit);
11359 pid = STAILQ_FIRST(parent_ids);
11360 if (pid) {
11361 error = collect_commits(&commits, commit_id, &pid->id,
11362 yca_id, got_worktree_get_path_prefix(worktree),
11363 GOT_ERR_REBASE_PATH, repo);
11364 if (error)
11365 goto done;
11368 got_object_commit_close(commit);
11369 commit = NULL;
11371 if (!continue_rebase) {
11372 error = got_worktree_rebase_prepare(&new_base_branch,
11373 &tmp_branch, &fileindex, worktree, branch, repo);
11374 if (error)
11375 goto done;
11378 if (STAILQ_EMPTY(&commits)) {
11379 if (continue_rebase) {
11380 error = rebase_complete(worktree, fileindex,
11381 branch, tmp_branch, repo, create_backup);
11382 goto done;
11383 } else {
11384 /* Fast-forward the reference of the branch. */
11385 struct got_object_id *new_head_commit_id;
11386 char *id_str;
11387 error = got_ref_resolve(&new_head_commit_id, repo,
11388 new_base_branch);
11389 if (error)
11390 goto done;
11391 error = got_object_id_str(&id_str, new_head_commit_id);
11392 if (error)
11393 goto done;
11394 printf("Forwarding %s to commit %s\n",
11395 got_ref_get_name(branch), id_str);
11396 free(id_str);
11397 error = got_ref_change_ref(branch,
11398 new_head_commit_id);
11399 if (error)
11400 goto done;
11401 /* No backup needed since objects did not change. */
11402 create_backup = 0;
11406 pid = NULL;
11407 STAILQ_FOREACH(qid, &commits, entry) {
11409 commit_id = &qid->id;
11410 parent_id = pid ? &pid->id : yca_id;
11411 pid = qid;
11413 memset(&upa, 0, sizeof(upa));
11414 error = got_worktree_rebase_merge_files(&merged_paths,
11415 worktree, fileindex, parent_id, commit_id, repo,
11416 update_progress, &upa, check_cancelled, NULL);
11417 if (error)
11418 goto done;
11420 print_merge_progress_stats(&upa);
11421 if (upa.conflicts > 0 || upa.missing > 0 ||
11422 upa.not_deleted > 0 || upa.unversioned > 0) {
11423 if (upa.conflicts > 0) {
11424 error = show_rebase_merge_conflict(&qid->id,
11425 repo);
11426 if (error)
11427 goto done;
11429 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11430 break;
11433 error = rebase_commit(&merged_paths, worktree, fileindex,
11434 tmp_branch, committer, commit_id, 0, repo);
11435 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11436 if (error)
11437 goto done;
11440 if (upa.conflicts > 0 || upa.missing > 0 ||
11441 upa.not_deleted > 0 || upa.unversioned > 0) {
11442 error = got_worktree_rebase_postpone(worktree, fileindex);
11443 if (error)
11444 goto done;
11445 if (upa.conflicts > 0 && upa.missing == 0 &&
11446 upa.not_deleted == 0 && upa.unversioned == 0) {
11447 error = got_error_msg(GOT_ERR_CONFLICTS,
11448 "conflicts must be resolved before rebasing "
11449 "can continue");
11450 } else if (upa.conflicts > 0) {
11451 error = got_error_msg(GOT_ERR_CONFLICTS,
11452 "conflicts must be resolved before rebasing "
11453 "can continue; changes destined for some "
11454 "files were not yet merged and should be "
11455 "merged manually if required before the "
11456 "rebase operation is continued");
11457 } else {
11458 error = got_error_msg(GOT_ERR_CONFLICTS,
11459 "changes destined for some files were not "
11460 "yet merged and should be merged manually "
11461 "if required before the rebase operation "
11462 "is continued");
11464 } else
11465 error = rebase_complete(worktree, fileindex, branch,
11466 tmp_branch, repo, create_backup);
11467 done:
11468 free(cwd);
11469 free(committer);
11470 free(gitconfig_path);
11471 got_object_id_queue_free(&commits);
11472 free(branch_head_commit_id);
11473 free(resume_commit_id);
11474 free(head_commit_id);
11475 free(yca_id);
11476 if (commit)
11477 got_object_commit_close(commit);
11478 if (branch)
11479 got_ref_close(branch);
11480 if (new_base_branch)
11481 got_ref_close(new_base_branch);
11482 if (tmp_branch)
11483 got_ref_close(tmp_branch);
11484 if (head_ref)
11485 got_ref_close(head_ref);
11486 if (worktree)
11487 got_worktree_close(worktree);
11488 if (repo) {
11489 const struct got_error *close_err = got_repo_close(repo);
11490 if (error == NULL)
11491 error = close_err;
11493 if (pack_fds) {
11494 const struct got_error *pack_err =
11495 got_repo_pack_fds_close(pack_fds);
11496 if (error == NULL)
11497 error = pack_err;
11499 return error;
11502 __dead static void
11503 usage_histedit(void)
11505 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11506 "[branch]\n", getprogname());
11507 exit(1);
11510 #define GOT_HISTEDIT_PICK 'p'
11511 #define GOT_HISTEDIT_EDIT 'e'
11512 #define GOT_HISTEDIT_FOLD 'f'
11513 #define GOT_HISTEDIT_DROP 'd'
11514 #define GOT_HISTEDIT_MESG 'm'
11516 static const struct got_histedit_cmd {
11517 unsigned char code;
11518 const char *name;
11519 const char *desc;
11520 } got_histedit_cmds[] = {
11521 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11522 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11523 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11524 "be used" },
11525 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11526 { GOT_HISTEDIT_MESG, "mesg",
11527 "single-line log message for commit above (open editor if empty)" },
11530 struct got_histedit_list_entry {
11531 TAILQ_ENTRY(got_histedit_list_entry) entry;
11532 struct got_object_id *commit_id;
11533 const struct got_histedit_cmd *cmd;
11534 char *logmsg;
11536 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11538 static const struct got_error *
11539 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11540 FILE *f, struct got_repository *repo)
11542 const struct got_error *err = NULL;
11543 char *logmsg = NULL, *id_str = NULL;
11544 struct got_commit_object *commit = NULL;
11545 int n;
11547 err = got_object_open_as_commit(&commit, repo, commit_id);
11548 if (err)
11549 goto done;
11551 err = get_short_logmsg(&logmsg, 34, commit);
11552 if (err)
11553 goto done;
11555 err = got_object_id_str(&id_str, commit_id);
11556 if (err)
11557 goto done;
11559 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11560 if (n < 0)
11561 err = got_ferror(f, GOT_ERR_IO);
11562 done:
11563 if (commit)
11564 got_object_commit_close(commit);
11565 free(id_str);
11566 free(logmsg);
11567 return err;
11570 static const struct got_error *
11571 histedit_write_commit_list(struct got_object_id_queue *commits,
11572 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11573 int edit_only, struct got_repository *repo)
11575 const struct got_error *err = NULL;
11576 struct got_object_qid *qid;
11577 const char *histedit_cmd = NULL;
11579 if (STAILQ_EMPTY(commits))
11580 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11582 STAILQ_FOREACH(qid, commits, entry) {
11583 histedit_cmd = got_histedit_cmds[0].name;
11584 if (drop_only)
11585 histedit_cmd = "drop";
11586 else if (edit_only)
11587 histedit_cmd = "edit";
11588 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11589 histedit_cmd = "fold";
11590 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11591 if (err)
11592 break;
11593 if (edit_logmsg_only) {
11594 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11595 if (n < 0) {
11596 err = got_ferror(f, GOT_ERR_IO);
11597 break;
11602 return err;
11605 static const struct got_error *
11606 write_cmd_list(FILE *f, const char *branch_name,
11607 struct got_object_id_queue *commits)
11609 const struct got_error *err = NULL;
11610 size_t i;
11611 int n;
11612 char *id_str;
11613 struct got_object_qid *qid;
11615 qid = STAILQ_FIRST(commits);
11616 err = got_object_id_str(&id_str, &qid->id);
11617 if (err)
11618 return err;
11620 n = fprintf(f,
11621 "# Editing the history of branch '%s' starting at\n"
11622 "# commit %s\n"
11623 "# Commits will be processed in order from top to "
11624 "bottom of this file.\n", branch_name, id_str);
11625 if (n < 0) {
11626 err = got_ferror(f, GOT_ERR_IO);
11627 goto done;
11630 n = fprintf(f, "# Available histedit commands:\n");
11631 if (n < 0) {
11632 err = got_ferror(f, GOT_ERR_IO);
11633 goto done;
11636 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11637 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11638 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11639 cmd->desc);
11640 if (n < 0) {
11641 err = got_ferror(f, GOT_ERR_IO);
11642 break;
11645 done:
11646 free(id_str);
11647 return err;
11650 static const struct got_error *
11651 histedit_syntax_error(int lineno)
11653 static char msg[42];
11654 int ret;
11656 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11657 lineno);
11658 if (ret < 0 || (size_t)ret >= sizeof(msg))
11659 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11661 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11664 static const struct got_error *
11665 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11666 char *logmsg, struct got_repository *repo)
11668 const struct got_error *err;
11669 struct got_commit_object *folded_commit = NULL;
11670 char *id_str, *folded_logmsg = NULL;
11672 err = got_object_id_str(&id_str, hle->commit_id);
11673 if (err)
11674 return err;
11676 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11677 if (err)
11678 goto done;
11680 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11681 if (err)
11682 goto done;
11683 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11684 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11685 folded_logmsg) == -1) {
11686 err = got_error_from_errno("asprintf");
11688 done:
11689 if (folded_commit)
11690 got_object_commit_close(folded_commit);
11691 free(id_str);
11692 free(folded_logmsg);
11693 return err;
11696 static struct got_histedit_list_entry *
11697 get_folded_commits(struct got_histedit_list_entry *hle)
11699 struct got_histedit_list_entry *prev, *folded = NULL;
11701 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11702 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11703 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11704 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11705 folded = prev;
11706 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11709 return folded;
11712 static const struct got_error *
11713 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11714 struct got_repository *repo)
11716 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11717 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11718 const struct got_error *err = NULL;
11719 struct got_commit_object *commit = NULL;
11720 int logmsg_len;
11721 int fd = -1;
11722 struct got_histedit_list_entry *folded = NULL;
11724 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11725 if (err)
11726 return err;
11728 folded = get_folded_commits(hle);
11729 if (folded) {
11730 while (folded != hle) {
11731 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11732 folded = TAILQ_NEXT(folded, entry);
11733 continue;
11735 err = append_folded_commit_msg(&new_msg, folded,
11736 logmsg, repo);
11737 if (err)
11738 goto done;
11739 free(logmsg);
11740 logmsg = new_msg;
11741 folded = TAILQ_NEXT(folded, entry);
11745 err = got_object_id_str(&id_str, hle->commit_id);
11746 if (err)
11747 goto done;
11748 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11749 if (err)
11750 goto done;
11751 logmsg_len = asprintf(&new_msg,
11752 "%s\n# original log message of commit %s: %s",
11753 logmsg ? logmsg : "", id_str, orig_logmsg);
11754 if (logmsg_len == -1) {
11755 err = got_error_from_errno("asprintf");
11756 goto done;
11758 free(logmsg);
11759 logmsg = new_msg;
11761 err = got_object_id_str(&id_str, hle->commit_id);
11762 if (err)
11763 goto done;
11765 err = got_opentemp_named_fd(&logmsg_path, &fd,
11766 GOT_TMPDIR_STR "/got-logmsg", "");
11767 if (err)
11768 goto done;
11770 if (write(fd, logmsg, logmsg_len) == -1) {
11771 err = got_error_from_errno2("write", logmsg_path);
11772 goto done;
11774 if (close(fd) == -1) {
11775 err = got_error_from_errno2("close", logmsg_path);
11776 goto done;
11778 fd = -1;
11780 err = get_editor(&editor);
11781 if (err)
11782 goto done;
11784 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11785 logmsg_len, 0);
11786 if (err) {
11787 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11788 goto done;
11789 err = NULL;
11790 hle->logmsg = strdup(new_msg);
11791 if (hle->logmsg == NULL)
11792 err = got_error_from_errno("strdup");
11794 done:
11795 if (fd != -1 && close(fd) == -1 && err == NULL)
11796 err = got_error_from_errno2("close", logmsg_path);
11797 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11798 err = got_error_from_errno2("unlink", logmsg_path);
11799 free(logmsg_path);
11800 free(logmsg);
11801 free(orig_logmsg);
11802 free(editor);
11803 if (commit)
11804 got_object_commit_close(commit);
11805 return err;
11808 static const struct got_error *
11809 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11810 FILE *f, struct got_repository *repo)
11812 const struct got_error *err = NULL;
11813 char *line = NULL, *p, *end;
11814 size_t i, linesize = 0;
11815 ssize_t linelen;
11816 int lineno = 0, lastcmd = -1;
11817 const struct got_histedit_cmd *cmd;
11818 struct got_object_id *commit_id = NULL;
11819 struct got_histedit_list_entry *hle = NULL;
11821 for (;;) {
11822 linelen = getline(&line, &linesize, f);
11823 if (linelen == -1) {
11824 const struct got_error *getline_err;
11825 if (feof(f))
11826 break;
11827 getline_err = got_error_from_errno("getline");
11828 err = got_ferror(f, getline_err->code);
11829 break;
11831 lineno++;
11832 p = line;
11833 while (isspace((unsigned char)p[0]))
11834 p++;
11835 if (p[0] == '#' || p[0] == '\0')
11836 continue;
11837 cmd = NULL;
11838 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11839 cmd = &got_histedit_cmds[i];
11840 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11841 isspace((unsigned char)p[strlen(cmd->name)])) {
11842 p += strlen(cmd->name);
11843 break;
11845 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11846 p++;
11847 break;
11850 if (i == nitems(got_histedit_cmds)) {
11851 err = histedit_syntax_error(lineno);
11852 break;
11854 while (isspace((unsigned char)p[0]))
11855 p++;
11856 if (cmd->code == GOT_HISTEDIT_MESG) {
11857 if (lastcmd != GOT_HISTEDIT_PICK &&
11858 lastcmd != GOT_HISTEDIT_EDIT) {
11859 err = got_error(GOT_ERR_HISTEDIT_CMD);
11860 break;
11862 if (p[0] == '\0') {
11863 err = histedit_edit_logmsg(hle, repo);
11864 if (err)
11865 break;
11866 } else {
11867 hle->logmsg = strdup(p);
11868 if (hle->logmsg == NULL) {
11869 err = got_error_from_errno("strdup");
11870 break;
11873 lastcmd = cmd->code;
11874 continue;
11875 } else {
11876 end = p;
11877 while (end[0] && !isspace((unsigned char)end[0]))
11878 end++;
11879 *end = '\0';
11881 err = got_object_resolve_id_str(&commit_id, repo, p);
11882 if (err) {
11883 /* override error code */
11884 err = histedit_syntax_error(lineno);
11885 break;
11888 hle = malloc(sizeof(*hle));
11889 if (hle == NULL) {
11890 err = got_error_from_errno("malloc");
11891 break;
11893 hle->cmd = cmd;
11894 hle->commit_id = commit_id;
11895 hle->logmsg = NULL;
11896 commit_id = NULL;
11897 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11898 lastcmd = cmd->code;
11901 free(line);
11902 free(commit_id);
11903 return err;
11906 static const struct got_error *
11907 histedit_check_script(struct got_histedit_list *histedit_cmds,
11908 struct got_object_id_queue *commits, struct got_repository *repo)
11910 const struct got_error *err = NULL;
11911 struct got_object_qid *qid;
11912 struct got_histedit_list_entry *hle;
11913 static char msg[92];
11914 char *id_str;
11916 if (TAILQ_EMPTY(histedit_cmds))
11917 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11918 "histedit script contains no commands");
11919 if (STAILQ_EMPTY(commits))
11920 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11922 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11923 struct got_histedit_list_entry *hle2;
11924 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11925 if (hle == hle2)
11926 continue;
11927 if (got_object_id_cmp(hle->commit_id,
11928 hle2->commit_id) != 0)
11929 continue;
11930 err = got_object_id_str(&id_str, hle->commit_id);
11931 if (err)
11932 return err;
11933 snprintf(msg, sizeof(msg), "commit %s is listed "
11934 "more than once in histedit script", id_str);
11935 free(id_str);
11936 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11940 STAILQ_FOREACH(qid, commits, entry) {
11941 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11942 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11943 break;
11945 if (hle == NULL) {
11946 err = got_object_id_str(&id_str, &qid->id);
11947 if (err)
11948 return err;
11949 snprintf(msg, sizeof(msg),
11950 "commit %s missing from histedit script", id_str);
11951 free(id_str);
11952 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11956 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11957 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11958 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11959 "last commit in histedit script cannot be folded");
11961 return NULL;
11964 static const struct got_error *
11965 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11966 const char *path, struct got_object_id_queue *commits,
11967 struct got_repository *repo)
11969 const struct got_error *err = NULL;
11970 char *editor;
11971 FILE *f = NULL;
11973 err = get_editor(&editor);
11974 if (err)
11975 return err;
11977 if (spawn_editor(editor, path) == -1) {
11978 err = got_error_from_errno("failed spawning editor");
11979 goto done;
11982 f = fopen(path, "re");
11983 if (f == NULL) {
11984 err = got_error_from_errno("fopen");
11985 goto done;
11987 err = histedit_parse_list(histedit_cmds, f, repo);
11988 if (err)
11989 goto done;
11991 err = histedit_check_script(histedit_cmds, commits, repo);
11992 done:
11993 if (f && fclose(f) == EOF && err == NULL)
11994 err = got_error_from_errno("fclose");
11995 free(editor);
11996 return err;
11999 static const struct got_error *
12000 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12001 struct got_object_id_queue *, const char *, const char *,
12002 struct got_repository *);
12004 static const struct got_error *
12005 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12006 struct got_object_id_queue *commits, const char *branch_name,
12007 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12008 struct got_repository *repo)
12010 const struct got_error *err;
12011 FILE *f = NULL;
12012 char *path = NULL;
12014 err = got_opentemp_named(&path, &f, "got-histedit", "");
12015 if (err)
12016 return err;
12018 err = write_cmd_list(f, branch_name, commits);
12019 if (err)
12020 goto done;
12022 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12023 fold_only, drop_only, edit_only, repo);
12024 if (err)
12025 goto done;
12027 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12028 rewind(f);
12029 err = histedit_parse_list(histedit_cmds, f, repo);
12030 } else {
12031 if (fclose(f) == EOF) {
12032 err = got_error_from_errno("fclose");
12033 goto done;
12035 f = NULL;
12036 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12037 if (err) {
12038 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12039 err->code != GOT_ERR_HISTEDIT_CMD)
12040 goto done;
12041 err = histedit_edit_list_retry(histedit_cmds, err,
12042 commits, path, branch_name, repo);
12045 done:
12046 if (f && fclose(f) == EOF && err == NULL)
12047 err = got_error_from_errno("fclose");
12048 if (path && unlink(path) != 0 && err == NULL)
12049 err = got_error_from_errno2("unlink", path);
12050 free(path);
12051 return err;
12054 static const struct got_error *
12055 histedit_save_list(struct got_histedit_list *histedit_cmds,
12056 struct got_worktree *worktree, struct got_repository *repo)
12058 const struct got_error *err = NULL;
12059 char *path = NULL;
12060 FILE *f = NULL;
12061 struct got_histedit_list_entry *hle;
12062 struct got_commit_object *commit = NULL;
12064 err = got_worktree_get_histedit_script_path(&path, worktree);
12065 if (err)
12066 return err;
12068 f = fopen(path, "we");
12069 if (f == NULL) {
12070 err = got_error_from_errno2("fopen", path);
12071 goto done;
12073 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12074 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12075 repo);
12076 if (err)
12077 break;
12079 if (hle->logmsg) {
12080 int n = fprintf(f, "%c %s\n",
12081 GOT_HISTEDIT_MESG, hle->logmsg);
12082 if (n < 0) {
12083 err = got_ferror(f, GOT_ERR_IO);
12084 break;
12088 done:
12089 if (f && fclose(f) == EOF && err == NULL)
12090 err = got_error_from_errno("fclose");
12091 free(path);
12092 if (commit)
12093 got_object_commit_close(commit);
12094 return err;
12097 static void
12098 histedit_free_list(struct got_histedit_list *histedit_cmds)
12100 struct got_histedit_list_entry *hle;
12102 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12103 TAILQ_REMOVE(histedit_cmds, hle, entry);
12104 free(hle);
12108 static const struct got_error *
12109 histedit_load_list(struct got_histedit_list *histedit_cmds,
12110 const char *path, struct got_repository *repo)
12112 const struct got_error *err = NULL;
12113 FILE *f = NULL;
12115 f = fopen(path, "re");
12116 if (f == NULL) {
12117 err = got_error_from_errno2("fopen", path);
12118 goto done;
12121 err = histedit_parse_list(histedit_cmds, f, repo);
12122 done:
12123 if (f && fclose(f) == EOF && err == NULL)
12124 err = got_error_from_errno("fclose");
12125 return err;
12128 static const struct got_error *
12129 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12130 const struct got_error *edit_err, struct got_object_id_queue *commits,
12131 const char *path, const char *branch_name, struct got_repository *repo)
12133 const struct got_error *err = NULL, *prev_err = edit_err;
12134 int resp = ' ';
12136 while (resp != 'c' && resp != 'r' && resp != 'a') {
12137 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12138 "or (a)bort: ", getprogname(), prev_err->msg);
12139 resp = getchar();
12140 if (resp == '\n')
12141 resp = getchar();
12142 if (resp == 'c') {
12143 histedit_free_list(histedit_cmds);
12144 err = histedit_run_editor(histedit_cmds, path, commits,
12145 repo);
12146 if (err) {
12147 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12148 err->code != GOT_ERR_HISTEDIT_CMD)
12149 break;
12150 prev_err = err;
12151 resp = ' ';
12152 continue;
12154 break;
12155 } else if (resp == 'r') {
12156 histedit_free_list(histedit_cmds);
12157 err = histedit_edit_script(histedit_cmds,
12158 commits, branch_name, 0, 0, 0, 0, repo);
12159 if (err) {
12160 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12161 err->code != GOT_ERR_HISTEDIT_CMD)
12162 break;
12163 prev_err = err;
12164 resp = ' ';
12165 continue;
12167 break;
12168 } else if (resp == 'a') {
12169 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12170 break;
12171 } else
12172 printf("invalid response '%c'\n", resp);
12175 return err;
12178 static const struct got_error *
12179 histedit_complete(struct got_worktree *worktree,
12180 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12181 struct got_reference *branch, struct got_repository *repo)
12183 printf("Switching work tree to %s\n",
12184 got_ref_get_symref_target(branch));
12185 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12186 branch, repo);
12189 static const struct got_error *
12190 show_histedit_progress(struct got_commit_object *commit,
12191 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12193 const struct got_error *err;
12194 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12196 err = got_object_id_str(&old_id_str, hle->commit_id);
12197 if (err)
12198 goto done;
12200 if (new_id) {
12201 err = got_object_id_str(&new_id_str, new_id);
12202 if (err)
12203 goto done;
12206 old_id_str[12] = '\0';
12207 if (new_id_str)
12208 new_id_str[12] = '\0';
12210 if (hle->logmsg) {
12211 logmsg = strdup(hle->logmsg);
12212 if (logmsg == NULL) {
12213 err = got_error_from_errno("strdup");
12214 goto done;
12216 trim_logmsg(logmsg, 42);
12217 } else {
12218 err = get_short_logmsg(&logmsg, 42, commit);
12219 if (err)
12220 goto done;
12223 switch (hle->cmd->code) {
12224 case GOT_HISTEDIT_PICK:
12225 case GOT_HISTEDIT_EDIT:
12226 printf("%s -> %s: %s\n", old_id_str,
12227 new_id_str ? new_id_str : "no-op change", logmsg);
12228 break;
12229 case GOT_HISTEDIT_DROP:
12230 case GOT_HISTEDIT_FOLD:
12231 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12232 logmsg);
12233 break;
12234 default:
12235 break;
12237 done:
12238 free(old_id_str);
12239 free(new_id_str);
12240 return err;
12243 static const struct got_error *
12244 histedit_commit(struct got_pathlist_head *merged_paths,
12245 struct got_worktree *worktree, struct got_fileindex *fileindex,
12246 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12247 const char *committer, int allow_conflict, struct got_repository *repo)
12249 const struct got_error *err;
12250 struct got_commit_object *commit;
12251 struct got_object_id *new_commit_id;
12253 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12254 && hle->logmsg == NULL) {
12255 err = histedit_edit_logmsg(hle, repo);
12256 if (err)
12257 return err;
12260 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12261 if (err)
12262 return err;
12264 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12265 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12266 hle->logmsg, allow_conflict, repo);
12267 if (err) {
12268 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12269 goto done;
12270 err = show_histedit_progress(commit, hle, NULL);
12271 } else {
12272 err = show_histedit_progress(commit, hle, new_commit_id);
12273 free(new_commit_id);
12275 done:
12276 got_object_commit_close(commit);
12277 return err;
12280 static const struct got_error *
12281 histedit_skip_commit(struct got_histedit_list_entry *hle,
12282 struct got_worktree *worktree, struct got_repository *repo)
12284 const struct got_error *error;
12285 struct got_commit_object *commit;
12287 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12288 repo);
12289 if (error)
12290 return error;
12292 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12293 if (error)
12294 return error;
12296 error = show_histedit_progress(commit, hle, NULL);
12297 got_object_commit_close(commit);
12298 return error;
12301 static const struct got_error *
12302 check_local_changes(void *arg, unsigned char status,
12303 unsigned char staged_status, const char *path,
12304 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12305 struct got_object_id *commit_id, int dirfd, const char *de_name)
12307 int *have_local_changes = arg;
12309 switch (status) {
12310 case GOT_STATUS_ADD:
12311 case GOT_STATUS_DELETE:
12312 case GOT_STATUS_MODIFY:
12313 case GOT_STATUS_CONFLICT:
12314 *have_local_changes = 1;
12315 return got_error(GOT_ERR_CANCELLED);
12316 default:
12317 break;
12320 switch (staged_status) {
12321 case GOT_STATUS_ADD:
12322 case GOT_STATUS_DELETE:
12323 case GOT_STATUS_MODIFY:
12324 *have_local_changes = 1;
12325 return got_error(GOT_ERR_CANCELLED);
12326 default:
12327 break;
12330 return NULL;
12333 static const struct got_error *
12334 cmd_histedit(int argc, char *argv[])
12336 const struct got_error *error = NULL;
12337 struct got_worktree *worktree = NULL;
12338 struct got_fileindex *fileindex = NULL;
12339 struct got_repository *repo = NULL;
12340 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12341 struct got_reference *branch = NULL;
12342 struct got_reference *tmp_branch = NULL;
12343 struct got_object_id *resume_commit_id = NULL;
12344 struct got_object_id *base_commit_id = NULL;
12345 struct got_object_id *head_commit_id = NULL;
12346 struct got_commit_object *commit = NULL;
12347 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12348 struct got_update_progress_arg upa;
12349 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12350 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12351 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12352 const char *edit_script_path = NULL;
12353 struct got_object_id_queue commits;
12354 struct got_pathlist_head merged_paths;
12355 const struct got_object_id_queue *parent_ids;
12356 struct got_object_qid *pid;
12357 struct got_histedit_list histedit_cmds;
12358 struct got_histedit_list_entry *hle;
12359 int *pack_fds = NULL;
12361 STAILQ_INIT(&commits);
12362 TAILQ_INIT(&histedit_cmds);
12363 TAILQ_INIT(&merged_paths);
12364 memset(&upa, 0, sizeof(upa));
12366 #ifndef PROFILE
12367 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12368 "unveil", NULL) == -1)
12369 err(1, "pledge");
12370 #endif
12372 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12373 switch (ch) {
12374 case 'a':
12375 abort_edit = 1;
12376 break;
12377 case 'C':
12378 allow_conflict = 1;
12379 break;
12380 case 'c':
12381 continue_edit = 1;
12382 break;
12383 case 'd':
12384 drop_only = 1;
12385 break;
12386 case 'e':
12387 edit_only = 1;
12388 break;
12389 case 'F':
12390 edit_script_path = optarg;
12391 break;
12392 case 'f':
12393 fold_only = 1;
12394 break;
12395 case 'l':
12396 list_backups = 1;
12397 break;
12398 case 'm':
12399 edit_logmsg_only = 1;
12400 break;
12401 case 'X':
12402 delete_backups = 1;
12403 break;
12404 default:
12405 usage_histedit();
12406 /* NOTREACHED */
12410 argc -= optind;
12411 argv += optind;
12413 if (abort_edit && allow_conflict)
12414 option_conflict('a', 'C');
12415 if (abort_edit && continue_edit)
12416 option_conflict('a', 'c');
12417 if (edit_script_path && allow_conflict)
12418 option_conflict('F', 'C');
12419 if (edit_script_path && edit_logmsg_only)
12420 option_conflict('F', 'm');
12421 if (abort_edit && edit_logmsg_only)
12422 option_conflict('a', 'm');
12423 if (edit_logmsg_only && allow_conflict)
12424 option_conflict('m', 'C');
12425 if (continue_edit && edit_logmsg_only)
12426 option_conflict('c', 'm');
12427 if (abort_edit && fold_only)
12428 option_conflict('a', 'f');
12429 if (fold_only && allow_conflict)
12430 option_conflict('f', 'C');
12431 if (continue_edit && fold_only)
12432 option_conflict('c', 'f');
12433 if (fold_only && edit_logmsg_only)
12434 option_conflict('f', 'm');
12435 if (edit_script_path && fold_only)
12436 option_conflict('F', 'f');
12437 if (abort_edit && edit_only)
12438 option_conflict('a', 'e');
12439 if (continue_edit && edit_only)
12440 option_conflict('c', 'e');
12441 if (edit_only && edit_logmsg_only)
12442 option_conflict('e', 'm');
12443 if (edit_script_path && edit_only)
12444 option_conflict('F', 'e');
12445 if (fold_only && edit_only)
12446 option_conflict('f', 'e');
12447 if (drop_only && abort_edit)
12448 option_conflict('d', 'a');
12449 if (drop_only && allow_conflict)
12450 option_conflict('d', 'C');
12451 if (drop_only && continue_edit)
12452 option_conflict('d', 'c');
12453 if (drop_only && edit_logmsg_only)
12454 option_conflict('d', 'm');
12455 if (drop_only && edit_only)
12456 option_conflict('d', 'e');
12457 if (drop_only && edit_script_path)
12458 option_conflict('d', 'F');
12459 if (drop_only && fold_only)
12460 option_conflict('d', 'f');
12461 if (list_backups) {
12462 if (abort_edit)
12463 option_conflict('l', 'a');
12464 if (allow_conflict)
12465 option_conflict('l', 'C');
12466 if (continue_edit)
12467 option_conflict('l', 'c');
12468 if (edit_script_path)
12469 option_conflict('l', 'F');
12470 if (edit_logmsg_only)
12471 option_conflict('l', 'm');
12472 if (drop_only)
12473 option_conflict('l', 'd');
12474 if (fold_only)
12475 option_conflict('l', 'f');
12476 if (edit_only)
12477 option_conflict('l', 'e');
12478 if (delete_backups)
12479 option_conflict('l', 'X');
12480 if (argc != 0 && argc != 1)
12481 usage_histedit();
12482 } else if (delete_backups) {
12483 if (abort_edit)
12484 option_conflict('X', 'a');
12485 if (allow_conflict)
12486 option_conflict('X', 'C');
12487 if (continue_edit)
12488 option_conflict('X', 'c');
12489 if (drop_only)
12490 option_conflict('X', 'd');
12491 if (edit_script_path)
12492 option_conflict('X', 'F');
12493 if (edit_logmsg_only)
12494 option_conflict('X', 'm');
12495 if (fold_only)
12496 option_conflict('X', 'f');
12497 if (edit_only)
12498 option_conflict('X', 'e');
12499 if (list_backups)
12500 option_conflict('X', 'l');
12501 if (argc != 0 && argc != 1)
12502 usage_histedit();
12503 } else if (allow_conflict && !continue_edit)
12504 errx(1, "-C option requires -c");
12505 else if (argc != 0)
12506 usage_histedit();
12509 * This command cannot apply unveil(2) in all cases because the
12510 * user may choose to run an editor to edit the histedit script
12511 * and to edit individual commit log messages.
12512 * unveil(2) traverses exec(2); if an editor is used we have to
12513 * apply unveil after edit script and log messages have been written.
12514 * XXX TODO: Make use of unveil(2) where possible.
12517 cwd = getcwd(NULL, 0);
12518 if (cwd == NULL) {
12519 error = got_error_from_errno("getcwd");
12520 goto done;
12523 error = got_repo_pack_fds_open(&pack_fds);
12524 if (error != NULL)
12525 goto done;
12527 error = got_worktree_open(&worktree, cwd);
12528 if (error) {
12529 if (list_backups || delete_backups) {
12530 if (error->code != GOT_ERR_NOT_WORKTREE)
12531 goto done;
12532 } else {
12533 if (error->code == GOT_ERR_NOT_WORKTREE)
12534 error = wrap_not_worktree_error(error,
12535 "histedit", cwd);
12536 goto done;
12540 if (list_backups || delete_backups) {
12541 error = got_repo_open(&repo,
12542 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12543 NULL, pack_fds);
12544 if (error != NULL)
12545 goto done;
12546 error = apply_unveil(got_repo_get_path(repo), 0,
12547 worktree ? got_worktree_get_root_path(worktree) : NULL);
12548 if (error)
12549 goto done;
12550 error = process_backup_refs(
12551 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12552 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12553 goto done; /* nothing else to do */
12556 error = get_gitconfig_path(&gitconfig_path);
12557 if (error)
12558 goto done;
12559 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12560 gitconfig_path, pack_fds);
12561 if (error != NULL)
12562 goto done;
12564 if (worktree != NULL && !list_backups && !delete_backups) {
12565 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12566 if (error)
12567 goto done;
12570 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12571 if (error)
12572 goto done;
12573 if (rebase_in_progress) {
12574 error = got_error(GOT_ERR_REBASING);
12575 goto done;
12578 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12579 repo);
12580 if (error)
12581 goto done;
12582 if (merge_in_progress) {
12583 error = got_error(GOT_ERR_MERGE_BUSY);
12584 goto done;
12587 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12588 if (error)
12589 goto done;
12591 if (edit_in_progress && edit_logmsg_only) {
12592 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12593 "histedit operation is in progress in this "
12594 "work tree and must be continued or aborted "
12595 "before the -m option can be used");
12596 goto done;
12598 if (edit_in_progress && drop_only) {
12599 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12600 "histedit operation is in progress in this "
12601 "work tree and must be continued or aborted "
12602 "before the -d option can be used");
12603 goto done;
12605 if (edit_in_progress && fold_only) {
12606 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12607 "histedit operation is in progress in this "
12608 "work tree and must be continued or aborted "
12609 "before the -f option can be used");
12610 goto done;
12612 if (edit_in_progress && edit_only) {
12613 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12614 "histedit operation is in progress in this "
12615 "work tree and must be continued or aborted "
12616 "before the -e option can be used");
12617 goto done;
12620 if (edit_in_progress && abort_edit) {
12621 error = got_worktree_histedit_continue(&resume_commit_id,
12622 &tmp_branch, &branch, &base_commit_id, &fileindex,
12623 worktree, repo);
12624 if (error)
12625 goto done;
12626 printf("Switching work tree to %s\n",
12627 got_ref_get_symref_target(branch));
12628 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12629 branch, base_commit_id, abort_progress, &upa);
12630 if (error)
12631 goto done;
12632 printf("Histedit of %s aborted\n",
12633 got_ref_get_symref_target(branch));
12634 print_merge_progress_stats(&upa);
12635 goto done; /* nothing else to do */
12636 } else if (abort_edit) {
12637 error = got_error(GOT_ERR_NOT_HISTEDIT);
12638 goto done;
12641 error = get_author(&committer, repo, worktree);
12642 if (error)
12643 goto done;
12645 if (continue_edit) {
12646 char *path;
12648 if (!edit_in_progress) {
12649 error = got_error(GOT_ERR_NOT_HISTEDIT);
12650 goto done;
12653 error = got_worktree_get_histedit_script_path(&path, worktree);
12654 if (error)
12655 goto done;
12657 error = histedit_load_list(&histedit_cmds, path, repo);
12658 free(path);
12659 if (error)
12660 goto done;
12662 error = got_worktree_histedit_continue(&resume_commit_id,
12663 &tmp_branch, &branch, &base_commit_id, &fileindex,
12664 worktree, repo);
12665 if (error)
12666 goto done;
12668 error = got_ref_resolve(&head_commit_id, repo, branch);
12669 if (error)
12670 goto done;
12672 error = got_object_open_as_commit(&commit, repo,
12673 head_commit_id);
12674 if (error)
12675 goto done;
12676 parent_ids = got_object_commit_get_parent_ids(commit);
12677 pid = STAILQ_FIRST(parent_ids);
12678 if (pid == NULL) {
12679 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12680 goto done;
12682 error = collect_commits(&commits, head_commit_id, &pid->id,
12683 base_commit_id, got_worktree_get_path_prefix(worktree),
12684 GOT_ERR_HISTEDIT_PATH, repo);
12685 got_object_commit_close(commit);
12686 commit = NULL;
12687 if (error)
12688 goto done;
12689 } else {
12690 if (edit_in_progress) {
12691 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12692 goto done;
12695 error = got_ref_open(&branch, repo,
12696 got_worktree_get_head_ref_name(worktree), 0);
12697 if (error != NULL)
12698 goto done;
12700 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12701 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12702 "will not edit commit history of a branch outside "
12703 "the \"refs/heads/\" reference namespace");
12704 goto done;
12707 error = got_ref_resolve(&head_commit_id, repo, branch);
12708 got_ref_close(branch);
12709 branch = NULL;
12710 if (error)
12711 goto done;
12713 error = got_object_open_as_commit(&commit, repo,
12714 head_commit_id);
12715 if (error)
12716 goto done;
12717 parent_ids = got_object_commit_get_parent_ids(commit);
12718 pid = STAILQ_FIRST(parent_ids);
12719 if (pid == NULL) {
12720 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12721 goto done;
12723 error = collect_commits(&commits, head_commit_id, &pid->id,
12724 got_worktree_get_base_commit_id(worktree),
12725 got_worktree_get_path_prefix(worktree),
12726 GOT_ERR_HISTEDIT_PATH, repo);
12727 got_object_commit_close(commit);
12728 commit = NULL;
12729 if (error)
12730 goto done;
12732 if (STAILQ_EMPTY(&commits)) {
12733 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12734 goto done;
12737 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12738 &base_commit_id, &fileindex, worktree, repo);
12739 if (error)
12740 goto done;
12742 if (edit_script_path) {
12743 error = histedit_load_list(&histedit_cmds,
12744 edit_script_path, repo);
12745 if (error) {
12746 got_worktree_histedit_abort(worktree, fileindex,
12747 repo, branch, base_commit_id,
12748 abort_progress, &upa);
12749 print_merge_progress_stats(&upa);
12750 goto done;
12752 } else {
12753 const char *branch_name;
12754 branch_name = got_ref_get_symref_target(branch);
12755 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12756 branch_name += 11;
12757 error = histedit_edit_script(&histedit_cmds, &commits,
12758 branch_name, edit_logmsg_only, fold_only,
12759 drop_only, edit_only, repo);
12760 if (error) {
12761 got_worktree_histedit_abort(worktree, fileindex,
12762 repo, branch, base_commit_id,
12763 abort_progress, &upa);
12764 print_merge_progress_stats(&upa);
12765 goto done;
12770 error = histedit_save_list(&histedit_cmds, worktree,
12771 repo);
12772 if (error) {
12773 got_worktree_histedit_abort(worktree, fileindex,
12774 repo, branch, base_commit_id,
12775 abort_progress, &upa);
12776 print_merge_progress_stats(&upa);
12777 goto done;
12782 error = histedit_check_script(&histedit_cmds, &commits, repo);
12783 if (error)
12784 goto done;
12786 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12787 if (resume_commit_id) {
12788 if (got_object_id_cmp(hle->commit_id,
12789 resume_commit_id) != 0)
12790 continue;
12792 resume_commit_id = NULL;
12793 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12794 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12795 error = histedit_skip_commit(hle, worktree,
12796 repo);
12797 if (error)
12798 goto done;
12799 } else {
12800 struct got_pathlist_head paths;
12801 int have_changes = 0;
12803 TAILQ_INIT(&paths);
12804 error = got_pathlist_append(&paths, "", NULL);
12805 if (error)
12806 goto done;
12807 error = got_worktree_status(worktree, &paths,
12808 repo, 0, check_local_changes, &have_changes,
12809 check_cancelled, NULL);
12810 got_pathlist_free(&paths,
12811 GOT_PATHLIST_FREE_NONE);
12812 if (error) {
12813 if (error->code != GOT_ERR_CANCELLED)
12814 goto done;
12815 if (sigint_received || sigpipe_received)
12816 goto done;
12818 if (have_changes) {
12819 error = histedit_commit(NULL, worktree,
12820 fileindex, tmp_branch, hle,
12821 committer, allow_conflict, repo);
12822 if (error)
12823 goto done;
12824 } else {
12825 error = got_object_open_as_commit(
12826 &commit, repo, hle->commit_id);
12827 if (error)
12828 goto done;
12829 error = show_histedit_progress(commit,
12830 hle, NULL);
12831 got_object_commit_close(commit);
12832 commit = NULL;
12833 if (error)
12834 goto done;
12837 continue;
12840 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12841 error = histedit_skip_commit(hle, worktree, repo);
12842 if (error)
12843 goto done;
12844 continue;
12847 error = got_object_open_as_commit(&commit, repo,
12848 hle->commit_id);
12849 if (error)
12850 goto done;
12851 parent_ids = got_object_commit_get_parent_ids(commit);
12852 pid = STAILQ_FIRST(parent_ids);
12854 error = got_worktree_histedit_merge_files(&merged_paths,
12855 worktree, fileindex, &pid->id, hle->commit_id, repo,
12856 update_progress, &upa, check_cancelled, NULL);
12857 if (error)
12858 goto done;
12859 got_object_commit_close(commit);
12860 commit = NULL;
12862 print_merge_progress_stats(&upa);
12863 if (upa.conflicts > 0 || upa.missing > 0 ||
12864 upa.not_deleted > 0 || upa.unversioned > 0) {
12865 if (upa.conflicts > 0) {
12866 error = show_rebase_merge_conflict(
12867 hle->commit_id, repo);
12868 if (error)
12869 goto done;
12871 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12872 break;
12875 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12876 char *id_str;
12877 error = got_object_id_str(&id_str, hle->commit_id);
12878 if (error)
12879 goto done;
12880 printf("Stopping histedit for amending commit %s\n",
12881 id_str);
12882 free(id_str);
12883 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12884 error = got_worktree_histedit_postpone(worktree,
12885 fileindex);
12886 goto done;
12889 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12890 error = histedit_skip_commit(hle, worktree, repo);
12891 if (error)
12892 goto done;
12893 continue;
12896 error = histedit_commit(&merged_paths, worktree, fileindex,
12897 tmp_branch, hle, committer, allow_conflict, repo);
12898 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12899 if (error)
12900 goto done;
12903 if (upa.conflicts > 0 || upa.missing > 0 ||
12904 upa.not_deleted > 0 || upa.unversioned > 0) {
12905 error = got_worktree_histedit_postpone(worktree, fileindex);
12906 if (error)
12907 goto done;
12908 if (upa.conflicts > 0 && upa.missing == 0 &&
12909 upa.not_deleted == 0 && upa.unversioned == 0) {
12910 error = got_error_msg(GOT_ERR_CONFLICTS,
12911 "conflicts must be resolved before histedit "
12912 "can continue");
12913 } else if (upa.conflicts > 0) {
12914 error = got_error_msg(GOT_ERR_CONFLICTS,
12915 "conflicts must be resolved before histedit "
12916 "can continue; changes destined for some "
12917 "files were not yet merged and should be "
12918 "merged manually if required before the "
12919 "histedit operation is continued");
12920 } else {
12921 error = got_error_msg(GOT_ERR_CONFLICTS,
12922 "changes destined for some files were not "
12923 "yet merged and should be merged manually "
12924 "if required before the histedit operation "
12925 "is continued");
12927 } else
12928 error = histedit_complete(worktree, fileindex, tmp_branch,
12929 branch, repo);
12930 done:
12931 free(cwd);
12932 free(committer);
12933 free(gitconfig_path);
12934 got_object_id_queue_free(&commits);
12935 histedit_free_list(&histedit_cmds);
12936 free(head_commit_id);
12937 free(base_commit_id);
12938 free(resume_commit_id);
12939 if (commit)
12940 got_object_commit_close(commit);
12941 if (branch)
12942 got_ref_close(branch);
12943 if (tmp_branch)
12944 got_ref_close(tmp_branch);
12945 if (worktree)
12946 got_worktree_close(worktree);
12947 if (repo) {
12948 const struct got_error *close_err = got_repo_close(repo);
12949 if (error == NULL)
12950 error = close_err;
12952 if (pack_fds) {
12953 const struct got_error *pack_err =
12954 got_repo_pack_fds_close(pack_fds);
12955 if (error == NULL)
12956 error = pack_err;
12958 return error;
12961 __dead static void
12962 usage_integrate(void)
12964 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12965 exit(1);
12968 static const struct got_error *
12969 cmd_integrate(int argc, char *argv[])
12971 const struct got_error *error = NULL;
12972 struct got_repository *repo = NULL;
12973 struct got_worktree *worktree = NULL;
12974 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12975 const char *branch_arg = NULL;
12976 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12977 struct got_fileindex *fileindex = NULL;
12978 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12979 int ch;
12980 struct got_update_progress_arg upa;
12981 int *pack_fds = NULL;
12983 #ifndef PROFILE
12984 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12985 "unveil", NULL) == -1)
12986 err(1, "pledge");
12987 #endif
12989 while ((ch = getopt(argc, argv, "")) != -1) {
12990 switch (ch) {
12991 default:
12992 usage_integrate();
12993 /* NOTREACHED */
12997 argc -= optind;
12998 argv += optind;
13000 if (argc != 1)
13001 usage_integrate();
13002 branch_arg = argv[0];
13004 cwd = getcwd(NULL, 0);
13005 if (cwd == NULL) {
13006 error = got_error_from_errno("getcwd");
13007 goto done;
13010 error = got_repo_pack_fds_open(&pack_fds);
13011 if (error != NULL)
13012 goto done;
13014 error = got_worktree_open(&worktree, cwd);
13015 if (error) {
13016 if (error->code == GOT_ERR_NOT_WORKTREE)
13017 error = wrap_not_worktree_error(error, "integrate",
13018 cwd);
13019 goto done;
13022 error = check_rebase_or_histedit_in_progress(worktree);
13023 if (error)
13024 goto done;
13026 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13027 NULL, pack_fds);
13028 if (error != NULL)
13029 goto done;
13031 error = apply_unveil(got_repo_get_path(repo), 0,
13032 got_worktree_get_root_path(worktree));
13033 if (error)
13034 goto done;
13036 error = check_merge_in_progress(worktree, repo);
13037 if (error)
13038 goto done;
13040 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13041 error = got_error_from_errno("asprintf");
13042 goto done;
13045 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13046 &base_branch_ref, worktree, refname, repo);
13047 if (error)
13048 goto done;
13050 refname = strdup(got_ref_get_name(branch_ref));
13051 if (refname == NULL) {
13052 error = got_error_from_errno("strdup");
13053 got_worktree_integrate_abort(worktree, fileindex, repo,
13054 branch_ref, base_branch_ref);
13055 goto done;
13057 base_refname = strdup(got_ref_get_name(base_branch_ref));
13058 if (base_refname == NULL) {
13059 error = got_error_from_errno("strdup");
13060 got_worktree_integrate_abort(worktree, fileindex, repo,
13061 branch_ref, base_branch_ref);
13062 goto done;
13064 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13065 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13066 got_worktree_integrate_abort(worktree, fileindex, repo,
13067 branch_ref, base_branch_ref);
13068 goto done;
13071 error = got_ref_resolve(&commit_id, repo, branch_ref);
13072 if (error)
13073 goto done;
13075 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13076 if (error)
13077 goto done;
13079 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13080 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13081 "specified branch has already been integrated");
13082 got_worktree_integrate_abort(worktree, fileindex, repo,
13083 branch_ref, base_branch_ref);
13084 goto done;
13087 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13088 if (error) {
13089 if (error->code == GOT_ERR_ANCESTRY)
13090 error = got_error(GOT_ERR_REBASE_REQUIRED);
13091 got_worktree_integrate_abort(worktree, fileindex, repo,
13092 branch_ref, base_branch_ref);
13093 goto done;
13096 memset(&upa, 0, sizeof(upa));
13097 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13098 branch_ref, base_branch_ref, update_progress, &upa,
13099 check_cancelled, NULL);
13100 if (error)
13101 goto done;
13103 printf("Integrated %s into %s\n", refname, base_refname);
13104 print_update_progress_stats(&upa);
13105 done:
13106 if (repo) {
13107 const struct got_error *close_err = got_repo_close(repo);
13108 if (error == NULL)
13109 error = close_err;
13111 if (worktree)
13112 got_worktree_close(worktree);
13113 if (pack_fds) {
13114 const struct got_error *pack_err =
13115 got_repo_pack_fds_close(pack_fds);
13116 if (error == NULL)
13117 error = pack_err;
13119 free(cwd);
13120 free(base_commit_id);
13121 free(commit_id);
13122 free(refname);
13123 free(base_refname);
13124 return error;
13127 __dead static void
13128 usage_merge(void)
13130 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13131 exit(1);
13134 static const struct got_error *
13135 cmd_merge(int argc, char *argv[])
13137 const struct got_error *error = NULL;
13138 struct got_worktree *worktree = NULL;
13139 struct got_repository *repo = NULL;
13140 struct got_fileindex *fileindex = NULL;
13141 char *cwd = NULL, *id_str = NULL, *author = NULL;
13142 char *gitconfig_path = NULL;
13143 struct got_reference *branch = NULL, *wt_branch = NULL;
13144 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13145 struct got_object_id *wt_branch_tip = NULL;
13146 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13147 int allow_conflict = 0, interrupt_merge = 0;
13148 struct got_update_progress_arg upa;
13149 struct got_object_id *merge_commit_id = NULL;
13150 char *branch_name = NULL;
13151 int *pack_fds = NULL;
13153 memset(&upa, 0, sizeof(upa));
13155 #ifndef PROFILE
13156 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13157 "unveil", NULL) == -1)
13158 err(1, "pledge");
13159 #endif
13161 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13162 switch (ch) {
13163 case 'a':
13164 abort_merge = 1;
13165 break;
13166 case 'C':
13167 allow_conflict = 1;
13168 case 'c':
13169 continue_merge = 1;
13170 break;
13171 case 'n':
13172 interrupt_merge = 1;
13173 break;
13174 default:
13175 usage_merge();
13176 /* NOTREACHED */
13180 argc -= optind;
13181 argv += optind;
13183 if (allow_conflict) {
13184 if (abort_merge)
13185 option_conflict('a', 'C');
13186 if (!continue_merge)
13187 errx(1, "-C option requires -c");
13189 if (abort_merge && continue_merge)
13190 option_conflict('a', 'c');
13191 if (abort_merge || continue_merge) {
13192 if (argc != 0)
13193 usage_merge();
13194 } else if (argc != 1)
13195 usage_merge();
13197 cwd = getcwd(NULL, 0);
13198 if (cwd == NULL) {
13199 error = got_error_from_errno("getcwd");
13200 goto done;
13203 error = got_repo_pack_fds_open(&pack_fds);
13204 if (error != NULL)
13205 goto done;
13207 error = got_worktree_open(&worktree, cwd);
13208 if (error) {
13209 if (error->code == GOT_ERR_NOT_WORKTREE)
13210 error = wrap_not_worktree_error(error,
13211 "merge", cwd);
13212 goto done;
13215 error = get_gitconfig_path(&gitconfig_path);
13216 if (error)
13217 goto done;
13218 error = got_repo_open(&repo,
13219 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13220 gitconfig_path, pack_fds);
13221 if (error != NULL)
13222 goto done;
13224 if (worktree != NULL) {
13225 error = worktree_has_logmsg_ref("merge", worktree, repo);
13226 if (error)
13227 goto done;
13230 error = apply_unveil(got_repo_get_path(repo), 0,
13231 worktree ? got_worktree_get_root_path(worktree) : NULL);
13232 if (error)
13233 goto done;
13235 error = check_rebase_or_histedit_in_progress(worktree);
13236 if (error)
13237 goto done;
13239 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13240 repo);
13241 if (error)
13242 goto done;
13244 if (merge_in_progress && !(abort_merge || continue_merge)) {
13245 error = got_error(GOT_ERR_MERGE_BUSY);
13246 goto done;
13249 if (!merge_in_progress && (abort_merge || continue_merge)) {
13250 error = got_error(GOT_ERR_NOT_MERGING);
13251 goto done;
13254 if (abort_merge) {
13255 error = got_worktree_merge_continue(&branch_name,
13256 &branch_tip, &fileindex, worktree, repo);
13257 if (error)
13258 goto done;
13259 error = got_worktree_merge_abort(worktree, fileindex, repo,
13260 abort_progress, &upa);
13261 if (error)
13262 goto done;
13263 printf("Merge of %s aborted\n", branch_name);
13264 goto done; /* nothing else to do */
13267 error = get_author(&author, repo, worktree);
13268 if (error)
13269 goto done;
13271 error = got_ref_open(&wt_branch, repo,
13272 got_worktree_get_head_ref_name(worktree), 0);
13273 if (error)
13274 goto done;
13275 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13276 if (error)
13277 goto done;
13279 if (continue_merge) {
13280 struct got_object_id *base_commit_id;
13281 base_commit_id = got_worktree_get_base_commit_id(worktree);
13282 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13283 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13284 goto done;
13286 error = got_worktree_merge_continue(&branch_name,
13287 &branch_tip, &fileindex, worktree, repo);
13288 if (error)
13289 goto done;
13290 } else {
13291 error = got_ref_open(&branch, repo, argv[0], 0);
13292 if (error != NULL)
13293 goto done;
13294 branch_name = strdup(got_ref_get_name(branch));
13295 if (branch_name == NULL) {
13296 error = got_error_from_errno("strdup");
13297 goto done;
13299 error = got_ref_resolve(&branch_tip, repo, branch);
13300 if (error)
13301 goto done;
13304 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13305 wt_branch_tip, branch_tip, 0, repo,
13306 check_cancelled, NULL);
13307 if (error && error->code != GOT_ERR_ANCESTRY)
13308 goto done;
13310 if (!continue_merge) {
13311 error = check_path_prefix(wt_branch_tip, branch_tip,
13312 got_worktree_get_path_prefix(worktree),
13313 GOT_ERR_MERGE_PATH, repo);
13314 if (error)
13315 goto done;
13316 if (yca_id && got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13317 static char msg[512];
13318 snprintf(msg, sizeof(msg),
13319 "cannot create a merge commit because %s is based "
13320 "on %s; %s can be integrated with 'got integrate' "
13321 "instead", branch_name,
13322 got_worktree_get_head_ref_name(worktree),
13323 branch_name);
13324 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13325 goto done;
13327 error = got_worktree_merge_prepare(&fileindex, worktree,
13328 branch, repo);
13329 if (error)
13330 goto done;
13332 error = got_worktree_merge_branch(worktree, fileindex,
13333 yca_id, branch_tip, repo, update_progress, &upa,
13334 check_cancelled, NULL);
13335 if (error)
13336 goto done;
13337 print_merge_progress_stats(&upa);
13338 if (!upa.did_something) {
13339 error = got_worktree_merge_abort(worktree, fileindex,
13340 repo, abort_progress, &upa);
13341 if (error)
13342 goto done;
13343 printf("Already up-to-date\n");
13344 goto done;
13348 if (interrupt_merge) {
13349 error = got_worktree_merge_postpone(worktree, fileindex);
13350 if (error)
13351 goto done;
13352 printf("Merge of %s interrupted on request\n", branch_name);
13353 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13354 upa.not_deleted > 0 || upa.unversioned > 0) {
13355 error = got_worktree_merge_postpone(worktree, fileindex);
13356 if (error)
13357 goto done;
13358 if (upa.conflicts > 0 && upa.missing == 0 &&
13359 upa.not_deleted == 0 && upa.unversioned == 0) {
13360 error = got_error_msg(GOT_ERR_CONFLICTS,
13361 "conflicts must be resolved before merging "
13362 "can continue");
13363 } else if (upa.conflicts > 0) {
13364 error = got_error_msg(GOT_ERR_CONFLICTS,
13365 "conflicts must be resolved before merging "
13366 "can continue; changes destined for some "
13367 "files were not yet merged and "
13368 "should be merged manually if required before the "
13369 "merge operation is continued");
13370 } else {
13371 error = got_error_msg(GOT_ERR_CONFLICTS,
13372 "changes destined for some "
13373 "files were not yet merged and should be "
13374 "merged manually if required before the "
13375 "merge operation is continued");
13377 goto done;
13378 } else {
13379 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13380 fileindex, author, NULL, 1, branch_tip, branch_name,
13381 allow_conflict, repo, continue_merge ? print_status : NULL,
13382 NULL);
13383 if (error)
13384 goto done;
13385 error = got_worktree_merge_complete(worktree, fileindex, repo);
13386 if (error)
13387 goto done;
13388 error = got_object_id_str(&id_str, merge_commit_id);
13389 if (error)
13390 goto done;
13391 printf("Merged %s into %s: %s\n", branch_name,
13392 got_worktree_get_head_ref_name(worktree),
13393 id_str);
13396 done:
13397 free(gitconfig_path);
13398 free(id_str);
13399 free(merge_commit_id);
13400 free(author);
13401 free(branch_tip);
13402 free(branch_name);
13403 free(yca_id);
13404 if (branch)
13405 got_ref_close(branch);
13406 if (wt_branch)
13407 got_ref_close(wt_branch);
13408 if (worktree)
13409 got_worktree_close(worktree);
13410 if (repo) {
13411 const struct got_error *close_err = got_repo_close(repo);
13412 if (error == NULL)
13413 error = close_err;
13415 if (pack_fds) {
13416 const struct got_error *pack_err =
13417 got_repo_pack_fds_close(pack_fds);
13418 if (error == NULL)
13419 error = pack_err;
13421 return error;
13424 __dead static void
13425 usage_stage(void)
13427 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13428 "[path ...]\n", getprogname());
13429 exit(1);
13432 static const struct got_error *
13433 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13434 const char *path, struct got_object_id *blob_id,
13435 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13436 int dirfd, const char *de_name)
13438 const struct got_error *err = NULL;
13439 char *id_str = NULL;
13441 if (staged_status != GOT_STATUS_ADD &&
13442 staged_status != GOT_STATUS_MODIFY &&
13443 staged_status != GOT_STATUS_DELETE)
13444 return NULL;
13446 if (staged_status == GOT_STATUS_ADD ||
13447 staged_status == GOT_STATUS_MODIFY)
13448 err = got_object_id_str(&id_str, staged_blob_id);
13449 else
13450 err = got_object_id_str(&id_str, blob_id);
13451 if (err)
13452 return err;
13454 printf("%s %c %s\n", id_str, staged_status, path);
13455 free(id_str);
13456 return NULL;
13459 static const struct got_error *
13460 cmd_stage(int argc, char *argv[])
13462 const struct got_error *error = NULL;
13463 struct got_repository *repo = NULL;
13464 struct got_worktree *worktree = NULL;
13465 char *cwd = NULL;
13466 struct got_pathlist_head paths;
13467 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13468 FILE *patch_script_file = NULL;
13469 const char *patch_script_path = NULL;
13470 struct choose_patch_arg cpa;
13471 int *pack_fds = NULL;
13473 TAILQ_INIT(&paths);
13475 #ifndef PROFILE
13476 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13477 "unveil", NULL) == -1)
13478 err(1, "pledge");
13479 #endif
13481 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13482 switch (ch) {
13483 case 'F':
13484 patch_script_path = optarg;
13485 break;
13486 case 'l':
13487 list_stage = 1;
13488 break;
13489 case 'p':
13490 pflag = 1;
13491 break;
13492 case 'S':
13493 allow_bad_symlinks = 1;
13494 break;
13495 default:
13496 usage_stage();
13497 /* NOTREACHED */
13501 argc -= optind;
13502 argv += optind;
13504 if (list_stage && (pflag || patch_script_path))
13505 errx(1, "-l option cannot be used with other options");
13506 if (patch_script_path && !pflag)
13507 errx(1, "-F option can only be used together with -p option");
13509 cwd = getcwd(NULL, 0);
13510 if (cwd == NULL) {
13511 error = got_error_from_errno("getcwd");
13512 goto done;
13515 error = got_repo_pack_fds_open(&pack_fds);
13516 if (error != NULL)
13517 goto done;
13519 error = got_worktree_open(&worktree, cwd);
13520 if (error) {
13521 if (error->code == GOT_ERR_NOT_WORKTREE)
13522 error = wrap_not_worktree_error(error, "stage", cwd);
13523 goto done;
13526 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13527 NULL, pack_fds);
13528 if (error != NULL)
13529 goto done;
13531 if (patch_script_path) {
13532 patch_script_file = fopen(patch_script_path, "re");
13533 if (patch_script_file == NULL) {
13534 error = got_error_from_errno2("fopen",
13535 patch_script_path);
13536 goto done;
13539 error = apply_unveil(got_repo_get_path(repo), 0,
13540 got_worktree_get_root_path(worktree));
13541 if (error)
13542 goto done;
13544 error = check_merge_in_progress(worktree, repo);
13545 if (error)
13546 goto done;
13548 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13549 if (error)
13550 goto done;
13552 if (list_stage)
13553 error = got_worktree_status(worktree, &paths, repo, 0,
13554 print_stage, NULL, check_cancelled, NULL);
13555 else {
13556 cpa.patch_script_file = patch_script_file;
13557 cpa.action = "stage";
13558 error = got_worktree_stage(worktree, &paths,
13559 pflag ? NULL : print_status, NULL,
13560 pflag ? choose_patch : NULL, &cpa,
13561 allow_bad_symlinks, repo);
13563 done:
13564 if (patch_script_file && fclose(patch_script_file) == EOF &&
13565 error == NULL)
13566 error = got_error_from_errno2("fclose", patch_script_path);
13567 if (repo) {
13568 const struct got_error *close_err = got_repo_close(repo);
13569 if (error == NULL)
13570 error = close_err;
13572 if (worktree)
13573 got_worktree_close(worktree);
13574 if (pack_fds) {
13575 const struct got_error *pack_err =
13576 got_repo_pack_fds_close(pack_fds);
13577 if (error == NULL)
13578 error = pack_err;
13580 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13581 free(cwd);
13582 return error;
13585 __dead static void
13586 usage_unstage(void)
13588 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13589 "[path ...]\n", getprogname());
13590 exit(1);
13594 static const struct got_error *
13595 cmd_unstage(int argc, char *argv[])
13597 const struct got_error *error = NULL;
13598 struct got_repository *repo = NULL;
13599 struct got_worktree *worktree = NULL;
13600 char *cwd = NULL;
13601 struct got_pathlist_head paths;
13602 int ch, pflag = 0;
13603 struct got_update_progress_arg upa;
13604 FILE *patch_script_file = NULL;
13605 const char *patch_script_path = NULL;
13606 struct choose_patch_arg cpa;
13607 int *pack_fds = NULL;
13609 TAILQ_INIT(&paths);
13611 #ifndef PROFILE
13612 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13613 "unveil", NULL) == -1)
13614 err(1, "pledge");
13615 #endif
13617 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13618 switch (ch) {
13619 case 'F':
13620 patch_script_path = optarg;
13621 break;
13622 case 'p':
13623 pflag = 1;
13624 break;
13625 default:
13626 usage_unstage();
13627 /* NOTREACHED */
13631 argc -= optind;
13632 argv += optind;
13634 if (patch_script_path && !pflag)
13635 errx(1, "-F option can only be used together with -p option");
13637 cwd = getcwd(NULL, 0);
13638 if (cwd == NULL) {
13639 error = got_error_from_errno("getcwd");
13640 goto done;
13643 error = got_repo_pack_fds_open(&pack_fds);
13644 if (error != NULL)
13645 goto done;
13647 error = got_worktree_open(&worktree, cwd);
13648 if (error) {
13649 if (error->code == GOT_ERR_NOT_WORKTREE)
13650 error = wrap_not_worktree_error(error, "unstage", cwd);
13651 goto done;
13654 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13655 NULL, pack_fds);
13656 if (error != NULL)
13657 goto done;
13659 if (patch_script_path) {
13660 patch_script_file = fopen(patch_script_path, "re");
13661 if (patch_script_file == NULL) {
13662 error = got_error_from_errno2("fopen",
13663 patch_script_path);
13664 goto done;
13668 error = apply_unveil(got_repo_get_path(repo), 0,
13669 got_worktree_get_root_path(worktree));
13670 if (error)
13671 goto done;
13673 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13674 if (error)
13675 goto done;
13677 cpa.patch_script_file = patch_script_file;
13678 cpa.action = "unstage";
13679 memset(&upa, 0, sizeof(upa));
13680 error = got_worktree_unstage(worktree, &paths, update_progress,
13681 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13682 if (!error)
13683 print_merge_progress_stats(&upa);
13684 done:
13685 if (patch_script_file && fclose(patch_script_file) == EOF &&
13686 error == NULL)
13687 error = got_error_from_errno2("fclose", patch_script_path);
13688 if (repo) {
13689 const struct got_error *close_err = got_repo_close(repo);
13690 if (error == NULL)
13691 error = close_err;
13693 if (worktree)
13694 got_worktree_close(worktree);
13695 if (pack_fds) {
13696 const struct got_error *pack_err =
13697 got_repo_pack_fds_close(pack_fds);
13698 if (error == NULL)
13699 error = pack_err;
13701 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13702 free(cwd);
13703 return error;
13706 __dead static void
13707 usage_cat(void)
13709 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13710 "arg ...\n", getprogname());
13711 exit(1);
13714 static const struct got_error *
13715 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13717 const struct got_error *err;
13718 struct got_blob_object *blob;
13719 int fd = -1;
13721 fd = got_opentempfd();
13722 if (fd == -1)
13723 return got_error_from_errno("got_opentempfd");
13725 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13726 if (err)
13727 goto done;
13729 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13730 done:
13731 if (fd != -1 && close(fd) == -1 && err == NULL)
13732 err = got_error_from_errno("close");
13733 if (blob)
13734 got_object_blob_close(blob);
13735 return err;
13738 static const struct got_error *
13739 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13741 const struct got_error *err;
13742 struct got_tree_object *tree;
13743 int nentries, i;
13745 err = got_object_open_as_tree(&tree, repo, id);
13746 if (err)
13747 return err;
13749 nentries = got_object_tree_get_nentries(tree);
13750 for (i = 0; i < nentries; i++) {
13751 struct got_tree_entry *te;
13752 char *id_str;
13753 if (sigint_received || sigpipe_received)
13754 break;
13755 te = got_object_tree_get_entry(tree, i);
13756 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13757 if (err)
13758 break;
13759 fprintf(outfile, "%s %.7o %s\n", id_str,
13760 got_tree_entry_get_mode(te),
13761 got_tree_entry_get_name(te));
13762 free(id_str);
13765 got_object_tree_close(tree);
13766 return err;
13769 static const struct got_error *
13770 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13772 const struct got_error *err;
13773 struct got_commit_object *commit;
13774 const struct got_object_id_queue *parent_ids;
13775 struct got_object_qid *pid;
13776 char *id_str = NULL;
13777 const char *logmsg = NULL;
13778 char gmtoff[6];
13780 err = got_object_open_as_commit(&commit, repo, id);
13781 if (err)
13782 return err;
13784 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13785 if (err)
13786 goto done;
13788 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13789 parent_ids = got_object_commit_get_parent_ids(commit);
13790 fprintf(outfile, "numparents %d\n",
13791 got_object_commit_get_nparents(commit));
13792 STAILQ_FOREACH(pid, parent_ids, entry) {
13793 char *pid_str;
13794 err = got_object_id_str(&pid_str, &pid->id);
13795 if (err)
13796 goto done;
13797 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13798 free(pid_str);
13800 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13801 got_object_commit_get_author_gmtoff(commit));
13802 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13803 got_object_commit_get_author(commit),
13804 (long long)got_object_commit_get_author_time(commit),
13805 gmtoff);
13807 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13808 got_object_commit_get_committer_gmtoff(commit));
13809 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13810 got_object_commit_get_committer(commit),
13811 (long long)got_object_commit_get_committer_time(commit),
13812 gmtoff);
13814 logmsg = got_object_commit_get_logmsg_raw(commit);
13815 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13816 fprintf(outfile, "%s", logmsg);
13817 done:
13818 free(id_str);
13819 got_object_commit_close(commit);
13820 return err;
13823 static const struct got_error *
13824 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13826 const struct got_error *err;
13827 struct got_tag_object *tag;
13828 char *id_str = NULL;
13829 const char *tagmsg = NULL;
13830 char gmtoff[6];
13832 err = got_object_open_as_tag(&tag, repo, id);
13833 if (err)
13834 return err;
13836 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13837 if (err)
13838 goto done;
13840 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13842 switch (got_object_tag_get_object_type(tag)) {
13843 case GOT_OBJ_TYPE_BLOB:
13844 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13845 GOT_OBJ_LABEL_BLOB);
13846 break;
13847 case GOT_OBJ_TYPE_TREE:
13848 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13849 GOT_OBJ_LABEL_TREE);
13850 break;
13851 case GOT_OBJ_TYPE_COMMIT:
13852 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13853 GOT_OBJ_LABEL_COMMIT);
13854 break;
13855 case GOT_OBJ_TYPE_TAG:
13856 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13857 GOT_OBJ_LABEL_TAG);
13858 break;
13859 default:
13860 break;
13863 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13864 got_object_tag_get_name(tag));
13866 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13867 got_object_tag_get_tagger_gmtoff(tag));
13868 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13869 got_object_tag_get_tagger(tag),
13870 (long long)got_object_tag_get_tagger_time(tag),
13871 gmtoff);
13873 tagmsg = got_object_tag_get_message(tag);
13874 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13875 fprintf(outfile, "%s", tagmsg);
13876 done:
13877 free(id_str);
13878 got_object_tag_close(tag);
13879 return err;
13882 static const struct got_error *
13883 cmd_cat(int argc, char *argv[])
13885 const struct got_error *error;
13886 struct got_repository *repo = NULL;
13887 struct got_worktree *worktree = NULL;
13888 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13889 const char *commit_id_str = NULL;
13890 struct got_object_id *id = NULL, *commit_id = NULL;
13891 struct got_commit_object *commit = NULL;
13892 int ch, obj_type, i, force_path = 0;
13893 struct got_reflist_head refs;
13894 int *pack_fds = NULL;
13896 TAILQ_INIT(&refs);
13898 #ifndef PROFILE
13899 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13900 NULL) == -1)
13901 err(1, "pledge");
13902 #endif
13904 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13905 switch (ch) {
13906 case 'c':
13907 commit_id_str = optarg;
13908 break;
13909 case 'P':
13910 force_path = 1;
13911 break;
13912 case 'r':
13913 repo_path = realpath(optarg, NULL);
13914 if (repo_path == NULL)
13915 return got_error_from_errno2("realpath",
13916 optarg);
13917 got_path_strip_trailing_slashes(repo_path);
13918 break;
13919 default:
13920 usage_cat();
13921 /* NOTREACHED */
13925 argc -= optind;
13926 argv += optind;
13928 cwd = getcwd(NULL, 0);
13929 if (cwd == NULL) {
13930 error = got_error_from_errno("getcwd");
13931 goto done;
13934 error = got_repo_pack_fds_open(&pack_fds);
13935 if (error != NULL)
13936 goto done;
13938 if (repo_path == NULL) {
13939 error = got_worktree_open(&worktree, cwd);
13940 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13941 goto done;
13942 if (worktree) {
13943 repo_path = strdup(
13944 got_worktree_get_repo_path(worktree));
13945 if (repo_path == NULL) {
13946 error = got_error_from_errno("strdup");
13947 goto done;
13950 /* Release work tree lock. */
13951 got_worktree_close(worktree);
13952 worktree = NULL;
13956 if (repo_path == NULL) {
13957 repo_path = strdup(cwd);
13958 if (repo_path == NULL)
13959 return got_error_from_errno("strdup");
13962 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13963 free(repo_path);
13964 if (error != NULL)
13965 goto done;
13967 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13968 if (error)
13969 goto done;
13971 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13972 if (error)
13973 goto done;
13975 if (commit_id_str == NULL)
13976 commit_id_str = GOT_REF_HEAD;
13977 error = got_repo_match_object_id(&commit_id, NULL,
13978 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13979 if (error)
13980 goto done;
13982 error = got_object_open_as_commit(&commit, repo, commit_id);
13983 if (error)
13984 goto done;
13986 for (i = 0; i < argc; i++) {
13987 if (force_path) {
13988 error = got_object_id_by_path(&id, repo, commit,
13989 argv[i]);
13990 if (error)
13991 break;
13992 } else {
13993 error = got_repo_match_object_id(&id, &label, argv[i],
13994 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13995 repo);
13996 if (error) {
13997 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13998 error->code != GOT_ERR_NOT_REF)
13999 break;
14000 error = got_object_id_by_path(&id, repo,
14001 commit, argv[i]);
14002 if (error)
14003 break;
14007 error = got_object_get_type(&obj_type, repo, id);
14008 if (error)
14009 break;
14011 switch (obj_type) {
14012 case GOT_OBJ_TYPE_BLOB:
14013 error = cat_blob(id, repo, stdout);
14014 break;
14015 case GOT_OBJ_TYPE_TREE:
14016 error = cat_tree(id, repo, stdout);
14017 break;
14018 case GOT_OBJ_TYPE_COMMIT:
14019 error = cat_commit(id, repo, stdout);
14020 break;
14021 case GOT_OBJ_TYPE_TAG:
14022 error = cat_tag(id, repo, stdout);
14023 break;
14024 default:
14025 error = got_error(GOT_ERR_OBJ_TYPE);
14026 break;
14028 if (error)
14029 break;
14030 free(label);
14031 label = NULL;
14032 free(id);
14033 id = NULL;
14035 done:
14036 free(label);
14037 free(id);
14038 free(commit_id);
14039 if (commit)
14040 got_object_commit_close(commit);
14041 if (worktree)
14042 got_worktree_close(worktree);
14043 if (repo) {
14044 const struct got_error *close_err = got_repo_close(repo);
14045 if (error == NULL)
14046 error = close_err;
14048 if (pack_fds) {
14049 const struct got_error *pack_err =
14050 got_repo_pack_fds_close(pack_fds);
14051 if (error == NULL)
14052 error = pack_err;
14055 got_ref_list_free(&refs);
14056 return error;
14059 __dead static void
14060 usage_info(void)
14062 fprintf(stderr, "usage: %s info [path ...]\n",
14063 getprogname());
14064 exit(1);
14067 static const struct got_error *
14068 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14069 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14070 struct got_object_id *commit_id)
14072 const struct got_error *err = NULL;
14073 char *id_str = NULL;
14074 char datebuf[128];
14075 struct tm mytm, *tm;
14076 struct got_pathlist_head *paths = arg;
14077 struct got_pathlist_entry *pe;
14080 * Clear error indication from any of the path arguments which
14081 * would cause this file index entry to be displayed.
14083 TAILQ_FOREACH(pe, paths, entry) {
14084 if (got_path_cmp(path, pe->path, strlen(path),
14085 pe->path_len) == 0 ||
14086 got_path_is_child(path, pe->path, pe->path_len))
14087 pe->data = NULL; /* no error */
14090 printf(GOT_COMMIT_SEP_STR);
14091 if (S_ISLNK(mode))
14092 printf("symlink: %s\n", path);
14093 else if (S_ISREG(mode)) {
14094 printf("file: %s\n", path);
14095 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14096 } else if (S_ISDIR(mode))
14097 printf("directory: %s\n", path);
14098 else
14099 printf("something: %s\n", path);
14101 tm = localtime_r(&mtime, &mytm);
14102 if (tm == NULL)
14103 return NULL;
14104 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14105 return got_error(GOT_ERR_NO_SPACE);
14106 printf("timestamp: %s\n", datebuf);
14108 if (blob_id) {
14109 err = got_object_id_str(&id_str, blob_id);
14110 if (err)
14111 return err;
14112 printf("based on blob: %s\n", id_str);
14113 free(id_str);
14116 if (staged_blob_id) {
14117 err = got_object_id_str(&id_str, staged_blob_id);
14118 if (err)
14119 return err;
14120 printf("based on staged blob: %s\n", id_str);
14121 free(id_str);
14124 if (commit_id) {
14125 err = got_object_id_str(&id_str, commit_id);
14126 if (err)
14127 return err;
14128 printf("based on commit: %s\n", id_str);
14129 free(id_str);
14132 return NULL;
14135 static const struct got_error *
14136 cmd_info(int argc, char *argv[])
14138 const struct got_error *error = NULL;
14139 struct got_worktree *worktree = NULL;
14140 char *cwd = NULL, *id_str = NULL;
14141 struct got_pathlist_head paths;
14142 char *uuidstr = NULL;
14143 int ch, show_files = 0;
14145 TAILQ_INIT(&paths);
14147 #ifndef PROFILE
14148 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14149 NULL) == -1)
14150 err(1, "pledge");
14151 #endif
14153 while ((ch = getopt(argc, argv, "")) != -1) {
14154 switch (ch) {
14155 default:
14156 usage_info();
14157 /* NOTREACHED */
14161 argc -= optind;
14162 argv += optind;
14164 cwd = getcwd(NULL, 0);
14165 if (cwd == NULL) {
14166 error = got_error_from_errno("getcwd");
14167 goto done;
14170 error = got_worktree_open(&worktree, cwd);
14171 if (error) {
14172 if (error->code == GOT_ERR_NOT_WORKTREE)
14173 error = wrap_not_worktree_error(error, "info", cwd);
14174 goto done;
14177 #ifndef PROFILE
14178 /* Remove "wpath cpath proc exec sendfd" promises. */
14179 if (pledge("stdio rpath flock unveil", NULL) == -1)
14180 err(1, "pledge");
14181 #endif
14182 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14183 if (error)
14184 goto done;
14186 if (argc >= 1) {
14187 error = get_worktree_paths_from_argv(&paths, argc, argv,
14188 worktree);
14189 if (error)
14190 goto done;
14191 show_files = 1;
14194 error = got_object_id_str(&id_str,
14195 got_worktree_get_base_commit_id(worktree));
14196 if (error)
14197 goto done;
14199 error = got_worktree_get_uuid(&uuidstr, worktree);
14200 if (error)
14201 goto done;
14203 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14204 printf("work tree base commit: %s\n", id_str);
14205 printf("work tree path prefix: %s\n",
14206 got_worktree_get_path_prefix(worktree));
14207 printf("work tree branch reference: %s\n",
14208 got_worktree_get_head_ref_name(worktree));
14209 printf("work tree UUID: %s\n", uuidstr);
14210 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14212 if (show_files) {
14213 struct got_pathlist_entry *pe;
14214 TAILQ_FOREACH(pe, &paths, entry) {
14215 if (pe->path_len == 0)
14216 continue;
14218 * Assume this path will fail. This will be corrected
14219 * in print_path_info() in case the path does suceeed.
14221 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14223 error = got_worktree_path_info(worktree, &paths,
14224 print_path_info, &paths, check_cancelled, NULL);
14225 if (error)
14226 goto done;
14227 TAILQ_FOREACH(pe, &paths, entry) {
14228 if (pe->data != NULL) {
14229 const struct got_error *perr;
14231 perr = pe->data;
14232 error = got_error_fmt(perr->code, "%s",
14233 pe->path);
14234 break;
14238 done:
14239 if (worktree)
14240 got_worktree_close(worktree);
14241 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14242 free(cwd);
14243 free(id_str);
14244 free(uuidstr);
14245 return error;