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_object_id *yca_id,
2906 struct got_repository *repo)
2908 const struct got_error *err = NULL;
2909 struct got_commit_graph *graph = NULL;
2910 struct got_object_id *head_commit_id = NULL;
2911 int is_same_branch = 0;
2913 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2914 if (err)
2915 goto done;
2917 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2918 is_same_branch = 1;
2919 goto done;
2921 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2922 is_same_branch = 1;
2923 goto done;
2926 err = got_commit_graph_open(&graph, "/", 1);
2927 if (err)
2928 goto done;
2930 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2931 check_cancelled, NULL);
2932 if (err)
2933 goto done;
2935 for (;;) {
2936 struct got_object_id id;
2938 err = got_commit_graph_iter_next(&id, graph, repo,
2939 check_cancelled, NULL);
2940 if (err) {
2941 if (err->code == GOT_ERR_ITER_COMPLETED)
2942 err = NULL;
2943 break;
2946 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2947 break;
2948 if (got_object_id_cmp(&id, commit_id) == 0) {
2949 is_same_branch = 1;
2950 break;
2953 done:
2954 if (graph)
2955 got_commit_graph_close(graph);
2956 free(head_commit_id);
2957 if (!err && !is_same_branch)
2958 err = got_error(GOT_ERR_ANCESTRY);
2959 return err;
2962 static const struct got_error *
2963 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2965 static char msg[512];
2966 const char *branch_name;
2968 if (got_ref_is_symbolic(ref))
2969 branch_name = got_ref_get_symref_target(ref);
2970 else
2971 branch_name = got_ref_get_name(ref);
2973 if (strncmp("refs/heads/", branch_name, 11) == 0)
2974 branch_name += 11;
2976 snprintf(msg, sizeof(msg),
2977 "target commit is not contained in branch '%s'; "
2978 "the branch to use must be specified with -b; "
2979 "if necessary a new branch can be created for "
2980 "this commit with 'got branch -c %s BRANCH_NAME'",
2981 branch_name, commit_id_str);
2983 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2986 static const struct got_error *
2987 cmd_checkout(int argc, char *argv[])
2989 const struct got_error *error = NULL;
2990 struct got_repository *repo = NULL;
2991 struct got_reference *head_ref = NULL, *ref = NULL;
2992 struct got_worktree *worktree = NULL;
2993 char *repo_path = NULL;
2994 char *worktree_path = NULL;
2995 const char *path_prefix = "";
2996 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2997 char *commit_id_str = NULL;
2998 struct got_object_id *commit_id = NULL;
2999 char *cwd = NULL;
3000 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3001 struct got_pathlist_head paths;
3002 struct got_checkout_progress_arg cpa;
3003 int *pack_fds = NULL;
3005 TAILQ_INIT(&paths);
3007 #ifndef PROFILE
3008 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3009 "unveil", NULL) == -1)
3010 err(1, "pledge");
3011 #endif
3013 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3014 switch (ch) {
3015 case 'b':
3016 branch_name = optarg;
3017 break;
3018 case 'c':
3019 commit_id_str = strdup(optarg);
3020 if (commit_id_str == NULL)
3021 return got_error_from_errno("strdup");
3022 break;
3023 case 'E':
3024 allow_nonempty = 1;
3025 break;
3026 case 'p':
3027 path_prefix = optarg;
3028 break;
3029 case 'q':
3030 verbosity = -1;
3031 break;
3032 default:
3033 usage_checkout();
3034 /* NOTREACHED */
3038 argc -= optind;
3039 argv += optind;
3041 if (argc == 1) {
3042 char *base, *dotgit;
3043 const char *path;
3044 repo_path = realpath(argv[0], NULL);
3045 if (repo_path == NULL)
3046 return got_error_from_errno2("realpath", argv[0]);
3047 cwd = getcwd(NULL, 0);
3048 if (cwd == NULL) {
3049 error = got_error_from_errno("getcwd");
3050 goto done;
3052 if (path_prefix[0])
3053 path = path_prefix;
3054 else
3055 path = repo_path;
3056 error = got_path_basename(&base, path);
3057 if (error)
3058 goto done;
3059 dotgit = strstr(base, ".git");
3060 if (dotgit)
3061 *dotgit = '\0';
3062 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3063 error = got_error_from_errno("asprintf");
3064 free(base);
3065 goto done;
3067 free(base);
3068 } else if (argc == 2) {
3069 repo_path = realpath(argv[0], NULL);
3070 if (repo_path == NULL) {
3071 error = got_error_from_errno2("realpath", argv[0]);
3072 goto done;
3074 worktree_path = realpath(argv[1], NULL);
3075 if (worktree_path == NULL) {
3076 if (errno != ENOENT) {
3077 error = got_error_from_errno2("realpath",
3078 argv[1]);
3079 goto done;
3081 worktree_path = strdup(argv[1]);
3082 if (worktree_path == NULL) {
3083 error = got_error_from_errno("strdup");
3084 goto done;
3087 } else
3088 usage_checkout();
3090 got_path_strip_trailing_slashes(repo_path);
3091 got_path_strip_trailing_slashes(worktree_path);
3093 error = got_repo_pack_fds_open(&pack_fds);
3094 if (error != NULL)
3095 goto done;
3097 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3098 if (error != NULL)
3099 goto done;
3101 /* Pre-create work tree path for unveil(2) */
3102 error = got_path_mkdir(worktree_path);
3103 if (error) {
3104 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3105 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3106 goto done;
3107 if (!allow_nonempty &&
3108 !got_path_dir_is_empty(worktree_path)) {
3109 error = got_error_path(worktree_path,
3110 GOT_ERR_DIR_NOT_EMPTY);
3111 goto done;
3115 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3116 if (error)
3117 goto done;
3119 error = got_ref_open(&head_ref, repo, branch_name, 0);
3120 if (error != NULL)
3121 goto done;
3123 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3124 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3125 goto done;
3127 error = got_worktree_open(&worktree, worktree_path);
3128 if (error != NULL)
3129 goto done;
3131 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3132 path_prefix);
3133 if (error != NULL)
3134 goto done;
3135 if (!same_path_prefix) {
3136 error = got_error(GOT_ERR_PATH_PREFIX);
3137 goto done;
3140 if (commit_id_str) {
3141 struct got_reflist_head refs;
3142 TAILQ_INIT(&refs);
3143 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3144 NULL);
3145 if (error)
3146 goto done;
3147 error = got_repo_match_object_id(&commit_id, NULL,
3148 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3149 got_ref_list_free(&refs);
3150 if (error)
3151 goto done;
3152 error = check_linear_ancestry(commit_id,
3153 got_worktree_get_base_commit_id(worktree), 0, repo);
3154 if (error != NULL) {
3155 if (error->code == GOT_ERR_ANCESTRY) {
3156 error = checkout_ancestry_error(
3157 head_ref, commit_id_str);
3159 goto done;
3161 error = check_same_branch(commit_id, head_ref, NULL, repo);
3162 if (error) {
3163 if (error->code == GOT_ERR_ANCESTRY) {
3164 error = checkout_ancestry_error(
3165 head_ref, commit_id_str);
3167 goto done;
3169 error = got_worktree_set_base_commit_id(worktree, repo,
3170 commit_id);
3171 if (error)
3172 goto done;
3173 /* Expand potentially abbreviated commit ID string. */
3174 free(commit_id_str);
3175 error = got_object_id_str(&commit_id_str, commit_id);
3176 if (error)
3177 goto done;
3178 } else {
3179 commit_id = got_object_id_dup(
3180 got_worktree_get_base_commit_id(worktree));
3181 if (commit_id == NULL) {
3182 error = got_error_from_errno("got_object_id_dup");
3183 goto done;
3185 error = got_object_id_str(&commit_id_str, commit_id);
3186 if (error)
3187 goto done;
3190 error = got_pathlist_append(&paths, "", NULL);
3191 if (error)
3192 goto done;
3193 cpa.worktree_path = worktree_path;
3194 cpa.had_base_commit_ref_error = 0;
3195 cpa.verbosity = verbosity;
3196 error = got_worktree_checkout_files(worktree, &paths, repo,
3197 checkout_progress, &cpa, check_cancelled, NULL);
3198 if (error != NULL)
3199 goto done;
3201 if (got_ref_is_symbolic(head_ref)) {
3202 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3203 if (error)
3204 goto done;
3205 refname = got_ref_get_name(ref);
3206 } else
3207 refname = got_ref_get_name(head_ref);
3208 printf("Checked out %s: %s\n", refname, commit_id_str);
3209 printf("Now shut up and hack\n");
3210 if (cpa.had_base_commit_ref_error)
3211 show_worktree_base_ref_warning();
3212 done:
3213 if (pack_fds) {
3214 const struct got_error *pack_err =
3215 got_repo_pack_fds_close(pack_fds);
3216 if (error == NULL)
3217 error = pack_err;
3219 if (head_ref)
3220 got_ref_close(head_ref);
3221 if (ref)
3222 got_ref_close(ref);
3223 if (repo) {
3224 const struct got_error *close_err = got_repo_close(repo);
3225 if (error == NULL)
3226 error = close_err;
3228 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3229 free(commit_id_str);
3230 free(commit_id);
3231 free(repo_path);
3232 free(worktree_path);
3233 free(cwd);
3234 return error;
3237 struct got_update_progress_arg {
3238 int did_something;
3239 int conflicts;
3240 int obstructed;
3241 int not_updated;
3242 int missing;
3243 int not_deleted;
3244 int unversioned;
3245 int verbosity;
3248 static void
3249 print_update_progress_stats(struct got_update_progress_arg *upa)
3251 if (!upa->did_something)
3252 return;
3254 if (upa->conflicts > 0)
3255 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3256 if (upa->obstructed > 0)
3257 printf("File paths obstructed by a non-regular file: %d\n",
3258 upa->obstructed);
3259 if (upa->not_updated > 0)
3260 printf("Files not updated because of existing merge "
3261 "conflicts: %d\n", upa->not_updated);
3265 * The meaning of some status codes differs between merge-style operations and
3266 * update operations. For example, the ! status code means "file was missing"
3267 * if changes were merged into the work tree, and "missing file was restored"
3268 * if the work tree was updated. This function should be used by any operation
3269 * which merges changes into the work tree without updating the work tree.
3271 static void
3272 print_merge_progress_stats(struct got_update_progress_arg *upa)
3274 if (!upa->did_something)
3275 return;
3277 if (upa->conflicts > 0)
3278 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3279 if (upa->obstructed > 0)
3280 printf("File paths obstructed by a non-regular file: %d\n",
3281 upa->obstructed);
3282 if (upa->missing > 0)
3283 printf("Files which had incoming changes but could not be "
3284 "found in the work tree: %d\n", upa->missing);
3285 if (upa->not_deleted > 0)
3286 printf("Files not deleted due to differences in deleted "
3287 "content: %d\n", upa->not_deleted);
3288 if (upa->unversioned > 0)
3289 printf("Files not merged because an unversioned file was "
3290 "found in the work tree: %d\n", upa->unversioned);
3293 __dead static void
3294 usage_update(void)
3296 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3297 "[path ...]\n", getprogname());
3298 exit(1);
3301 static const struct got_error *
3302 update_progress(void *arg, unsigned char status, const char *path)
3304 struct got_update_progress_arg *upa = arg;
3306 if (status == GOT_STATUS_EXISTS ||
3307 status == GOT_STATUS_BASE_REF_ERR)
3308 return NULL;
3310 upa->did_something = 1;
3312 /* Base commit bump happens silently. */
3313 if (status == GOT_STATUS_BUMP_BASE)
3314 return NULL;
3316 if (status == GOT_STATUS_CONFLICT)
3317 upa->conflicts++;
3318 if (status == GOT_STATUS_OBSTRUCTED)
3319 upa->obstructed++;
3320 if (status == GOT_STATUS_CANNOT_UPDATE)
3321 upa->not_updated++;
3322 if (status == GOT_STATUS_MISSING)
3323 upa->missing++;
3324 if (status == GOT_STATUS_CANNOT_DELETE)
3325 upa->not_deleted++;
3326 if (status == GOT_STATUS_UNVERSIONED)
3327 upa->unversioned++;
3329 while (path[0] == '/')
3330 path++;
3331 if (upa->verbosity >= 0)
3332 printf("%c %s\n", status, path);
3334 return NULL;
3337 static const struct got_error *
3338 switch_head_ref(struct got_reference *head_ref,
3339 struct got_object_id *commit_id, struct got_worktree *worktree,
3340 struct got_repository *repo)
3342 const struct got_error *err = NULL;
3343 char *base_id_str;
3344 int ref_has_moved = 0;
3346 /* Trivial case: switching between two different references. */
3347 if (strcmp(got_ref_get_name(head_ref),
3348 got_worktree_get_head_ref_name(worktree)) != 0) {
3349 printf("Switching work tree from %s to %s\n",
3350 got_worktree_get_head_ref_name(worktree),
3351 got_ref_get_name(head_ref));
3352 return got_worktree_set_head_ref(worktree, head_ref);
3355 err = check_linear_ancestry(commit_id,
3356 got_worktree_get_base_commit_id(worktree), 0, repo);
3357 if (err) {
3358 if (err->code != GOT_ERR_ANCESTRY)
3359 return err;
3360 ref_has_moved = 1;
3362 if (!ref_has_moved)
3363 return NULL;
3365 /* Switching to a rebased branch with the same reference name. */
3366 err = got_object_id_str(&base_id_str,
3367 got_worktree_get_base_commit_id(worktree));
3368 if (err)
3369 return err;
3370 printf("Reference %s now points at a different branch\n",
3371 got_worktree_get_head_ref_name(worktree));
3372 printf("Switching work tree from %s to %s\n", base_id_str,
3373 got_worktree_get_head_ref_name(worktree));
3374 return NULL;
3377 static const struct got_error *
3378 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3380 const struct got_error *err;
3381 int in_progress;
3383 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3384 if (err)
3385 return err;
3386 if (in_progress)
3387 return got_error(GOT_ERR_REBASING);
3389 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3390 if (err)
3391 return err;
3392 if (in_progress)
3393 return got_error(GOT_ERR_HISTEDIT_BUSY);
3395 return NULL;
3398 static const struct got_error *
3399 check_merge_in_progress(struct got_worktree *worktree,
3400 struct got_repository *repo)
3402 const struct got_error *err;
3403 int in_progress;
3405 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3406 if (err)
3407 return err;
3408 if (in_progress)
3409 return got_error(GOT_ERR_MERGE_BUSY);
3411 return NULL;
3414 static const struct got_error *
3415 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3416 char *argv[], struct got_worktree *worktree)
3418 const struct got_error *err = NULL;
3419 char *path;
3420 struct got_pathlist_entry *new;
3421 int i;
3423 if (argc == 0) {
3424 path = strdup("");
3425 if (path == NULL)
3426 return got_error_from_errno("strdup");
3427 return got_pathlist_append(paths, path, NULL);
3430 for (i = 0; i < argc; i++) {
3431 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3432 if (err)
3433 break;
3434 err = got_pathlist_insert(&new, paths, path, NULL);
3435 if (err || new == NULL /* duplicate */) {
3436 free(path);
3437 if (err)
3438 break;
3442 return err;
3445 static const struct got_error *
3446 wrap_not_worktree_error(const struct got_error *orig_err,
3447 const char *cmdname, const char *path)
3449 const struct got_error *err;
3450 struct got_repository *repo;
3451 static char msg[512];
3452 int *pack_fds = NULL;
3454 err = got_repo_pack_fds_open(&pack_fds);
3455 if (err)
3456 return err;
3458 err = got_repo_open(&repo, path, NULL, pack_fds);
3459 if (err)
3460 return orig_err;
3462 snprintf(msg, sizeof(msg),
3463 "'got %s' needs a work tree in addition to a git repository\n"
3464 "Work trees can be checked out from this Git repository with "
3465 "'got checkout'.\n"
3466 "The got(1) manual page contains more information.", cmdname);
3467 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3468 if (repo) {
3469 const struct got_error *close_err = got_repo_close(repo);
3470 if (close_err == NULL)
3471 err = close_err;
3473 if (pack_fds) {
3474 const struct got_error *pack_err =
3475 got_repo_pack_fds_close(pack_fds);
3476 if (err == NULL)
3477 err = pack_err;
3479 return err;
3482 static const struct got_error *
3483 cmd_update(int argc, char *argv[])
3485 const struct got_error *error = NULL;
3486 struct got_repository *repo = NULL;
3487 struct got_worktree *worktree = NULL;
3488 char *worktree_path = NULL;
3489 struct got_object_id *commit_id = NULL;
3490 char *commit_id_str = NULL;
3491 const char *branch_name = NULL;
3492 struct got_reference *head_ref = NULL;
3493 struct got_pathlist_head paths;
3494 struct got_pathlist_entry *pe;
3495 int ch, verbosity = 0;
3496 struct got_update_progress_arg upa;
3497 int *pack_fds = NULL;
3499 TAILQ_INIT(&paths);
3501 #ifndef PROFILE
3502 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3503 "unveil", NULL) == -1)
3504 err(1, "pledge");
3505 #endif
3507 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3508 switch (ch) {
3509 case 'b':
3510 branch_name = optarg;
3511 break;
3512 case 'c':
3513 commit_id_str = strdup(optarg);
3514 if (commit_id_str == NULL)
3515 return got_error_from_errno("strdup");
3516 break;
3517 case 'q':
3518 verbosity = -1;
3519 break;
3520 default:
3521 usage_update();
3522 /* NOTREACHED */
3526 argc -= optind;
3527 argv += optind;
3529 worktree_path = getcwd(NULL, 0);
3530 if (worktree_path == NULL) {
3531 error = got_error_from_errno("getcwd");
3532 goto done;
3535 error = got_repo_pack_fds_open(&pack_fds);
3536 if (error != NULL)
3537 goto done;
3539 error = got_worktree_open(&worktree, worktree_path);
3540 if (error) {
3541 if (error->code == GOT_ERR_NOT_WORKTREE)
3542 error = wrap_not_worktree_error(error, "update",
3543 worktree_path);
3544 goto done;
3547 error = check_rebase_or_histedit_in_progress(worktree);
3548 if (error)
3549 goto done;
3551 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3552 NULL, pack_fds);
3553 if (error != NULL)
3554 goto done;
3556 error = apply_unveil(got_repo_get_path(repo), 0,
3557 got_worktree_get_root_path(worktree));
3558 if (error)
3559 goto done;
3561 error = check_merge_in_progress(worktree, repo);
3562 if (error)
3563 goto done;
3565 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3566 if (error)
3567 goto done;
3569 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3570 got_worktree_get_head_ref_name(worktree), 0);
3571 if (error != NULL)
3572 goto done;
3573 if (commit_id_str == NULL) {
3574 error = got_ref_resolve(&commit_id, repo, head_ref);
3575 if (error != NULL)
3576 goto done;
3577 error = got_object_id_str(&commit_id_str, commit_id);
3578 if (error != NULL)
3579 goto done;
3580 } else {
3581 struct got_reflist_head refs;
3582 TAILQ_INIT(&refs);
3583 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3584 NULL);
3585 if (error)
3586 goto done;
3587 error = got_repo_match_object_id(&commit_id, NULL,
3588 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3589 got_ref_list_free(&refs);
3590 free(commit_id_str);
3591 commit_id_str = NULL;
3592 if (error)
3593 goto done;
3594 error = got_object_id_str(&commit_id_str, commit_id);
3595 if (error)
3596 goto done;
3599 if (branch_name) {
3600 struct got_object_id *head_commit_id;
3601 TAILQ_FOREACH(pe, &paths, entry) {
3602 if (pe->path_len == 0)
3603 continue;
3604 error = got_error_msg(GOT_ERR_BAD_PATH,
3605 "switching between branches requires that "
3606 "the entire work tree gets updated");
3607 goto done;
3609 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3610 if (error)
3611 goto done;
3612 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3613 repo);
3614 free(head_commit_id);
3615 if (error != NULL)
3616 goto done;
3617 error = check_same_branch(commit_id, head_ref, NULL, repo);
3618 if (error)
3619 goto done;
3620 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3621 if (error)
3622 goto done;
3623 } else {
3624 error = check_linear_ancestry(commit_id,
3625 got_worktree_get_base_commit_id(worktree), 0, repo);
3626 if (error != NULL) {
3627 if (error->code == GOT_ERR_ANCESTRY)
3628 error = got_error(GOT_ERR_BRANCH_MOVED);
3629 goto done;
3631 error = check_same_branch(commit_id, head_ref, NULL, repo);
3632 if (error)
3633 goto done;
3636 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3637 commit_id) != 0) {
3638 error = got_worktree_set_base_commit_id(worktree, repo,
3639 commit_id);
3640 if (error)
3641 goto done;
3644 memset(&upa, 0, sizeof(upa));
3645 upa.verbosity = verbosity;
3646 error = got_worktree_checkout_files(worktree, &paths, repo,
3647 update_progress, &upa, check_cancelled, NULL);
3648 if (error != NULL)
3649 goto done;
3651 if (upa.did_something) {
3652 printf("Updated to %s: %s\n",
3653 got_worktree_get_head_ref_name(worktree), commit_id_str);
3654 } else
3655 printf("Already up-to-date\n");
3657 print_update_progress_stats(&upa);
3658 done:
3659 if (pack_fds) {
3660 const struct got_error *pack_err =
3661 got_repo_pack_fds_close(pack_fds);
3662 if (error == NULL)
3663 error = pack_err;
3665 if (repo) {
3666 const struct got_error *close_err = got_repo_close(repo);
3667 if (error == NULL)
3668 error = close_err;
3670 free(worktree_path);
3671 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3672 free(commit_id);
3673 free(commit_id_str);
3674 return error;
3677 static const struct got_error *
3678 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3679 const char *path, int diff_context, int ignore_whitespace,
3680 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3681 struct got_repository *repo, FILE *outfile)
3683 const struct got_error *err = NULL;
3684 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3685 FILE *f1 = NULL, *f2 = NULL;
3686 int fd1 = -1, fd2 = -1;
3688 fd1 = got_opentempfd();
3689 if (fd1 == -1)
3690 return got_error_from_errno("got_opentempfd");
3691 fd2 = got_opentempfd();
3692 if (fd2 == -1) {
3693 err = got_error_from_errno("got_opentempfd");
3694 goto done;
3697 if (blob_id1) {
3698 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3699 fd1);
3700 if (err)
3701 goto done;
3704 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3705 if (err)
3706 goto done;
3708 f1 = got_opentemp();
3709 if (f1 == NULL) {
3710 err = got_error_from_errno("got_opentemp");
3711 goto done;
3713 f2 = got_opentemp();
3714 if (f2 == NULL) {
3715 err = got_error_from_errno("got_opentemp");
3716 goto done;
3719 while (path[0] == '/')
3720 path++;
3721 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3722 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3723 force_text_diff, dsa, outfile);
3724 done:
3725 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3726 err = got_error_from_errno("close");
3727 if (blob1)
3728 got_object_blob_close(blob1);
3729 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3730 err = got_error_from_errno("close");
3731 if (blob2)
3732 got_object_blob_close(blob2);
3733 if (f1 && fclose(f1) == EOF && err == NULL)
3734 err = got_error_from_errno("fclose");
3735 if (f2 && fclose(f2) == EOF && err == NULL)
3736 err = got_error_from_errno("fclose");
3737 return err;
3740 static const struct got_error *
3741 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3742 const char *path, int diff_context, int ignore_whitespace,
3743 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3744 struct got_repository *repo, FILE *outfile)
3746 const struct got_error *err = NULL;
3747 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3748 struct got_diff_blob_output_unidiff_arg arg;
3749 FILE *f1 = NULL, *f2 = NULL;
3750 int fd1 = -1, fd2 = -1;
3752 if (tree_id1) {
3753 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3754 if (err)
3755 goto done;
3756 fd1 = got_opentempfd();
3757 if (fd1 == -1) {
3758 err = got_error_from_errno("got_opentempfd");
3759 goto done;
3763 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3764 if (err)
3765 goto done;
3767 f1 = got_opentemp();
3768 if (f1 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3773 f2 = got_opentemp();
3774 if (f2 == NULL) {
3775 err = got_error_from_errno("got_opentemp");
3776 goto done;
3778 fd2 = got_opentempfd();
3779 if (fd2 == -1) {
3780 err = got_error_from_errno("got_opentempfd");
3781 goto done;
3783 arg.diff_context = diff_context;
3784 arg.ignore_whitespace = ignore_whitespace;
3785 arg.force_text_diff = force_text_diff;
3786 arg.diffstat = dsa;
3787 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3788 arg.outfile = outfile;
3789 arg.lines = NULL;
3790 arg.nlines = 0;
3791 while (path[0] == '/')
3792 path++;
3793 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3794 got_diff_blob_output_unidiff, &arg, 1);
3795 done:
3796 if (tree1)
3797 got_object_tree_close(tree1);
3798 if (tree2)
3799 got_object_tree_close(tree2);
3800 if (f1 && fclose(f1) == EOF && err == NULL)
3801 err = got_error_from_errno("fclose");
3802 if (f2 && fclose(f2) == EOF && err == NULL)
3803 err = got_error_from_errno("fclose");
3804 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3805 err = got_error_from_errno("close");
3806 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3807 err = got_error_from_errno("close");
3808 return err;
3811 static const struct got_error *
3812 get_changed_paths(struct got_pathlist_head *paths,
3813 struct got_commit_object *commit, struct got_repository *repo,
3814 struct got_diffstat_cb_arg *dsa)
3816 const struct got_error *err = NULL;
3817 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3818 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3819 struct got_object_qid *qid;
3820 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3821 FILE *f1 = NULL, *f2 = NULL;
3822 int fd1 = -1, fd2 = -1;
3824 if (dsa) {
3825 cb = got_diff_tree_compute_diffstat;
3827 f1 = got_opentemp();
3828 if (f1 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3832 f2 = got_opentemp();
3833 if (f2 == NULL) {
3834 err = got_error_from_errno("got_opentemp");
3835 goto done;
3837 fd1 = got_opentempfd();
3838 if (fd1 == -1) {
3839 err = got_error_from_errno("got_opentempfd");
3840 goto done;
3842 fd2 = got_opentempfd();
3843 if (fd2 == -1) {
3844 err = got_error_from_errno("got_opentempfd");
3845 goto done;
3849 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3850 if (qid != NULL) {
3851 struct got_commit_object *pcommit;
3852 err = got_object_open_as_commit(&pcommit, repo,
3853 &qid->id);
3854 if (err)
3855 return err;
3857 tree_id1 = got_object_id_dup(
3858 got_object_commit_get_tree_id(pcommit));
3859 if (tree_id1 == NULL) {
3860 got_object_commit_close(pcommit);
3861 return got_error_from_errno("got_object_id_dup");
3863 got_object_commit_close(pcommit);
3867 if (tree_id1) {
3868 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3869 if (err)
3870 goto done;
3873 tree_id2 = got_object_commit_get_tree_id(commit);
3874 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3875 if (err)
3876 goto done;
3878 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3879 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3880 done:
3881 if (tree1)
3882 got_object_tree_close(tree1);
3883 if (tree2)
3884 got_object_tree_close(tree2);
3885 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3886 err = got_error_from_errno("close");
3887 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3888 err = got_error_from_errno("close");
3889 if (f1 && fclose(f1) == EOF && err == NULL)
3890 err = got_error_from_errno("fclose");
3891 if (f2 && fclose(f2) == EOF && err == NULL)
3892 err = got_error_from_errno("fclose");
3893 free(tree_id1);
3894 return err;
3897 static const struct got_error *
3898 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3899 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3900 struct got_repository *repo, FILE *outfile)
3902 const struct got_error *err = NULL;
3903 struct got_commit_object *pcommit = NULL;
3904 char *id_str1 = NULL, *id_str2 = NULL;
3905 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3906 struct got_object_qid *qid;
3908 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3909 if (qid != NULL) {
3910 err = got_object_open_as_commit(&pcommit, repo,
3911 &qid->id);
3912 if (err)
3913 return err;
3914 err = got_object_id_str(&id_str1, &qid->id);
3915 if (err)
3916 goto done;
3919 err = got_object_id_str(&id_str2, id);
3920 if (err)
3921 goto done;
3923 if (path && path[0] != '\0') {
3924 int obj_type;
3925 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3926 if (err)
3927 goto done;
3928 if (pcommit) {
3929 err = got_object_id_by_path(&obj_id1, repo,
3930 pcommit, path);
3931 if (err) {
3932 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3933 free(obj_id2);
3934 goto done;
3938 err = got_object_get_type(&obj_type, repo, obj_id2);
3939 if (err) {
3940 free(obj_id2);
3941 goto done;
3943 fprintf(outfile,
3944 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3945 fprintf(outfile, "commit - %s\n",
3946 id_str1 ? id_str1 : "/dev/null");
3947 fprintf(outfile, "commit + %s\n", id_str2);
3948 switch (obj_type) {
3949 case GOT_OBJ_TYPE_BLOB:
3950 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3951 0, 0, dsa, repo, outfile);
3952 break;
3953 case GOT_OBJ_TYPE_TREE:
3954 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3955 0, 0, dsa, repo, outfile);
3956 break;
3957 default:
3958 err = got_error(GOT_ERR_OBJ_TYPE);
3959 break;
3961 free(obj_id1);
3962 free(obj_id2);
3963 } else {
3964 obj_id2 = got_object_commit_get_tree_id(commit);
3965 if (pcommit)
3966 obj_id1 = got_object_commit_get_tree_id(pcommit);
3967 fprintf(outfile,
3968 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3969 fprintf(outfile, "commit - %s\n",
3970 id_str1 ? id_str1 : "/dev/null");
3971 fprintf(outfile, "commit + %s\n", id_str2);
3972 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3973 dsa, repo, outfile);
3975 done:
3976 free(id_str1);
3977 free(id_str2);
3978 if (pcommit)
3979 got_object_commit_close(pcommit);
3980 return err;
3983 static char *
3984 get_datestr(time_t *time, char *datebuf)
3986 struct tm mytm, *tm;
3987 char *p, *s;
3989 tm = gmtime_r(time, &mytm);
3990 if (tm == NULL)
3991 return NULL;
3992 s = asctime_r(tm, datebuf);
3993 if (s == NULL)
3994 return NULL;
3995 p = strchr(s, '\n');
3996 if (p)
3997 *p = '\0';
3998 return s;
4001 static const struct got_error *
4002 match_commit(int *have_match, struct got_object_id *id,
4003 struct got_commit_object *commit, regex_t *regex)
4005 const struct got_error *err = NULL;
4006 regmatch_t regmatch;
4007 char *id_str = NULL, *logmsg = NULL;
4009 *have_match = 0;
4011 err = got_object_id_str(&id_str, id);
4012 if (err)
4013 return err;
4015 err = got_object_commit_get_logmsg(&logmsg, commit);
4016 if (err)
4017 goto done;
4019 if (regexec(regex, got_object_commit_get_author(commit), 1,
4020 &regmatch, 0) == 0 ||
4021 regexec(regex, got_object_commit_get_committer(commit), 1,
4022 &regmatch, 0) == 0 ||
4023 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4024 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4025 *have_match = 1;
4026 done:
4027 free(id_str);
4028 free(logmsg);
4029 return err;
4032 static void
4033 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4034 regex_t *regex)
4036 regmatch_t regmatch;
4037 struct got_pathlist_entry *pe;
4039 *have_match = 0;
4041 TAILQ_FOREACH(pe, changed_paths, entry) {
4042 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4043 *have_match = 1;
4044 break;
4049 static const struct got_error *
4050 match_patch(int *have_match, struct got_commit_object *commit,
4051 struct got_object_id *id, const char *path, int diff_context,
4052 struct got_repository *repo, regex_t *regex, FILE *f)
4054 const struct got_error *err = NULL;
4055 char *line = NULL;
4056 size_t linesize = 0;
4057 regmatch_t regmatch;
4059 *have_match = 0;
4061 err = got_opentemp_truncate(f);
4062 if (err)
4063 return err;
4065 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4066 if (err)
4067 goto done;
4069 if (fseeko(f, 0L, SEEK_SET) == -1) {
4070 err = got_error_from_errno("fseeko");
4071 goto done;
4074 while (getline(&line, &linesize, f) != -1) {
4075 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4076 *have_match = 1;
4077 break;
4080 done:
4081 free(line);
4082 return err;
4085 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4087 static const struct got_error*
4088 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4089 struct got_object_id *id, struct got_repository *repo,
4090 int local_only)
4092 static const struct got_error *err = NULL;
4093 struct got_reflist_entry *re;
4094 char *s;
4095 const char *name;
4097 *refs_str = NULL;
4099 TAILQ_FOREACH(re, refs, entry) {
4100 struct got_tag_object *tag = NULL;
4101 struct got_object_id *ref_id;
4102 int cmp;
4104 name = got_ref_get_name(re->ref);
4105 if (strcmp(name, GOT_REF_HEAD) == 0)
4106 continue;
4107 if (strncmp(name, "refs/", 5) == 0)
4108 name += 5;
4109 if (strncmp(name, "got/", 4) == 0)
4110 continue;
4111 if (strncmp(name, "heads/", 6) == 0)
4112 name += 6;
4113 if (strncmp(name, "remotes/", 8) == 0) {
4114 if (local_only)
4115 continue;
4116 name += 8;
4117 s = strstr(name, "/" GOT_REF_HEAD);
4118 if (s != NULL && s[strlen(s)] == '\0')
4119 continue;
4121 err = got_ref_resolve(&ref_id, repo, re->ref);
4122 if (err)
4123 break;
4124 if (strncmp(name, "tags/", 5) == 0) {
4125 err = got_object_open_as_tag(&tag, repo, ref_id);
4126 if (err) {
4127 if (err->code != GOT_ERR_OBJ_TYPE) {
4128 free(ref_id);
4129 break;
4131 /* Ref points at something other than a tag. */
4132 err = NULL;
4133 tag = NULL;
4136 cmp = got_object_id_cmp(tag ?
4137 got_object_tag_get_object_id(tag) : ref_id, id);
4138 free(ref_id);
4139 if (tag)
4140 got_object_tag_close(tag);
4141 if (cmp != 0)
4142 continue;
4143 s = *refs_str;
4144 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4145 s ? ", " : "", name) == -1) {
4146 err = got_error_from_errno("asprintf");
4147 free(s);
4148 *refs_str = NULL;
4149 break;
4151 free(s);
4154 return err;
4157 static const struct got_error *
4158 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4159 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4161 const struct got_error *err = NULL;
4162 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4163 char *comma, *s, *nl;
4164 struct got_reflist_head *refs;
4165 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4166 struct tm tm;
4167 time_t committer_time;
4169 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4170 if (refs) {
4171 err = build_refs_str(&ref_str, refs, id, repo, 1);
4172 if (err)
4173 return err;
4175 /* Display the first matching ref only. */
4176 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4177 *comma = '\0';
4180 if (ref_str == NULL) {
4181 err = got_object_id_str(&id_str, id);
4182 if (err)
4183 return err;
4186 committer_time = got_object_commit_get_committer_time(commit);
4187 if (gmtime_r(&committer_time, &tm) == NULL) {
4188 err = got_error_from_errno("gmtime_r");
4189 goto done;
4191 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4192 err = got_error(GOT_ERR_NO_SPACE);
4193 goto done;
4196 err = got_object_commit_get_logmsg(&logmsg0, commit);
4197 if (err)
4198 goto done;
4200 s = logmsg0;
4201 while (isspace((unsigned char)s[0]))
4202 s++;
4204 nl = strchr(s, '\n');
4205 if (nl) {
4206 *nl = '\0';
4209 if (ref_str)
4210 printf("%s%-7s %s\n", datebuf, ref_str, s);
4211 else
4212 printf("%s%.7s %s\n", datebuf, id_str, s);
4214 if (fflush(stdout) != 0 && err == NULL)
4215 err = got_error_from_errno("fflush");
4216 done:
4217 free(id_str);
4218 free(ref_str);
4219 free(logmsg0);
4220 return err;
4223 static const struct got_error *
4224 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4226 struct got_pathlist_entry *pe;
4228 if (header != NULL)
4229 printf("%s\n", header);
4231 TAILQ_FOREACH(pe, dsa->paths, entry) {
4232 struct got_diff_changed_path *cp = pe->data;
4233 int pad = dsa->max_path_len - pe->path_len + 1;
4235 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4236 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4238 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4239 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4240 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4242 if (fflush(stdout) != 0)
4243 return got_error_from_errno("fflush");
4245 return NULL;
4248 static const struct got_error *
4249 printfile(FILE *f)
4251 char buf[8192];
4252 size_t r;
4254 if (fseeko(f, 0L, SEEK_SET) == -1)
4255 return got_error_from_errno("fseek");
4257 for (;;) {
4258 r = fread(buf, 1, sizeof(buf), f);
4259 if (r == 0) {
4260 if (ferror(f))
4261 return got_error_from_errno("fread");
4262 if (feof(f))
4263 break;
4265 if (fwrite(buf, 1, r, stdout) != r)
4266 return got_ferror(stdout, GOT_ERR_IO);
4269 return NULL;
4272 static const struct got_error *
4273 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4274 struct got_repository *repo, const char *path,
4275 struct got_pathlist_head *changed_paths,
4276 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4277 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4278 const char *prefix)
4280 const struct got_error *err = NULL;
4281 FILE *f = NULL;
4282 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4283 char datebuf[26];
4284 time_t committer_time;
4285 const char *author, *committer;
4286 char *refs_str = NULL;
4288 err = got_object_id_str(&id_str, id);
4289 if (err)
4290 return err;
4292 if (custom_refs_str == NULL) {
4293 struct got_reflist_head *refs;
4294 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4295 if (refs) {
4296 err = build_refs_str(&refs_str, refs, id, repo, 0);
4297 if (err)
4298 goto done;
4302 printf(GOT_COMMIT_SEP_STR);
4303 if (custom_refs_str)
4304 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4305 custom_refs_str);
4306 else
4307 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4308 refs_str ? " (" : "", refs_str ? refs_str : "",
4309 refs_str ? ")" : "");
4310 free(id_str);
4311 id_str = NULL;
4312 free(refs_str);
4313 refs_str = NULL;
4314 printf("from: %s\n", got_object_commit_get_author(commit));
4315 author = got_object_commit_get_author(commit);
4316 committer = got_object_commit_get_committer(commit);
4317 if (strcmp(author, committer) != 0)
4318 printf("via: %s\n", committer);
4319 committer_time = got_object_commit_get_committer_time(commit);
4320 datestr = get_datestr(&committer_time, datebuf);
4321 if (datestr)
4322 printf("date: %s UTC\n", datestr);
4323 if (got_object_commit_get_nparents(commit) > 1) {
4324 const struct got_object_id_queue *parent_ids;
4325 struct got_object_qid *qid;
4326 int n = 1;
4327 parent_ids = got_object_commit_get_parent_ids(commit);
4328 STAILQ_FOREACH(qid, parent_ids, entry) {
4329 err = got_object_id_str(&id_str, &qid->id);
4330 if (err)
4331 goto done;
4332 printf("parent %d: %s\n", n++, id_str);
4333 free(id_str);
4334 id_str = NULL;
4338 err = got_object_commit_get_logmsg(&logmsg0, commit);
4339 if (err)
4340 goto done;
4342 logmsg = logmsg0;
4343 do {
4344 line = strsep(&logmsg, "\n");
4345 if (line)
4346 printf(" %s\n", line);
4347 } while (line);
4348 free(logmsg0);
4350 if (changed_paths && diffstat == NULL) {
4351 struct got_pathlist_entry *pe;
4353 TAILQ_FOREACH(pe, changed_paths, entry) {
4354 struct got_diff_changed_path *cp = pe->data;
4356 printf(" %c %s\n", cp->status, pe->path);
4358 printf("\n");
4360 if (show_patch) {
4361 if (diffstat) {
4362 f = got_opentemp();
4363 if (f == NULL) {
4364 err = got_error_from_errno("got_opentemp");
4365 goto done;
4369 err = print_patch(commit, id, path, diff_context, diffstat,
4370 repo, diffstat == NULL ? stdout : f);
4371 if (err)
4372 goto done;
4374 if (diffstat) {
4375 err = print_diffstat(diffstat, NULL);
4376 if (err)
4377 goto done;
4378 if (show_patch) {
4379 err = printfile(f);
4380 if (err)
4381 goto done;
4384 if (show_patch)
4385 printf("\n");
4387 if (fflush(stdout) != 0 && err == NULL)
4388 err = got_error_from_errno("fflush");
4389 done:
4390 if (f && fclose(f) == EOF && err == NULL)
4391 err = got_error_from_errno("fclose");
4392 free(id_str);
4393 free(refs_str);
4394 return err;
4397 static const struct got_error *
4398 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4399 struct got_repository *repo, const char *path, int show_changed_paths,
4400 int show_diffstat, int show_patch, const char *search_pattern,
4401 int diff_context, int limit, int log_branches, int reverse_display_order,
4402 struct got_reflist_object_id_map *refs_idmap, int one_line,
4403 FILE *tmpfile)
4405 const struct got_error *err;
4406 struct got_commit_graph *graph;
4407 regex_t regex;
4408 int have_match;
4409 struct got_object_id_queue reversed_commits;
4410 struct got_object_qid *qid;
4411 struct got_commit_object *commit;
4412 struct got_pathlist_head changed_paths;
4414 STAILQ_INIT(&reversed_commits);
4415 TAILQ_INIT(&changed_paths);
4417 if (search_pattern && regcomp(&regex, search_pattern,
4418 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4419 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4421 err = got_commit_graph_open(&graph, path, !log_branches);
4422 if (err)
4423 return err;
4424 err = got_commit_graph_iter_start(graph, root_id, repo,
4425 check_cancelled, NULL);
4426 if (err)
4427 goto done;
4428 for (;;) {
4429 struct got_object_id id;
4430 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4431 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4433 if (sigint_received || sigpipe_received)
4434 break;
4436 err = got_commit_graph_iter_next(&id, graph, repo,
4437 check_cancelled, NULL);
4438 if (err) {
4439 if (err->code == GOT_ERR_ITER_COMPLETED)
4440 err = NULL;
4441 break;
4444 err = got_object_open_as_commit(&commit, repo, &id);
4445 if (err)
4446 break;
4448 if ((show_changed_paths || (show_diffstat && !show_patch))
4449 && !reverse_display_order) {
4450 err = get_changed_paths(&changed_paths, commit, repo,
4451 show_diffstat ? &dsa : NULL);
4452 if (err)
4453 break;
4456 if (search_pattern) {
4457 err = match_commit(&have_match, &id, commit, &regex);
4458 if (err) {
4459 got_object_commit_close(commit);
4460 break;
4462 if (have_match == 0 && show_changed_paths)
4463 match_changed_paths(&have_match,
4464 &changed_paths, &regex);
4465 if (have_match == 0 && show_patch) {
4466 err = match_patch(&have_match, commit, &id,
4467 path, diff_context, repo, &regex, tmpfile);
4468 if (err)
4469 break;
4471 if (have_match == 0) {
4472 got_object_commit_close(commit);
4473 got_pathlist_free(&changed_paths,
4474 GOT_PATHLIST_FREE_ALL);
4475 continue;
4479 if (reverse_display_order) {
4480 err = got_object_qid_alloc(&qid, &id);
4481 if (err)
4482 break;
4483 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4484 got_object_commit_close(commit);
4485 } else {
4486 if (one_line)
4487 err = print_commit_oneline(commit, &id,
4488 repo, refs_idmap);
4489 else
4490 err = print_commit(commit, &id, repo, path,
4491 (show_changed_paths || show_diffstat) ?
4492 &changed_paths : NULL,
4493 show_diffstat ? &dsa : NULL, show_patch,
4494 diff_context, refs_idmap, NULL, NULL);
4495 got_object_commit_close(commit);
4496 if (err)
4497 break;
4499 if ((limit && --limit == 0) ||
4500 (end_id && got_object_id_cmp(&id, end_id) == 0))
4501 break;
4503 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4505 if (reverse_display_order) {
4506 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4507 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4508 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4510 err = got_object_open_as_commit(&commit, repo,
4511 &qid->id);
4512 if (err)
4513 break;
4514 if (show_changed_paths ||
4515 (show_diffstat && !show_patch)) {
4516 err = get_changed_paths(&changed_paths, commit,
4517 repo, show_diffstat ? &dsa : NULL);
4518 if (err)
4519 break;
4521 if (one_line)
4522 err = print_commit_oneline(commit, &qid->id,
4523 repo, refs_idmap);
4524 else
4525 err = print_commit(commit, &qid->id, repo, path,
4526 (show_changed_paths || show_diffstat) ?
4527 &changed_paths : NULL,
4528 show_diffstat ? &dsa : NULL, show_patch,
4529 diff_context, refs_idmap, NULL, NULL);
4530 got_object_commit_close(commit);
4531 if (err)
4532 break;
4533 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4536 done:
4537 while (!STAILQ_EMPTY(&reversed_commits)) {
4538 qid = STAILQ_FIRST(&reversed_commits);
4539 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4540 got_object_qid_free(qid);
4542 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4543 if (search_pattern)
4544 regfree(&regex);
4545 got_commit_graph_close(graph);
4546 return err;
4549 __dead static void
4550 usage_log(void)
4552 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4553 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4554 "[path]\n", getprogname());
4555 exit(1);
4558 static int
4559 get_default_log_limit(void)
4561 const char *got_default_log_limit;
4562 long long n;
4563 const char *errstr;
4565 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4566 if (got_default_log_limit == NULL)
4567 return 0;
4568 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4569 if (errstr != NULL)
4570 return 0;
4571 return n;
4574 static const struct got_error *
4575 cmd_log(int argc, char *argv[])
4577 const struct got_error *error;
4578 struct got_repository *repo = NULL;
4579 struct got_worktree *worktree = NULL;
4580 struct got_object_id *start_id = NULL, *end_id = NULL;
4581 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4582 const char *start_commit = NULL, *end_commit = NULL;
4583 const char *search_pattern = NULL;
4584 int diff_context = -1, ch;
4585 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4586 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4587 const char *errstr;
4588 struct got_reflist_head refs;
4589 struct got_reflist_object_id_map *refs_idmap = NULL;
4590 FILE *tmpfile = NULL;
4591 int *pack_fds = NULL;
4593 TAILQ_INIT(&refs);
4595 #ifndef PROFILE
4596 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4597 NULL)
4598 == -1)
4599 err(1, "pledge");
4600 #endif
4602 limit = get_default_log_limit();
4604 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4605 switch (ch) {
4606 case 'b':
4607 log_branches = 1;
4608 break;
4609 case 'C':
4610 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4611 &errstr);
4612 if (errstr != NULL)
4613 errx(1, "number of context lines is %s: %s",
4614 errstr, optarg);
4615 break;
4616 case 'c':
4617 start_commit = optarg;
4618 break;
4619 case 'd':
4620 show_diffstat = 1;
4621 break;
4622 case 'l':
4623 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4624 if (errstr != NULL)
4625 errx(1, "number of commits is %s: %s",
4626 errstr, optarg);
4627 break;
4628 case 'P':
4629 show_changed_paths = 1;
4630 break;
4631 case 'p':
4632 show_patch = 1;
4633 break;
4634 case 'R':
4635 reverse_display_order = 1;
4636 break;
4637 case 'r':
4638 repo_path = realpath(optarg, NULL);
4639 if (repo_path == NULL)
4640 return got_error_from_errno2("realpath",
4641 optarg);
4642 got_path_strip_trailing_slashes(repo_path);
4643 break;
4644 case 'S':
4645 search_pattern = optarg;
4646 break;
4647 case 's':
4648 one_line = 1;
4649 break;
4650 case 'x':
4651 end_commit = optarg;
4652 break;
4653 default:
4654 usage_log();
4655 /* NOTREACHED */
4659 argc -= optind;
4660 argv += optind;
4662 if (diff_context == -1)
4663 diff_context = 3;
4664 else if (!show_patch)
4665 errx(1, "-C requires -p");
4667 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4668 errx(1, "cannot use -s with -d, -p or -P");
4670 cwd = getcwd(NULL, 0);
4671 if (cwd == NULL) {
4672 error = got_error_from_errno("getcwd");
4673 goto done;
4676 error = got_repo_pack_fds_open(&pack_fds);
4677 if (error != NULL)
4678 goto done;
4680 if (repo_path == NULL) {
4681 error = got_worktree_open(&worktree, cwd);
4682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4683 goto done;
4684 error = NULL;
4687 if (argc == 1) {
4688 if (worktree) {
4689 error = got_worktree_resolve_path(&path, worktree,
4690 argv[0]);
4691 if (error)
4692 goto done;
4693 } else {
4694 path = strdup(argv[0]);
4695 if (path == NULL) {
4696 error = got_error_from_errno("strdup");
4697 goto done;
4700 } else if (argc != 0)
4701 usage_log();
4703 if (repo_path == NULL) {
4704 repo_path = worktree ?
4705 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4707 if (repo_path == NULL) {
4708 error = got_error_from_errno("strdup");
4709 goto done;
4712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4713 if (error != NULL)
4714 goto done;
4716 error = apply_unveil(got_repo_get_path(repo), 1,
4717 worktree ? got_worktree_get_root_path(worktree) : NULL);
4718 if (error)
4719 goto done;
4721 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4722 if (error)
4723 goto done;
4725 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4726 if (error)
4727 goto done;
4729 if (start_commit == NULL) {
4730 struct got_reference *head_ref;
4731 struct got_commit_object *commit = NULL;
4732 error = got_ref_open(&head_ref, repo,
4733 worktree ? got_worktree_get_head_ref_name(worktree)
4734 : GOT_REF_HEAD, 0);
4735 if (error != NULL)
4736 goto done;
4737 error = got_ref_resolve(&start_id, repo, head_ref);
4738 got_ref_close(head_ref);
4739 if (error != NULL)
4740 goto done;
4741 error = got_object_open_as_commit(&commit, repo,
4742 start_id);
4743 if (error != NULL)
4744 goto done;
4745 got_object_commit_close(commit);
4746 } else {
4747 error = got_repo_match_object_id(&start_id, NULL,
4748 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4749 if (error != NULL)
4750 goto done;
4752 if (end_commit != NULL) {
4753 error = got_repo_match_object_id(&end_id, NULL,
4754 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4755 if (error != NULL)
4756 goto done;
4759 if (worktree) {
4761 * If a path was specified on the command line it was resolved
4762 * to a path in the work tree above. Prepend the work tree's
4763 * path prefix to obtain the corresponding in-repository path.
4765 if (path) {
4766 const char *prefix;
4767 prefix = got_worktree_get_path_prefix(worktree);
4768 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4769 (path[0] != '\0') ? "/" : "", path) == -1) {
4770 error = got_error_from_errno("asprintf");
4771 goto done;
4774 } else
4775 error = got_repo_map_path(&in_repo_path, repo,
4776 path ? path : "");
4777 if (error != NULL)
4778 goto done;
4779 if (in_repo_path) {
4780 free(path);
4781 path = in_repo_path;
4784 if (worktree) {
4785 /* Release work tree lock. */
4786 got_worktree_close(worktree);
4787 worktree = NULL;
4790 if (search_pattern && show_patch) {
4791 tmpfile = got_opentemp();
4792 if (tmpfile == NULL) {
4793 error = got_error_from_errno("got_opentemp");
4794 goto done;
4798 error = print_commits(start_id, end_id, repo, path ? path : "",
4799 show_changed_paths, show_diffstat, show_patch, search_pattern,
4800 diff_context, limit, log_branches, reverse_display_order,
4801 refs_idmap, one_line, tmpfile);
4802 done:
4803 free(path);
4804 free(repo_path);
4805 free(cwd);
4806 if (worktree)
4807 got_worktree_close(worktree);
4808 if (repo) {
4809 const struct got_error *close_err = got_repo_close(repo);
4810 if (error == NULL)
4811 error = close_err;
4813 if (pack_fds) {
4814 const struct got_error *pack_err =
4815 got_repo_pack_fds_close(pack_fds);
4816 if (error == NULL)
4817 error = pack_err;
4819 if (refs_idmap)
4820 got_reflist_object_id_map_free(refs_idmap);
4821 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4822 error = got_error_from_errno("fclose");
4823 got_ref_list_free(&refs);
4824 return error;
4827 __dead static void
4828 usage_diff(void)
4830 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4831 "[-r repository-path] [object1 object2 | path ...]\n",
4832 getprogname());
4833 exit(1);
4836 struct print_diff_arg {
4837 struct got_repository *repo;
4838 struct got_worktree *worktree;
4839 struct got_diffstat_cb_arg *diffstat;
4840 int diff_context;
4841 const char *id_str;
4842 int header_shown;
4843 int diff_staged;
4844 enum got_diff_algorithm diff_algo;
4845 int ignore_whitespace;
4846 int force_text_diff;
4847 FILE *f1;
4848 FILE *f2;
4849 FILE *outfile;
4853 * Create a file which contains the target path of a symlink so we can feed
4854 * it as content to the diff engine.
4856 static const struct got_error *
4857 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4858 const char *abspath)
4860 const struct got_error *err = NULL;
4861 char target_path[PATH_MAX];
4862 ssize_t target_len, outlen;
4864 *fd = -1;
4866 if (dirfd != -1) {
4867 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4868 if (target_len == -1)
4869 return got_error_from_errno2("readlinkat", abspath);
4870 } else {
4871 target_len = readlink(abspath, target_path, PATH_MAX);
4872 if (target_len == -1)
4873 return got_error_from_errno2("readlink", abspath);
4876 *fd = got_opentempfd();
4877 if (*fd == -1)
4878 return got_error_from_errno("got_opentempfd");
4880 outlen = write(*fd, target_path, target_len);
4881 if (outlen == -1) {
4882 err = got_error_from_errno("got_opentempfd");
4883 goto done;
4886 if (lseek(*fd, 0, SEEK_SET) == -1) {
4887 err = got_error_from_errno2("lseek", abspath);
4888 goto done;
4890 done:
4891 if (err) {
4892 close(*fd);
4893 *fd = -1;
4895 return err;
4898 static const struct got_error *
4899 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4900 const char *path, struct got_object_id *blob_id,
4901 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4902 int dirfd, const char *de_name)
4904 struct print_diff_arg *a = arg;
4905 const struct got_error *err = NULL;
4906 struct got_blob_object *blob1 = NULL;
4907 int fd = -1, fd1 = -1, fd2 = -1;
4908 FILE *f2 = NULL;
4909 char *abspath = NULL, *label1 = NULL;
4910 struct stat sb;
4911 off_t size1 = 0;
4912 int f2_exists = 0;
4914 memset(&sb, 0, sizeof(sb));
4916 if (a->diff_staged) {
4917 if (staged_status != GOT_STATUS_MODIFY &&
4918 staged_status != GOT_STATUS_ADD &&
4919 staged_status != GOT_STATUS_DELETE)
4920 return NULL;
4921 } else {
4922 if (staged_status == GOT_STATUS_DELETE)
4923 return NULL;
4924 if (status == GOT_STATUS_NONEXISTENT)
4925 return got_error_set_errno(ENOENT, path);
4926 if (status != GOT_STATUS_MODIFY &&
4927 status != GOT_STATUS_ADD &&
4928 status != GOT_STATUS_DELETE &&
4929 status != GOT_STATUS_CONFLICT)
4930 return NULL;
4933 err = got_opentemp_truncate(a->f1);
4934 if (err)
4935 return got_error_from_errno("got_opentemp_truncate");
4936 err = got_opentemp_truncate(a->f2);
4937 if (err)
4938 return got_error_from_errno("got_opentemp_truncate");
4940 if (!a->header_shown) {
4941 if (fprintf(a->outfile, "diff %s%s\n",
4942 a->diff_staged ? "-s " : "",
4943 got_worktree_get_root_path(a->worktree)) < 0) {
4944 err = got_error_from_errno("fprintf");
4945 goto done;
4947 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4948 err = got_error_from_errno("fprintf");
4949 goto done;
4951 if (fprintf(a->outfile, "path + %s%s\n",
4952 got_worktree_get_root_path(a->worktree),
4953 a->diff_staged ? " (staged changes)" : "") < 0) {
4954 err = got_error_from_errno("fprintf");
4955 goto done;
4957 a->header_shown = 1;
4960 if (a->diff_staged) {
4961 const char *label1 = NULL, *label2 = NULL;
4962 switch (staged_status) {
4963 case GOT_STATUS_MODIFY:
4964 label1 = path;
4965 label2 = path;
4966 break;
4967 case GOT_STATUS_ADD:
4968 label2 = path;
4969 break;
4970 case GOT_STATUS_DELETE:
4971 label1 = path;
4972 break;
4973 default:
4974 return got_error(GOT_ERR_FILE_STATUS);
4976 fd1 = got_opentempfd();
4977 if (fd1 == -1) {
4978 err = got_error_from_errno("got_opentempfd");
4979 goto done;
4981 fd2 = got_opentempfd();
4982 if (fd2 == -1) {
4983 err = got_error_from_errno("got_opentempfd");
4984 goto done;
4986 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4987 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4988 a->diff_algo, a->diff_context, a->ignore_whitespace,
4989 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4990 goto done;
4993 fd1 = got_opentempfd();
4994 if (fd1 == -1) {
4995 err = got_error_from_errno("got_opentempfd");
4996 goto done;
4999 if (staged_status == GOT_STATUS_ADD ||
5000 staged_status == GOT_STATUS_MODIFY) {
5001 char *id_str;
5002 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5003 8192, fd1);
5004 if (err)
5005 goto done;
5006 err = got_object_id_str(&id_str, staged_blob_id);
5007 if (err)
5008 goto done;
5009 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5010 err = got_error_from_errno("asprintf");
5011 free(id_str);
5012 goto done;
5014 free(id_str);
5015 } else if (status != GOT_STATUS_ADD) {
5016 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5017 fd1);
5018 if (err)
5019 goto done;
5022 if (status != GOT_STATUS_DELETE) {
5023 if (asprintf(&abspath, "%s/%s",
5024 got_worktree_get_root_path(a->worktree), path) == -1) {
5025 err = got_error_from_errno("asprintf");
5026 goto done;
5029 if (dirfd != -1) {
5030 fd = openat(dirfd, de_name,
5031 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5032 if (fd == -1) {
5033 if (!got_err_open_nofollow_on_symlink()) {
5034 err = got_error_from_errno2("openat",
5035 abspath);
5036 goto done;
5038 err = get_symlink_target_file(&fd, dirfd,
5039 de_name, abspath);
5040 if (err)
5041 goto done;
5043 } else {
5044 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5045 if (fd == -1) {
5046 if (!got_err_open_nofollow_on_symlink()) {
5047 err = got_error_from_errno2("open",
5048 abspath);
5049 goto done;
5051 err = get_symlink_target_file(&fd, dirfd,
5052 de_name, abspath);
5053 if (err)
5054 goto done;
5057 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5058 err = got_error_from_errno2("fstatat", abspath);
5059 goto done;
5061 f2 = fdopen(fd, "r");
5062 if (f2 == NULL) {
5063 err = got_error_from_errno2("fdopen", abspath);
5064 goto done;
5066 fd = -1;
5067 f2_exists = 1;
5070 if (blob1) {
5071 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5072 a->f1, blob1);
5073 if (err)
5074 goto done;
5077 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5078 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5079 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5080 done:
5081 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5082 err = got_error_from_errno("close");
5083 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5084 err = got_error_from_errno("close");
5085 if (blob1)
5086 got_object_blob_close(blob1);
5087 if (fd != -1 && close(fd) == -1 && err == NULL)
5088 err = got_error_from_errno("close");
5089 if (f2 && fclose(f2) == EOF && err == NULL)
5090 err = got_error_from_errno("fclose");
5091 free(abspath);
5092 return err;
5095 static const struct got_error *
5096 cmd_diff(int argc, char *argv[])
5098 const struct got_error *error;
5099 struct got_repository *repo = NULL;
5100 struct got_worktree *worktree = NULL;
5101 char *cwd = NULL, *repo_path = NULL;
5102 const char *commit_args[2] = { NULL, NULL };
5103 int ncommit_args = 0;
5104 struct got_object_id *ids[2] = { NULL, NULL };
5105 char *labels[2] = { NULL, NULL };
5106 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5107 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5108 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5109 const char *errstr;
5110 struct got_reflist_head refs;
5111 struct got_pathlist_head diffstat_paths, paths;
5112 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5113 int fd1 = -1, fd2 = -1;
5114 int *pack_fds = NULL;
5115 struct got_diffstat_cb_arg dsa;
5117 memset(&dsa, 0, sizeof(dsa));
5119 TAILQ_INIT(&refs);
5120 TAILQ_INIT(&paths);
5121 TAILQ_INIT(&diffstat_paths);
5123 #ifndef PROFILE
5124 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5125 NULL) == -1)
5126 err(1, "pledge");
5127 #endif
5129 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5130 switch (ch) {
5131 case 'a':
5132 force_text_diff = 1;
5133 break;
5134 case 'C':
5135 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5136 &errstr);
5137 if (errstr != NULL)
5138 errx(1, "number of context lines is %s: %s",
5139 errstr, optarg);
5140 break;
5141 case 'c':
5142 if (ncommit_args >= 2)
5143 errx(1, "too many -c options used");
5144 commit_args[ncommit_args++] = optarg;
5145 break;
5146 case 'd':
5147 show_diffstat = 1;
5148 break;
5149 case 'P':
5150 force_path = 1;
5151 break;
5152 case 'r':
5153 repo_path = realpath(optarg, NULL);
5154 if (repo_path == NULL)
5155 return got_error_from_errno2("realpath",
5156 optarg);
5157 got_path_strip_trailing_slashes(repo_path);
5158 rflag = 1;
5159 break;
5160 case 's':
5161 diff_staged = 1;
5162 break;
5163 case 'w':
5164 ignore_whitespace = 1;
5165 break;
5166 default:
5167 usage_diff();
5168 /* NOTREACHED */
5172 argc -= optind;
5173 argv += optind;
5175 cwd = getcwd(NULL, 0);
5176 if (cwd == NULL) {
5177 error = got_error_from_errno("getcwd");
5178 goto done;
5181 error = got_repo_pack_fds_open(&pack_fds);
5182 if (error != NULL)
5183 goto done;
5185 if (repo_path == NULL) {
5186 error = got_worktree_open(&worktree, cwd);
5187 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5188 goto done;
5189 else
5190 error = NULL;
5191 if (worktree) {
5192 repo_path =
5193 strdup(got_worktree_get_repo_path(worktree));
5194 if (repo_path == NULL) {
5195 error = got_error_from_errno("strdup");
5196 goto done;
5198 } else {
5199 repo_path = strdup(cwd);
5200 if (repo_path == NULL) {
5201 error = got_error_from_errno("strdup");
5202 goto done;
5207 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5208 free(repo_path);
5209 if (error != NULL)
5210 goto done;
5212 if (show_diffstat) {
5213 dsa.paths = &diffstat_paths;
5214 dsa.force_text = force_text_diff;
5215 dsa.ignore_ws = ignore_whitespace;
5216 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5219 if (rflag || worktree == NULL || ncommit_args > 0) {
5220 if (force_path) {
5221 error = got_error_msg(GOT_ERR_NOT_IMPL,
5222 "-P option can only be used when diffing "
5223 "a work tree");
5224 goto done;
5226 if (diff_staged) {
5227 error = got_error_msg(GOT_ERR_NOT_IMPL,
5228 "-s option can only be used when diffing "
5229 "a work tree");
5230 goto done;
5234 error = apply_unveil(got_repo_get_path(repo), 1,
5235 worktree ? got_worktree_get_root_path(worktree) : NULL);
5236 if (error)
5237 goto done;
5239 if ((!force_path && argc == 2) || ncommit_args > 0) {
5240 int obj_type = (ncommit_args > 0 ?
5241 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5242 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5243 NULL);
5244 if (error)
5245 goto done;
5246 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5247 const char *arg;
5248 if (ncommit_args > 0)
5249 arg = commit_args[i];
5250 else
5251 arg = argv[i];
5252 error = got_repo_match_object_id(&ids[i], &labels[i],
5253 arg, obj_type, &refs, repo);
5254 if (error) {
5255 if (error->code != GOT_ERR_NOT_REF &&
5256 error->code != GOT_ERR_NO_OBJ)
5257 goto done;
5258 if (ncommit_args > 0)
5259 goto done;
5260 error = NULL;
5261 break;
5266 f1 = got_opentemp();
5267 if (f1 == NULL) {
5268 error = got_error_from_errno("got_opentemp");
5269 goto done;
5272 f2 = got_opentemp();
5273 if (f2 == NULL) {
5274 error = got_error_from_errno("got_opentemp");
5275 goto done;
5278 outfile = got_opentemp();
5279 if (outfile == NULL) {
5280 error = got_error_from_errno("got_opentemp");
5281 goto done;
5284 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5285 struct print_diff_arg arg;
5286 char *id_str;
5288 if (worktree == NULL) {
5289 if (argc == 2 && ids[0] == NULL) {
5290 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5291 goto done;
5292 } else if (argc == 2 && ids[1] == NULL) {
5293 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5294 goto done;
5295 } else if (argc > 0) {
5296 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5297 "%s", "specified paths cannot be resolved");
5298 goto done;
5299 } else {
5300 error = got_error(GOT_ERR_NOT_WORKTREE);
5301 goto done;
5305 error = get_worktree_paths_from_argv(&paths, argc, argv,
5306 worktree);
5307 if (error)
5308 goto done;
5310 error = got_object_id_str(&id_str,
5311 got_worktree_get_base_commit_id(worktree));
5312 if (error)
5313 goto done;
5314 arg.repo = repo;
5315 arg.worktree = worktree;
5316 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5317 arg.diff_context = diff_context;
5318 arg.id_str = id_str;
5319 arg.header_shown = 0;
5320 arg.diff_staged = diff_staged;
5321 arg.ignore_whitespace = ignore_whitespace;
5322 arg.force_text_diff = force_text_diff;
5323 arg.diffstat = show_diffstat ? &dsa : NULL;
5324 arg.f1 = f1;
5325 arg.f2 = f2;
5326 arg.outfile = outfile;
5328 error = got_worktree_status(worktree, &paths, repo, 0,
5329 print_diff, &arg, check_cancelled, NULL);
5330 free(id_str);
5331 if (error)
5332 goto done;
5334 if (show_diffstat && dsa.nfiles > 0) {
5335 char *header;
5337 if (asprintf(&header, "diffstat %s%s",
5338 diff_staged ? "-s " : "",
5339 got_worktree_get_root_path(worktree)) == -1) {
5340 error = got_error_from_errno("asprintf");
5341 goto done;
5344 error = print_diffstat(&dsa, header);
5345 free(header);
5346 if (error)
5347 goto done;
5350 error = printfile(outfile);
5351 goto done;
5354 if (ncommit_args == 1) {
5355 struct got_commit_object *commit;
5356 error = got_object_open_as_commit(&commit, repo, ids[0]);
5357 if (error)
5358 goto done;
5360 labels[1] = labels[0];
5361 ids[1] = ids[0];
5362 if (got_object_commit_get_nparents(commit) > 0) {
5363 const struct got_object_id_queue *pids;
5364 struct got_object_qid *pid;
5365 pids = got_object_commit_get_parent_ids(commit);
5366 pid = STAILQ_FIRST(pids);
5367 ids[0] = got_object_id_dup(&pid->id);
5368 if (ids[0] == NULL) {
5369 error = got_error_from_errno(
5370 "got_object_id_dup");
5371 got_object_commit_close(commit);
5372 goto done;
5374 error = got_object_id_str(&labels[0], ids[0]);
5375 if (error) {
5376 got_object_commit_close(commit);
5377 goto done;
5379 } else {
5380 ids[0] = NULL;
5381 labels[0] = strdup("/dev/null");
5382 if (labels[0] == NULL) {
5383 error = got_error_from_errno("strdup");
5384 got_object_commit_close(commit);
5385 goto done;
5389 got_object_commit_close(commit);
5392 if (ncommit_args == 0 && argc > 2) {
5393 error = got_error_msg(GOT_ERR_BAD_PATH,
5394 "path arguments cannot be used when diffing two objects");
5395 goto done;
5398 if (ids[0]) {
5399 error = got_object_get_type(&type1, repo, ids[0]);
5400 if (error)
5401 goto done;
5404 error = got_object_get_type(&type2, repo, ids[1]);
5405 if (error)
5406 goto done;
5407 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5408 error = got_error(GOT_ERR_OBJ_TYPE);
5409 goto done;
5411 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5412 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5413 "path arguments cannot be used when diffing blobs");
5414 goto done;
5417 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5418 char *in_repo_path;
5419 struct got_pathlist_entry *new;
5420 if (worktree) {
5421 const char *prefix;
5422 char *p;
5423 error = got_worktree_resolve_path(&p, worktree,
5424 argv[i]);
5425 if (error)
5426 goto done;
5427 prefix = got_worktree_get_path_prefix(worktree);
5428 while (prefix[0] == '/')
5429 prefix++;
5430 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5431 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5432 p) == -1) {
5433 error = got_error_from_errno("asprintf");
5434 free(p);
5435 goto done;
5437 free(p);
5438 } else {
5439 char *mapped_path, *s;
5440 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5441 if (error)
5442 goto done;
5443 s = mapped_path;
5444 while (s[0] == '/')
5445 s++;
5446 in_repo_path = strdup(s);
5447 if (in_repo_path == NULL) {
5448 error = got_error_from_errno("asprintf");
5449 free(mapped_path);
5450 goto done;
5452 free(mapped_path);
5455 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5456 if (error || new == NULL /* duplicate */)
5457 free(in_repo_path);
5458 if (error)
5459 goto done;
5462 if (worktree) {
5463 /* Release work tree lock. */
5464 got_worktree_close(worktree);
5465 worktree = NULL;
5468 fd1 = got_opentempfd();
5469 if (fd1 == -1) {
5470 error = got_error_from_errno("got_opentempfd");
5471 goto done;
5474 fd2 = got_opentempfd();
5475 if (fd2 == -1) {
5476 error = got_error_from_errno("got_opentempfd");
5477 goto done;
5480 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5481 case GOT_OBJ_TYPE_BLOB:
5482 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5483 fd1, fd2, ids[0], ids[1], NULL, NULL,
5484 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5485 ignore_whitespace, force_text_diff,
5486 show_diffstat ? &dsa : NULL, repo, outfile);
5487 break;
5488 case GOT_OBJ_TYPE_TREE:
5489 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5490 ids[0], ids[1], &paths, "", "",
5491 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5492 ignore_whitespace, force_text_diff,
5493 show_diffstat ? &dsa : NULL, repo, outfile);
5494 break;
5495 case GOT_OBJ_TYPE_COMMIT:
5496 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5497 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5498 fd1, fd2, ids[0], ids[1], &paths,
5499 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5500 ignore_whitespace, force_text_diff,
5501 show_diffstat ? &dsa : NULL, repo, outfile);
5502 break;
5503 default:
5504 error = got_error(GOT_ERR_OBJ_TYPE);
5506 if (error)
5507 goto done;
5509 if (show_diffstat && dsa.nfiles > 0) {
5510 char *header = NULL;
5512 if (asprintf(&header, "diffstat %s %s",
5513 labels[0], labels[1]) == -1) {
5514 error = got_error_from_errno("asprintf");
5515 goto done;
5518 error = print_diffstat(&dsa, header);
5519 free(header);
5520 if (error)
5521 goto done;
5524 error = printfile(outfile);
5526 done:
5527 free(labels[0]);
5528 free(labels[1]);
5529 free(ids[0]);
5530 free(ids[1]);
5531 if (worktree)
5532 got_worktree_close(worktree);
5533 if (repo) {
5534 const struct got_error *close_err = got_repo_close(repo);
5535 if (error == NULL)
5536 error = close_err;
5538 if (pack_fds) {
5539 const struct got_error *pack_err =
5540 got_repo_pack_fds_close(pack_fds);
5541 if (error == NULL)
5542 error = pack_err;
5544 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5545 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5546 got_ref_list_free(&refs);
5547 if (outfile && fclose(outfile) == EOF && error == NULL)
5548 error = got_error_from_errno("fclose");
5549 if (f1 && fclose(f1) == EOF && error == NULL)
5550 error = got_error_from_errno("fclose");
5551 if (f2 && fclose(f2) == EOF && error == NULL)
5552 error = got_error_from_errno("fclose");
5553 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5554 error = got_error_from_errno("close");
5555 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5556 error = got_error_from_errno("close");
5557 return error;
5560 __dead static void
5561 usage_blame(void)
5563 fprintf(stderr,
5564 "usage: %s blame [-c commit] [-r repository-path] path\n",
5565 getprogname());
5566 exit(1);
5569 struct blame_line {
5570 int annotated;
5571 char *id_str;
5572 char *committer;
5573 char datebuf[11]; /* YYYY-MM-DD + NUL */
5576 struct blame_cb_args {
5577 struct blame_line *lines;
5578 int nlines;
5579 int nlines_prec;
5580 int lineno_cur;
5581 off_t *line_offsets;
5582 FILE *f;
5583 struct got_repository *repo;
5586 static const struct got_error *
5587 blame_cb(void *arg, int nlines, int lineno,
5588 struct got_commit_object *commit, struct got_object_id *id)
5590 const struct got_error *err = NULL;
5591 struct blame_cb_args *a = arg;
5592 struct blame_line *bline;
5593 char *line = NULL;
5594 size_t linesize = 0;
5595 off_t offset;
5596 struct tm tm;
5597 time_t committer_time;
5599 if (nlines != a->nlines ||
5600 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5601 return got_error(GOT_ERR_RANGE);
5603 if (sigint_received)
5604 return got_error(GOT_ERR_ITER_COMPLETED);
5606 if (lineno == -1)
5607 return NULL; /* no change in this commit */
5609 /* Annotate this line. */
5610 bline = &a->lines[lineno - 1];
5611 if (bline->annotated)
5612 return NULL;
5613 err = got_object_id_str(&bline->id_str, id);
5614 if (err)
5615 return err;
5617 bline->committer = strdup(got_object_commit_get_committer(commit));
5618 if (bline->committer == NULL) {
5619 err = got_error_from_errno("strdup");
5620 goto done;
5623 committer_time = got_object_commit_get_committer_time(commit);
5624 if (gmtime_r(&committer_time, &tm) == NULL)
5625 return got_error_from_errno("gmtime_r");
5626 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5627 &tm) == 0) {
5628 err = got_error(GOT_ERR_NO_SPACE);
5629 goto done;
5631 bline->annotated = 1;
5633 /* Print lines annotated so far. */
5634 bline = &a->lines[a->lineno_cur - 1];
5635 if (!bline->annotated)
5636 goto done;
5638 offset = a->line_offsets[a->lineno_cur - 1];
5639 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5640 err = got_error_from_errno("fseeko");
5641 goto done;
5644 while (a->lineno_cur <= a->nlines && bline->annotated) {
5645 char *smallerthan, *at, *nl, *committer;
5646 size_t len;
5648 if (getline(&line, &linesize, a->f) == -1) {
5649 if (ferror(a->f))
5650 err = got_error_from_errno("getline");
5651 break;
5654 committer = bline->committer;
5655 smallerthan = strchr(committer, '<');
5656 if (smallerthan && smallerthan[1] != '\0')
5657 committer = smallerthan + 1;
5658 at = strchr(committer, '@');
5659 if (at)
5660 *at = '\0';
5661 len = strlen(committer);
5662 if (len >= 9)
5663 committer[8] = '\0';
5665 nl = strchr(line, '\n');
5666 if (nl)
5667 *nl = '\0';
5668 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5669 bline->id_str, bline->datebuf, committer, line);
5671 a->lineno_cur++;
5672 bline = &a->lines[a->lineno_cur - 1];
5674 done:
5675 free(line);
5676 return err;
5679 static const struct got_error *
5680 cmd_blame(int argc, char *argv[])
5682 const struct got_error *error;
5683 struct got_repository *repo = NULL;
5684 struct got_worktree *worktree = NULL;
5685 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5686 char *link_target = NULL;
5687 struct got_object_id *obj_id = NULL;
5688 struct got_object_id *commit_id = NULL;
5689 struct got_commit_object *commit = NULL;
5690 struct got_blob_object *blob = NULL;
5691 char *commit_id_str = NULL;
5692 struct blame_cb_args bca;
5693 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5694 off_t filesize;
5695 int *pack_fds = NULL;
5696 FILE *f1 = NULL, *f2 = NULL;
5698 fd1 = got_opentempfd();
5699 if (fd1 == -1)
5700 return got_error_from_errno("got_opentempfd");
5702 memset(&bca, 0, sizeof(bca));
5704 #ifndef PROFILE
5705 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5706 NULL) == -1)
5707 err(1, "pledge");
5708 #endif
5710 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5711 switch (ch) {
5712 case 'c':
5713 commit_id_str = optarg;
5714 break;
5715 case 'r':
5716 repo_path = realpath(optarg, NULL);
5717 if (repo_path == NULL)
5718 return got_error_from_errno2("realpath",
5719 optarg);
5720 got_path_strip_trailing_slashes(repo_path);
5721 break;
5722 default:
5723 usage_blame();
5724 /* NOTREACHED */
5728 argc -= optind;
5729 argv += optind;
5731 if (argc == 1)
5732 path = argv[0];
5733 else
5734 usage_blame();
5736 cwd = getcwd(NULL, 0);
5737 if (cwd == NULL) {
5738 error = got_error_from_errno("getcwd");
5739 goto done;
5742 error = got_repo_pack_fds_open(&pack_fds);
5743 if (error != NULL)
5744 goto done;
5746 if (repo_path == NULL) {
5747 error = got_worktree_open(&worktree, cwd);
5748 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5749 goto done;
5750 else
5751 error = NULL;
5752 if (worktree) {
5753 repo_path =
5754 strdup(got_worktree_get_repo_path(worktree));
5755 if (repo_path == NULL) {
5756 error = got_error_from_errno("strdup");
5757 if (error)
5758 goto done;
5760 } else {
5761 repo_path = strdup(cwd);
5762 if (repo_path == NULL) {
5763 error = got_error_from_errno("strdup");
5764 goto done;
5769 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5770 if (error != NULL)
5771 goto done;
5773 if (worktree) {
5774 const char *prefix = got_worktree_get_path_prefix(worktree);
5775 char *p;
5777 error = got_worktree_resolve_path(&p, worktree, path);
5778 if (error)
5779 goto done;
5780 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5781 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5782 p) == -1) {
5783 error = got_error_from_errno("asprintf");
5784 free(p);
5785 goto done;
5787 free(p);
5788 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5789 } else {
5790 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5791 if (error)
5792 goto done;
5793 error = got_repo_map_path(&in_repo_path, repo, path);
5795 if (error)
5796 goto done;
5798 if (commit_id_str == NULL) {
5799 struct got_reference *head_ref;
5800 error = got_ref_open(&head_ref, repo, worktree ?
5801 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5802 if (error != NULL)
5803 goto done;
5804 error = got_ref_resolve(&commit_id, repo, head_ref);
5805 got_ref_close(head_ref);
5806 if (error != NULL)
5807 goto done;
5808 } else {
5809 struct got_reflist_head refs;
5810 TAILQ_INIT(&refs);
5811 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5812 NULL);
5813 if (error)
5814 goto done;
5815 error = got_repo_match_object_id(&commit_id, NULL,
5816 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5817 got_ref_list_free(&refs);
5818 if (error)
5819 goto done;
5822 if (worktree) {
5823 /* Release work tree lock. */
5824 got_worktree_close(worktree);
5825 worktree = NULL;
5828 error = got_object_open_as_commit(&commit, repo, commit_id);
5829 if (error)
5830 goto done;
5832 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5833 commit, repo);
5834 if (error)
5835 goto done;
5837 error = got_object_id_by_path(&obj_id, repo, commit,
5838 link_target ? link_target : in_repo_path);
5839 if (error)
5840 goto done;
5842 error = got_object_get_type(&obj_type, repo, obj_id);
5843 if (error)
5844 goto done;
5846 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5847 error = got_error_path(link_target ? link_target : in_repo_path,
5848 GOT_ERR_OBJ_TYPE);
5849 goto done;
5852 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5853 if (error)
5854 goto done;
5855 bca.f = got_opentemp();
5856 if (bca.f == NULL) {
5857 error = got_error_from_errno("got_opentemp");
5858 goto done;
5860 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5861 &bca.line_offsets, bca.f, blob);
5862 if (error || bca.nlines == 0)
5863 goto done;
5865 /* Don't include \n at EOF in the blame line count. */
5866 if (bca.line_offsets[bca.nlines - 1] == filesize)
5867 bca.nlines--;
5869 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5870 if (bca.lines == NULL) {
5871 error = got_error_from_errno("calloc");
5872 goto done;
5874 bca.lineno_cur = 1;
5875 bca.nlines_prec = 0;
5876 i = bca.nlines;
5877 while (i > 0) {
5878 i /= 10;
5879 bca.nlines_prec++;
5881 bca.repo = repo;
5883 fd2 = got_opentempfd();
5884 if (fd2 == -1) {
5885 error = got_error_from_errno("got_opentempfd");
5886 goto done;
5888 fd3 = got_opentempfd();
5889 if (fd3 == -1) {
5890 error = got_error_from_errno("got_opentempfd");
5891 goto done;
5893 f1 = got_opentemp();
5894 if (f1 == NULL) {
5895 error = got_error_from_errno("got_opentemp");
5896 goto done;
5898 f2 = got_opentemp();
5899 if (f2 == NULL) {
5900 error = got_error_from_errno("got_opentemp");
5901 goto done;
5903 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5904 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5905 check_cancelled, NULL, fd2, fd3, f1, f2);
5906 done:
5907 free(in_repo_path);
5908 free(link_target);
5909 free(repo_path);
5910 free(cwd);
5911 free(commit_id);
5912 free(obj_id);
5913 if (commit)
5914 got_object_commit_close(commit);
5916 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5917 error = got_error_from_errno("close");
5918 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5919 error = got_error_from_errno("close");
5920 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5921 error = got_error_from_errno("close");
5922 if (f1 && fclose(f1) == EOF && error == NULL)
5923 error = got_error_from_errno("fclose");
5924 if (f2 && fclose(f2) == EOF && error == NULL)
5925 error = got_error_from_errno("fclose");
5927 if (blob)
5928 got_object_blob_close(blob);
5929 if (worktree)
5930 got_worktree_close(worktree);
5931 if (repo) {
5932 const struct got_error *close_err = got_repo_close(repo);
5933 if (error == NULL)
5934 error = close_err;
5936 if (pack_fds) {
5937 const struct got_error *pack_err =
5938 got_repo_pack_fds_close(pack_fds);
5939 if (error == NULL)
5940 error = pack_err;
5942 if (bca.lines) {
5943 for (i = 0; i < bca.nlines; i++) {
5944 struct blame_line *bline = &bca.lines[i];
5945 free(bline->id_str);
5946 free(bline->committer);
5948 free(bca.lines);
5950 free(bca.line_offsets);
5951 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5952 error = got_error_from_errno("fclose");
5953 return error;
5956 __dead static void
5957 usage_tree(void)
5959 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5960 "[path]\n", getprogname());
5961 exit(1);
5964 static const struct got_error *
5965 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5966 const char *root_path, struct got_repository *repo)
5968 const struct got_error *err = NULL;
5969 int is_root_path = (strcmp(path, root_path) == 0);
5970 const char *modestr = "";
5971 mode_t mode = got_tree_entry_get_mode(te);
5972 char *link_target = NULL;
5974 path += strlen(root_path);
5975 while (path[0] == '/')
5976 path++;
5978 if (got_object_tree_entry_is_submodule(te))
5979 modestr = "$";
5980 else if (S_ISLNK(mode)) {
5981 int i;
5983 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5984 if (err)
5985 return err;
5986 for (i = 0; i < strlen(link_target); i++) {
5987 if (!isprint((unsigned char)link_target[i]))
5988 link_target[i] = '?';
5991 modestr = "@";
5993 else if (S_ISDIR(mode))
5994 modestr = "/";
5995 else if (mode & S_IXUSR)
5996 modestr = "*";
5998 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5999 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6000 link_target ? " -> ": "", link_target ? link_target : "");
6002 free(link_target);
6003 return NULL;
6006 static const struct got_error *
6007 print_tree(const char *path, struct got_commit_object *commit,
6008 int show_ids, int recurse, const char *root_path,
6009 struct got_repository *repo)
6011 const struct got_error *err = NULL;
6012 struct got_object_id *tree_id = NULL;
6013 struct got_tree_object *tree = NULL;
6014 int nentries, i;
6016 err = got_object_id_by_path(&tree_id, repo, commit, path);
6017 if (err)
6018 goto done;
6020 err = got_object_open_as_tree(&tree, repo, tree_id);
6021 if (err)
6022 goto done;
6023 nentries = got_object_tree_get_nentries(tree);
6024 for (i = 0; i < nentries; i++) {
6025 struct got_tree_entry *te;
6026 char *id = NULL;
6028 if (sigint_received || sigpipe_received)
6029 break;
6031 te = got_object_tree_get_entry(tree, i);
6032 if (show_ids) {
6033 char *id_str;
6034 err = got_object_id_str(&id_str,
6035 got_tree_entry_get_id(te));
6036 if (err)
6037 goto done;
6038 if (asprintf(&id, "%s ", id_str) == -1) {
6039 err = got_error_from_errno("asprintf");
6040 free(id_str);
6041 goto done;
6043 free(id_str);
6045 err = print_entry(te, id, path, root_path, repo);
6046 free(id);
6047 if (err)
6048 goto done;
6050 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6051 char *child_path;
6052 if (asprintf(&child_path, "%s%s%s", path,
6053 path[0] == '/' && path[1] == '\0' ? "" : "/",
6054 got_tree_entry_get_name(te)) == -1) {
6055 err = got_error_from_errno("asprintf");
6056 goto done;
6058 err = print_tree(child_path, commit, show_ids, 1,
6059 root_path, repo);
6060 free(child_path);
6061 if (err)
6062 goto done;
6065 done:
6066 if (tree)
6067 got_object_tree_close(tree);
6068 free(tree_id);
6069 return err;
6072 static const struct got_error *
6073 cmd_tree(int argc, char *argv[])
6075 const struct got_error *error;
6076 struct got_repository *repo = NULL;
6077 struct got_worktree *worktree = NULL;
6078 const char *path, *refname = NULL;
6079 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6080 struct got_object_id *commit_id = NULL;
6081 struct got_commit_object *commit = NULL;
6082 char *commit_id_str = NULL;
6083 int show_ids = 0, recurse = 0;
6084 int ch;
6085 int *pack_fds = NULL;
6087 #ifndef PROFILE
6088 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6089 NULL) == -1)
6090 err(1, "pledge");
6091 #endif
6093 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6094 switch (ch) {
6095 case 'c':
6096 commit_id_str = optarg;
6097 break;
6098 case 'i':
6099 show_ids = 1;
6100 break;
6101 case 'R':
6102 recurse = 1;
6103 break;
6104 case 'r':
6105 repo_path = realpath(optarg, NULL);
6106 if (repo_path == NULL)
6107 return got_error_from_errno2("realpath",
6108 optarg);
6109 got_path_strip_trailing_slashes(repo_path);
6110 break;
6111 default:
6112 usage_tree();
6113 /* NOTREACHED */
6117 argc -= optind;
6118 argv += optind;
6120 if (argc == 1)
6121 path = argv[0];
6122 else if (argc > 1)
6123 usage_tree();
6124 else
6125 path = NULL;
6127 cwd = getcwd(NULL, 0);
6128 if (cwd == NULL) {
6129 error = got_error_from_errno("getcwd");
6130 goto done;
6133 error = got_repo_pack_fds_open(&pack_fds);
6134 if (error != NULL)
6135 goto done;
6137 if (repo_path == NULL) {
6138 error = got_worktree_open(&worktree, cwd);
6139 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6140 goto done;
6141 else
6142 error = NULL;
6143 if (worktree) {
6144 repo_path =
6145 strdup(got_worktree_get_repo_path(worktree));
6146 if (repo_path == NULL)
6147 error = got_error_from_errno("strdup");
6148 if (error)
6149 goto done;
6150 } else {
6151 repo_path = strdup(cwd);
6152 if (repo_path == NULL) {
6153 error = got_error_from_errno("strdup");
6154 goto done;
6159 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6160 if (error != NULL)
6161 goto done;
6163 if (worktree) {
6164 const char *prefix = got_worktree_get_path_prefix(worktree);
6165 char *p;
6167 if (path == NULL)
6168 path = "";
6169 error = got_worktree_resolve_path(&p, worktree, path);
6170 if (error)
6171 goto done;
6172 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6173 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6174 p) == -1) {
6175 error = got_error_from_errno("asprintf");
6176 free(p);
6177 goto done;
6179 free(p);
6180 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6181 if (error)
6182 goto done;
6183 } else {
6184 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6185 if (error)
6186 goto done;
6187 if (path == NULL)
6188 path = "/";
6189 error = got_repo_map_path(&in_repo_path, repo, path);
6190 if (error != NULL)
6191 goto done;
6194 if (commit_id_str == NULL) {
6195 struct got_reference *head_ref;
6196 if (worktree)
6197 refname = got_worktree_get_head_ref_name(worktree);
6198 else
6199 refname = GOT_REF_HEAD;
6200 error = got_ref_open(&head_ref, repo, refname, 0);
6201 if (error != NULL)
6202 goto done;
6203 error = got_ref_resolve(&commit_id, repo, head_ref);
6204 got_ref_close(head_ref);
6205 if (error != NULL)
6206 goto done;
6207 } else {
6208 struct got_reflist_head refs;
6209 TAILQ_INIT(&refs);
6210 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6211 NULL);
6212 if (error)
6213 goto done;
6214 error = got_repo_match_object_id(&commit_id, NULL,
6215 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6216 got_ref_list_free(&refs);
6217 if (error)
6218 goto done;
6221 if (worktree) {
6222 /* Release work tree lock. */
6223 got_worktree_close(worktree);
6224 worktree = NULL;
6227 error = got_object_open_as_commit(&commit, repo, commit_id);
6228 if (error)
6229 goto done;
6231 error = print_tree(in_repo_path, commit, show_ids, recurse,
6232 in_repo_path, repo);
6233 done:
6234 free(in_repo_path);
6235 free(repo_path);
6236 free(cwd);
6237 free(commit_id);
6238 if (commit)
6239 got_object_commit_close(commit);
6240 if (worktree)
6241 got_worktree_close(worktree);
6242 if (repo) {
6243 const struct got_error *close_err = got_repo_close(repo);
6244 if (error == NULL)
6245 error = close_err;
6247 if (pack_fds) {
6248 const struct got_error *pack_err =
6249 got_repo_pack_fds_close(pack_fds);
6250 if (error == NULL)
6251 error = pack_err;
6253 return error;
6256 __dead static void
6257 usage_status(void)
6259 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6260 "[-s status-codes] [path ...]\n", getprogname());
6261 exit(1);
6264 struct got_status_arg {
6265 char *status_codes;
6266 int suppress;
6269 static const struct got_error *
6270 print_status(void *arg, unsigned char status, unsigned char staged_status,
6271 const char *path, struct got_object_id *blob_id,
6272 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6273 int dirfd, const char *de_name)
6275 struct got_status_arg *st = arg;
6277 if (status == staged_status && (status == GOT_STATUS_DELETE))
6278 status = GOT_STATUS_NO_CHANGE;
6279 if (st != NULL && st->status_codes) {
6280 size_t ncodes = strlen(st->status_codes);
6281 int i, j = 0;
6283 for (i = 0; i < ncodes ; i++) {
6284 if (st->suppress) {
6285 if (status == st->status_codes[i] ||
6286 staged_status == st->status_codes[i]) {
6287 j++;
6288 continue;
6290 } else {
6291 if (status == st->status_codes[i] ||
6292 staged_status == st->status_codes[i])
6293 break;
6297 if (st->suppress && j == 0)
6298 goto print;
6300 if (i == ncodes)
6301 return NULL;
6303 print:
6304 printf("%c%c %s\n", status, staged_status, path);
6305 return NULL;
6308 static const struct got_error *
6309 cmd_status(int argc, char *argv[])
6311 const struct got_error *error = NULL;
6312 struct got_repository *repo = NULL;
6313 struct got_worktree *worktree = NULL;
6314 struct got_status_arg st;
6315 char *cwd = NULL;
6316 struct got_pathlist_head paths;
6317 int ch, i, no_ignores = 0;
6318 int *pack_fds = NULL;
6320 TAILQ_INIT(&paths);
6322 memset(&st, 0, sizeof(st));
6323 st.status_codes = NULL;
6324 st.suppress = 0;
6326 #ifndef PROFILE
6327 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6328 NULL) == -1)
6329 err(1, "pledge");
6330 #endif
6332 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6333 switch (ch) {
6334 case 'I':
6335 no_ignores = 1;
6336 break;
6337 case 'S':
6338 if (st.status_codes != NULL && st.suppress == 0)
6339 option_conflict('S', 's');
6340 st.suppress = 1;
6341 /* fallthrough */
6342 case 's':
6343 for (i = 0; i < strlen(optarg); i++) {
6344 switch (optarg[i]) {
6345 case GOT_STATUS_MODIFY:
6346 case GOT_STATUS_ADD:
6347 case GOT_STATUS_DELETE:
6348 case GOT_STATUS_CONFLICT:
6349 case GOT_STATUS_MISSING:
6350 case GOT_STATUS_OBSTRUCTED:
6351 case GOT_STATUS_UNVERSIONED:
6352 case GOT_STATUS_MODE_CHANGE:
6353 case GOT_STATUS_NONEXISTENT:
6354 break;
6355 default:
6356 errx(1, "invalid status code '%c'",
6357 optarg[i]);
6360 if (ch == 's' && st.suppress)
6361 option_conflict('s', 'S');
6362 st.status_codes = optarg;
6363 break;
6364 default:
6365 usage_status();
6366 /* NOTREACHED */
6370 argc -= optind;
6371 argv += optind;
6373 cwd = getcwd(NULL, 0);
6374 if (cwd == NULL) {
6375 error = got_error_from_errno("getcwd");
6376 goto done;
6379 error = got_repo_pack_fds_open(&pack_fds);
6380 if (error != NULL)
6381 goto done;
6383 error = got_worktree_open(&worktree, cwd);
6384 if (error) {
6385 if (error->code == GOT_ERR_NOT_WORKTREE)
6386 error = wrap_not_worktree_error(error, "status", cwd);
6387 goto done;
6390 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6391 NULL, pack_fds);
6392 if (error != NULL)
6393 goto done;
6395 error = apply_unveil(got_repo_get_path(repo), 1,
6396 got_worktree_get_root_path(worktree));
6397 if (error)
6398 goto done;
6400 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6401 if (error)
6402 goto done;
6404 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6405 print_status, &st, check_cancelled, NULL);
6406 done:
6407 if (pack_fds) {
6408 const struct got_error *pack_err =
6409 got_repo_pack_fds_close(pack_fds);
6410 if (error == NULL)
6411 error = pack_err;
6413 if (repo) {
6414 const struct got_error *close_err = got_repo_close(repo);
6415 if (error == NULL)
6416 error = close_err;
6419 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6420 free(cwd);
6421 return error;
6424 __dead static void
6425 usage_ref(void)
6427 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6428 "[-s reference] [name]\n", getprogname());
6429 exit(1);
6432 static const struct got_error *
6433 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6435 static const struct got_error *err = NULL;
6436 struct got_reflist_head refs;
6437 struct got_reflist_entry *re;
6439 TAILQ_INIT(&refs);
6440 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6441 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6442 repo);
6443 if (err)
6444 return err;
6446 TAILQ_FOREACH(re, &refs, entry) {
6447 char *refstr;
6448 refstr = got_ref_to_str(re->ref);
6449 if (refstr == NULL) {
6450 err = got_error_from_errno("got_ref_to_str");
6451 break;
6453 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6454 free(refstr);
6457 got_ref_list_free(&refs);
6458 return err;
6461 static const struct got_error *
6462 delete_ref_by_name(struct got_repository *repo, const char *refname)
6464 const struct got_error *err;
6465 struct got_reference *ref;
6467 err = got_ref_open(&ref, repo, refname, 0);
6468 if (err)
6469 return err;
6471 err = delete_ref(repo, ref);
6472 got_ref_close(ref);
6473 return err;
6476 static const struct got_error *
6477 add_ref(struct got_repository *repo, const char *refname, const char *target)
6479 const struct got_error *err = NULL;
6480 struct got_object_id *id = NULL;
6481 struct got_reference *ref = NULL;
6482 struct got_reflist_head refs;
6485 * Don't let the user create a reference name with a leading '-'.
6486 * While technically a valid reference name, this case is usually
6487 * an unintended typo.
6489 if (refname[0] == '-')
6490 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6492 TAILQ_INIT(&refs);
6493 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6494 if (err)
6495 goto done;
6496 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6497 &refs, repo);
6498 got_ref_list_free(&refs);
6499 if (err)
6500 goto done;
6502 err = got_ref_alloc(&ref, refname, id);
6503 if (err)
6504 goto done;
6506 err = got_ref_write(ref, repo);
6507 done:
6508 if (ref)
6509 got_ref_close(ref);
6510 free(id);
6511 return err;
6514 static const struct got_error *
6515 add_symref(struct got_repository *repo, const char *refname, const char *target)
6517 const struct got_error *err = NULL;
6518 struct got_reference *ref = NULL;
6519 struct got_reference *target_ref = NULL;
6522 * Don't let the user create a reference name with a leading '-'.
6523 * While technically a valid reference name, this case is usually
6524 * an unintended typo.
6526 if (refname[0] == '-')
6527 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6529 err = got_ref_open(&target_ref, repo, target, 0);
6530 if (err)
6531 return err;
6533 err = got_ref_alloc_symref(&ref, refname, target_ref);
6534 if (err)
6535 goto done;
6537 err = got_ref_write(ref, repo);
6538 done:
6539 if (target_ref)
6540 got_ref_close(target_ref);
6541 if (ref)
6542 got_ref_close(ref);
6543 return err;
6546 static const struct got_error *
6547 cmd_ref(int argc, char *argv[])
6549 const struct got_error *error = NULL;
6550 struct got_repository *repo = NULL;
6551 struct got_worktree *worktree = NULL;
6552 char *cwd = NULL, *repo_path = NULL;
6553 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6554 const char *obj_arg = NULL, *symref_target= NULL;
6555 char *refname = NULL;
6556 int *pack_fds = NULL;
6558 #ifndef PROFILE
6559 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6560 "sendfd unveil", NULL) == -1)
6561 err(1, "pledge");
6562 #endif
6564 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6565 switch (ch) {
6566 case 'c':
6567 obj_arg = optarg;
6568 break;
6569 case 'd':
6570 do_delete = 1;
6571 break;
6572 case 'l':
6573 do_list = 1;
6574 break;
6575 case 'r':
6576 repo_path = realpath(optarg, NULL);
6577 if (repo_path == NULL)
6578 return got_error_from_errno2("realpath",
6579 optarg);
6580 got_path_strip_trailing_slashes(repo_path);
6581 break;
6582 case 's':
6583 symref_target = optarg;
6584 break;
6585 case 't':
6586 sort_by_time = 1;
6587 break;
6588 default:
6589 usage_ref();
6590 /* NOTREACHED */
6594 if (obj_arg && do_list)
6595 option_conflict('c', 'l');
6596 if (obj_arg && do_delete)
6597 option_conflict('c', 'd');
6598 if (obj_arg && symref_target)
6599 option_conflict('c', 's');
6600 if (symref_target && do_delete)
6601 option_conflict('s', 'd');
6602 if (symref_target && do_list)
6603 option_conflict('s', 'l');
6604 if (do_delete && do_list)
6605 option_conflict('d', 'l');
6606 if (sort_by_time && !do_list)
6607 errx(1, "-t option requires -l option");
6609 argc -= optind;
6610 argv += optind;
6612 if (do_list) {
6613 if (argc != 0 && argc != 1)
6614 usage_ref();
6615 if (argc == 1) {
6616 refname = strdup(argv[0]);
6617 if (refname == NULL) {
6618 error = got_error_from_errno("strdup");
6619 goto done;
6622 } else {
6623 if (argc != 1)
6624 usage_ref();
6625 refname = strdup(argv[0]);
6626 if (refname == NULL) {
6627 error = got_error_from_errno("strdup");
6628 goto done;
6632 if (refname)
6633 got_path_strip_trailing_slashes(refname);
6635 cwd = getcwd(NULL, 0);
6636 if (cwd == NULL) {
6637 error = got_error_from_errno("getcwd");
6638 goto done;
6641 error = got_repo_pack_fds_open(&pack_fds);
6642 if (error != NULL)
6643 goto done;
6645 if (repo_path == NULL) {
6646 error = got_worktree_open(&worktree, cwd);
6647 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6648 goto done;
6649 else
6650 error = NULL;
6651 if (worktree) {
6652 repo_path =
6653 strdup(got_worktree_get_repo_path(worktree));
6654 if (repo_path == NULL)
6655 error = got_error_from_errno("strdup");
6656 if (error)
6657 goto done;
6658 } else {
6659 repo_path = strdup(cwd);
6660 if (repo_path == NULL) {
6661 error = got_error_from_errno("strdup");
6662 goto done;
6667 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6668 if (error != NULL)
6669 goto done;
6671 #ifndef PROFILE
6672 if (do_list) {
6673 /* Remove "cpath" promise. */
6674 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6675 NULL) == -1)
6676 err(1, "pledge");
6678 #endif
6680 error = apply_unveil(got_repo_get_path(repo), do_list,
6681 worktree ? got_worktree_get_root_path(worktree) : NULL);
6682 if (error)
6683 goto done;
6685 if (do_list)
6686 error = list_refs(repo, refname, sort_by_time);
6687 else if (do_delete)
6688 error = delete_ref_by_name(repo, refname);
6689 else if (symref_target)
6690 error = add_symref(repo, refname, symref_target);
6691 else {
6692 if (obj_arg == NULL)
6693 usage_ref();
6694 error = add_ref(repo, refname, obj_arg);
6696 done:
6697 free(refname);
6698 if (repo) {
6699 const struct got_error *close_err = got_repo_close(repo);
6700 if (error == NULL)
6701 error = close_err;
6703 if (worktree)
6704 got_worktree_close(worktree);
6705 if (pack_fds) {
6706 const struct got_error *pack_err =
6707 got_repo_pack_fds_close(pack_fds);
6708 if (error == NULL)
6709 error = pack_err;
6711 free(cwd);
6712 free(repo_path);
6713 return error;
6716 __dead static void
6717 usage_branch(void)
6719 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6720 "[-r repository-path] [name]\n", getprogname());
6721 exit(1);
6724 static const struct got_error *
6725 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6726 struct got_reference *ref)
6728 const struct got_error *err = NULL;
6729 const char *refname, *marker = " ";
6730 char *refstr;
6732 refname = got_ref_get_name(ref);
6733 if (worktree && strcmp(refname,
6734 got_worktree_get_head_ref_name(worktree)) == 0) {
6735 struct got_object_id *id = NULL;
6737 err = got_ref_resolve(&id, repo, ref);
6738 if (err)
6739 return err;
6740 if (got_object_id_cmp(id,
6741 got_worktree_get_base_commit_id(worktree)) == 0)
6742 marker = "* ";
6743 else
6744 marker = "~ ";
6745 free(id);
6748 if (strncmp(refname, "refs/heads/", 11) == 0)
6749 refname += 11;
6750 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6751 refname += 18;
6752 if (strncmp(refname, "refs/remotes/", 13) == 0)
6753 refname += 13;
6755 refstr = got_ref_to_str(ref);
6756 if (refstr == NULL)
6757 return got_error_from_errno("got_ref_to_str");
6759 printf("%s%s: %s\n", marker, refname, refstr);
6760 free(refstr);
6761 return NULL;
6764 static const struct got_error *
6765 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6767 const char *refname;
6769 if (worktree == NULL)
6770 return got_error(GOT_ERR_NOT_WORKTREE);
6772 refname = got_worktree_get_head_ref_name(worktree);
6774 if (strncmp(refname, "refs/heads/", 11) == 0)
6775 refname += 11;
6776 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6777 refname += 18;
6779 printf("%s\n", refname);
6781 return NULL;
6784 static const struct got_error *
6785 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6786 int sort_by_time)
6788 static const struct got_error *err = NULL;
6789 struct got_reflist_head refs;
6790 struct got_reflist_entry *re;
6791 struct got_reference *temp_ref = NULL;
6792 int rebase_in_progress, histedit_in_progress;
6794 TAILQ_INIT(&refs);
6796 if (worktree) {
6797 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6798 worktree);
6799 if (err)
6800 return err;
6802 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6803 worktree);
6804 if (err)
6805 return err;
6807 if (rebase_in_progress || histedit_in_progress) {
6808 err = got_ref_open(&temp_ref, repo,
6809 got_worktree_get_head_ref_name(worktree), 0);
6810 if (err)
6811 return err;
6812 list_branch(repo, worktree, temp_ref);
6813 got_ref_close(temp_ref);
6817 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6818 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6819 repo);
6820 if (err)
6821 return err;
6823 TAILQ_FOREACH(re, &refs, entry)
6824 list_branch(repo, worktree, re->ref);
6826 got_ref_list_free(&refs);
6828 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6829 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6830 repo);
6831 if (err)
6832 return err;
6834 TAILQ_FOREACH(re, &refs, entry)
6835 list_branch(repo, worktree, re->ref);
6837 got_ref_list_free(&refs);
6839 return NULL;
6842 static const struct got_error *
6843 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6844 const char *branch_name)
6846 const struct got_error *err = NULL;
6847 struct got_reference *ref = NULL;
6848 char *refname, *remote_refname = NULL;
6850 if (strncmp(branch_name, "refs/", 5) == 0)
6851 branch_name += 5;
6852 if (strncmp(branch_name, "heads/", 6) == 0)
6853 branch_name += 6;
6854 else if (strncmp(branch_name, "remotes/", 8) == 0)
6855 branch_name += 8;
6857 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6858 return got_error_from_errno("asprintf");
6860 if (asprintf(&remote_refname, "refs/remotes/%s",
6861 branch_name) == -1) {
6862 err = got_error_from_errno("asprintf");
6863 goto done;
6866 err = got_ref_open(&ref, repo, refname, 0);
6867 if (err) {
6868 const struct got_error *err2;
6869 if (err->code != GOT_ERR_NOT_REF)
6870 goto done;
6872 * Keep 'err' intact such that if neither branch exists
6873 * we report "refs/heads" rather than "refs/remotes" in
6874 * our error message.
6876 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6877 if (err2)
6878 goto done;
6879 err = NULL;
6882 if (worktree &&
6883 strcmp(got_worktree_get_head_ref_name(worktree),
6884 got_ref_get_name(ref)) == 0) {
6885 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6886 "will not delete this work tree's current branch");
6887 goto done;
6890 err = delete_ref(repo, ref);
6891 done:
6892 if (ref)
6893 got_ref_close(ref);
6894 free(refname);
6895 free(remote_refname);
6896 return err;
6899 static const struct got_error *
6900 add_branch(struct got_repository *repo, const char *branch_name,
6901 struct got_object_id *base_commit_id)
6903 const struct got_error *err = NULL;
6904 struct got_reference *ref = NULL;
6905 char *refname = NULL;
6908 * Don't let the user create a branch name with a leading '-'.
6909 * While technically a valid reference name, this case is usually
6910 * an unintended typo.
6912 if (branch_name[0] == '-')
6913 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6915 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6916 branch_name += 11;
6918 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6919 err = got_error_from_errno("asprintf");
6920 goto done;
6923 err = got_ref_open(&ref, repo, refname, 0);
6924 if (err == NULL) {
6925 err = got_error(GOT_ERR_BRANCH_EXISTS);
6926 goto done;
6927 } else if (err->code != GOT_ERR_NOT_REF)
6928 goto done;
6930 err = got_ref_alloc(&ref, refname, base_commit_id);
6931 if (err)
6932 goto done;
6934 err = got_ref_write(ref, repo);
6935 done:
6936 if (ref)
6937 got_ref_close(ref);
6938 free(refname);
6939 return err;
6942 static const struct got_error *
6943 cmd_branch(int argc, char *argv[])
6945 const struct got_error *error = NULL;
6946 struct got_repository *repo = NULL;
6947 struct got_worktree *worktree = NULL;
6948 char *cwd = NULL, *repo_path = NULL;
6949 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6950 const char *delref = NULL, *commit_id_arg = NULL;
6951 struct got_reference *ref = NULL;
6952 struct got_pathlist_head paths;
6953 struct got_object_id *commit_id = NULL;
6954 char *commit_id_str = NULL;
6955 int *pack_fds = NULL;
6957 TAILQ_INIT(&paths);
6959 #ifndef PROFILE
6960 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6961 "sendfd unveil", NULL) == -1)
6962 err(1, "pledge");
6963 #endif
6965 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6966 switch (ch) {
6967 case 'c':
6968 commit_id_arg = optarg;
6969 break;
6970 case 'd':
6971 delref = optarg;
6972 break;
6973 case 'l':
6974 do_list = 1;
6975 break;
6976 case 'n':
6977 do_update = 0;
6978 break;
6979 case 'r':
6980 repo_path = realpath(optarg, NULL);
6981 if (repo_path == NULL)
6982 return got_error_from_errno2("realpath",
6983 optarg);
6984 got_path_strip_trailing_slashes(repo_path);
6985 break;
6986 case 't':
6987 sort_by_time = 1;
6988 break;
6989 default:
6990 usage_branch();
6991 /* NOTREACHED */
6995 if (do_list && delref)
6996 option_conflict('l', 'd');
6997 if (sort_by_time && !do_list)
6998 errx(1, "-t option requires -l option");
7000 argc -= optind;
7001 argv += optind;
7003 if (!do_list && !delref && argc == 0)
7004 do_show = 1;
7006 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7007 errx(1, "-c option can only be used when creating a branch");
7009 if (do_list || delref) {
7010 if (argc > 0)
7011 usage_branch();
7012 } else if (!do_show && argc != 1)
7013 usage_branch();
7015 cwd = getcwd(NULL, 0);
7016 if (cwd == NULL) {
7017 error = got_error_from_errno("getcwd");
7018 goto done;
7021 error = got_repo_pack_fds_open(&pack_fds);
7022 if (error != NULL)
7023 goto done;
7025 if (repo_path == NULL) {
7026 error = got_worktree_open(&worktree, cwd);
7027 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7028 goto done;
7029 else
7030 error = NULL;
7031 if (worktree) {
7032 repo_path =
7033 strdup(got_worktree_get_repo_path(worktree));
7034 if (repo_path == NULL)
7035 error = got_error_from_errno("strdup");
7036 if (error)
7037 goto done;
7038 } else {
7039 repo_path = strdup(cwd);
7040 if (repo_path == NULL) {
7041 error = got_error_from_errno("strdup");
7042 goto done;
7047 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7048 if (error != NULL)
7049 goto done;
7051 #ifndef PROFILE
7052 if (do_list || do_show) {
7053 /* Remove "cpath" promise. */
7054 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7055 NULL) == -1)
7056 err(1, "pledge");
7058 #endif
7060 error = apply_unveil(got_repo_get_path(repo), do_list,
7061 worktree ? got_worktree_get_root_path(worktree) : NULL);
7062 if (error)
7063 goto done;
7065 if (do_show)
7066 error = show_current_branch(repo, worktree);
7067 else if (do_list)
7068 error = list_branches(repo, worktree, sort_by_time);
7069 else if (delref)
7070 error = delete_branch(repo, worktree, delref);
7071 else {
7072 struct got_reflist_head refs;
7073 TAILQ_INIT(&refs);
7074 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7075 NULL);
7076 if (error)
7077 goto done;
7078 if (commit_id_arg == NULL)
7079 commit_id_arg = worktree ?
7080 got_worktree_get_head_ref_name(worktree) :
7081 GOT_REF_HEAD;
7082 error = got_repo_match_object_id(&commit_id, NULL,
7083 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7084 got_ref_list_free(&refs);
7085 if (error)
7086 goto done;
7087 error = add_branch(repo, argv[0], commit_id);
7088 if (error)
7089 goto done;
7090 if (worktree && do_update) {
7091 struct got_update_progress_arg upa;
7092 char *branch_refname = NULL;
7094 error = got_object_id_str(&commit_id_str, commit_id);
7095 if (error)
7096 goto done;
7097 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7098 worktree);
7099 if (error)
7100 goto done;
7101 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7102 == -1) {
7103 error = got_error_from_errno("asprintf");
7104 goto done;
7106 error = got_ref_open(&ref, repo, branch_refname, 0);
7107 free(branch_refname);
7108 if (error)
7109 goto done;
7110 error = switch_head_ref(ref, commit_id, worktree,
7111 repo);
7112 if (error)
7113 goto done;
7114 error = got_worktree_set_base_commit_id(worktree, repo,
7115 commit_id);
7116 if (error)
7117 goto done;
7118 memset(&upa, 0, sizeof(upa));
7119 error = got_worktree_checkout_files(worktree, &paths,
7120 repo, update_progress, &upa, check_cancelled,
7121 NULL);
7122 if (error)
7123 goto done;
7124 if (upa.did_something) {
7125 printf("Updated to %s: %s\n",
7126 got_worktree_get_head_ref_name(worktree),
7127 commit_id_str);
7129 print_update_progress_stats(&upa);
7132 done:
7133 if (ref)
7134 got_ref_close(ref);
7135 if (repo) {
7136 const struct got_error *close_err = got_repo_close(repo);
7137 if (error == NULL)
7138 error = close_err;
7140 if (worktree)
7141 got_worktree_close(worktree);
7142 if (pack_fds) {
7143 const struct got_error *pack_err =
7144 got_repo_pack_fds_close(pack_fds);
7145 if (error == NULL)
7146 error = pack_err;
7148 free(cwd);
7149 free(repo_path);
7150 free(commit_id);
7151 free(commit_id_str);
7152 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7153 return error;
7157 __dead static void
7158 usage_tag(void)
7160 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7161 "[-r repository-path] [-s signer-id] name\n", getprogname());
7162 exit(1);
7165 #if 0
7166 static const struct got_error *
7167 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7169 const struct got_error *err = NULL;
7170 struct got_reflist_entry *re, *se, *new;
7171 struct got_object_id *re_id, *se_id;
7172 struct got_tag_object *re_tag, *se_tag;
7173 time_t re_time, se_time;
7175 STAILQ_FOREACH(re, tags, entry) {
7176 se = STAILQ_FIRST(sorted);
7177 if (se == NULL) {
7178 err = got_reflist_entry_dup(&new, re);
7179 if (err)
7180 return err;
7181 STAILQ_INSERT_HEAD(sorted, new, entry);
7182 continue;
7183 } else {
7184 err = got_ref_resolve(&re_id, repo, re->ref);
7185 if (err)
7186 break;
7187 err = got_object_open_as_tag(&re_tag, repo, re_id);
7188 free(re_id);
7189 if (err)
7190 break;
7191 re_time = got_object_tag_get_tagger_time(re_tag);
7192 got_object_tag_close(re_tag);
7195 while (se) {
7196 err = got_ref_resolve(&se_id, repo, re->ref);
7197 if (err)
7198 break;
7199 err = got_object_open_as_tag(&se_tag, repo, se_id);
7200 free(se_id);
7201 if (err)
7202 break;
7203 se_time = got_object_tag_get_tagger_time(se_tag);
7204 got_object_tag_close(se_tag);
7206 if (se_time > re_time) {
7207 err = got_reflist_entry_dup(&new, re);
7208 if (err)
7209 return err;
7210 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7211 break;
7213 se = STAILQ_NEXT(se, entry);
7214 continue;
7217 done:
7218 return err;
7220 #endif
7222 static const struct got_error *
7223 get_tag_refname(char **refname, const char *tag_name)
7225 const struct got_error *err;
7227 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7228 *refname = strdup(tag_name);
7229 if (*refname == NULL)
7230 return got_error_from_errno("strdup");
7231 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7232 err = got_error_from_errno("asprintf");
7233 *refname = NULL;
7234 return err;
7237 return NULL;
7240 static const struct got_error *
7241 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7242 const char *allowed_signers, const char *revoked_signers, int verbosity)
7244 static const struct got_error *err = NULL;
7245 struct got_reflist_head refs;
7246 struct got_reflist_entry *re;
7247 char *wanted_refname = NULL;
7248 int bad_sigs = 0;
7250 TAILQ_INIT(&refs);
7252 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7253 if (err)
7254 return err;
7256 if (tag_name) {
7257 struct got_reference *ref;
7258 err = get_tag_refname(&wanted_refname, tag_name);
7259 if (err)
7260 goto done;
7261 /* Wanted tag reference should exist. */
7262 err = got_ref_open(&ref, repo, wanted_refname, 0);
7263 if (err)
7264 goto done;
7265 got_ref_close(ref);
7268 TAILQ_FOREACH(re, &refs, entry) {
7269 const char *refname;
7270 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7271 char datebuf[26];
7272 const char *tagger, *ssh_sig = NULL;
7273 char *sig_msg = NULL;
7274 time_t tagger_time;
7275 struct got_object_id *id;
7276 struct got_tag_object *tag;
7277 struct got_commit_object *commit = NULL;
7279 refname = got_ref_get_name(re->ref);
7280 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7281 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7282 continue;
7283 refname += 10;
7284 refstr = got_ref_to_str(re->ref);
7285 if (refstr == NULL) {
7286 err = got_error_from_errno("got_ref_to_str");
7287 break;
7290 err = got_ref_resolve(&id, repo, re->ref);
7291 if (err)
7292 break;
7293 err = got_object_open_as_tag(&tag, repo, id);
7294 if (err) {
7295 if (err->code != GOT_ERR_OBJ_TYPE) {
7296 free(id);
7297 break;
7299 /* "lightweight" tag */
7300 err = got_object_open_as_commit(&commit, repo, id);
7301 if (err) {
7302 free(id);
7303 break;
7305 tagger = got_object_commit_get_committer(commit);
7306 tagger_time =
7307 got_object_commit_get_committer_time(commit);
7308 err = got_object_id_str(&id_str, id);
7309 free(id);
7310 if (err)
7311 break;
7312 } else {
7313 free(id);
7314 tagger = got_object_tag_get_tagger(tag);
7315 tagger_time = got_object_tag_get_tagger_time(tag);
7316 err = got_object_id_str(&id_str,
7317 got_object_tag_get_object_id(tag));
7318 if (err)
7319 break;
7322 if (tag && verify_tags) {
7323 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7324 got_object_tag_get_message(tag));
7325 if (ssh_sig && allowed_signers == NULL) {
7326 err = got_error_msg(
7327 GOT_ERR_VERIFY_TAG_SIGNATURE,
7328 "SSH signature verification requires "
7329 "setting allowed_signers in "
7330 "got.conf(5)");
7331 break;
7335 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7336 free(refstr);
7337 printf("from: %s\n", tagger);
7338 datestr = get_datestr(&tagger_time, datebuf);
7339 if (datestr)
7340 printf("date: %s UTC\n", datestr);
7341 if (commit)
7342 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7343 else {
7344 switch (got_object_tag_get_object_type(tag)) {
7345 case GOT_OBJ_TYPE_BLOB:
7346 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7347 id_str);
7348 break;
7349 case GOT_OBJ_TYPE_TREE:
7350 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7351 id_str);
7352 break;
7353 case GOT_OBJ_TYPE_COMMIT:
7354 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7355 id_str);
7356 break;
7357 case GOT_OBJ_TYPE_TAG:
7358 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7359 id_str);
7360 break;
7361 default:
7362 break;
7365 free(id_str);
7367 if (ssh_sig) {
7368 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7369 allowed_signers, revoked_signers, verbosity);
7370 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7371 bad_sigs = 1;
7372 else if (err)
7373 break;
7374 printf("signature: %s", sig_msg);
7375 free(sig_msg);
7376 sig_msg = NULL;
7379 if (commit) {
7380 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7381 if (err)
7382 break;
7383 got_object_commit_close(commit);
7384 } else {
7385 tagmsg0 = strdup(got_object_tag_get_message(tag));
7386 got_object_tag_close(tag);
7387 if (tagmsg0 == NULL) {
7388 err = got_error_from_errno("strdup");
7389 break;
7393 tagmsg = tagmsg0;
7394 do {
7395 line = strsep(&tagmsg, "\n");
7396 if (line)
7397 printf(" %s\n", line);
7398 } while (line);
7399 free(tagmsg0);
7401 done:
7402 got_ref_list_free(&refs);
7403 free(wanted_refname);
7405 if (err == NULL && bad_sigs)
7406 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7407 return err;
7410 static const struct got_error *
7411 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7412 const char *tag_name, const char *repo_path)
7414 const struct got_error *err = NULL;
7415 char *template = NULL, *initial_content = NULL;
7416 char *editor = NULL;
7417 int initial_content_len;
7418 int fd = -1;
7420 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7421 err = got_error_from_errno("asprintf");
7422 goto done;
7425 initial_content_len = asprintf(&initial_content,
7426 "\n# tagging commit %s as %s\n",
7427 commit_id_str, tag_name);
7428 if (initial_content_len == -1) {
7429 err = got_error_from_errno("asprintf");
7430 goto done;
7433 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7434 if (err)
7435 goto done;
7437 if (write(fd, initial_content, initial_content_len) == -1) {
7438 err = got_error_from_errno2("write", *tagmsg_path);
7439 goto done;
7441 if (close(fd) == -1) {
7442 err = got_error_from_errno2("close", *tagmsg_path);
7443 goto done;
7445 fd = -1;
7447 err = get_editor(&editor);
7448 if (err)
7449 goto done;
7450 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7451 initial_content_len, 1);
7452 done:
7453 free(initial_content);
7454 free(template);
7455 free(editor);
7457 if (fd != -1 && close(fd) == -1 && err == NULL)
7458 err = got_error_from_errno2("close", *tagmsg_path);
7460 if (err) {
7461 free(*tagmsg);
7462 *tagmsg = NULL;
7464 return err;
7467 static const struct got_error *
7468 add_tag(struct got_repository *repo, const char *tagger,
7469 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7470 const char *signer_id, int verbosity)
7472 const struct got_error *err = NULL;
7473 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7474 char *label = NULL, *commit_id_str = NULL;
7475 struct got_reference *ref = NULL;
7476 char *refname = NULL, *tagmsg = NULL;
7477 char *tagmsg_path = NULL, *tag_id_str = NULL;
7478 int preserve_tagmsg = 0;
7479 struct got_reflist_head refs;
7481 TAILQ_INIT(&refs);
7484 * Don't let the user create a tag name with a leading '-'.
7485 * While technically a valid reference name, this case is usually
7486 * an unintended typo.
7488 if (tag_name[0] == '-')
7489 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7491 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7492 if (err)
7493 goto done;
7495 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7496 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7497 if (err)
7498 goto done;
7500 err = got_object_id_str(&commit_id_str, commit_id);
7501 if (err)
7502 goto done;
7504 err = get_tag_refname(&refname, tag_name);
7505 if (err)
7506 goto done;
7507 if (strncmp("refs/tags/", tag_name, 10) == 0)
7508 tag_name += 10;
7510 err = got_ref_open(&ref, repo, refname, 0);
7511 if (err == NULL) {
7512 err = got_error(GOT_ERR_TAG_EXISTS);
7513 goto done;
7514 } else if (err->code != GOT_ERR_NOT_REF)
7515 goto done;
7517 if (tagmsg_arg == NULL) {
7518 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7519 tag_name, got_repo_get_path(repo));
7520 if (err) {
7521 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7522 tagmsg_path != NULL)
7523 preserve_tagmsg = 1;
7524 goto done;
7526 /* Editor is done; we can now apply unveil(2) */
7527 err = got_sigs_apply_unveil();
7528 if (err)
7529 goto done;
7530 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7531 if (err)
7532 goto done;
7535 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7536 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7537 verbosity);
7538 if (err) {
7539 if (tagmsg_path)
7540 preserve_tagmsg = 1;
7541 goto done;
7544 err = got_ref_alloc(&ref, refname, tag_id);
7545 if (err) {
7546 if (tagmsg_path)
7547 preserve_tagmsg = 1;
7548 goto done;
7551 err = got_ref_write(ref, repo);
7552 if (err) {
7553 if (tagmsg_path)
7554 preserve_tagmsg = 1;
7555 goto done;
7558 err = got_object_id_str(&tag_id_str, tag_id);
7559 if (err) {
7560 if (tagmsg_path)
7561 preserve_tagmsg = 1;
7562 goto done;
7564 printf("Created tag %s\n", tag_id_str);
7565 done:
7566 if (preserve_tagmsg) {
7567 fprintf(stderr, "%s: tag message preserved in %s\n",
7568 getprogname(), tagmsg_path);
7569 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7570 err = got_error_from_errno2("unlink", tagmsg_path);
7571 free(tag_id_str);
7572 if (ref)
7573 got_ref_close(ref);
7574 free(commit_id);
7575 free(commit_id_str);
7576 free(refname);
7577 free(tagmsg);
7578 free(tagmsg_path);
7579 got_ref_list_free(&refs);
7580 return err;
7583 static const struct got_error *
7584 cmd_tag(int argc, char *argv[])
7586 const struct got_error *error = NULL;
7587 struct got_repository *repo = NULL;
7588 struct got_worktree *worktree = NULL;
7589 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7590 char *gitconfig_path = NULL, *tagger = NULL;
7591 char *allowed_signers = NULL, *revoked_signers = NULL;
7592 const char *signer_id = NULL;
7593 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7594 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7595 int *pack_fds = NULL;
7597 #ifndef PROFILE
7598 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7599 "sendfd unveil", NULL) == -1)
7600 err(1, "pledge");
7601 #endif
7603 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7604 switch (ch) {
7605 case 'c':
7606 commit_id_arg = optarg;
7607 break;
7608 case 'l':
7609 do_list = 1;
7610 break;
7611 case 'm':
7612 tagmsg = optarg;
7613 break;
7614 case 'r':
7615 repo_path = realpath(optarg, NULL);
7616 if (repo_path == NULL) {
7617 error = got_error_from_errno2("realpath",
7618 optarg);
7619 goto done;
7621 got_path_strip_trailing_slashes(repo_path);
7622 break;
7623 case 's':
7624 signer_id = optarg;
7625 break;
7626 case 'V':
7627 verify_tags = 1;
7628 break;
7629 case 'v':
7630 if (verbosity < 0)
7631 verbosity = 0;
7632 else if (verbosity < 3)
7633 verbosity++;
7634 break;
7635 default:
7636 usage_tag();
7637 /* NOTREACHED */
7641 argc -= optind;
7642 argv += optind;
7644 if (do_list || verify_tags) {
7645 if (commit_id_arg != NULL)
7646 errx(1,
7647 "-c option can only be used when creating a tag");
7648 if (tagmsg) {
7649 if (do_list)
7650 option_conflict('l', 'm');
7651 else
7652 option_conflict('V', 'm');
7654 if (signer_id) {
7655 if (do_list)
7656 option_conflict('l', 's');
7657 else
7658 option_conflict('V', 's');
7660 if (argc > 1)
7661 usage_tag();
7662 } else if (argc != 1)
7663 usage_tag();
7665 if (argc == 1)
7666 tag_name = argv[0];
7668 cwd = getcwd(NULL, 0);
7669 if (cwd == NULL) {
7670 error = got_error_from_errno("getcwd");
7671 goto done;
7674 error = got_repo_pack_fds_open(&pack_fds);
7675 if (error != NULL)
7676 goto done;
7678 if (repo_path == NULL) {
7679 error = got_worktree_open(&worktree, cwd);
7680 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7681 goto done;
7682 else
7683 error = NULL;
7684 if (worktree) {
7685 repo_path =
7686 strdup(got_worktree_get_repo_path(worktree));
7687 if (repo_path == NULL)
7688 error = got_error_from_errno("strdup");
7689 if (error)
7690 goto done;
7691 } else {
7692 repo_path = strdup(cwd);
7693 if (repo_path == NULL) {
7694 error = got_error_from_errno("strdup");
7695 goto done;
7700 if (do_list || verify_tags) {
7701 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7702 if (error != NULL)
7703 goto done;
7704 error = get_allowed_signers(&allowed_signers, repo, worktree);
7705 if (error)
7706 goto done;
7707 error = get_revoked_signers(&revoked_signers, repo, worktree);
7708 if (error)
7709 goto done;
7710 if (worktree) {
7711 /* Release work tree lock. */
7712 got_worktree_close(worktree);
7713 worktree = NULL;
7717 * Remove "cpath" promise unless needed for signature tmpfile
7718 * creation.
7720 if (verify_tags)
7721 got_sigs_apply_unveil();
7722 else {
7723 #ifndef PROFILE
7724 if (pledge("stdio rpath wpath flock proc exec sendfd "
7725 "unveil", NULL) == -1)
7726 err(1, "pledge");
7727 #endif
7729 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7730 if (error)
7731 goto done;
7732 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7733 revoked_signers, verbosity);
7734 } else {
7735 error = get_gitconfig_path(&gitconfig_path);
7736 if (error)
7737 goto done;
7738 error = got_repo_open(&repo, repo_path, gitconfig_path,
7739 pack_fds);
7740 if (error != NULL)
7741 goto done;
7743 error = get_author(&tagger, repo, worktree);
7744 if (error)
7745 goto done;
7746 if (signer_id == NULL)
7747 signer_id = get_signer_id(repo, worktree);
7749 if (tagmsg) {
7750 if (signer_id) {
7751 error = got_sigs_apply_unveil();
7752 if (error)
7753 goto done;
7755 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7756 if (error)
7757 goto done;
7760 if (commit_id_arg == NULL) {
7761 struct got_reference *head_ref;
7762 struct got_object_id *commit_id;
7763 error = got_ref_open(&head_ref, repo,
7764 worktree ? got_worktree_get_head_ref_name(worktree)
7765 : GOT_REF_HEAD, 0);
7766 if (error)
7767 goto done;
7768 error = got_ref_resolve(&commit_id, repo, head_ref);
7769 got_ref_close(head_ref);
7770 if (error)
7771 goto done;
7772 error = got_object_id_str(&commit_id_str, commit_id);
7773 free(commit_id);
7774 if (error)
7775 goto done;
7778 if (worktree) {
7779 /* Release work tree lock. */
7780 got_worktree_close(worktree);
7781 worktree = NULL;
7784 error = add_tag(repo, tagger, tag_name,
7785 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7786 signer_id, verbosity);
7788 done:
7789 if (repo) {
7790 const struct got_error *close_err = got_repo_close(repo);
7791 if (error == NULL)
7792 error = close_err;
7794 if (worktree)
7795 got_worktree_close(worktree);
7796 if (pack_fds) {
7797 const struct got_error *pack_err =
7798 got_repo_pack_fds_close(pack_fds);
7799 if (error == NULL)
7800 error = pack_err;
7802 free(cwd);
7803 free(repo_path);
7804 free(gitconfig_path);
7805 free(commit_id_str);
7806 free(tagger);
7807 free(allowed_signers);
7808 free(revoked_signers);
7809 return error;
7812 __dead static void
7813 usage_add(void)
7815 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7816 exit(1);
7819 static const struct got_error *
7820 add_progress(void *arg, unsigned char status, const char *path)
7822 while (path[0] == '/')
7823 path++;
7824 printf("%c %s\n", status, path);
7825 return NULL;
7828 static const struct got_error *
7829 cmd_add(int argc, char *argv[])
7831 const struct got_error *error = NULL;
7832 struct got_repository *repo = NULL;
7833 struct got_worktree *worktree = NULL;
7834 char *cwd = NULL;
7835 struct got_pathlist_head paths;
7836 struct got_pathlist_entry *pe;
7837 int ch, can_recurse = 0, no_ignores = 0;
7838 int *pack_fds = NULL;
7840 TAILQ_INIT(&paths);
7842 #ifndef PROFILE
7843 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7844 NULL) == -1)
7845 err(1, "pledge");
7846 #endif
7848 while ((ch = getopt(argc, argv, "IR")) != -1) {
7849 switch (ch) {
7850 case 'I':
7851 no_ignores = 1;
7852 break;
7853 case 'R':
7854 can_recurse = 1;
7855 break;
7856 default:
7857 usage_add();
7858 /* NOTREACHED */
7862 argc -= optind;
7863 argv += optind;
7865 if (argc < 1)
7866 usage_add();
7868 cwd = getcwd(NULL, 0);
7869 if (cwd == NULL) {
7870 error = got_error_from_errno("getcwd");
7871 goto done;
7874 error = got_repo_pack_fds_open(&pack_fds);
7875 if (error != NULL)
7876 goto done;
7878 error = got_worktree_open(&worktree, cwd);
7879 if (error) {
7880 if (error->code == GOT_ERR_NOT_WORKTREE)
7881 error = wrap_not_worktree_error(error, "add", cwd);
7882 goto done;
7885 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7886 NULL, pack_fds);
7887 if (error != NULL)
7888 goto done;
7890 error = apply_unveil(got_repo_get_path(repo), 1,
7891 got_worktree_get_root_path(worktree));
7892 if (error)
7893 goto done;
7895 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7896 if (error)
7897 goto done;
7899 if (!can_recurse) {
7900 char *ondisk_path;
7901 struct stat sb;
7902 TAILQ_FOREACH(pe, &paths, entry) {
7903 if (asprintf(&ondisk_path, "%s/%s",
7904 got_worktree_get_root_path(worktree),
7905 pe->path) == -1) {
7906 error = got_error_from_errno("asprintf");
7907 goto done;
7909 if (lstat(ondisk_path, &sb) == -1) {
7910 if (errno == ENOENT) {
7911 free(ondisk_path);
7912 continue;
7914 error = got_error_from_errno2("lstat",
7915 ondisk_path);
7916 free(ondisk_path);
7917 goto done;
7919 free(ondisk_path);
7920 if (S_ISDIR(sb.st_mode)) {
7921 error = got_error_msg(GOT_ERR_BAD_PATH,
7922 "adding directories requires -R option");
7923 goto done;
7928 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7929 NULL, repo, no_ignores);
7930 done:
7931 if (repo) {
7932 const struct got_error *close_err = got_repo_close(repo);
7933 if (error == NULL)
7934 error = close_err;
7936 if (worktree)
7937 got_worktree_close(worktree);
7938 if (pack_fds) {
7939 const struct got_error *pack_err =
7940 got_repo_pack_fds_close(pack_fds);
7941 if (error == NULL)
7942 error = pack_err;
7944 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7945 free(cwd);
7946 return error;
7949 __dead static void
7950 usage_remove(void)
7952 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7953 getprogname());
7954 exit(1);
7957 static const struct got_error *
7958 print_remove_status(void *arg, unsigned char status,
7959 unsigned char staged_status, const char *path)
7961 while (path[0] == '/')
7962 path++;
7963 if (status == GOT_STATUS_NONEXISTENT)
7964 return NULL;
7965 if (status == staged_status && (status == GOT_STATUS_DELETE))
7966 status = GOT_STATUS_NO_CHANGE;
7967 printf("%c%c %s\n", status, staged_status, path);
7968 return NULL;
7971 static const struct got_error *
7972 cmd_remove(int argc, char *argv[])
7974 const struct got_error *error = NULL;
7975 struct got_worktree *worktree = NULL;
7976 struct got_repository *repo = NULL;
7977 const char *status_codes = NULL;
7978 char *cwd = NULL;
7979 struct got_pathlist_head paths;
7980 struct got_pathlist_entry *pe;
7981 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7982 int ignore_missing_paths = 0;
7983 int *pack_fds = NULL;
7985 TAILQ_INIT(&paths);
7987 #ifndef PROFILE
7988 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7989 NULL) == -1)
7990 err(1, "pledge");
7991 #endif
7993 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7994 switch (ch) {
7995 case 'f':
7996 delete_local_mods = 1;
7997 ignore_missing_paths = 1;
7998 break;
7999 case 'k':
8000 keep_on_disk = 1;
8001 break;
8002 case 'R':
8003 can_recurse = 1;
8004 break;
8005 case 's':
8006 for (i = 0; i < strlen(optarg); i++) {
8007 switch (optarg[i]) {
8008 case GOT_STATUS_MODIFY:
8009 delete_local_mods = 1;
8010 break;
8011 case GOT_STATUS_MISSING:
8012 ignore_missing_paths = 1;
8013 break;
8014 default:
8015 errx(1, "invalid status code '%c'",
8016 optarg[i]);
8019 status_codes = optarg;
8020 break;
8021 default:
8022 usage_remove();
8023 /* NOTREACHED */
8027 argc -= optind;
8028 argv += optind;
8030 if (argc < 1)
8031 usage_remove();
8033 cwd = getcwd(NULL, 0);
8034 if (cwd == NULL) {
8035 error = got_error_from_errno("getcwd");
8036 goto done;
8039 error = got_repo_pack_fds_open(&pack_fds);
8040 if (error != NULL)
8041 goto done;
8043 error = got_worktree_open(&worktree, cwd);
8044 if (error) {
8045 if (error->code == GOT_ERR_NOT_WORKTREE)
8046 error = wrap_not_worktree_error(error, "remove", cwd);
8047 goto done;
8050 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8051 NULL, pack_fds);
8052 if (error)
8053 goto done;
8055 error = apply_unveil(got_repo_get_path(repo), 1,
8056 got_worktree_get_root_path(worktree));
8057 if (error)
8058 goto done;
8060 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8061 if (error)
8062 goto done;
8064 if (!can_recurse) {
8065 char *ondisk_path;
8066 struct stat sb;
8067 TAILQ_FOREACH(pe, &paths, entry) {
8068 if (asprintf(&ondisk_path, "%s/%s",
8069 got_worktree_get_root_path(worktree),
8070 pe->path) == -1) {
8071 error = got_error_from_errno("asprintf");
8072 goto done;
8074 if (lstat(ondisk_path, &sb) == -1) {
8075 if (errno == ENOENT) {
8076 free(ondisk_path);
8077 continue;
8079 error = got_error_from_errno2("lstat",
8080 ondisk_path);
8081 free(ondisk_path);
8082 goto done;
8084 free(ondisk_path);
8085 if (S_ISDIR(sb.st_mode)) {
8086 error = got_error_msg(GOT_ERR_BAD_PATH,
8087 "removing directories requires -R option");
8088 goto done;
8093 error = got_worktree_schedule_delete(worktree, &paths,
8094 delete_local_mods, status_codes, print_remove_status, NULL,
8095 repo, keep_on_disk, ignore_missing_paths);
8096 done:
8097 if (repo) {
8098 const struct got_error *close_err = got_repo_close(repo);
8099 if (error == NULL)
8100 error = close_err;
8102 if (worktree)
8103 got_worktree_close(worktree);
8104 if (pack_fds) {
8105 const struct got_error *pack_err =
8106 got_repo_pack_fds_close(pack_fds);
8107 if (error == NULL)
8108 error = pack_err;
8110 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8111 free(cwd);
8112 return error;
8115 __dead static void
8116 usage_patch(void)
8118 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8119 "[patchfile]\n", getprogname());
8120 exit(1);
8123 static const struct got_error *
8124 patch_from_stdin(int *patchfd)
8126 const struct got_error *err = NULL;
8127 ssize_t r;
8128 char buf[BUFSIZ];
8129 sig_t sighup, sigint, sigquit;
8131 *patchfd = got_opentempfd();
8132 if (*patchfd == -1)
8133 return got_error_from_errno("got_opentempfd");
8135 sighup = signal(SIGHUP, SIG_DFL);
8136 sigint = signal(SIGINT, SIG_DFL);
8137 sigquit = signal(SIGQUIT, SIG_DFL);
8139 for (;;) {
8140 r = read(0, buf, sizeof(buf));
8141 if (r == -1) {
8142 err = got_error_from_errno("read");
8143 break;
8145 if (r == 0)
8146 break;
8147 if (write(*patchfd, buf, r) == -1) {
8148 err = got_error_from_errno("write");
8149 break;
8153 signal(SIGHUP, sighup);
8154 signal(SIGINT, sigint);
8155 signal(SIGQUIT, sigquit);
8157 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8158 err = got_error_from_errno("lseek");
8160 if (err != NULL) {
8161 close(*patchfd);
8162 *patchfd = -1;
8165 return err;
8168 static const struct got_error *
8169 patch_progress(void *arg, const char *old, const char *new,
8170 unsigned char status, const struct got_error *error, int old_from,
8171 int old_lines, int new_from, int new_lines, int offset,
8172 int ws_mangled, const struct got_error *hunk_err)
8174 const char *path = new == NULL ? old : new;
8176 while (*path == '/')
8177 path++;
8179 if (status != 0)
8180 printf("%c %s\n", status, path);
8182 if (error != NULL)
8183 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8185 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8186 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8187 old_lines, new_from, new_lines);
8188 if (hunk_err != NULL)
8189 printf("%s\n", hunk_err->msg);
8190 else if (offset != 0)
8191 printf("applied with offset %d\n", offset);
8192 else
8193 printf("hunk contains mangled whitespace\n");
8196 return NULL;
8199 static const struct got_error *
8200 cmd_patch(int argc, char *argv[])
8202 const struct got_error *error = NULL, *close_error = NULL;
8203 struct got_worktree *worktree = NULL;
8204 struct got_repository *repo = NULL;
8205 struct got_reflist_head refs;
8206 struct got_object_id *commit_id = NULL;
8207 const char *commit_id_str = NULL;
8208 struct stat sb;
8209 const char *errstr;
8210 char *cwd = NULL;
8211 int ch, nop = 0, strip = -1, reverse = 0;
8212 int patchfd;
8213 int *pack_fds = NULL;
8215 TAILQ_INIT(&refs);
8217 #ifndef PROFILE
8218 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8219 "unveil", NULL) == -1)
8220 err(1, "pledge");
8221 #endif
8223 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8224 switch (ch) {
8225 case 'c':
8226 commit_id_str = optarg;
8227 break;
8228 case 'n':
8229 nop = 1;
8230 break;
8231 case 'p':
8232 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8233 if (errstr != NULL)
8234 errx(1, "pathname strip count is %s: %s",
8235 errstr, optarg);
8236 break;
8237 case 'R':
8238 reverse = 1;
8239 break;
8240 default:
8241 usage_patch();
8242 /* NOTREACHED */
8246 argc -= optind;
8247 argv += optind;
8249 if (argc == 0) {
8250 error = patch_from_stdin(&patchfd);
8251 if (error)
8252 return error;
8253 } else if (argc == 1) {
8254 patchfd = open(argv[0], O_RDONLY);
8255 if (patchfd == -1) {
8256 error = got_error_from_errno2("open", argv[0]);
8257 return error;
8259 if (fstat(patchfd, &sb) == -1) {
8260 error = got_error_from_errno2("fstat", argv[0]);
8261 goto done;
8263 if (!S_ISREG(sb.st_mode)) {
8264 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8265 goto done;
8267 } else
8268 usage_patch();
8270 if ((cwd = getcwd(NULL, 0)) == NULL) {
8271 error = got_error_from_errno("getcwd");
8272 goto done;
8275 error = got_repo_pack_fds_open(&pack_fds);
8276 if (error != NULL)
8277 goto done;
8279 error = got_worktree_open(&worktree, cwd);
8280 if (error != NULL)
8281 goto done;
8283 const char *repo_path = got_worktree_get_repo_path(worktree);
8284 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8285 if (error != NULL)
8286 goto done;
8288 error = apply_unveil(got_repo_get_path(repo), 0,
8289 got_worktree_get_root_path(worktree));
8290 if (error != NULL)
8291 goto done;
8293 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8294 if (error)
8295 goto done;
8297 if (commit_id_str != NULL) {
8298 error = got_repo_match_object_id(&commit_id, NULL,
8299 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8300 if (error)
8301 goto done;
8304 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8305 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8307 done:
8308 got_ref_list_free(&refs);
8309 free(commit_id);
8310 if (repo) {
8311 close_error = got_repo_close(repo);
8312 if (error == NULL)
8313 error = close_error;
8315 if (worktree != NULL) {
8316 close_error = got_worktree_close(worktree);
8317 if (error == NULL)
8318 error = close_error;
8320 if (pack_fds) {
8321 const struct got_error *pack_err =
8322 got_repo_pack_fds_close(pack_fds);
8323 if (error == NULL)
8324 error = pack_err;
8326 free(cwd);
8327 return error;
8330 __dead static void
8331 usage_revert(void)
8333 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8334 getprogname());
8335 exit(1);
8338 static const struct got_error *
8339 revert_progress(void *arg, unsigned char status, const char *path)
8341 if (status == GOT_STATUS_UNVERSIONED)
8342 return NULL;
8344 while (path[0] == '/')
8345 path++;
8346 printf("%c %s\n", status, path);
8347 return NULL;
8350 struct choose_patch_arg {
8351 FILE *patch_script_file;
8352 const char *action;
8355 static const struct got_error *
8356 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8357 int nchanges, const char *action)
8359 const struct got_error *err;
8360 char *line = NULL;
8361 size_t linesize = 0;
8362 ssize_t linelen;
8364 switch (status) {
8365 case GOT_STATUS_ADD:
8366 printf("A %s\n%s this addition? [y/n] ", path, action);
8367 break;
8368 case GOT_STATUS_DELETE:
8369 printf("D %s\n%s this deletion? [y/n] ", path, action);
8370 break;
8371 case GOT_STATUS_MODIFY:
8372 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8373 return got_error_from_errno("fseek");
8374 printf(GOT_COMMIT_SEP_STR);
8375 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8376 printf("%s", line);
8377 if (linelen == -1 && ferror(patch_file)) {
8378 err = got_error_from_errno("getline");
8379 free(line);
8380 return err;
8382 free(line);
8383 printf(GOT_COMMIT_SEP_STR);
8384 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8385 path, n, nchanges, action);
8386 break;
8387 default:
8388 return got_error_path(path, GOT_ERR_FILE_STATUS);
8391 fflush(stdout);
8392 return NULL;
8395 static const struct got_error *
8396 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8397 FILE *patch_file, int n, int nchanges)
8399 const struct got_error *err = NULL;
8400 char *line = NULL;
8401 size_t linesize = 0;
8402 ssize_t linelen;
8403 int resp = ' ';
8404 struct choose_patch_arg *a = arg;
8406 *choice = GOT_PATCH_CHOICE_NONE;
8408 if (a->patch_script_file) {
8409 char *nl;
8410 err = show_change(status, path, patch_file, n, nchanges,
8411 a->action);
8412 if (err)
8413 return err;
8414 linelen = getline(&line, &linesize, a->patch_script_file);
8415 if (linelen == -1) {
8416 if (ferror(a->patch_script_file))
8417 return got_error_from_errno("getline");
8418 return NULL;
8420 nl = strchr(line, '\n');
8421 if (nl)
8422 *nl = '\0';
8423 if (strcmp(line, "y") == 0) {
8424 *choice = GOT_PATCH_CHOICE_YES;
8425 printf("y\n");
8426 } else if (strcmp(line, "n") == 0) {
8427 *choice = GOT_PATCH_CHOICE_NO;
8428 printf("n\n");
8429 } else if (strcmp(line, "q") == 0 &&
8430 status == GOT_STATUS_MODIFY) {
8431 *choice = GOT_PATCH_CHOICE_QUIT;
8432 printf("q\n");
8433 } else
8434 printf("invalid response '%s'\n", line);
8435 free(line);
8436 return NULL;
8439 while (resp != 'y' && resp != 'n' && resp != 'q') {
8440 err = show_change(status, path, patch_file, n, nchanges,
8441 a->action);
8442 if (err)
8443 return err;
8444 resp = getchar();
8445 if (resp == '\n')
8446 resp = getchar();
8447 if (status == GOT_STATUS_MODIFY) {
8448 if (resp != 'y' && resp != 'n' && resp != 'q') {
8449 printf("invalid response '%c'\n", resp);
8450 resp = ' ';
8452 } else if (resp != 'y' && resp != 'n') {
8453 printf("invalid response '%c'\n", resp);
8454 resp = ' ';
8458 if (resp == 'y')
8459 *choice = GOT_PATCH_CHOICE_YES;
8460 else if (resp == 'n')
8461 *choice = GOT_PATCH_CHOICE_NO;
8462 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8463 *choice = GOT_PATCH_CHOICE_QUIT;
8465 return NULL;
8468 struct wt_commitable_path_arg {
8469 struct got_pathlist_head *commit_paths;
8470 int *has_changes;
8474 * Shortcut work tree status callback to determine if the set of paths scanned
8475 * has at least one versioned path that is being modified and, if not NULL, is
8476 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8477 * soon as a path is passed with a status that satisfies this criteria.
8479 static const struct got_error *
8480 worktree_has_commitable_path(void *arg, unsigned char status,
8481 unsigned char staged_status, const char *path,
8482 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8483 struct got_object_id *commit_id, int dirfd, const char *de_name)
8485 struct wt_commitable_path_arg *a = arg;
8487 if (status == staged_status && (status == GOT_STATUS_DELETE))
8488 status = GOT_STATUS_NO_CHANGE;
8490 if (!(status == GOT_STATUS_NO_CHANGE ||
8491 status == GOT_STATUS_UNVERSIONED) ||
8492 staged_status != GOT_STATUS_NO_CHANGE) {
8493 if (a->commit_paths != NULL) {
8494 struct got_pathlist_entry *pe;
8496 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8497 if (strncmp(path, pe->path,
8498 pe->path_len) == 0) {
8499 *a->has_changes = 1;
8500 break;
8503 } else
8504 *a->has_changes = 1;
8506 if (*a->has_changes)
8507 return got_error(GOT_ERR_FILE_MODIFIED);
8510 return NULL;
8514 * Check that the changeset of the commit identified by id is
8515 * comprised of at least one modified path that is being committed.
8517 static const struct got_error *
8518 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8519 struct got_object_id *id, struct got_worktree *worktree,
8520 struct got_repository *repo)
8522 const struct got_error *err;
8523 struct got_pathlist_head paths;
8524 struct got_commit_object *commit = NULL, *pcommit = NULL;
8525 struct got_tree_object *tree = NULL, *ptree = NULL;
8526 struct got_object_qid *pid;
8528 TAILQ_INIT(&paths);
8530 err = got_object_open_as_commit(&commit, repo, id);
8531 if (err)
8532 goto done;
8534 err = got_object_open_as_tree(&tree, repo,
8535 got_object_commit_get_tree_id(commit));
8536 if (err)
8537 goto done;
8539 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8540 if (pid != NULL) {
8541 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8542 if (err)
8543 goto done;
8545 err = got_object_open_as_tree(&ptree, repo,
8546 got_object_commit_get_tree_id(pcommit));
8547 if (err)
8548 goto done;
8551 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8552 got_diff_tree_collect_changed_paths, &paths, 0);
8553 if (err)
8554 goto done;
8556 err = got_worktree_status(worktree, &paths, repo, 0,
8557 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8558 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8560 * At least one changed path in the referenced commit is
8561 * modified in the work tree, that's all we need to know!
8563 err = NULL;
8566 done:
8567 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8568 if (commit)
8569 got_object_commit_close(commit);
8570 if (pcommit)
8571 got_object_commit_close(pcommit);
8572 if (tree)
8573 got_object_tree_close(tree);
8574 if (ptree)
8575 got_object_tree_close(ptree);
8576 return err;
8580 * Remove any "logmsg" reference comprised entirely of paths that have
8581 * been reverted in this work tree. If any path in the logmsg ref changeset
8582 * remains in a changed state in the worktree, do not remove the reference.
8584 static const struct got_error *
8585 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8587 const struct got_error *err;
8588 struct got_reflist_head refs;
8589 struct got_reflist_entry *re;
8590 struct got_commit_object *commit = NULL;
8591 struct got_object_id *commit_id = NULL;
8592 struct wt_commitable_path_arg wcpa;
8593 char *uuidstr = NULL;
8595 TAILQ_INIT(&refs);
8597 err = got_worktree_get_uuid(&uuidstr, worktree);
8598 if (err)
8599 goto done;
8601 err = got_ref_list(&refs, repo, "refs/got/worktree",
8602 got_ref_cmp_by_name, repo);
8603 if (err)
8604 goto done;
8606 TAILQ_FOREACH(re, &refs, entry) {
8607 const char *refname;
8608 int has_changes = 0;
8610 refname = got_ref_get_name(re->ref);
8612 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8613 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8614 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8615 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8616 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8617 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8618 else
8619 continue;
8621 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8622 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8623 else
8624 continue;
8626 err = got_repo_match_object_id(&commit_id, NULL, refname,
8627 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8628 if (err)
8629 goto done;
8631 err = got_object_open_as_commit(&commit, repo, commit_id);
8632 if (err)
8633 goto done;
8635 wcpa.commit_paths = NULL;
8636 wcpa.has_changes = &has_changes;
8638 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8639 worktree, repo);
8640 if (err)
8641 goto done;
8643 if (!has_changes) {
8644 err = got_ref_delete(re->ref, repo);
8645 if (err)
8646 goto done;
8649 got_object_commit_close(commit);
8650 commit = NULL;
8651 free(commit_id);
8652 commit_id = NULL;
8655 done:
8656 free(uuidstr);
8657 free(commit_id);
8658 got_ref_list_free(&refs);
8659 if (commit)
8660 got_object_commit_close(commit);
8661 return err;
8664 static const struct got_error *
8665 cmd_revert(int argc, char *argv[])
8667 const struct got_error *error = NULL;
8668 struct got_worktree *worktree = NULL;
8669 struct got_repository *repo = NULL;
8670 char *cwd = NULL, *path = NULL;
8671 struct got_pathlist_head paths;
8672 struct got_pathlist_entry *pe;
8673 int ch, can_recurse = 0, pflag = 0;
8674 FILE *patch_script_file = NULL;
8675 const char *patch_script_path = NULL;
8676 struct choose_patch_arg cpa;
8677 int *pack_fds = NULL;
8679 TAILQ_INIT(&paths);
8681 #ifndef PROFILE
8682 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8683 "unveil", NULL) == -1)
8684 err(1, "pledge");
8685 #endif
8687 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8688 switch (ch) {
8689 case 'F':
8690 patch_script_path = optarg;
8691 break;
8692 case 'p':
8693 pflag = 1;
8694 break;
8695 case 'R':
8696 can_recurse = 1;
8697 break;
8698 default:
8699 usage_revert();
8700 /* NOTREACHED */
8704 argc -= optind;
8705 argv += optind;
8707 if (argc < 1)
8708 usage_revert();
8709 if (patch_script_path && !pflag)
8710 errx(1, "-F option can only be used together with -p option");
8712 cwd = getcwd(NULL, 0);
8713 if (cwd == NULL) {
8714 error = got_error_from_errno("getcwd");
8715 goto done;
8718 error = got_repo_pack_fds_open(&pack_fds);
8719 if (error != NULL)
8720 goto done;
8722 error = got_worktree_open(&worktree, cwd);
8723 if (error) {
8724 if (error->code == GOT_ERR_NOT_WORKTREE)
8725 error = wrap_not_worktree_error(error, "revert", cwd);
8726 goto done;
8729 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8730 NULL, pack_fds);
8731 if (error != NULL)
8732 goto done;
8734 if (patch_script_path) {
8735 patch_script_file = fopen(patch_script_path, "re");
8736 if (patch_script_file == NULL) {
8737 error = got_error_from_errno2("fopen",
8738 patch_script_path);
8739 goto done;
8744 * XXX "c" perm needed on repo dir to delete merge references.
8746 error = apply_unveil(got_repo_get_path(repo), 0,
8747 got_worktree_get_root_path(worktree));
8748 if (error)
8749 goto done;
8751 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8752 if (error)
8753 goto done;
8755 if (!can_recurse) {
8756 char *ondisk_path;
8757 struct stat sb;
8758 TAILQ_FOREACH(pe, &paths, entry) {
8759 if (asprintf(&ondisk_path, "%s/%s",
8760 got_worktree_get_root_path(worktree),
8761 pe->path) == -1) {
8762 error = got_error_from_errno("asprintf");
8763 goto done;
8765 if (lstat(ondisk_path, &sb) == -1) {
8766 if (errno == ENOENT) {
8767 free(ondisk_path);
8768 continue;
8770 error = got_error_from_errno2("lstat",
8771 ondisk_path);
8772 free(ondisk_path);
8773 goto done;
8775 free(ondisk_path);
8776 if (S_ISDIR(sb.st_mode)) {
8777 error = got_error_msg(GOT_ERR_BAD_PATH,
8778 "reverting directories requires -R option");
8779 goto done;
8784 cpa.patch_script_file = patch_script_file;
8785 cpa.action = "revert";
8786 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8787 pflag ? choose_patch : NULL, &cpa, repo);
8789 error = rm_logmsg_ref(worktree, repo);
8790 done:
8791 if (patch_script_file && fclose(patch_script_file) == EOF &&
8792 error == NULL)
8793 error = got_error_from_errno2("fclose", patch_script_path);
8794 if (repo) {
8795 const struct got_error *close_err = got_repo_close(repo);
8796 if (error == NULL)
8797 error = close_err;
8799 if (worktree)
8800 got_worktree_close(worktree);
8801 if (pack_fds) {
8802 const struct got_error *pack_err =
8803 got_repo_pack_fds_close(pack_fds);
8804 if (error == NULL)
8805 error = pack_err;
8807 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8808 free(path);
8809 free(cwd);
8810 return error;
8813 __dead static void
8814 usage_commit(void)
8816 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8817 "[-m message] [path ...]\n", getprogname());
8818 exit(1);
8821 struct collect_commit_logmsg_arg {
8822 const char *cmdline_log;
8823 const char *prepared_log;
8824 const char *merged_log;
8825 int non_interactive;
8826 const char *editor;
8827 const char *worktree_path;
8828 const char *branch_name;
8829 const char *repo_path;
8830 char *logmsg_path;
8834 static const struct got_error *
8835 read_prepared_logmsg(char **logmsg, const char *path)
8837 const struct got_error *err = NULL;
8838 FILE *f = NULL;
8839 struct stat sb;
8840 size_t r;
8842 *logmsg = NULL;
8843 memset(&sb, 0, sizeof(sb));
8845 f = fopen(path, "re");
8846 if (f == NULL)
8847 return got_error_from_errno2("fopen", path);
8849 if (fstat(fileno(f), &sb) == -1) {
8850 err = got_error_from_errno2("fstat", path);
8851 goto done;
8853 if (sb.st_size == 0) {
8854 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8855 goto done;
8858 *logmsg = malloc(sb.st_size + 1);
8859 if (*logmsg == NULL) {
8860 err = got_error_from_errno("malloc");
8861 goto done;
8864 r = fread(*logmsg, 1, sb.st_size, f);
8865 if (r != sb.st_size) {
8866 if (ferror(f))
8867 err = got_error_from_errno2("fread", path);
8868 else
8869 err = got_error(GOT_ERR_IO);
8870 goto done;
8872 (*logmsg)[sb.st_size] = '\0';
8873 done:
8874 if (fclose(f) == EOF && err == NULL)
8875 err = got_error_from_errno2("fclose", path);
8876 if (err) {
8877 free(*logmsg);
8878 *logmsg = NULL;
8880 return err;
8883 static const struct got_error *
8884 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8885 const char *diff_path, char **logmsg, void *arg)
8887 char *initial_content = NULL;
8888 struct got_pathlist_entry *pe;
8889 const struct got_error *err = NULL;
8890 char *template = NULL;
8891 char *prepared_msg = NULL, *merged_msg = NULL;
8892 struct collect_commit_logmsg_arg *a = arg;
8893 int initial_content_len;
8894 int fd = -1;
8895 size_t len;
8897 /* if a message was specified on the command line, just use it */
8898 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8899 len = strlen(a->cmdline_log) + 1;
8900 *logmsg = malloc(len + 1);
8901 if (*logmsg == NULL)
8902 return got_error_from_errno("malloc");
8903 strlcpy(*logmsg, a->cmdline_log, len);
8904 return NULL;
8905 } else if (a->prepared_log != NULL && a->non_interactive)
8906 return read_prepared_logmsg(logmsg, a->prepared_log);
8908 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8909 return got_error_from_errno("asprintf");
8911 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8912 if (err)
8913 goto done;
8915 if (a->prepared_log) {
8916 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8917 if (err)
8918 goto done;
8919 } else if (a->merged_log) {
8920 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8921 if (err)
8922 goto done;
8925 initial_content_len = asprintf(&initial_content,
8926 "%s%s\n# changes to be committed on branch %s:\n",
8927 prepared_msg ? prepared_msg : "",
8928 merged_msg ? merged_msg : "", a->branch_name);
8929 if (initial_content_len == -1) {
8930 err = got_error_from_errno("asprintf");
8931 goto done;
8934 if (write(fd, initial_content, initial_content_len) == -1) {
8935 err = got_error_from_errno2("write", a->logmsg_path);
8936 goto done;
8939 TAILQ_FOREACH(pe, commitable_paths, entry) {
8940 struct got_commitable *ct = pe->data;
8941 dprintf(fd, "# %c %s\n",
8942 got_commitable_get_status(ct),
8943 got_commitable_get_path(ct));
8946 if (diff_path) {
8947 dprintf(fd, "# detailed changes can be viewed in %s\n",
8948 diff_path);
8951 if (close(fd) == -1) {
8952 err = got_error_from_errno2("close", a->logmsg_path);
8953 goto done;
8955 fd = -1;
8957 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8958 initial_content_len, a->prepared_log ? 0 : 1);
8959 done:
8960 free(initial_content);
8961 free(template);
8962 free(prepared_msg);
8963 free(merged_msg);
8965 if (fd != -1 && close(fd) == -1 && err == NULL)
8966 err = got_error_from_errno2("close", a->logmsg_path);
8968 /* Editor is done; we can now apply unveil(2) */
8969 if (err == NULL)
8970 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8971 if (err) {
8972 free(*logmsg);
8973 *logmsg = NULL;
8975 return err;
8978 static const struct got_error *
8979 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8980 const char *type, int has_content)
8982 const struct got_error *err = NULL;
8983 char *logmsg = NULL;
8985 err = got_object_commit_get_logmsg(&logmsg, commit);
8986 if (err)
8987 return err;
8989 if (fprintf(f, "%s# log message of %s commit %s:%s",
8990 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8991 err = got_ferror(f, GOT_ERR_IO);
8993 free(logmsg);
8994 return err;
8998 * Lookup "logmsg" references of backed-out and cherrypicked commits
8999 * belonging to the current work tree. If found, and the worktree has
9000 * at least one modified file that was changed in the referenced commit,
9001 * add its log message to a new temporary file at *logmsg_path.
9002 * Add all refs found to matched_refs to be scheduled for removal on
9003 * successful commit.
9005 static const struct got_error *
9006 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9007 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9008 struct got_repository *repo)
9010 const struct got_error *err;
9011 struct got_commit_object *commit = NULL;
9012 struct got_object_id *id = NULL;
9013 struct got_reflist_head refs;
9014 struct got_reflist_entry *re, *re_match;
9015 FILE *f = NULL;
9016 char *uuidstr = NULL;
9017 int added_logmsg = 0;
9019 TAILQ_INIT(&refs);
9021 *logmsg_path = NULL;
9023 err = got_worktree_get_uuid(&uuidstr, worktree);
9024 if (err)
9025 goto done;
9027 err = got_ref_list(&refs, repo, "refs/got/worktree",
9028 got_ref_cmp_by_name, repo);
9029 if (err)
9030 goto done;
9032 TAILQ_FOREACH(re, &refs, entry) {
9033 const char *refname, *type;
9034 struct wt_commitable_path_arg wcpa;
9035 int add_logmsg = 0;
9037 refname = got_ref_get_name(re->ref);
9039 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9040 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9041 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9042 type = "cherrypicked";
9043 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9044 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9045 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9046 type = "backed-out";
9047 } else
9048 continue;
9050 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9051 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9052 else
9053 continue;
9055 err = got_repo_match_object_id(&id, NULL, refname,
9056 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9057 if (err)
9058 goto done;
9060 err = got_object_open_as_commit(&commit, repo, id);
9061 if (err)
9062 goto done;
9064 wcpa.commit_paths = paths;
9065 wcpa.has_changes = &add_logmsg;
9067 err = commit_path_changed_in_worktree(&wcpa, id,
9068 worktree, repo);
9069 if (err)
9070 goto done;
9072 if (add_logmsg) {
9073 if (f == NULL) {
9074 err = got_opentemp_named(logmsg_path, &f,
9075 "got-commit-logmsg", "");
9076 if (err)
9077 goto done;
9079 err = cat_logmsg(f, commit, refname, type,
9080 added_logmsg);
9081 if (err)
9082 goto done;
9083 if (!added_logmsg)
9084 ++added_logmsg;
9086 err = got_reflist_entry_dup(&re_match, re);
9087 if (err)
9088 goto done;
9089 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9092 got_object_commit_close(commit);
9093 commit = NULL;
9094 free(id);
9095 id = NULL;
9098 done:
9099 free(id);
9100 free(uuidstr);
9101 got_ref_list_free(&refs);
9102 if (commit)
9103 got_object_commit_close(commit);
9104 if (f && fclose(f) == EOF && err == NULL)
9105 err = got_error_from_errno("fclose");
9106 if (!added_logmsg) {
9107 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9108 err = got_error_from_errno2("unlink", *logmsg_path);
9109 *logmsg_path = NULL;
9111 return err;
9114 static const struct got_error *
9115 cmd_commit(int argc, char *argv[])
9117 const struct got_error *error = NULL;
9118 struct got_worktree *worktree = NULL;
9119 struct got_repository *repo = NULL;
9120 char *cwd = NULL, *id_str = NULL;
9121 struct got_object_id *id = NULL;
9122 const char *logmsg = NULL;
9123 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9124 struct collect_commit_logmsg_arg cl_arg;
9125 const char *author = NULL;
9126 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9127 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9128 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9129 int show_diff = 1, commit_conflicts = 0;
9130 struct got_pathlist_head paths;
9131 struct got_reflist_head refs;
9132 struct got_reflist_entry *re;
9133 int *pack_fds = NULL;
9135 TAILQ_INIT(&refs);
9136 TAILQ_INIT(&paths);
9137 cl_arg.logmsg_path = NULL;
9139 #ifndef PROFILE
9140 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9141 "unveil", NULL) == -1)
9142 err(1, "pledge");
9143 #endif
9145 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9146 switch (ch) {
9147 case 'A':
9148 author = optarg;
9149 error = valid_author(author);
9150 if (error)
9151 return error;
9152 break;
9153 case 'C':
9154 commit_conflicts = 1;
9155 break;
9156 case 'F':
9157 if (logmsg != NULL)
9158 option_conflict('F', 'm');
9159 prepared_logmsg = realpath(optarg, NULL);
9160 if (prepared_logmsg == NULL)
9161 return got_error_from_errno2("realpath",
9162 optarg);
9163 break;
9164 case 'm':
9165 if (prepared_logmsg)
9166 option_conflict('m', 'F');
9167 logmsg = optarg;
9168 break;
9169 case 'N':
9170 non_interactive = 1;
9171 break;
9172 case 'n':
9173 show_diff = 0;
9174 break;
9175 case 'S':
9176 allow_bad_symlinks = 1;
9177 break;
9178 default:
9179 usage_commit();
9180 /* NOTREACHED */
9184 argc -= optind;
9185 argv += optind;
9187 cwd = getcwd(NULL, 0);
9188 if (cwd == NULL) {
9189 error = got_error_from_errno("getcwd");
9190 goto done;
9193 error = got_repo_pack_fds_open(&pack_fds);
9194 if (error != NULL)
9195 goto done;
9197 error = got_worktree_open(&worktree, cwd);
9198 if (error) {
9199 if (error->code == GOT_ERR_NOT_WORKTREE)
9200 error = wrap_not_worktree_error(error, "commit", cwd);
9201 goto done;
9204 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9205 if (error)
9206 goto done;
9207 if (rebase_in_progress) {
9208 error = got_error(GOT_ERR_REBASING);
9209 goto done;
9212 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9213 worktree);
9214 if (error)
9215 goto done;
9217 error = get_gitconfig_path(&gitconfig_path);
9218 if (error)
9219 goto done;
9220 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9221 gitconfig_path, pack_fds);
9222 if (error != NULL)
9223 goto done;
9225 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9226 if (error)
9227 goto done;
9228 if (merge_in_progress) {
9229 error = got_error(GOT_ERR_MERGE_BUSY);
9230 goto done;
9233 error = get_author(&committer, repo, worktree);
9234 if (error)
9235 goto done;
9237 if (author == NULL)
9238 author = committer;
9241 * unveil(2) traverses exec(2); if an editor is used we have
9242 * to apply unveil after the log message has been written.
9244 if (logmsg == NULL || strlen(logmsg) == 0)
9245 error = get_editor(&editor);
9246 else
9247 error = apply_unveil(got_repo_get_path(repo), 0,
9248 got_worktree_get_root_path(worktree));
9249 if (error)
9250 goto done;
9252 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9253 if (error)
9254 goto done;
9256 if (prepared_logmsg == NULL) {
9257 error = lookup_logmsg_ref(&merged_logmsg,
9258 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9259 if (error)
9260 goto done;
9263 cl_arg.editor = editor;
9264 cl_arg.cmdline_log = logmsg;
9265 cl_arg.prepared_log = prepared_logmsg;
9266 cl_arg.merged_log = merged_logmsg;
9267 cl_arg.non_interactive = non_interactive;
9268 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9269 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9270 if (!histedit_in_progress) {
9271 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9272 error = got_error(GOT_ERR_COMMIT_BRANCH);
9273 goto done;
9275 cl_arg.branch_name += 11;
9277 cl_arg.repo_path = got_repo_get_path(repo);
9278 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9279 allow_bad_symlinks, show_diff, commit_conflicts,
9280 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9281 if (error) {
9282 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9283 cl_arg.logmsg_path != NULL)
9284 preserve_logmsg = 1;
9285 goto done;
9288 error = got_object_id_str(&id_str, id);
9289 if (error)
9290 goto done;
9291 printf("Created commit %s\n", id_str);
9293 TAILQ_FOREACH(re, &refs, entry) {
9294 error = got_ref_delete(re->ref, repo);
9295 if (error)
9296 goto done;
9299 done:
9300 if (preserve_logmsg) {
9301 fprintf(stderr, "%s: log message preserved in %s\n",
9302 getprogname(), cl_arg.logmsg_path);
9303 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9304 error == NULL)
9305 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9306 free(cl_arg.logmsg_path);
9307 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9308 error = got_error_from_errno2("unlink", merged_logmsg);
9309 free(merged_logmsg);
9310 if (repo) {
9311 const struct got_error *close_err = got_repo_close(repo);
9312 if (error == NULL)
9313 error = close_err;
9315 if (worktree)
9316 got_worktree_close(worktree);
9317 if (pack_fds) {
9318 const struct got_error *pack_err =
9319 got_repo_pack_fds_close(pack_fds);
9320 if (error == NULL)
9321 error = pack_err;
9323 got_ref_list_free(&refs);
9324 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9325 free(cwd);
9326 free(id_str);
9327 free(gitconfig_path);
9328 free(editor);
9329 free(committer);
9330 free(prepared_logmsg);
9331 return error;
9334 __dead static void
9335 usage_send(void)
9337 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9338 "[-r repository-path] [-t tag] [remote-repository]\n",
9339 getprogname());
9340 exit(1);
9343 static void
9344 print_load_info(int print_colored, int print_found, int print_trees,
9345 int ncolored, int nfound, int ntrees)
9347 if (print_colored) {
9348 printf("%d commit%s colored", ncolored,
9349 ncolored == 1 ? "" : "s");
9351 if (print_found) {
9352 printf("%s%d object%s found",
9353 ncolored > 0 ? "; " : "",
9354 nfound, nfound == 1 ? "" : "s");
9356 if (print_trees) {
9357 printf("; %d tree%s scanned", ntrees,
9358 ntrees == 1 ? "" : "s");
9362 struct got_send_progress_arg {
9363 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9364 int verbosity;
9365 int last_ncolored;
9366 int last_nfound;
9367 int last_ntrees;
9368 int loading_done;
9369 int last_ncommits;
9370 int last_nobj_total;
9371 int last_p_deltify;
9372 int last_p_written;
9373 int last_p_sent;
9374 int printed_something;
9375 int sent_something;
9376 struct got_pathlist_head *delete_branches;
9379 static const struct got_error *
9380 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9381 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9382 int nobj_written, off_t bytes_sent, const char *refname,
9383 const char *errmsg, int success)
9385 struct got_send_progress_arg *a = arg;
9386 char scaled_packsize[FMT_SCALED_STRSIZE];
9387 char scaled_sent[FMT_SCALED_STRSIZE];
9388 int p_deltify = 0, p_written = 0, p_sent = 0;
9389 int print_colored = 0, print_found = 0, print_trees = 0;
9390 int print_searching = 0, print_total = 0;
9391 int print_deltify = 0, print_written = 0, print_sent = 0;
9393 if (a->verbosity < 0)
9394 return NULL;
9396 if (refname) {
9397 const char *status = success ? "accepted" : "rejected";
9399 if (success) {
9400 struct got_pathlist_entry *pe;
9401 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9402 const char *branchname = pe->path;
9403 if (got_path_cmp(branchname, refname,
9404 strlen(branchname), strlen(refname)) == 0) {
9405 status = "deleted";
9406 a->sent_something = 1;
9407 break;
9412 if (a->printed_something)
9413 putchar('\n');
9414 printf("Server has %s %s", status, refname);
9415 if (errmsg)
9416 printf(": %s", errmsg);
9417 a->printed_something = 1;
9418 return NULL;
9421 if (a->last_ncolored != ncolored) {
9422 print_colored = 1;
9423 a->last_ncolored = ncolored;
9426 if (a->last_nfound != nfound) {
9427 print_colored = 1;
9428 print_found = 1;
9429 a->last_nfound = nfound;
9432 if (a->last_ntrees != ntrees) {
9433 print_colored = 1;
9434 print_found = 1;
9435 print_trees = 1;
9436 a->last_ntrees = ntrees;
9439 if ((print_colored || print_found || print_trees) &&
9440 !a->loading_done) {
9441 printf("\r");
9442 print_load_info(print_colored, print_found, print_trees,
9443 ncolored, nfound, ntrees);
9444 a->printed_something = 1;
9445 fflush(stdout);
9446 return NULL;
9447 } else if (!a->loading_done) {
9448 printf("\r");
9449 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9450 printf("\n");
9451 a->loading_done = 1;
9454 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9455 return got_error_from_errno("fmt_scaled");
9456 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9457 return got_error_from_errno("fmt_scaled");
9459 if (a->last_ncommits != ncommits) {
9460 print_searching = 1;
9461 a->last_ncommits = ncommits;
9464 if (a->last_nobj_total != nobj_total) {
9465 print_searching = 1;
9466 print_total = 1;
9467 a->last_nobj_total = nobj_total;
9470 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9471 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9472 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9473 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9474 return got_error(GOT_ERR_NO_SPACE);
9477 if (nobj_deltify > 0 || nobj_written > 0) {
9478 if (nobj_deltify > 0) {
9479 p_deltify = (nobj_deltify * 100) / nobj_total;
9480 if (p_deltify != a->last_p_deltify) {
9481 a->last_p_deltify = p_deltify;
9482 print_searching = 1;
9483 print_total = 1;
9484 print_deltify = 1;
9487 if (nobj_written > 0) {
9488 p_written = (nobj_written * 100) / nobj_total;
9489 if (p_written != a->last_p_written) {
9490 a->last_p_written = p_written;
9491 print_searching = 1;
9492 print_total = 1;
9493 print_deltify = 1;
9494 print_written = 1;
9499 if (bytes_sent > 0) {
9500 p_sent = (bytes_sent * 100) / packfile_size;
9501 if (p_sent != a->last_p_sent) {
9502 a->last_p_sent = p_sent;
9503 print_searching = 1;
9504 print_total = 1;
9505 print_deltify = 1;
9506 print_written = 1;
9507 print_sent = 1;
9509 a->sent_something = 1;
9512 if (print_searching || print_total || print_deltify || print_written ||
9513 print_sent)
9514 printf("\r");
9515 if (print_searching)
9516 printf("packing %d reference%s", ncommits,
9517 ncommits == 1 ? "" : "s");
9518 if (print_total)
9519 printf("; %d object%s", nobj_total,
9520 nobj_total == 1 ? "" : "s");
9521 if (print_deltify)
9522 printf("; deltify: %d%%", p_deltify);
9523 if (print_sent)
9524 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9525 scaled_packsize, p_sent);
9526 else if (print_written)
9527 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9528 scaled_packsize, p_written);
9529 if (print_searching || print_total || print_deltify ||
9530 print_written || print_sent) {
9531 a->printed_something = 1;
9532 fflush(stdout);
9534 return NULL;
9537 static const struct got_error *
9538 cmd_send(int argc, char *argv[])
9540 const struct got_error *error = NULL;
9541 char *cwd = NULL, *repo_path = NULL;
9542 const char *remote_name;
9543 char *proto = NULL, *host = NULL, *port = NULL;
9544 char *repo_name = NULL, *server_path = NULL;
9545 const struct got_remote_repo *remotes, *remote = NULL;
9546 int nremotes, nbranches = 0, ndelete_branches = 0;
9547 struct got_repository *repo = NULL;
9548 struct got_worktree *worktree = NULL;
9549 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9550 struct got_pathlist_head branches;
9551 struct got_pathlist_head tags;
9552 struct got_reflist_head all_branches;
9553 struct got_reflist_head all_tags;
9554 struct got_pathlist_head delete_args;
9555 struct got_pathlist_head delete_branches;
9556 struct got_reflist_entry *re;
9557 struct got_pathlist_entry *pe;
9558 int i, ch, sendfd = -1, sendstatus;
9559 pid_t sendpid = -1;
9560 struct got_send_progress_arg spa;
9561 int verbosity = 0, overwrite_refs = 0;
9562 int send_all_branches = 0, send_all_tags = 0;
9563 struct got_reference *ref = NULL;
9564 int *pack_fds = NULL;
9566 TAILQ_INIT(&branches);
9567 TAILQ_INIT(&tags);
9568 TAILQ_INIT(&all_branches);
9569 TAILQ_INIT(&all_tags);
9570 TAILQ_INIT(&delete_args);
9571 TAILQ_INIT(&delete_branches);
9573 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9574 switch (ch) {
9575 case 'a':
9576 send_all_branches = 1;
9577 break;
9578 case 'b':
9579 error = got_pathlist_append(&branches, optarg, NULL);
9580 if (error)
9581 return error;
9582 nbranches++;
9583 break;
9584 case 'd':
9585 error = got_pathlist_append(&delete_args, optarg, NULL);
9586 if (error)
9587 return error;
9588 break;
9589 case 'f':
9590 overwrite_refs = 1;
9591 break;
9592 case 'q':
9593 verbosity = -1;
9594 break;
9595 case 'r':
9596 repo_path = realpath(optarg, NULL);
9597 if (repo_path == NULL)
9598 return got_error_from_errno2("realpath",
9599 optarg);
9600 got_path_strip_trailing_slashes(repo_path);
9601 break;
9602 case 'T':
9603 send_all_tags = 1;
9604 break;
9605 case 't':
9606 error = got_pathlist_append(&tags, optarg, NULL);
9607 if (error)
9608 return error;
9609 break;
9610 case 'v':
9611 if (verbosity < 0)
9612 verbosity = 0;
9613 else if (verbosity < 3)
9614 verbosity++;
9615 break;
9616 default:
9617 usage_send();
9618 /* NOTREACHED */
9621 argc -= optind;
9622 argv += optind;
9624 if (send_all_branches && !TAILQ_EMPTY(&branches))
9625 option_conflict('a', 'b');
9626 if (send_all_tags && !TAILQ_EMPTY(&tags))
9627 option_conflict('T', 't');
9630 if (argc == 0)
9631 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9632 else if (argc == 1)
9633 remote_name = argv[0];
9634 else
9635 usage_send();
9637 cwd = getcwd(NULL, 0);
9638 if (cwd == NULL) {
9639 error = got_error_from_errno("getcwd");
9640 goto done;
9643 error = got_repo_pack_fds_open(&pack_fds);
9644 if (error != NULL)
9645 goto done;
9647 if (repo_path == NULL) {
9648 error = got_worktree_open(&worktree, cwd);
9649 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9650 goto done;
9651 else
9652 error = NULL;
9653 if (worktree) {
9654 repo_path =
9655 strdup(got_worktree_get_repo_path(worktree));
9656 if (repo_path == NULL)
9657 error = got_error_from_errno("strdup");
9658 if (error)
9659 goto done;
9660 } else {
9661 repo_path = strdup(cwd);
9662 if (repo_path == NULL) {
9663 error = got_error_from_errno("strdup");
9664 goto done;
9669 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9670 if (error)
9671 goto done;
9673 if (worktree) {
9674 worktree_conf = got_worktree_get_gotconfig(worktree);
9675 if (worktree_conf) {
9676 got_gotconfig_get_remotes(&nremotes, &remotes,
9677 worktree_conf);
9678 for (i = 0; i < nremotes; i++) {
9679 if (strcmp(remotes[i].name, remote_name) == 0) {
9680 remote = &remotes[i];
9681 break;
9686 if (remote == NULL) {
9687 repo_conf = got_repo_get_gotconfig(repo);
9688 if (repo_conf) {
9689 got_gotconfig_get_remotes(&nremotes, &remotes,
9690 repo_conf);
9691 for (i = 0; i < nremotes; i++) {
9692 if (strcmp(remotes[i].name, remote_name) == 0) {
9693 remote = &remotes[i];
9694 break;
9699 if (remote == NULL) {
9700 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9701 for (i = 0; i < nremotes; i++) {
9702 if (strcmp(remotes[i].name, remote_name) == 0) {
9703 remote = &remotes[i];
9704 break;
9708 if (remote == NULL) {
9709 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9710 goto done;
9713 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9714 &repo_name, remote->send_url);
9715 if (error)
9716 goto done;
9718 if (strcmp(proto, "git") == 0) {
9719 #ifndef PROFILE
9720 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9721 "sendfd dns inet unveil", NULL) == -1)
9722 err(1, "pledge");
9723 #endif
9724 } else if (strcmp(proto, "git+ssh") == 0 ||
9725 strcmp(proto, "ssh") == 0) {
9726 #ifndef PROFILE
9727 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9728 "sendfd unveil", NULL) == -1)
9729 err(1, "pledge");
9730 #endif
9731 } else if (strcmp(proto, "http") == 0 ||
9732 strcmp(proto, "git+http") == 0) {
9733 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9734 goto done;
9735 } else {
9736 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9737 goto done;
9740 error = got_dial_apply_unveil(proto);
9741 if (error)
9742 goto done;
9744 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9745 if (error)
9746 goto done;
9748 if (send_all_branches) {
9749 error = got_ref_list(&all_branches, repo, "refs/heads",
9750 got_ref_cmp_by_name, NULL);
9751 if (error)
9752 goto done;
9753 TAILQ_FOREACH(re, &all_branches, entry) {
9754 const char *branchname = got_ref_get_name(re->ref);
9755 error = got_pathlist_append(&branches,
9756 branchname, NULL);
9757 if (error)
9758 goto done;
9759 nbranches++;
9761 } else if (nbranches == 0) {
9762 for (i = 0; i < remote->nsend_branches; i++) {
9763 error = got_pathlist_append(&branches,
9764 remote->send_branches[i], NULL);
9765 if (error)
9766 goto done;
9770 if (send_all_tags) {
9771 error = got_ref_list(&all_tags, repo, "refs/tags",
9772 got_ref_cmp_by_name, NULL);
9773 if (error)
9774 goto done;
9775 TAILQ_FOREACH(re, &all_tags, entry) {
9776 const char *tagname = got_ref_get_name(re->ref);
9777 error = got_pathlist_append(&tags,
9778 tagname, NULL);
9779 if (error)
9780 goto done;
9785 * To prevent accidents only branches in refs/heads/ can be deleted
9786 * with 'got send -d'.
9787 * Deleting anything else requires local repository access or Git.
9789 TAILQ_FOREACH(pe, &delete_args, entry) {
9790 const char *branchname = pe->path;
9791 char *s;
9792 struct got_pathlist_entry *new;
9793 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9794 s = strdup(branchname);
9795 if (s == NULL) {
9796 error = got_error_from_errno("strdup");
9797 goto done;
9799 } else {
9800 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9801 error = got_error_from_errno("asprintf");
9802 goto done;
9805 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9806 if (error || new == NULL /* duplicate */)
9807 free(s);
9808 if (error)
9809 goto done;
9810 ndelete_branches++;
9813 if (nbranches == 0 && ndelete_branches == 0) {
9814 struct got_reference *head_ref;
9815 if (worktree)
9816 error = got_ref_open(&head_ref, repo,
9817 got_worktree_get_head_ref_name(worktree), 0);
9818 else
9819 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9820 if (error)
9821 goto done;
9822 if (got_ref_is_symbolic(head_ref)) {
9823 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9824 got_ref_close(head_ref);
9825 if (error)
9826 goto done;
9827 } else
9828 ref = head_ref;
9829 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9830 NULL);
9831 if (error)
9832 goto done;
9833 nbranches++;
9836 if (verbosity >= 0) {
9837 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9838 remote->name, proto, host,
9839 port ? ":" : "", port ? port : "",
9840 *server_path == '/' ? "" : "/", server_path);
9843 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9844 server_path, verbosity);
9845 if (error)
9846 goto done;
9848 memset(&spa, 0, sizeof(spa));
9849 spa.last_scaled_packsize[0] = '\0';
9850 spa.last_p_deltify = -1;
9851 spa.last_p_written = -1;
9852 spa.verbosity = verbosity;
9853 spa.delete_branches = &delete_branches;
9854 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9855 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9856 check_cancelled, NULL);
9857 if (spa.printed_something)
9858 putchar('\n');
9859 if (error)
9860 goto done;
9861 if (!spa.sent_something && verbosity >= 0)
9862 printf("Already up-to-date\n");
9863 done:
9864 if (sendpid > 0) {
9865 if (kill(sendpid, SIGTERM) == -1)
9866 error = got_error_from_errno("kill");
9867 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9868 error = got_error_from_errno("waitpid");
9870 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9871 error = got_error_from_errno("close");
9872 if (repo) {
9873 const struct got_error *close_err = got_repo_close(repo);
9874 if (error == NULL)
9875 error = close_err;
9877 if (worktree)
9878 got_worktree_close(worktree);
9879 if (pack_fds) {
9880 const struct got_error *pack_err =
9881 got_repo_pack_fds_close(pack_fds);
9882 if (error == NULL)
9883 error = pack_err;
9885 if (ref)
9886 got_ref_close(ref);
9887 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9888 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9889 got_ref_list_free(&all_branches);
9890 got_ref_list_free(&all_tags);
9891 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9892 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9893 free(cwd);
9894 free(repo_path);
9895 free(proto);
9896 free(host);
9897 free(port);
9898 free(server_path);
9899 free(repo_name);
9900 return error;
9904 * Print and if delete is set delete all ref_prefix references.
9905 * If wanted_ref is not NULL, only print or delete this reference.
9907 static const struct got_error *
9908 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9909 const char *wanted_ref, int delete, struct got_worktree *worktree,
9910 struct got_repository *repo)
9912 const struct got_error *err;
9913 struct got_pathlist_head paths;
9914 struct got_reflist_head refs;
9915 struct got_reflist_entry *re;
9916 struct got_reflist_object_id_map *refs_idmap = NULL;
9917 struct got_commit_object *commit = NULL;
9918 struct got_object_id *id = NULL;
9919 const char *header_prefix;
9920 char *uuidstr = NULL;
9921 int found = 0;
9923 TAILQ_INIT(&refs);
9924 TAILQ_INIT(&paths);
9926 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9927 if (err)
9928 goto done;
9930 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9931 if (err)
9932 goto done;
9934 if (worktree != NULL) {
9935 err = got_worktree_get_uuid(&uuidstr, worktree);
9936 if (err)
9937 goto done;
9940 if (wanted_ref) {
9941 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9942 wanted_ref += 11;
9945 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9946 header_prefix = "backout";
9947 else
9948 header_prefix = "cherrypick";
9950 TAILQ_FOREACH(re, &refs, entry) {
9951 const char *refname, *wt;
9953 refname = got_ref_get_name(re->ref);
9955 err = check_cancelled(NULL);
9956 if (err)
9957 goto done;
9959 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9960 refname += prefix_len + 1; /* skip '-' delimiter */
9961 else
9962 continue;
9964 wt = refname;
9966 if (worktree == NULL || strncmp(refname, uuidstr,
9967 GOT_WORKTREE_UUID_STRLEN) == 0)
9968 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9969 else
9970 continue;
9972 err = got_repo_match_object_id(&id, NULL, refname,
9973 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9974 if (err)
9975 goto done;
9977 err = got_object_open_as_commit(&commit, repo, id);
9978 if (err)
9979 goto done;
9981 if (wanted_ref)
9982 found = strncmp(wanted_ref, refname,
9983 strlen(wanted_ref)) == 0;
9984 if (wanted_ref && !found) {
9985 struct got_reflist_head *ci_refs;
9987 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9988 id);
9990 if (ci_refs) {
9991 char *refs_str = NULL;
9992 char const *r = NULL;
9994 err = build_refs_str(&refs_str, ci_refs, id,
9995 repo, 1);
9996 if (err)
9997 goto done;
9999 r = refs_str;
10000 while (r) {
10001 if (strncmp(r, wanted_ref,
10002 strlen(wanted_ref)) == 0) {
10003 found = 1;
10004 break;
10006 r = strchr(r, ' ');
10007 if (r)
10008 ++r;
10010 free(refs_str);
10014 if (wanted_ref == NULL || found) {
10015 if (delete) {
10016 err = got_ref_delete(re->ref, repo);
10017 if (err)
10018 goto done;
10019 printf("Deleted: ");
10020 err = print_commit_oneline(commit, id, repo,
10021 refs_idmap);
10022 } else {
10024 * Print paths modified by commit to help
10025 * associate commits with worktree changes.
10027 err = get_changed_paths(&paths, commit,
10028 repo, NULL);
10029 if (err)
10030 goto done;
10032 err = print_commit(commit, id, repo, NULL,
10033 &paths, NULL, 0, 0, refs_idmap, NULL,
10034 header_prefix);
10035 got_pathlist_free(&paths,
10036 GOT_PATHLIST_FREE_ALL);
10038 if (worktree == NULL)
10039 printf("work tree: %.*s\n\n",
10040 GOT_WORKTREE_UUID_STRLEN, wt);
10042 if (err || found)
10043 goto done;
10046 got_object_commit_close(commit);
10047 commit = NULL;
10048 free(id);
10049 id = NULL;
10052 if (wanted_ref != NULL && !found)
10053 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10055 done:
10056 free(id);
10057 free(uuidstr);
10058 got_ref_list_free(&refs);
10059 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10060 if (refs_idmap)
10061 got_reflist_object_id_map_free(refs_idmap);
10062 if (commit)
10063 got_object_commit_close(commit);
10064 return err;
10068 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10069 * identified by id for log messages to prepopulate the editor on commit.
10071 static const struct got_error *
10072 logmsg_ref(struct got_object_id *id, const char *prefix,
10073 struct got_worktree *worktree, struct got_repository *repo)
10075 const struct got_error *err = NULL;
10076 char *idstr, *ref = NULL, *refname = NULL;
10077 int histedit_in_progress;
10078 int rebase_in_progress, merge_in_progress;
10081 * Silenty refuse to create merge reference if any histedit, merge,
10082 * or rebase operation is in progress.
10084 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10085 worktree);
10086 if (err)
10087 return err;
10088 if (histedit_in_progress)
10089 return NULL;
10091 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10092 if (err)
10093 return err;
10094 if (rebase_in_progress)
10095 return NULL;
10097 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10098 repo);
10099 if (err)
10100 return err;
10101 if (merge_in_progress)
10102 return NULL;
10104 err = got_object_id_str(&idstr, id);
10105 if (err)
10106 return err;
10108 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10109 if (err)
10110 goto done;
10112 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10113 err = got_error_from_errno("asprintf");
10114 goto done;
10117 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10118 -1, repo);
10119 done:
10120 free(ref);
10121 free(idstr);
10122 free(refname);
10123 return err;
10126 __dead static void
10127 usage_cherrypick(void)
10129 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10130 getprogname());
10131 exit(1);
10134 static const struct got_error *
10135 cmd_cherrypick(int argc, char *argv[])
10137 const struct got_error *error = NULL;
10138 struct got_worktree *worktree = NULL;
10139 struct got_repository *repo = NULL;
10140 char *cwd = NULL, *commit_id_str = NULL;
10141 struct got_object_id *commit_id = NULL;
10142 struct got_commit_object *commit = NULL;
10143 struct got_object_qid *pid;
10144 int ch, list_refs = 0, remove_refs = 0;
10145 struct got_update_progress_arg upa;
10146 int *pack_fds = NULL;
10148 #ifndef PROFILE
10149 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10150 "unveil", NULL) == -1)
10151 err(1, "pledge");
10152 #endif
10154 while ((ch = getopt(argc, argv, "lX")) != -1) {
10155 switch (ch) {
10156 case 'l':
10157 list_refs = 1;
10158 break;
10159 case 'X':
10160 remove_refs = 1;
10161 break;
10162 default:
10163 usage_cherrypick();
10164 /* NOTREACHED */
10168 argc -= optind;
10169 argv += optind;
10171 if (list_refs || remove_refs) {
10172 if (argc != 0 && argc != 1)
10173 usage_cherrypick();
10174 } else if (argc != 1)
10175 usage_cherrypick();
10176 if (list_refs && remove_refs)
10177 option_conflict('l', 'X');
10179 cwd = getcwd(NULL, 0);
10180 if (cwd == NULL) {
10181 error = got_error_from_errno("getcwd");
10182 goto done;
10185 error = got_repo_pack_fds_open(&pack_fds);
10186 if (error != NULL)
10187 goto done;
10189 error = got_worktree_open(&worktree, cwd);
10190 if (error) {
10191 if (list_refs || remove_refs) {
10192 if (error->code != GOT_ERR_NOT_WORKTREE)
10193 goto done;
10194 } else {
10195 if (error->code == GOT_ERR_NOT_WORKTREE)
10196 error = wrap_not_worktree_error(error,
10197 "cherrypick", cwd);
10198 goto done;
10202 error = got_repo_open(&repo,
10203 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10204 NULL, pack_fds);
10205 if (error != NULL)
10206 goto done;
10208 error = apply_unveil(got_repo_get_path(repo), 0,
10209 worktree ? got_worktree_get_root_path(worktree) : NULL);
10210 if (error)
10211 goto done;
10213 if (list_refs || remove_refs) {
10214 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10215 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10216 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10217 goto done;
10220 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10221 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10222 if (error)
10223 goto done;
10224 error = got_object_id_str(&commit_id_str, commit_id);
10225 if (error)
10226 goto done;
10228 error = got_object_open_as_commit(&commit, repo, commit_id);
10229 if (error)
10230 goto done;
10231 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10232 memset(&upa, 0, sizeof(upa));
10233 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10234 commit_id, repo, update_progress, &upa, check_cancelled,
10235 NULL);
10236 if (error != NULL)
10237 goto done;
10239 if (upa.did_something) {
10240 error = logmsg_ref(commit_id,
10241 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10242 if (error)
10243 goto done;
10244 printf("Merged commit %s\n", commit_id_str);
10246 print_merge_progress_stats(&upa);
10247 done:
10248 free(cwd);
10249 if (commit)
10250 got_object_commit_close(commit);
10251 free(commit_id_str);
10252 if (worktree)
10253 got_worktree_close(worktree);
10254 if (repo) {
10255 const struct got_error *close_err = got_repo_close(repo);
10256 if (error == NULL)
10257 error = close_err;
10259 if (pack_fds) {
10260 const struct got_error *pack_err =
10261 got_repo_pack_fds_close(pack_fds);
10262 if (error == NULL)
10263 error = pack_err;
10266 return error;
10269 __dead static void
10270 usage_backout(void)
10272 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10273 exit(1);
10276 static const struct got_error *
10277 cmd_backout(int argc, char *argv[])
10279 const struct got_error *error = NULL;
10280 struct got_worktree *worktree = NULL;
10281 struct got_repository *repo = NULL;
10282 char *cwd = NULL, *commit_id_str = NULL;
10283 struct got_object_id *commit_id = NULL;
10284 struct got_commit_object *commit = NULL;
10285 struct got_object_qid *pid;
10286 int ch, list_refs = 0, remove_refs = 0;
10287 struct got_update_progress_arg upa;
10288 int *pack_fds = NULL;
10290 #ifndef PROFILE
10291 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10292 "unveil", NULL) == -1)
10293 err(1, "pledge");
10294 #endif
10296 while ((ch = getopt(argc, argv, "lX")) != -1) {
10297 switch (ch) {
10298 case 'l':
10299 list_refs = 1;
10300 break;
10301 case 'X':
10302 remove_refs = 1;
10303 break;
10304 default:
10305 usage_backout();
10306 /* NOTREACHED */
10310 argc -= optind;
10311 argv += optind;
10313 if (list_refs || remove_refs) {
10314 if (argc != 0 && argc != 1)
10315 usage_backout();
10316 } else if (argc != 1)
10317 usage_backout();
10318 if (list_refs && remove_refs)
10319 option_conflict('l', 'X');
10321 cwd = getcwd(NULL, 0);
10322 if (cwd == NULL) {
10323 error = got_error_from_errno("getcwd");
10324 goto done;
10327 error = got_repo_pack_fds_open(&pack_fds);
10328 if (error != NULL)
10329 goto done;
10331 error = got_worktree_open(&worktree, cwd);
10332 if (error) {
10333 if (list_refs || remove_refs) {
10334 if (error->code != GOT_ERR_NOT_WORKTREE)
10335 goto done;
10336 } else {
10337 if (error->code == GOT_ERR_NOT_WORKTREE)
10338 error = wrap_not_worktree_error(error,
10339 "backout", cwd);
10340 goto done;
10344 error = got_repo_open(&repo,
10345 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10346 NULL, pack_fds);
10347 if (error != NULL)
10348 goto done;
10350 error = apply_unveil(got_repo_get_path(repo), 0,
10351 worktree ? got_worktree_get_root_path(worktree) : NULL);
10352 if (error)
10353 goto done;
10355 if (list_refs || remove_refs) {
10356 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10357 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10358 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10359 goto done;
10362 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10363 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10364 if (error)
10365 goto done;
10366 error = got_object_id_str(&commit_id_str, commit_id);
10367 if (error)
10368 goto done;
10370 error = got_object_open_as_commit(&commit, repo, commit_id);
10371 if (error)
10372 goto done;
10373 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10374 if (pid == NULL) {
10375 error = got_error(GOT_ERR_ROOT_COMMIT);
10376 goto done;
10379 memset(&upa, 0, sizeof(upa));
10380 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10381 repo, update_progress, &upa, check_cancelled, NULL);
10382 if (error != NULL)
10383 goto done;
10385 if (upa.did_something) {
10386 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10387 worktree, repo);
10388 if (error)
10389 goto done;
10390 printf("Backed out commit %s\n", commit_id_str);
10392 print_merge_progress_stats(&upa);
10393 done:
10394 free(cwd);
10395 if (commit)
10396 got_object_commit_close(commit);
10397 free(commit_id_str);
10398 if (worktree)
10399 got_worktree_close(worktree);
10400 if (repo) {
10401 const struct got_error *close_err = got_repo_close(repo);
10402 if (error == NULL)
10403 error = close_err;
10405 if (pack_fds) {
10406 const struct got_error *pack_err =
10407 got_repo_pack_fds_close(pack_fds);
10408 if (error == NULL)
10409 error = pack_err;
10411 return error;
10414 __dead static void
10415 usage_rebase(void)
10417 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10418 exit(1);
10421 static void
10422 trim_logmsg(char *logmsg, int limit)
10424 char *nl;
10425 size_t len;
10427 len = strlen(logmsg);
10428 if (len > limit)
10429 len = limit;
10430 logmsg[len] = '\0';
10431 nl = strchr(logmsg, '\n');
10432 if (nl)
10433 *nl = '\0';
10436 static const struct got_error *
10437 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10439 const struct got_error *err;
10440 char *logmsg0 = NULL;
10441 const char *s;
10443 err = got_object_commit_get_logmsg(&logmsg0, commit);
10444 if (err)
10445 return err;
10447 s = logmsg0;
10448 while (isspace((unsigned char)s[0]))
10449 s++;
10451 *logmsg = strdup(s);
10452 if (*logmsg == NULL) {
10453 err = got_error_from_errno("strdup");
10454 goto done;
10457 trim_logmsg(*logmsg, limit);
10458 done:
10459 free(logmsg0);
10460 return err;
10463 static const struct got_error *
10464 show_rebase_merge_conflict(struct got_object_id *id,
10465 struct got_repository *repo)
10467 const struct got_error *err;
10468 struct got_commit_object *commit = NULL;
10469 char *id_str = NULL, *logmsg = NULL;
10471 err = got_object_open_as_commit(&commit, repo, id);
10472 if (err)
10473 return err;
10475 err = got_object_id_str(&id_str, id);
10476 if (err)
10477 goto done;
10479 id_str[12] = '\0';
10481 err = get_short_logmsg(&logmsg, 42, commit);
10482 if (err)
10483 goto done;
10485 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10486 done:
10487 free(id_str);
10488 got_object_commit_close(commit);
10489 free(logmsg);
10490 return err;
10493 static const struct got_error *
10494 show_rebase_progress(struct got_commit_object *commit,
10495 struct got_object_id *old_id, struct got_object_id *new_id)
10497 const struct got_error *err;
10498 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10500 err = got_object_id_str(&old_id_str, old_id);
10501 if (err)
10502 goto done;
10504 if (new_id) {
10505 err = got_object_id_str(&new_id_str, new_id);
10506 if (err)
10507 goto done;
10510 old_id_str[12] = '\0';
10511 if (new_id_str)
10512 new_id_str[12] = '\0';
10514 err = get_short_logmsg(&logmsg, 42, commit);
10515 if (err)
10516 goto done;
10518 printf("%s -> %s: %s\n", old_id_str,
10519 new_id_str ? new_id_str : "no-op change", logmsg);
10520 done:
10521 free(old_id_str);
10522 free(new_id_str);
10523 free(logmsg);
10524 return err;
10527 static const struct got_error *
10528 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10529 struct got_reference *branch, struct got_reference *tmp_branch,
10530 struct got_repository *repo, int create_backup)
10532 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10533 return got_worktree_rebase_complete(worktree, fileindex,
10534 tmp_branch, branch, repo, create_backup);
10537 static const struct got_error *
10538 rebase_commit(struct got_pathlist_head *merged_paths,
10539 struct got_worktree *worktree, struct got_fileindex *fileindex,
10540 struct got_reference *tmp_branch, const char *committer,
10541 struct got_object_id *commit_id, int allow_conflict,
10542 struct got_repository *repo)
10544 const struct got_error *error;
10545 struct got_commit_object *commit;
10546 struct got_object_id *new_commit_id;
10548 error = got_object_open_as_commit(&commit, repo, commit_id);
10549 if (error)
10550 return error;
10552 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10553 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10554 allow_conflict, repo);
10555 if (error) {
10556 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10557 goto done;
10558 error = show_rebase_progress(commit, commit_id, NULL);
10559 } else {
10560 error = show_rebase_progress(commit, commit_id, new_commit_id);
10561 free(new_commit_id);
10563 done:
10564 got_object_commit_close(commit);
10565 return error;
10568 struct check_path_prefix_arg {
10569 const char *path_prefix;
10570 size_t len;
10571 int errcode;
10574 static const struct got_error *
10575 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10576 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10577 struct got_object_id *id1, struct got_object_id *id2,
10578 const char *path1, const char *path2,
10579 mode_t mode1, mode_t mode2, struct got_repository *repo)
10581 struct check_path_prefix_arg *a = arg;
10583 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10584 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10585 return got_error(a->errcode);
10587 return NULL;
10590 static const struct got_error *
10591 check_path_prefix(struct got_object_id *parent_id,
10592 struct got_object_id *commit_id, const char *path_prefix,
10593 int errcode, struct got_repository *repo)
10595 const struct got_error *err;
10596 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10597 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10598 struct check_path_prefix_arg cpp_arg;
10600 if (got_path_is_root_dir(path_prefix))
10601 return NULL;
10603 err = got_object_open_as_commit(&commit, repo, commit_id);
10604 if (err)
10605 goto done;
10607 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10608 if (err)
10609 goto done;
10611 err = got_object_open_as_tree(&tree1, repo,
10612 got_object_commit_get_tree_id(parent_commit));
10613 if (err)
10614 goto done;
10616 err = got_object_open_as_tree(&tree2, repo,
10617 got_object_commit_get_tree_id(commit));
10618 if (err)
10619 goto done;
10621 cpp_arg.path_prefix = path_prefix;
10622 while (cpp_arg.path_prefix[0] == '/')
10623 cpp_arg.path_prefix++;
10624 cpp_arg.len = strlen(cpp_arg.path_prefix);
10625 cpp_arg.errcode = errcode;
10626 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10627 check_path_prefix_in_diff, &cpp_arg, 0);
10628 done:
10629 if (tree1)
10630 got_object_tree_close(tree1);
10631 if (tree2)
10632 got_object_tree_close(tree2);
10633 if (commit)
10634 got_object_commit_close(commit);
10635 if (parent_commit)
10636 got_object_commit_close(parent_commit);
10637 return err;
10640 static const struct got_error *
10641 collect_commits(struct got_object_id_queue *commits,
10642 struct got_object_id *initial_commit_id,
10643 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10644 const char *path_prefix, int path_prefix_errcode,
10645 struct got_repository *repo)
10647 const struct got_error *err = NULL;
10648 struct got_commit_graph *graph = NULL;
10649 struct got_object_id parent_id, commit_id;
10650 struct got_object_qid *qid;
10652 err = got_commit_graph_open(&graph, "/", 1);
10653 if (err)
10654 return err;
10656 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10657 check_cancelled, NULL);
10658 if (err)
10659 goto done;
10661 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10662 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10663 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10664 check_cancelled, NULL);
10665 if (err) {
10666 if (err->code == GOT_ERR_ITER_COMPLETED) {
10667 err = got_error_msg(GOT_ERR_ANCESTRY,
10668 "ran out of commits to rebase before "
10669 "youngest common ancestor commit has "
10670 "been reached?!?");
10672 goto done;
10673 } else {
10674 err = check_path_prefix(&parent_id, &commit_id,
10675 path_prefix, path_prefix_errcode, repo);
10676 if (err)
10677 goto done;
10679 err = got_object_qid_alloc(&qid, &commit_id);
10680 if (err)
10681 goto done;
10682 STAILQ_INSERT_HEAD(commits, qid, entry);
10684 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10687 done:
10688 got_commit_graph_close(graph);
10689 return err;
10692 static const struct got_error *
10693 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10695 const struct got_error *err = NULL;
10696 time_t committer_time;
10697 struct tm tm;
10698 char datebuf[11]; /* YYYY-MM-DD + NUL */
10699 char *author0 = NULL, *author, *smallerthan;
10700 char *logmsg0 = NULL, *logmsg, *newline;
10702 committer_time = got_object_commit_get_committer_time(commit);
10703 if (gmtime_r(&committer_time, &tm) == NULL)
10704 return got_error_from_errno("gmtime_r");
10705 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10706 return got_error(GOT_ERR_NO_SPACE);
10708 author0 = strdup(got_object_commit_get_author(commit));
10709 if (author0 == NULL)
10710 return got_error_from_errno("strdup");
10711 author = author0;
10712 smallerthan = strchr(author, '<');
10713 if (smallerthan && smallerthan[1] != '\0')
10714 author = smallerthan + 1;
10715 author[strcspn(author, "@>")] = '\0';
10717 err = got_object_commit_get_logmsg(&logmsg0, commit);
10718 if (err)
10719 goto done;
10720 logmsg = logmsg0;
10721 while (*logmsg == '\n')
10722 logmsg++;
10723 newline = strchr(logmsg, '\n');
10724 if (newline)
10725 *newline = '\0';
10727 if (asprintf(brief_str, "%s %s %s",
10728 datebuf, author, logmsg) == -1)
10729 err = got_error_from_errno("asprintf");
10730 done:
10731 free(author0);
10732 free(logmsg0);
10733 return err;
10736 static const struct got_error *
10737 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10738 struct got_repository *repo)
10740 const struct got_error *err;
10741 char *id_str;
10743 err = got_object_id_str(&id_str, id);
10744 if (err)
10745 return err;
10747 err = got_ref_delete(ref, repo);
10748 if (err)
10749 goto done;
10751 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10752 done:
10753 free(id_str);
10754 return err;
10757 static const struct got_error *
10758 print_backup_ref(const char *branch_name, const char *new_id_str,
10759 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10760 struct got_reflist_object_id_map *refs_idmap,
10761 struct got_repository *repo)
10763 const struct got_error *err = NULL;
10764 struct got_reflist_head *refs;
10765 char *refs_str = NULL;
10766 struct got_object_id *new_commit_id = NULL;
10767 struct got_commit_object *new_commit = NULL;
10768 char *new_commit_brief_str = NULL;
10769 struct got_object_id *yca_id = NULL;
10770 struct got_commit_object *yca_commit = NULL;
10771 char *yca_id_str = NULL, *yca_brief_str = NULL;
10772 char *custom_refs_str;
10774 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10775 return got_error_from_errno("asprintf");
10777 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10778 0, 0, refs_idmap, custom_refs_str, NULL);
10779 if (err)
10780 goto done;
10782 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10783 if (err)
10784 goto done;
10786 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10787 if (refs) {
10788 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10789 if (err)
10790 goto done;
10793 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10794 if (err)
10795 goto done;
10797 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10798 if (err)
10799 goto done;
10801 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10802 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10803 if (err)
10804 goto done;
10806 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10807 refs_str ? " (" : "", refs_str ? refs_str : "",
10808 refs_str ? ")" : "", new_commit_brief_str);
10809 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10810 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10811 free(refs_str);
10812 refs_str = NULL;
10814 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10815 if (err)
10816 goto done;
10818 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10819 if (err)
10820 goto done;
10822 err = got_object_id_str(&yca_id_str, yca_id);
10823 if (err)
10824 goto done;
10826 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10827 if (refs) {
10828 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10829 if (err)
10830 goto done;
10832 printf("history forked at %s%s%s%s\n %s\n",
10833 yca_id_str,
10834 refs_str ? " (" : "", refs_str ? refs_str : "",
10835 refs_str ? ")" : "", yca_brief_str);
10837 done:
10838 free(custom_refs_str);
10839 free(new_commit_id);
10840 free(refs_str);
10841 free(yca_id);
10842 free(yca_id_str);
10843 free(yca_brief_str);
10844 if (new_commit)
10845 got_object_commit_close(new_commit);
10846 if (yca_commit)
10847 got_object_commit_close(yca_commit);
10849 return err;
10852 static const struct got_error *
10853 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10854 struct got_repository *repo)
10856 const struct got_error *err;
10857 struct got_reflist_head refs;
10858 struct got_reflist_entry *re;
10859 char *uuidstr = NULL;
10860 static char msg[160];
10862 TAILQ_INIT(&refs);
10864 err = got_worktree_get_uuid(&uuidstr, worktree);
10865 if (err)
10866 goto done;
10868 err = got_ref_list(&refs, repo, "refs/got/worktree",
10869 got_ref_cmp_by_name, repo);
10870 if (err)
10871 goto done;
10873 TAILQ_FOREACH(re, &refs, entry) {
10874 const char *cmd, *refname, *type;
10876 refname = got_ref_get_name(re->ref);
10878 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10879 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10880 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10881 cmd = "cherrypick";
10882 type = "cherrypicked";
10883 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10884 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10885 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10886 cmd = "backout";
10887 type = "backed-out";
10888 } else
10889 continue;
10891 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10892 continue;
10894 snprintf(msg, sizeof(msg),
10895 "work tree has references created by %s commits which "
10896 "must be removed with 'got %s -X' before running the %s "
10897 "command", type, cmd, caller);
10898 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10899 goto done;
10902 done:
10903 free(uuidstr);
10904 got_ref_list_free(&refs);
10905 return err;
10908 static const struct got_error *
10909 process_backup_refs(const char *backup_ref_prefix,
10910 const char *wanted_branch_name,
10911 int delete, struct got_repository *repo)
10913 const struct got_error *err;
10914 struct got_reflist_head refs, backup_refs;
10915 struct got_reflist_entry *re;
10916 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10917 struct got_object_id *old_commit_id = NULL;
10918 char *branch_name = NULL;
10919 struct got_commit_object *old_commit = NULL;
10920 struct got_reflist_object_id_map *refs_idmap = NULL;
10921 int wanted_branch_found = 0;
10923 TAILQ_INIT(&refs);
10924 TAILQ_INIT(&backup_refs);
10926 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10927 if (err)
10928 return err;
10930 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10931 if (err)
10932 goto done;
10934 if (wanted_branch_name) {
10935 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10936 wanted_branch_name += 11;
10939 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10940 got_ref_cmp_by_commit_timestamp_descending, repo);
10941 if (err)
10942 goto done;
10944 TAILQ_FOREACH(re, &backup_refs, entry) {
10945 const char *refname = got_ref_get_name(re->ref);
10946 char *slash;
10948 err = check_cancelled(NULL);
10949 if (err)
10950 break;
10952 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10953 if (err)
10954 break;
10956 err = got_object_open_as_commit(&old_commit, repo,
10957 old_commit_id);
10958 if (err)
10959 break;
10961 if (strncmp(backup_ref_prefix, refname,
10962 backup_ref_prefix_len) == 0)
10963 refname += backup_ref_prefix_len;
10965 while (refname[0] == '/')
10966 refname++;
10968 branch_name = strdup(refname);
10969 if (branch_name == NULL) {
10970 err = got_error_from_errno("strdup");
10971 break;
10973 slash = strrchr(branch_name, '/');
10974 if (slash) {
10975 *slash = '\0';
10976 refname += strlen(branch_name) + 1;
10979 if (wanted_branch_name == NULL ||
10980 strcmp(wanted_branch_name, branch_name) == 0) {
10981 wanted_branch_found = 1;
10982 if (delete) {
10983 err = delete_backup_ref(re->ref,
10984 old_commit_id, repo);
10985 } else {
10986 err = print_backup_ref(branch_name, refname,
10987 old_commit_id, old_commit, refs_idmap,
10988 repo);
10990 if (err)
10991 break;
10994 free(old_commit_id);
10995 old_commit_id = NULL;
10996 free(branch_name);
10997 branch_name = NULL;
10998 got_object_commit_close(old_commit);
10999 old_commit = NULL;
11002 if (wanted_branch_name && !wanted_branch_found) {
11003 err = got_error_fmt(GOT_ERR_NOT_REF,
11004 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11006 done:
11007 if (refs_idmap)
11008 got_reflist_object_id_map_free(refs_idmap);
11009 got_ref_list_free(&refs);
11010 got_ref_list_free(&backup_refs);
11011 free(old_commit_id);
11012 free(branch_name);
11013 if (old_commit)
11014 got_object_commit_close(old_commit);
11015 return err;
11018 static const struct got_error *
11019 abort_progress(void *arg, unsigned char status, const char *path)
11022 * Unversioned files should not clutter progress output when
11023 * an operation is aborted.
11025 if (status == GOT_STATUS_UNVERSIONED)
11026 return NULL;
11028 return update_progress(arg, status, path);
11031 static const struct got_error *
11032 cmd_rebase(int argc, char *argv[])
11034 const struct got_error *error = NULL;
11035 struct got_worktree *worktree = NULL;
11036 struct got_repository *repo = NULL;
11037 struct got_fileindex *fileindex = NULL;
11038 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11039 struct got_reference *branch = NULL;
11040 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11041 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11042 struct got_object_id *resume_commit_id = NULL;
11043 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11044 struct got_object_id *head_commit_id = NULL;
11045 struct got_reference *head_ref = NULL;
11046 struct got_commit_object *commit = NULL;
11047 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11048 int histedit_in_progress = 0, merge_in_progress = 0;
11049 int create_backup = 1, list_backups = 0, delete_backups = 0;
11050 int allow_conflict = 0;
11051 struct got_object_id_queue commits;
11052 struct got_pathlist_head merged_paths;
11053 const struct got_object_id_queue *parent_ids;
11054 struct got_object_qid *qid, *pid;
11055 struct got_update_progress_arg upa;
11056 int *pack_fds = NULL;
11058 STAILQ_INIT(&commits);
11059 TAILQ_INIT(&merged_paths);
11060 memset(&upa, 0, sizeof(upa));
11062 #ifndef PROFILE
11063 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11064 "unveil", NULL) == -1)
11065 err(1, "pledge");
11066 #endif
11068 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11069 switch (ch) {
11070 case 'a':
11071 abort_rebase = 1;
11072 break;
11073 case 'C':
11074 allow_conflict = 1;
11075 break;
11076 case 'c':
11077 continue_rebase = 1;
11078 break;
11079 case 'l':
11080 list_backups = 1;
11081 break;
11082 case 'X':
11083 delete_backups = 1;
11084 break;
11085 default:
11086 usage_rebase();
11087 /* NOTREACHED */
11091 argc -= optind;
11092 argv += optind;
11094 if (list_backups) {
11095 if (abort_rebase)
11096 option_conflict('l', 'a');
11097 if (allow_conflict)
11098 option_conflict('l', 'C');
11099 if (continue_rebase)
11100 option_conflict('l', 'c');
11101 if (delete_backups)
11102 option_conflict('l', 'X');
11103 if (argc != 0 && argc != 1)
11104 usage_rebase();
11105 } else if (delete_backups) {
11106 if (abort_rebase)
11107 option_conflict('X', 'a');
11108 if (allow_conflict)
11109 option_conflict('X', 'C');
11110 if (continue_rebase)
11111 option_conflict('X', 'c');
11112 if (list_backups)
11113 option_conflict('l', 'X');
11114 if (argc != 0 && argc != 1)
11115 usage_rebase();
11116 } else if (allow_conflict) {
11117 if (abort_rebase)
11118 option_conflict('C', 'a');
11119 if (!continue_rebase)
11120 errx(1, "-C option requires -c");
11121 } else {
11122 if (abort_rebase && continue_rebase)
11123 usage_rebase();
11124 else if (abort_rebase || continue_rebase) {
11125 if (argc != 0)
11126 usage_rebase();
11127 } else if (argc != 1)
11128 usage_rebase();
11131 cwd = getcwd(NULL, 0);
11132 if (cwd == NULL) {
11133 error = got_error_from_errno("getcwd");
11134 goto done;
11137 error = got_repo_pack_fds_open(&pack_fds);
11138 if (error != NULL)
11139 goto done;
11141 error = got_worktree_open(&worktree, cwd);
11142 if (error) {
11143 if (list_backups || delete_backups) {
11144 if (error->code != GOT_ERR_NOT_WORKTREE)
11145 goto done;
11146 } else {
11147 if (error->code == GOT_ERR_NOT_WORKTREE)
11148 error = wrap_not_worktree_error(error,
11149 "rebase", cwd);
11150 goto done;
11154 error = get_gitconfig_path(&gitconfig_path);
11155 if (error)
11156 goto done;
11157 error = got_repo_open(&repo,
11158 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11159 gitconfig_path, pack_fds);
11160 if (error != NULL)
11161 goto done;
11163 if (worktree != NULL && !list_backups && !delete_backups) {
11164 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11165 if (error)
11166 goto done;
11169 error = get_author(&committer, repo, worktree);
11170 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11171 goto done;
11173 error = apply_unveil(got_repo_get_path(repo), 0,
11174 worktree ? got_worktree_get_root_path(worktree) : NULL);
11175 if (error)
11176 goto done;
11178 if (list_backups || delete_backups) {
11179 error = process_backup_refs(
11180 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11181 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11182 goto done; /* nothing else to do */
11185 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11186 worktree);
11187 if (error)
11188 goto done;
11189 if (histedit_in_progress) {
11190 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11191 goto done;
11194 error = got_worktree_merge_in_progress(&merge_in_progress,
11195 worktree, repo);
11196 if (error)
11197 goto done;
11198 if (merge_in_progress) {
11199 error = got_error(GOT_ERR_MERGE_BUSY);
11200 goto done;
11203 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11204 if (error)
11205 goto done;
11207 if (abort_rebase) {
11208 if (!rebase_in_progress) {
11209 error = got_error(GOT_ERR_NOT_REBASING);
11210 goto done;
11212 error = got_worktree_rebase_continue(&resume_commit_id,
11213 &new_base_branch, &tmp_branch, &branch, &fileindex,
11214 worktree, repo);
11215 if (error)
11216 goto done;
11217 printf("Switching work tree to %s\n",
11218 got_ref_get_symref_target(new_base_branch));
11219 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11220 new_base_branch, abort_progress, &upa);
11221 if (error)
11222 goto done;
11223 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11224 print_merge_progress_stats(&upa);
11225 goto done; /* nothing else to do */
11228 if (continue_rebase) {
11229 if (!rebase_in_progress) {
11230 error = got_error(GOT_ERR_NOT_REBASING);
11231 goto done;
11233 error = got_worktree_rebase_continue(&resume_commit_id,
11234 &new_base_branch, &tmp_branch, &branch, &fileindex,
11235 worktree, repo);
11236 if (error)
11237 goto done;
11239 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11240 committer, resume_commit_id, allow_conflict, repo);
11241 if (error)
11242 goto done;
11244 yca_id = got_object_id_dup(resume_commit_id);
11245 if (yca_id == NULL) {
11246 error = got_error_from_errno("got_object_id_dup");
11247 goto done;
11249 } else {
11250 error = got_ref_open(&branch, repo, argv[0], 0);
11251 if (error != NULL)
11252 goto done;
11253 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11254 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11255 "will not rebase a branch which lives outside "
11256 "the \"refs/heads/\" reference namespace");
11257 goto done;
11261 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11262 if (error)
11263 goto done;
11265 if (!continue_rebase) {
11266 struct got_object_id *base_commit_id;
11268 error = got_ref_open(&head_ref, repo,
11269 got_worktree_get_head_ref_name(worktree), 0);
11270 if (error)
11271 goto done;
11272 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11273 if (error)
11274 goto done;
11275 base_commit_id = got_worktree_get_base_commit_id(worktree);
11276 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11277 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11278 goto done;
11281 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11282 base_commit_id, branch_head_commit_id, 1, repo,
11283 check_cancelled, NULL);
11284 if (error) {
11285 if (error->code == GOT_ERR_ANCESTRY) {
11286 error = got_error_msg(GOT_ERR_ANCESTRY,
11287 "specified branch shares no common "
11288 "ancestry with work tree's branch");
11290 goto done;
11293 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11294 if (error) {
11295 if (error->code != GOT_ERR_ANCESTRY)
11296 goto done;
11297 error = NULL;
11298 } else {
11299 struct got_pathlist_head paths;
11300 printf("%s is already based on %s\n",
11301 got_ref_get_name(branch),
11302 got_worktree_get_head_ref_name(worktree));
11303 error = switch_head_ref(branch, branch_head_commit_id,
11304 worktree, repo);
11305 if (error)
11306 goto done;
11307 error = got_worktree_set_base_commit_id(worktree, repo,
11308 branch_head_commit_id);
11309 if (error)
11310 goto done;
11311 TAILQ_INIT(&paths);
11312 error = got_pathlist_append(&paths, "", NULL);
11313 if (error)
11314 goto done;
11315 error = got_worktree_checkout_files(worktree,
11316 &paths, repo, update_progress, &upa,
11317 check_cancelled, NULL);
11318 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11319 if (error)
11320 goto done;
11321 if (upa.did_something) {
11322 char *id_str;
11323 error = got_object_id_str(&id_str,
11324 branch_head_commit_id);
11325 if (error)
11326 goto done;
11327 printf("Updated to %s: %s\n",
11328 got_worktree_get_head_ref_name(worktree),
11329 id_str);
11330 free(id_str);
11331 } else
11332 printf("Already up-to-date\n");
11333 print_update_progress_stats(&upa);
11334 goto done;
11338 commit_id = branch_head_commit_id;
11339 error = got_object_open_as_commit(&commit, repo, commit_id);
11340 if (error)
11341 goto done;
11343 parent_ids = got_object_commit_get_parent_ids(commit);
11344 pid = STAILQ_FIRST(parent_ids);
11345 if (pid) {
11346 error = collect_commits(&commits, commit_id, &pid->id,
11347 yca_id, got_worktree_get_path_prefix(worktree),
11348 GOT_ERR_REBASE_PATH, repo);
11349 if (error)
11350 goto done;
11353 got_object_commit_close(commit);
11354 commit = NULL;
11356 if (!continue_rebase) {
11357 error = got_worktree_rebase_prepare(&new_base_branch,
11358 &tmp_branch, &fileindex, worktree, branch, repo);
11359 if (error)
11360 goto done;
11363 if (STAILQ_EMPTY(&commits)) {
11364 if (continue_rebase) {
11365 error = rebase_complete(worktree, fileindex,
11366 branch, tmp_branch, repo, create_backup);
11367 goto done;
11368 } else {
11369 /* Fast-forward the reference of the branch. */
11370 struct got_object_id *new_head_commit_id;
11371 char *id_str;
11372 error = got_ref_resolve(&new_head_commit_id, repo,
11373 new_base_branch);
11374 if (error)
11375 goto done;
11376 error = got_object_id_str(&id_str, new_head_commit_id);
11377 if (error)
11378 goto done;
11379 printf("Forwarding %s to commit %s\n",
11380 got_ref_get_name(branch), id_str);
11381 free(id_str);
11382 error = got_ref_change_ref(branch,
11383 new_head_commit_id);
11384 if (error)
11385 goto done;
11386 /* No backup needed since objects did not change. */
11387 create_backup = 0;
11391 pid = NULL;
11392 STAILQ_FOREACH(qid, &commits, entry) {
11394 commit_id = &qid->id;
11395 parent_id = pid ? &pid->id : yca_id;
11396 pid = qid;
11398 memset(&upa, 0, sizeof(upa));
11399 error = got_worktree_rebase_merge_files(&merged_paths,
11400 worktree, fileindex, parent_id, commit_id, repo,
11401 update_progress, &upa, check_cancelled, NULL);
11402 if (error)
11403 goto done;
11405 print_merge_progress_stats(&upa);
11406 if (upa.conflicts > 0 || upa.missing > 0 ||
11407 upa.not_deleted > 0 || upa.unversioned > 0) {
11408 if (upa.conflicts > 0) {
11409 error = show_rebase_merge_conflict(&qid->id,
11410 repo);
11411 if (error)
11412 goto done;
11414 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11415 break;
11418 error = rebase_commit(&merged_paths, worktree, fileindex,
11419 tmp_branch, committer, commit_id, 0, repo);
11420 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11421 if (error)
11422 goto done;
11425 if (upa.conflicts > 0 || upa.missing > 0 ||
11426 upa.not_deleted > 0 || upa.unversioned > 0) {
11427 error = got_worktree_rebase_postpone(worktree, fileindex);
11428 if (error)
11429 goto done;
11430 if (upa.conflicts > 0 && upa.missing == 0 &&
11431 upa.not_deleted == 0 && upa.unversioned == 0) {
11432 error = got_error_msg(GOT_ERR_CONFLICTS,
11433 "conflicts must be resolved before rebasing "
11434 "can continue");
11435 } else if (upa.conflicts > 0) {
11436 error = got_error_msg(GOT_ERR_CONFLICTS,
11437 "conflicts must be resolved before rebasing "
11438 "can continue; changes destined for some "
11439 "files were not yet merged and should be "
11440 "merged manually if required before the "
11441 "rebase operation is continued");
11442 } else {
11443 error = got_error_msg(GOT_ERR_CONFLICTS,
11444 "changes destined for some files were not "
11445 "yet merged and should be merged manually "
11446 "if required before the rebase operation "
11447 "is continued");
11449 } else
11450 error = rebase_complete(worktree, fileindex, branch,
11451 tmp_branch, repo, create_backup);
11452 done:
11453 free(cwd);
11454 free(committer);
11455 free(gitconfig_path);
11456 got_object_id_queue_free(&commits);
11457 free(branch_head_commit_id);
11458 free(resume_commit_id);
11459 free(head_commit_id);
11460 free(yca_id);
11461 if (commit)
11462 got_object_commit_close(commit);
11463 if (branch)
11464 got_ref_close(branch);
11465 if (new_base_branch)
11466 got_ref_close(new_base_branch);
11467 if (tmp_branch)
11468 got_ref_close(tmp_branch);
11469 if (head_ref)
11470 got_ref_close(head_ref);
11471 if (worktree)
11472 got_worktree_close(worktree);
11473 if (repo) {
11474 const struct got_error *close_err = got_repo_close(repo);
11475 if (error == NULL)
11476 error = close_err;
11478 if (pack_fds) {
11479 const struct got_error *pack_err =
11480 got_repo_pack_fds_close(pack_fds);
11481 if (error == NULL)
11482 error = pack_err;
11484 return error;
11487 __dead static void
11488 usage_histedit(void)
11490 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11491 "[branch]\n", getprogname());
11492 exit(1);
11495 #define GOT_HISTEDIT_PICK 'p'
11496 #define GOT_HISTEDIT_EDIT 'e'
11497 #define GOT_HISTEDIT_FOLD 'f'
11498 #define GOT_HISTEDIT_DROP 'd'
11499 #define GOT_HISTEDIT_MESG 'm'
11501 static const struct got_histedit_cmd {
11502 unsigned char code;
11503 const char *name;
11504 const char *desc;
11505 } got_histedit_cmds[] = {
11506 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11507 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11508 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11509 "be used" },
11510 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11511 { GOT_HISTEDIT_MESG, "mesg",
11512 "single-line log message for commit above (open editor if empty)" },
11515 struct got_histedit_list_entry {
11516 TAILQ_ENTRY(got_histedit_list_entry) entry;
11517 struct got_object_id *commit_id;
11518 const struct got_histedit_cmd *cmd;
11519 char *logmsg;
11521 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11523 static const struct got_error *
11524 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11525 FILE *f, struct got_repository *repo)
11527 const struct got_error *err = NULL;
11528 char *logmsg = NULL, *id_str = NULL;
11529 struct got_commit_object *commit = NULL;
11530 int n;
11532 err = got_object_open_as_commit(&commit, repo, commit_id);
11533 if (err)
11534 goto done;
11536 err = get_short_logmsg(&logmsg, 34, commit);
11537 if (err)
11538 goto done;
11540 err = got_object_id_str(&id_str, commit_id);
11541 if (err)
11542 goto done;
11544 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11545 if (n < 0)
11546 err = got_ferror(f, GOT_ERR_IO);
11547 done:
11548 if (commit)
11549 got_object_commit_close(commit);
11550 free(id_str);
11551 free(logmsg);
11552 return err;
11555 static const struct got_error *
11556 histedit_write_commit_list(struct got_object_id_queue *commits,
11557 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11558 int edit_only, struct got_repository *repo)
11560 const struct got_error *err = NULL;
11561 struct got_object_qid *qid;
11562 const char *histedit_cmd = NULL;
11564 if (STAILQ_EMPTY(commits))
11565 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11567 STAILQ_FOREACH(qid, commits, entry) {
11568 histedit_cmd = got_histedit_cmds[0].name;
11569 if (drop_only)
11570 histedit_cmd = "drop";
11571 else if (edit_only)
11572 histedit_cmd = "edit";
11573 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11574 histedit_cmd = "fold";
11575 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11576 if (err)
11577 break;
11578 if (edit_logmsg_only) {
11579 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11580 if (n < 0) {
11581 err = got_ferror(f, GOT_ERR_IO);
11582 break;
11587 return err;
11590 static const struct got_error *
11591 write_cmd_list(FILE *f, const char *branch_name,
11592 struct got_object_id_queue *commits)
11594 const struct got_error *err = NULL;
11595 size_t i;
11596 int n;
11597 char *id_str;
11598 struct got_object_qid *qid;
11600 qid = STAILQ_FIRST(commits);
11601 err = got_object_id_str(&id_str, &qid->id);
11602 if (err)
11603 return err;
11605 n = fprintf(f,
11606 "# Editing the history of branch '%s' starting at\n"
11607 "# commit %s\n"
11608 "# Commits will be processed in order from top to "
11609 "bottom of this file.\n", branch_name, id_str);
11610 if (n < 0) {
11611 err = got_ferror(f, GOT_ERR_IO);
11612 goto done;
11615 n = fprintf(f, "# Available histedit commands:\n");
11616 if (n < 0) {
11617 err = got_ferror(f, GOT_ERR_IO);
11618 goto done;
11621 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11622 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11623 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11624 cmd->desc);
11625 if (n < 0) {
11626 err = got_ferror(f, GOT_ERR_IO);
11627 break;
11630 done:
11631 free(id_str);
11632 return err;
11635 static const struct got_error *
11636 histedit_syntax_error(int lineno)
11638 static char msg[42];
11639 int ret;
11641 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11642 lineno);
11643 if (ret < 0 || (size_t)ret >= sizeof(msg))
11644 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11646 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11649 static const struct got_error *
11650 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11651 char *logmsg, struct got_repository *repo)
11653 const struct got_error *err;
11654 struct got_commit_object *folded_commit = NULL;
11655 char *id_str, *folded_logmsg = NULL;
11657 err = got_object_id_str(&id_str, hle->commit_id);
11658 if (err)
11659 return err;
11661 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11662 if (err)
11663 goto done;
11665 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11666 if (err)
11667 goto done;
11668 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11669 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11670 folded_logmsg) == -1) {
11671 err = got_error_from_errno("asprintf");
11673 done:
11674 if (folded_commit)
11675 got_object_commit_close(folded_commit);
11676 free(id_str);
11677 free(folded_logmsg);
11678 return err;
11681 static struct got_histedit_list_entry *
11682 get_folded_commits(struct got_histedit_list_entry *hle)
11684 struct got_histedit_list_entry *prev, *folded = NULL;
11686 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11687 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11688 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11689 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11690 folded = prev;
11691 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11694 return folded;
11697 static const struct got_error *
11698 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11699 struct got_repository *repo)
11701 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11702 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11703 const struct got_error *err = NULL;
11704 struct got_commit_object *commit = NULL;
11705 int logmsg_len;
11706 int fd = -1;
11707 struct got_histedit_list_entry *folded = NULL;
11709 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11710 if (err)
11711 return err;
11713 folded = get_folded_commits(hle);
11714 if (folded) {
11715 while (folded != hle) {
11716 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11717 folded = TAILQ_NEXT(folded, entry);
11718 continue;
11720 err = append_folded_commit_msg(&new_msg, folded,
11721 logmsg, repo);
11722 if (err)
11723 goto done;
11724 free(logmsg);
11725 logmsg = new_msg;
11726 folded = TAILQ_NEXT(folded, entry);
11730 err = got_object_id_str(&id_str, hle->commit_id);
11731 if (err)
11732 goto done;
11733 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11734 if (err)
11735 goto done;
11736 logmsg_len = asprintf(&new_msg,
11737 "%s\n# original log message of commit %s: %s",
11738 logmsg ? logmsg : "", id_str, orig_logmsg);
11739 if (logmsg_len == -1) {
11740 err = got_error_from_errno("asprintf");
11741 goto done;
11743 free(logmsg);
11744 logmsg = new_msg;
11746 err = got_object_id_str(&id_str, hle->commit_id);
11747 if (err)
11748 goto done;
11750 err = got_opentemp_named_fd(&logmsg_path, &fd,
11751 GOT_TMPDIR_STR "/got-logmsg", "");
11752 if (err)
11753 goto done;
11755 if (write(fd, logmsg, logmsg_len) == -1) {
11756 err = got_error_from_errno2("write", logmsg_path);
11757 goto done;
11759 if (close(fd) == -1) {
11760 err = got_error_from_errno2("close", logmsg_path);
11761 goto done;
11763 fd = -1;
11765 err = get_editor(&editor);
11766 if (err)
11767 goto done;
11769 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11770 logmsg_len, 0);
11771 if (err) {
11772 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11773 goto done;
11774 err = NULL;
11775 hle->logmsg = strdup(new_msg);
11776 if (hle->logmsg == NULL)
11777 err = got_error_from_errno("strdup");
11779 done:
11780 if (fd != -1 && close(fd) == -1 && err == NULL)
11781 err = got_error_from_errno2("close", logmsg_path);
11782 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11783 err = got_error_from_errno2("unlink", logmsg_path);
11784 free(logmsg_path);
11785 free(logmsg);
11786 free(orig_logmsg);
11787 free(editor);
11788 if (commit)
11789 got_object_commit_close(commit);
11790 return err;
11793 static const struct got_error *
11794 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11795 FILE *f, struct got_repository *repo)
11797 const struct got_error *err = NULL;
11798 char *line = NULL, *p, *end;
11799 size_t i, linesize = 0;
11800 ssize_t linelen;
11801 int lineno = 0, lastcmd = -1;
11802 const struct got_histedit_cmd *cmd;
11803 struct got_object_id *commit_id = NULL;
11804 struct got_histedit_list_entry *hle = NULL;
11806 for (;;) {
11807 linelen = getline(&line, &linesize, f);
11808 if (linelen == -1) {
11809 const struct got_error *getline_err;
11810 if (feof(f))
11811 break;
11812 getline_err = got_error_from_errno("getline");
11813 err = got_ferror(f, getline_err->code);
11814 break;
11816 lineno++;
11817 p = line;
11818 while (isspace((unsigned char)p[0]))
11819 p++;
11820 if (p[0] == '#' || p[0] == '\0')
11821 continue;
11822 cmd = NULL;
11823 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11824 cmd = &got_histedit_cmds[i];
11825 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11826 isspace((unsigned char)p[strlen(cmd->name)])) {
11827 p += strlen(cmd->name);
11828 break;
11830 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11831 p++;
11832 break;
11835 if (i == nitems(got_histedit_cmds)) {
11836 err = histedit_syntax_error(lineno);
11837 break;
11839 while (isspace((unsigned char)p[0]))
11840 p++;
11841 if (cmd->code == GOT_HISTEDIT_MESG) {
11842 if (lastcmd != GOT_HISTEDIT_PICK &&
11843 lastcmd != GOT_HISTEDIT_EDIT) {
11844 err = got_error(GOT_ERR_HISTEDIT_CMD);
11845 break;
11847 if (p[0] == '\0') {
11848 err = histedit_edit_logmsg(hle, repo);
11849 if (err)
11850 break;
11851 } else {
11852 hle->logmsg = strdup(p);
11853 if (hle->logmsg == NULL) {
11854 err = got_error_from_errno("strdup");
11855 break;
11858 lastcmd = cmd->code;
11859 continue;
11860 } else {
11861 end = p;
11862 while (end[0] && !isspace((unsigned char)end[0]))
11863 end++;
11864 *end = '\0';
11866 err = got_object_resolve_id_str(&commit_id, repo, p);
11867 if (err) {
11868 /* override error code */
11869 err = histedit_syntax_error(lineno);
11870 break;
11873 hle = malloc(sizeof(*hle));
11874 if (hle == NULL) {
11875 err = got_error_from_errno("malloc");
11876 break;
11878 hle->cmd = cmd;
11879 hle->commit_id = commit_id;
11880 hle->logmsg = NULL;
11881 commit_id = NULL;
11882 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11883 lastcmd = cmd->code;
11886 free(line);
11887 free(commit_id);
11888 return err;
11891 static const struct got_error *
11892 histedit_check_script(struct got_histedit_list *histedit_cmds,
11893 struct got_object_id_queue *commits, struct got_repository *repo)
11895 const struct got_error *err = NULL;
11896 struct got_object_qid *qid;
11897 struct got_histedit_list_entry *hle;
11898 static char msg[92];
11899 char *id_str;
11901 if (TAILQ_EMPTY(histedit_cmds))
11902 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11903 "histedit script contains no commands");
11904 if (STAILQ_EMPTY(commits))
11905 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11907 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11908 struct got_histedit_list_entry *hle2;
11909 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11910 if (hle == hle2)
11911 continue;
11912 if (got_object_id_cmp(hle->commit_id,
11913 hle2->commit_id) != 0)
11914 continue;
11915 err = got_object_id_str(&id_str, hle->commit_id);
11916 if (err)
11917 return err;
11918 snprintf(msg, sizeof(msg), "commit %s is listed "
11919 "more than once in histedit script", id_str);
11920 free(id_str);
11921 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11925 STAILQ_FOREACH(qid, commits, entry) {
11926 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11927 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11928 break;
11930 if (hle == NULL) {
11931 err = got_object_id_str(&id_str, &qid->id);
11932 if (err)
11933 return err;
11934 snprintf(msg, sizeof(msg),
11935 "commit %s missing from histedit script", id_str);
11936 free(id_str);
11937 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11941 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11942 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11943 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11944 "last commit in histedit script cannot be folded");
11946 return NULL;
11949 static const struct got_error *
11950 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11951 const char *path, struct got_object_id_queue *commits,
11952 struct got_repository *repo)
11954 const struct got_error *err = NULL;
11955 char *editor;
11956 FILE *f = NULL;
11958 err = get_editor(&editor);
11959 if (err)
11960 return err;
11962 if (spawn_editor(editor, path) == -1) {
11963 err = got_error_from_errno("failed spawning editor");
11964 goto done;
11967 f = fopen(path, "re");
11968 if (f == NULL) {
11969 err = got_error_from_errno("fopen");
11970 goto done;
11972 err = histedit_parse_list(histedit_cmds, f, repo);
11973 if (err)
11974 goto done;
11976 err = histedit_check_script(histedit_cmds, commits, repo);
11977 done:
11978 if (f && fclose(f) == EOF && err == NULL)
11979 err = got_error_from_errno("fclose");
11980 free(editor);
11981 return err;
11984 static const struct got_error *
11985 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11986 struct got_object_id_queue *, const char *, const char *,
11987 struct got_repository *);
11989 static const struct got_error *
11990 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11991 struct got_object_id_queue *commits, const char *branch_name,
11992 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11993 struct got_repository *repo)
11995 const struct got_error *err;
11996 FILE *f = NULL;
11997 char *path = NULL;
11999 err = got_opentemp_named(&path, &f, "got-histedit", "");
12000 if (err)
12001 return err;
12003 err = write_cmd_list(f, branch_name, commits);
12004 if (err)
12005 goto done;
12007 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12008 fold_only, drop_only, edit_only, repo);
12009 if (err)
12010 goto done;
12012 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12013 rewind(f);
12014 err = histedit_parse_list(histedit_cmds, f, repo);
12015 } else {
12016 if (fclose(f) == EOF) {
12017 err = got_error_from_errno("fclose");
12018 goto done;
12020 f = NULL;
12021 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12022 if (err) {
12023 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12024 err->code != GOT_ERR_HISTEDIT_CMD)
12025 goto done;
12026 err = histedit_edit_list_retry(histedit_cmds, err,
12027 commits, path, branch_name, repo);
12030 done:
12031 if (f && fclose(f) == EOF && err == NULL)
12032 err = got_error_from_errno("fclose");
12033 if (path && unlink(path) != 0 && err == NULL)
12034 err = got_error_from_errno2("unlink", path);
12035 free(path);
12036 return err;
12039 static const struct got_error *
12040 histedit_save_list(struct got_histedit_list *histedit_cmds,
12041 struct got_worktree *worktree, struct got_repository *repo)
12043 const struct got_error *err = NULL;
12044 char *path = NULL;
12045 FILE *f = NULL;
12046 struct got_histedit_list_entry *hle;
12047 struct got_commit_object *commit = NULL;
12049 err = got_worktree_get_histedit_script_path(&path, worktree);
12050 if (err)
12051 return err;
12053 f = fopen(path, "we");
12054 if (f == NULL) {
12055 err = got_error_from_errno2("fopen", path);
12056 goto done;
12058 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12059 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12060 repo);
12061 if (err)
12062 break;
12064 if (hle->logmsg) {
12065 int n = fprintf(f, "%c %s\n",
12066 GOT_HISTEDIT_MESG, hle->logmsg);
12067 if (n < 0) {
12068 err = got_ferror(f, GOT_ERR_IO);
12069 break;
12073 done:
12074 if (f && fclose(f) == EOF && err == NULL)
12075 err = got_error_from_errno("fclose");
12076 free(path);
12077 if (commit)
12078 got_object_commit_close(commit);
12079 return err;
12082 static void
12083 histedit_free_list(struct got_histedit_list *histedit_cmds)
12085 struct got_histedit_list_entry *hle;
12087 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12088 TAILQ_REMOVE(histedit_cmds, hle, entry);
12089 free(hle);
12093 static const struct got_error *
12094 histedit_load_list(struct got_histedit_list *histedit_cmds,
12095 const char *path, struct got_repository *repo)
12097 const struct got_error *err = NULL;
12098 FILE *f = NULL;
12100 f = fopen(path, "re");
12101 if (f == NULL) {
12102 err = got_error_from_errno2("fopen", path);
12103 goto done;
12106 err = histedit_parse_list(histedit_cmds, f, repo);
12107 done:
12108 if (f && fclose(f) == EOF && err == NULL)
12109 err = got_error_from_errno("fclose");
12110 return err;
12113 static const struct got_error *
12114 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12115 const struct got_error *edit_err, struct got_object_id_queue *commits,
12116 const char *path, const char *branch_name, struct got_repository *repo)
12118 const struct got_error *err = NULL, *prev_err = edit_err;
12119 int resp = ' ';
12121 while (resp != 'c' && resp != 'r' && resp != 'a') {
12122 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12123 "or (a)bort: ", getprogname(), prev_err->msg);
12124 resp = getchar();
12125 if (resp == '\n')
12126 resp = getchar();
12127 if (resp == 'c') {
12128 histedit_free_list(histedit_cmds);
12129 err = histedit_run_editor(histedit_cmds, path, commits,
12130 repo);
12131 if (err) {
12132 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12133 err->code != GOT_ERR_HISTEDIT_CMD)
12134 break;
12135 prev_err = err;
12136 resp = ' ';
12137 continue;
12139 break;
12140 } else if (resp == 'r') {
12141 histedit_free_list(histedit_cmds);
12142 err = histedit_edit_script(histedit_cmds,
12143 commits, branch_name, 0, 0, 0, 0, repo);
12144 if (err) {
12145 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12146 err->code != GOT_ERR_HISTEDIT_CMD)
12147 break;
12148 prev_err = err;
12149 resp = ' ';
12150 continue;
12152 break;
12153 } else if (resp == 'a') {
12154 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12155 break;
12156 } else
12157 printf("invalid response '%c'\n", resp);
12160 return err;
12163 static const struct got_error *
12164 histedit_complete(struct got_worktree *worktree,
12165 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12166 struct got_reference *branch, struct got_repository *repo)
12168 printf("Switching work tree to %s\n",
12169 got_ref_get_symref_target(branch));
12170 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12171 branch, repo);
12174 static const struct got_error *
12175 show_histedit_progress(struct got_commit_object *commit,
12176 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12178 const struct got_error *err;
12179 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12181 err = got_object_id_str(&old_id_str, hle->commit_id);
12182 if (err)
12183 goto done;
12185 if (new_id) {
12186 err = got_object_id_str(&new_id_str, new_id);
12187 if (err)
12188 goto done;
12191 old_id_str[12] = '\0';
12192 if (new_id_str)
12193 new_id_str[12] = '\0';
12195 if (hle->logmsg) {
12196 logmsg = strdup(hle->logmsg);
12197 if (logmsg == NULL) {
12198 err = got_error_from_errno("strdup");
12199 goto done;
12201 trim_logmsg(logmsg, 42);
12202 } else {
12203 err = get_short_logmsg(&logmsg, 42, commit);
12204 if (err)
12205 goto done;
12208 switch (hle->cmd->code) {
12209 case GOT_HISTEDIT_PICK:
12210 case GOT_HISTEDIT_EDIT:
12211 printf("%s -> %s: %s\n", old_id_str,
12212 new_id_str ? new_id_str : "no-op change", logmsg);
12213 break;
12214 case GOT_HISTEDIT_DROP:
12215 case GOT_HISTEDIT_FOLD:
12216 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12217 logmsg);
12218 break;
12219 default:
12220 break;
12222 done:
12223 free(old_id_str);
12224 free(new_id_str);
12225 return err;
12228 static const struct got_error *
12229 histedit_commit(struct got_pathlist_head *merged_paths,
12230 struct got_worktree *worktree, struct got_fileindex *fileindex,
12231 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12232 const char *committer, int allow_conflict, struct got_repository *repo)
12234 const struct got_error *err;
12235 struct got_commit_object *commit;
12236 struct got_object_id *new_commit_id;
12238 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12239 && hle->logmsg == NULL) {
12240 err = histedit_edit_logmsg(hle, repo);
12241 if (err)
12242 return err;
12245 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12246 if (err)
12247 return err;
12249 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12250 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12251 hle->logmsg, allow_conflict, repo);
12252 if (err) {
12253 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12254 goto done;
12255 err = show_histedit_progress(commit, hle, NULL);
12256 } else {
12257 err = show_histedit_progress(commit, hle, new_commit_id);
12258 free(new_commit_id);
12260 done:
12261 got_object_commit_close(commit);
12262 return err;
12265 static const struct got_error *
12266 histedit_skip_commit(struct got_histedit_list_entry *hle,
12267 struct got_worktree *worktree, struct got_repository *repo)
12269 const struct got_error *error;
12270 struct got_commit_object *commit;
12272 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12273 repo);
12274 if (error)
12275 return error;
12277 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12278 if (error)
12279 return error;
12281 error = show_histedit_progress(commit, hle, NULL);
12282 got_object_commit_close(commit);
12283 return error;
12286 static const struct got_error *
12287 check_local_changes(void *arg, unsigned char status,
12288 unsigned char staged_status, const char *path,
12289 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12290 struct got_object_id *commit_id, int dirfd, const char *de_name)
12292 int *have_local_changes = arg;
12294 switch (status) {
12295 case GOT_STATUS_ADD:
12296 case GOT_STATUS_DELETE:
12297 case GOT_STATUS_MODIFY:
12298 case GOT_STATUS_CONFLICT:
12299 *have_local_changes = 1;
12300 return got_error(GOT_ERR_CANCELLED);
12301 default:
12302 break;
12305 switch (staged_status) {
12306 case GOT_STATUS_ADD:
12307 case GOT_STATUS_DELETE:
12308 case GOT_STATUS_MODIFY:
12309 *have_local_changes = 1;
12310 return got_error(GOT_ERR_CANCELLED);
12311 default:
12312 break;
12315 return NULL;
12318 static const struct got_error *
12319 cmd_histedit(int argc, char *argv[])
12321 const struct got_error *error = NULL;
12322 struct got_worktree *worktree = NULL;
12323 struct got_fileindex *fileindex = NULL;
12324 struct got_repository *repo = NULL;
12325 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12326 struct got_reference *branch = NULL;
12327 struct got_reference *tmp_branch = NULL;
12328 struct got_object_id *resume_commit_id = NULL;
12329 struct got_object_id *base_commit_id = NULL;
12330 struct got_object_id *head_commit_id = NULL;
12331 struct got_commit_object *commit = NULL;
12332 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12333 struct got_update_progress_arg upa;
12334 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12335 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12336 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12337 const char *edit_script_path = NULL;
12338 struct got_object_id_queue commits;
12339 struct got_pathlist_head merged_paths;
12340 const struct got_object_id_queue *parent_ids;
12341 struct got_object_qid *pid;
12342 struct got_histedit_list histedit_cmds;
12343 struct got_histedit_list_entry *hle;
12344 int *pack_fds = NULL;
12346 STAILQ_INIT(&commits);
12347 TAILQ_INIT(&histedit_cmds);
12348 TAILQ_INIT(&merged_paths);
12349 memset(&upa, 0, sizeof(upa));
12351 #ifndef PROFILE
12352 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12353 "unveil", NULL) == -1)
12354 err(1, "pledge");
12355 #endif
12357 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12358 switch (ch) {
12359 case 'a':
12360 abort_edit = 1;
12361 break;
12362 case 'C':
12363 allow_conflict = 1;
12364 break;
12365 case 'c':
12366 continue_edit = 1;
12367 break;
12368 case 'd':
12369 drop_only = 1;
12370 break;
12371 case 'e':
12372 edit_only = 1;
12373 break;
12374 case 'F':
12375 edit_script_path = optarg;
12376 break;
12377 case 'f':
12378 fold_only = 1;
12379 break;
12380 case 'l':
12381 list_backups = 1;
12382 break;
12383 case 'm':
12384 edit_logmsg_only = 1;
12385 break;
12386 case 'X':
12387 delete_backups = 1;
12388 break;
12389 default:
12390 usage_histedit();
12391 /* NOTREACHED */
12395 argc -= optind;
12396 argv += optind;
12398 if (abort_edit && allow_conflict)
12399 option_conflict('a', 'C');
12400 if (abort_edit && continue_edit)
12401 option_conflict('a', 'c');
12402 if (edit_script_path && allow_conflict)
12403 option_conflict('F', 'C');
12404 if (edit_script_path && edit_logmsg_only)
12405 option_conflict('F', 'm');
12406 if (abort_edit && edit_logmsg_only)
12407 option_conflict('a', 'm');
12408 if (edit_logmsg_only && allow_conflict)
12409 option_conflict('m', 'C');
12410 if (continue_edit && edit_logmsg_only)
12411 option_conflict('c', 'm');
12412 if (abort_edit && fold_only)
12413 option_conflict('a', 'f');
12414 if (fold_only && allow_conflict)
12415 option_conflict('f', 'C');
12416 if (continue_edit && fold_only)
12417 option_conflict('c', 'f');
12418 if (fold_only && edit_logmsg_only)
12419 option_conflict('f', 'm');
12420 if (edit_script_path && fold_only)
12421 option_conflict('F', 'f');
12422 if (abort_edit && edit_only)
12423 option_conflict('a', 'e');
12424 if (continue_edit && edit_only)
12425 option_conflict('c', 'e');
12426 if (edit_only && edit_logmsg_only)
12427 option_conflict('e', 'm');
12428 if (edit_script_path && edit_only)
12429 option_conflict('F', 'e');
12430 if (fold_only && edit_only)
12431 option_conflict('f', 'e');
12432 if (drop_only && abort_edit)
12433 option_conflict('d', 'a');
12434 if (drop_only && allow_conflict)
12435 option_conflict('d', 'C');
12436 if (drop_only && continue_edit)
12437 option_conflict('d', 'c');
12438 if (drop_only && edit_logmsg_only)
12439 option_conflict('d', 'm');
12440 if (drop_only && edit_only)
12441 option_conflict('d', 'e');
12442 if (drop_only && edit_script_path)
12443 option_conflict('d', 'F');
12444 if (drop_only && fold_only)
12445 option_conflict('d', 'f');
12446 if (list_backups) {
12447 if (abort_edit)
12448 option_conflict('l', 'a');
12449 if (allow_conflict)
12450 option_conflict('l', 'C');
12451 if (continue_edit)
12452 option_conflict('l', 'c');
12453 if (edit_script_path)
12454 option_conflict('l', 'F');
12455 if (edit_logmsg_only)
12456 option_conflict('l', 'm');
12457 if (drop_only)
12458 option_conflict('l', 'd');
12459 if (fold_only)
12460 option_conflict('l', 'f');
12461 if (edit_only)
12462 option_conflict('l', 'e');
12463 if (delete_backups)
12464 option_conflict('l', 'X');
12465 if (argc != 0 && argc != 1)
12466 usage_histedit();
12467 } else if (delete_backups) {
12468 if (abort_edit)
12469 option_conflict('X', 'a');
12470 if (allow_conflict)
12471 option_conflict('X', 'C');
12472 if (continue_edit)
12473 option_conflict('X', 'c');
12474 if (drop_only)
12475 option_conflict('X', 'd');
12476 if (edit_script_path)
12477 option_conflict('X', 'F');
12478 if (edit_logmsg_only)
12479 option_conflict('X', 'm');
12480 if (fold_only)
12481 option_conflict('X', 'f');
12482 if (edit_only)
12483 option_conflict('X', 'e');
12484 if (list_backups)
12485 option_conflict('X', 'l');
12486 if (argc != 0 && argc != 1)
12487 usage_histedit();
12488 } else if (allow_conflict && !continue_edit)
12489 errx(1, "-C option requires -c");
12490 else if (argc != 0)
12491 usage_histedit();
12494 * This command cannot apply unveil(2) in all cases because the
12495 * user may choose to run an editor to edit the histedit script
12496 * and to edit individual commit log messages.
12497 * unveil(2) traverses exec(2); if an editor is used we have to
12498 * apply unveil after edit script and log messages have been written.
12499 * XXX TODO: Make use of unveil(2) where possible.
12502 cwd = getcwd(NULL, 0);
12503 if (cwd == NULL) {
12504 error = got_error_from_errno("getcwd");
12505 goto done;
12508 error = got_repo_pack_fds_open(&pack_fds);
12509 if (error != NULL)
12510 goto done;
12512 error = got_worktree_open(&worktree, cwd);
12513 if (error) {
12514 if (list_backups || delete_backups) {
12515 if (error->code != GOT_ERR_NOT_WORKTREE)
12516 goto done;
12517 } else {
12518 if (error->code == GOT_ERR_NOT_WORKTREE)
12519 error = wrap_not_worktree_error(error,
12520 "histedit", cwd);
12521 goto done;
12525 if (list_backups || delete_backups) {
12526 error = got_repo_open(&repo,
12527 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12528 NULL, pack_fds);
12529 if (error != NULL)
12530 goto done;
12531 error = apply_unveil(got_repo_get_path(repo), 0,
12532 worktree ? got_worktree_get_root_path(worktree) : NULL);
12533 if (error)
12534 goto done;
12535 error = process_backup_refs(
12536 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12537 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12538 goto done; /* nothing else to do */
12541 error = get_gitconfig_path(&gitconfig_path);
12542 if (error)
12543 goto done;
12544 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12545 gitconfig_path, pack_fds);
12546 if (error != NULL)
12547 goto done;
12549 if (worktree != NULL && !list_backups && !delete_backups) {
12550 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12551 if (error)
12552 goto done;
12555 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12556 if (error)
12557 goto done;
12558 if (rebase_in_progress) {
12559 error = got_error(GOT_ERR_REBASING);
12560 goto done;
12563 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12564 repo);
12565 if (error)
12566 goto done;
12567 if (merge_in_progress) {
12568 error = got_error(GOT_ERR_MERGE_BUSY);
12569 goto done;
12572 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12573 if (error)
12574 goto done;
12576 if (edit_in_progress && edit_logmsg_only) {
12577 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12578 "histedit operation is in progress in this "
12579 "work tree and must be continued or aborted "
12580 "before the -m option can be used");
12581 goto done;
12583 if (edit_in_progress && drop_only) {
12584 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12585 "histedit operation is in progress in this "
12586 "work tree and must be continued or aborted "
12587 "before the -d option can be used");
12588 goto done;
12590 if (edit_in_progress && fold_only) {
12591 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12592 "histedit operation is in progress in this "
12593 "work tree and must be continued or aborted "
12594 "before the -f option can be used");
12595 goto done;
12597 if (edit_in_progress && edit_only) {
12598 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12599 "histedit operation is in progress in this "
12600 "work tree and must be continued or aborted "
12601 "before the -e option can be used");
12602 goto done;
12605 if (edit_in_progress && abort_edit) {
12606 error = got_worktree_histedit_continue(&resume_commit_id,
12607 &tmp_branch, &branch, &base_commit_id, &fileindex,
12608 worktree, repo);
12609 if (error)
12610 goto done;
12611 printf("Switching work tree to %s\n",
12612 got_ref_get_symref_target(branch));
12613 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12614 branch, base_commit_id, abort_progress, &upa);
12615 if (error)
12616 goto done;
12617 printf("Histedit of %s aborted\n",
12618 got_ref_get_symref_target(branch));
12619 print_merge_progress_stats(&upa);
12620 goto done; /* nothing else to do */
12621 } else if (abort_edit) {
12622 error = got_error(GOT_ERR_NOT_HISTEDIT);
12623 goto done;
12626 error = get_author(&committer, repo, worktree);
12627 if (error)
12628 goto done;
12630 if (continue_edit) {
12631 char *path;
12633 if (!edit_in_progress) {
12634 error = got_error(GOT_ERR_NOT_HISTEDIT);
12635 goto done;
12638 error = got_worktree_get_histedit_script_path(&path, worktree);
12639 if (error)
12640 goto done;
12642 error = histedit_load_list(&histedit_cmds, path, repo);
12643 free(path);
12644 if (error)
12645 goto done;
12647 error = got_worktree_histedit_continue(&resume_commit_id,
12648 &tmp_branch, &branch, &base_commit_id, &fileindex,
12649 worktree, repo);
12650 if (error)
12651 goto done;
12653 error = got_ref_resolve(&head_commit_id, repo, branch);
12654 if (error)
12655 goto done;
12657 error = got_object_open_as_commit(&commit, repo,
12658 head_commit_id);
12659 if (error)
12660 goto done;
12661 parent_ids = got_object_commit_get_parent_ids(commit);
12662 pid = STAILQ_FIRST(parent_ids);
12663 if (pid == NULL) {
12664 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12665 goto done;
12667 error = collect_commits(&commits, head_commit_id, &pid->id,
12668 base_commit_id, got_worktree_get_path_prefix(worktree),
12669 GOT_ERR_HISTEDIT_PATH, repo);
12670 got_object_commit_close(commit);
12671 commit = NULL;
12672 if (error)
12673 goto done;
12674 } else {
12675 if (edit_in_progress) {
12676 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12677 goto done;
12680 error = got_ref_open(&branch, repo,
12681 got_worktree_get_head_ref_name(worktree), 0);
12682 if (error != NULL)
12683 goto done;
12685 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12686 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12687 "will not edit commit history of a branch outside "
12688 "the \"refs/heads/\" reference namespace");
12689 goto done;
12692 error = got_ref_resolve(&head_commit_id, repo, branch);
12693 got_ref_close(branch);
12694 branch = NULL;
12695 if (error)
12696 goto done;
12698 error = got_object_open_as_commit(&commit, repo,
12699 head_commit_id);
12700 if (error)
12701 goto done;
12702 parent_ids = got_object_commit_get_parent_ids(commit);
12703 pid = STAILQ_FIRST(parent_ids);
12704 if (pid == NULL) {
12705 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12706 goto done;
12708 error = collect_commits(&commits, head_commit_id, &pid->id,
12709 got_worktree_get_base_commit_id(worktree),
12710 got_worktree_get_path_prefix(worktree),
12711 GOT_ERR_HISTEDIT_PATH, repo);
12712 got_object_commit_close(commit);
12713 commit = NULL;
12714 if (error)
12715 goto done;
12717 if (STAILQ_EMPTY(&commits)) {
12718 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12719 goto done;
12722 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12723 &base_commit_id, &fileindex, worktree, repo);
12724 if (error)
12725 goto done;
12727 if (edit_script_path) {
12728 error = histedit_load_list(&histedit_cmds,
12729 edit_script_path, repo);
12730 if (error) {
12731 got_worktree_histedit_abort(worktree, fileindex,
12732 repo, branch, base_commit_id,
12733 abort_progress, &upa);
12734 print_merge_progress_stats(&upa);
12735 goto done;
12737 } else {
12738 const char *branch_name;
12739 branch_name = got_ref_get_symref_target(branch);
12740 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12741 branch_name += 11;
12742 error = histedit_edit_script(&histedit_cmds, &commits,
12743 branch_name, edit_logmsg_only, fold_only,
12744 drop_only, edit_only, 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;
12755 error = histedit_save_list(&histedit_cmds, worktree,
12756 repo);
12757 if (error) {
12758 got_worktree_histedit_abort(worktree, fileindex,
12759 repo, branch, base_commit_id,
12760 abort_progress, &upa);
12761 print_merge_progress_stats(&upa);
12762 goto done;
12767 error = histedit_check_script(&histedit_cmds, &commits, repo);
12768 if (error)
12769 goto done;
12771 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12772 if (resume_commit_id) {
12773 if (got_object_id_cmp(hle->commit_id,
12774 resume_commit_id) != 0)
12775 continue;
12777 resume_commit_id = NULL;
12778 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12779 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12780 error = histedit_skip_commit(hle, worktree,
12781 repo);
12782 if (error)
12783 goto done;
12784 } else {
12785 struct got_pathlist_head paths;
12786 int have_changes = 0;
12788 TAILQ_INIT(&paths);
12789 error = got_pathlist_append(&paths, "", NULL);
12790 if (error)
12791 goto done;
12792 error = got_worktree_status(worktree, &paths,
12793 repo, 0, check_local_changes, &have_changes,
12794 check_cancelled, NULL);
12795 got_pathlist_free(&paths,
12796 GOT_PATHLIST_FREE_NONE);
12797 if (error) {
12798 if (error->code != GOT_ERR_CANCELLED)
12799 goto done;
12800 if (sigint_received || sigpipe_received)
12801 goto done;
12803 if (have_changes) {
12804 error = histedit_commit(NULL, worktree,
12805 fileindex, tmp_branch, hle,
12806 committer, allow_conflict, repo);
12807 if (error)
12808 goto done;
12809 } else {
12810 error = got_object_open_as_commit(
12811 &commit, repo, hle->commit_id);
12812 if (error)
12813 goto done;
12814 error = show_histedit_progress(commit,
12815 hle, NULL);
12816 got_object_commit_close(commit);
12817 commit = NULL;
12818 if (error)
12819 goto done;
12822 continue;
12825 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12826 error = histedit_skip_commit(hle, worktree, repo);
12827 if (error)
12828 goto done;
12829 continue;
12832 error = got_object_open_as_commit(&commit, repo,
12833 hle->commit_id);
12834 if (error)
12835 goto done;
12836 parent_ids = got_object_commit_get_parent_ids(commit);
12837 pid = STAILQ_FIRST(parent_ids);
12839 error = got_worktree_histedit_merge_files(&merged_paths,
12840 worktree, fileindex, &pid->id, hle->commit_id, repo,
12841 update_progress, &upa, check_cancelled, NULL);
12842 if (error)
12843 goto done;
12844 got_object_commit_close(commit);
12845 commit = NULL;
12847 print_merge_progress_stats(&upa);
12848 if (upa.conflicts > 0 || upa.missing > 0 ||
12849 upa.not_deleted > 0 || upa.unversioned > 0) {
12850 if (upa.conflicts > 0) {
12851 error = show_rebase_merge_conflict(
12852 hle->commit_id, repo);
12853 if (error)
12854 goto done;
12856 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12857 break;
12860 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12861 char *id_str;
12862 error = got_object_id_str(&id_str, hle->commit_id);
12863 if (error)
12864 goto done;
12865 printf("Stopping histedit for amending commit %s\n",
12866 id_str);
12867 free(id_str);
12868 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12869 error = got_worktree_histedit_postpone(worktree,
12870 fileindex);
12871 goto done;
12874 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12875 error = histedit_skip_commit(hle, worktree, repo);
12876 if (error)
12877 goto done;
12878 continue;
12881 error = histedit_commit(&merged_paths, worktree, fileindex,
12882 tmp_branch, hle, committer, allow_conflict, repo);
12883 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12884 if (error)
12885 goto done;
12888 if (upa.conflicts > 0 || upa.missing > 0 ||
12889 upa.not_deleted > 0 || upa.unversioned > 0) {
12890 error = got_worktree_histedit_postpone(worktree, fileindex);
12891 if (error)
12892 goto done;
12893 if (upa.conflicts > 0 && upa.missing == 0 &&
12894 upa.not_deleted == 0 && upa.unversioned == 0) {
12895 error = got_error_msg(GOT_ERR_CONFLICTS,
12896 "conflicts must be resolved before histedit "
12897 "can continue");
12898 } else if (upa.conflicts > 0) {
12899 error = got_error_msg(GOT_ERR_CONFLICTS,
12900 "conflicts must be resolved before histedit "
12901 "can continue; changes destined for some "
12902 "files were not yet merged and should be "
12903 "merged manually if required before the "
12904 "histedit operation is continued");
12905 } else {
12906 error = got_error_msg(GOT_ERR_CONFLICTS,
12907 "changes destined for some files were not "
12908 "yet merged and should be merged manually "
12909 "if required before the histedit operation "
12910 "is continued");
12912 } else
12913 error = histedit_complete(worktree, fileindex, tmp_branch,
12914 branch, repo);
12915 done:
12916 free(cwd);
12917 free(committer);
12918 free(gitconfig_path);
12919 got_object_id_queue_free(&commits);
12920 histedit_free_list(&histedit_cmds);
12921 free(head_commit_id);
12922 free(base_commit_id);
12923 free(resume_commit_id);
12924 if (commit)
12925 got_object_commit_close(commit);
12926 if (branch)
12927 got_ref_close(branch);
12928 if (tmp_branch)
12929 got_ref_close(tmp_branch);
12930 if (worktree)
12931 got_worktree_close(worktree);
12932 if (repo) {
12933 const struct got_error *close_err = got_repo_close(repo);
12934 if (error == NULL)
12935 error = close_err;
12937 if (pack_fds) {
12938 const struct got_error *pack_err =
12939 got_repo_pack_fds_close(pack_fds);
12940 if (error == NULL)
12941 error = pack_err;
12943 return error;
12946 __dead static void
12947 usage_integrate(void)
12949 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12950 exit(1);
12953 static const struct got_error *
12954 cmd_integrate(int argc, char *argv[])
12956 const struct got_error *error = NULL;
12957 struct got_repository *repo = NULL;
12958 struct got_worktree *worktree = NULL;
12959 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12960 const char *branch_arg = NULL;
12961 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12962 struct got_fileindex *fileindex = NULL;
12963 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12964 int ch;
12965 struct got_update_progress_arg upa;
12966 int *pack_fds = NULL;
12968 #ifndef PROFILE
12969 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12970 "unveil", NULL) == -1)
12971 err(1, "pledge");
12972 #endif
12974 while ((ch = getopt(argc, argv, "")) != -1) {
12975 switch (ch) {
12976 default:
12977 usage_integrate();
12978 /* NOTREACHED */
12982 argc -= optind;
12983 argv += optind;
12985 if (argc != 1)
12986 usage_integrate();
12987 branch_arg = argv[0];
12989 cwd = getcwd(NULL, 0);
12990 if (cwd == NULL) {
12991 error = got_error_from_errno("getcwd");
12992 goto done;
12995 error = got_repo_pack_fds_open(&pack_fds);
12996 if (error != NULL)
12997 goto done;
12999 error = got_worktree_open(&worktree, cwd);
13000 if (error) {
13001 if (error->code == GOT_ERR_NOT_WORKTREE)
13002 error = wrap_not_worktree_error(error, "integrate",
13003 cwd);
13004 goto done;
13007 error = check_rebase_or_histedit_in_progress(worktree);
13008 if (error)
13009 goto done;
13011 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13012 NULL, pack_fds);
13013 if (error != NULL)
13014 goto done;
13016 error = apply_unveil(got_repo_get_path(repo), 0,
13017 got_worktree_get_root_path(worktree));
13018 if (error)
13019 goto done;
13021 error = check_merge_in_progress(worktree, repo);
13022 if (error)
13023 goto done;
13025 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13026 error = got_error_from_errno("asprintf");
13027 goto done;
13030 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13031 &base_branch_ref, worktree, refname, repo);
13032 if (error)
13033 goto done;
13035 refname = strdup(got_ref_get_name(branch_ref));
13036 if (refname == NULL) {
13037 error = got_error_from_errno("strdup");
13038 got_worktree_integrate_abort(worktree, fileindex, repo,
13039 branch_ref, base_branch_ref);
13040 goto done;
13042 base_refname = strdup(got_ref_get_name(base_branch_ref));
13043 if (base_refname == NULL) {
13044 error = got_error_from_errno("strdup");
13045 got_worktree_integrate_abort(worktree, fileindex, repo,
13046 branch_ref, base_branch_ref);
13047 goto done;
13049 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13050 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13051 got_worktree_integrate_abort(worktree, fileindex, repo,
13052 branch_ref, base_branch_ref);
13053 goto done;
13056 error = got_ref_resolve(&commit_id, repo, branch_ref);
13057 if (error)
13058 goto done;
13060 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13061 if (error)
13062 goto done;
13064 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13065 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13066 "specified branch has already been integrated");
13067 got_worktree_integrate_abort(worktree, fileindex, repo,
13068 branch_ref, base_branch_ref);
13069 goto done;
13072 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13073 if (error) {
13074 if (error->code == GOT_ERR_ANCESTRY)
13075 error = got_error(GOT_ERR_REBASE_REQUIRED);
13076 got_worktree_integrate_abort(worktree, fileindex, repo,
13077 branch_ref, base_branch_ref);
13078 goto done;
13081 memset(&upa, 0, sizeof(upa));
13082 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13083 branch_ref, base_branch_ref, update_progress, &upa,
13084 check_cancelled, NULL);
13085 if (error)
13086 goto done;
13088 printf("Integrated %s into %s\n", refname, base_refname);
13089 print_update_progress_stats(&upa);
13090 done:
13091 if (repo) {
13092 const struct got_error *close_err = got_repo_close(repo);
13093 if (error == NULL)
13094 error = close_err;
13096 if (worktree)
13097 got_worktree_close(worktree);
13098 if (pack_fds) {
13099 const struct got_error *pack_err =
13100 got_repo_pack_fds_close(pack_fds);
13101 if (error == NULL)
13102 error = pack_err;
13104 free(cwd);
13105 free(base_commit_id);
13106 free(commit_id);
13107 free(refname);
13108 free(base_refname);
13109 return error;
13112 __dead static void
13113 usage_merge(void)
13115 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13116 exit(1);
13119 static const struct got_error *
13120 cmd_merge(int argc, char *argv[])
13122 const struct got_error *error = NULL;
13123 struct got_worktree *worktree = NULL;
13124 struct got_repository *repo = NULL;
13125 struct got_fileindex *fileindex = NULL;
13126 char *cwd = NULL, *id_str = NULL, *author = NULL;
13127 char *gitconfig_path = NULL;
13128 struct got_reference *branch = NULL, *wt_branch = NULL;
13129 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13130 struct got_object_id *wt_branch_tip = NULL;
13131 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13132 int allow_conflict = 0, interrupt_merge = 0;
13133 struct got_update_progress_arg upa;
13134 struct got_object_id *merge_commit_id = NULL;
13135 char *branch_name = NULL;
13136 int *pack_fds = NULL;
13138 memset(&upa, 0, sizeof(upa));
13140 #ifndef PROFILE
13141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13142 "unveil", NULL) == -1)
13143 err(1, "pledge");
13144 #endif
13146 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13147 switch (ch) {
13148 case 'a':
13149 abort_merge = 1;
13150 break;
13151 case 'C':
13152 allow_conflict = 1;
13153 case 'c':
13154 continue_merge = 1;
13155 break;
13156 case 'n':
13157 interrupt_merge = 1;
13158 break;
13159 default:
13160 usage_merge();
13161 /* NOTREACHED */
13165 argc -= optind;
13166 argv += optind;
13168 if (allow_conflict) {
13169 if (abort_merge)
13170 option_conflict('a', 'C');
13171 if (!continue_merge)
13172 errx(1, "-C option requires -c");
13174 if (abort_merge && continue_merge)
13175 option_conflict('a', 'c');
13176 if (abort_merge || continue_merge) {
13177 if (argc != 0)
13178 usage_merge();
13179 } else if (argc != 1)
13180 usage_merge();
13182 cwd = getcwd(NULL, 0);
13183 if (cwd == NULL) {
13184 error = got_error_from_errno("getcwd");
13185 goto done;
13188 error = got_repo_pack_fds_open(&pack_fds);
13189 if (error != NULL)
13190 goto done;
13192 error = got_worktree_open(&worktree, cwd);
13193 if (error) {
13194 if (error->code == GOT_ERR_NOT_WORKTREE)
13195 error = wrap_not_worktree_error(error,
13196 "merge", cwd);
13197 goto done;
13200 error = get_gitconfig_path(&gitconfig_path);
13201 if (error)
13202 goto done;
13203 error = got_repo_open(&repo,
13204 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13205 gitconfig_path, pack_fds);
13206 if (error != NULL)
13207 goto done;
13209 if (worktree != NULL) {
13210 error = worktree_has_logmsg_ref("merge", worktree, repo);
13211 if (error)
13212 goto done;
13215 error = apply_unveil(got_repo_get_path(repo), 0,
13216 worktree ? got_worktree_get_root_path(worktree) : NULL);
13217 if (error)
13218 goto done;
13220 error = check_rebase_or_histedit_in_progress(worktree);
13221 if (error)
13222 goto done;
13224 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13225 repo);
13226 if (error)
13227 goto done;
13229 if (abort_merge) {
13230 if (!merge_in_progress) {
13231 error = got_error(GOT_ERR_NOT_MERGING);
13232 goto done;
13234 error = got_worktree_merge_continue(&branch_name,
13235 &branch_tip, &fileindex, worktree, repo);
13236 if (error)
13237 goto done;
13238 error = got_worktree_merge_abort(worktree, fileindex, repo,
13239 abort_progress, &upa);
13240 if (error)
13241 goto done;
13242 printf("Merge of %s aborted\n", branch_name);
13243 goto done; /* nothing else to do */
13246 error = get_author(&author, repo, worktree);
13247 if (error)
13248 goto done;
13250 if (continue_merge) {
13251 if (!merge_in_progress) {
13252 error = got_error(GOT_ERR_NOT_MERGING);
13253 goto done;
13255 error = got_worktree_merge_continue(&branch_name,
13256 &branch_tip, &fileindex, worktree, repo);
13257 if (error)
13258 goto done;
13259 } else {
13260 error = got_ref_open(&branch, repo, argv[0], 0);
13261 if (error != NULL)
13262 goto done;
13263 branch_name = strdup(got_ref_get_name(branch));
13264 if (branch_name == NULL) {
13265 error = got_error_from_errno("strdup");
13266 goto done;
13268 error = got_ref_resolve(&branch_tip, repo, branch);
13269 if (error)
13270 goto done;
13273 error = got_ref_open(&wt_branch, repo,
13274 got_worktree_get_head_ref_name(worktree), 0);
13275 if (error)
13276 goto done;
13277 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13278 if (error)
13279 goto done;
13280 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13281 wt_branch_tip, branch_tip, 0, repo,
13282 check_cancelled, NULL);
13283 if (error && error->code != GOT_ERR_ANCESTRY)
13284 goto done;
13286 if (!continue_merge) {
13287 error = check_path_prefix(wt_branch_tip, branch_tip,
13288 got_worktree_get_path_prefix(worktree),
13289 GOT_ERR_MERGE_PATH, repo);
13290 if (error)
13291 goto done;
13292 if (yca_id) {
13293 error = check_same_branch(wt_branch_tip, branch,
13294 yca_id, repo);
13295 if (error) {
13296 if (error->code != GOT_ERR_ANCESTRY)
13297 goto done;
13298 error = NULL;
13299 } else {
13300 static char msg[512];
13301 snprintf(msg, sizeof(msg),
13302 "cannot create a merge commit because "
13303 "%s is based on %s; %s can be integrated "
13304 "with 'got integrate' instead", branch_name,
13305 got_worktree_get_head_ref_name(worktree),
13306 branch_name);
13307 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13308 goto done;
13311 error = got_worktree_merge_prepare(&fileindex, worktree,
13312 branch, repo);
13313 if (error)
13314 goto done;
13316 error = got_worktree_merge_branch(worktree, fileindex,
13317 yca_id, branch_tip, repo, update_progress, &upa,
13318 check_cancelled, NULL);
13319 if (error)
13320 goto done;
13321 print_merge_progress_stats(&upa);
13322 if (!upa.did_something) {
13323 error = got_worktree_merge_abort(worktree, fileindex,
13324 repo, abort_progress, &upa);
13325 if (error)
13326 goto done;
13327 printf("Already up-to-date\n");
13328 goto done;
13332 if (interrupt_merge) {
13333 error = got_worktree_merge_postpone(worktree, fileindex);
13334 if (error)
13335 goto done;
13336 printf("Merge of %s interrupted on request\n", branch_name);
13337 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13338 upa.not_deleted > 0 || upa.unversioned > 0) {
13339 error = got_worktree_merge_postpone(worktree, fileindex);
13340 if (error)
13341 goto done;
13342 if (upa.conflicts > 0 && upa.missing == 0 &&
13343 upa.not_deleted == 0 && upa.unversioned == 0) {
13344 error = got_error_msg(GOT_ERR_CONFLICTS,
13345 "conflicts must be resolved before merging "
13346 "can continue");
13347 } else if (upa.conflicts > 0) {
13348 error = got_error_msg(GOT_ERR_CONFLICTS,
13349 "conflicts must be resolved before merging "
13350 "can continue; changes destined for some "
13351 "files were not yet merged and "
13352 "should be merged manually if required before the "
13353 "merge operation is continued");
13354 } else {
13355 error = got_error_msg(GOT_ERR_CONFLICTS,
13356 "changes destined for some "
13357 "files were not yet merged and should be "
13358 "merged manually if required before the "
13359 "merge operation is continued");
13361 goto done;
13362 } else {
13363 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13364 fileindex, author, NULL, 1, branch_tip, branch_name,
13365 allow_conflict, repo, continue_merge ? print_status : NULL,
13366 NULL);
13367 if (error)
13368 goto done;
13369 error = got_worktree_merge_complete(worktree, fileindex, repo);
13370 if (error)
13371 goto done;
13372 error = got_object_id_str(&id_str, merge_commit_id);
13373 if (error)
13374 goto done;
13375 printf("Merged %s into %s: %s\n", branch_name,
13376 got_worktree_get_head_ref_name(worktree),
13377 id_str);
13380 done:
13381 free(gitconfig_path);
13382 free(id_str);
13383 free(merge_commit_id);
13384 free(author);
13385 free(branch_tip);
13386 free(branch_name);
13387 free(yca_id);
13388 if (branch)
13389 got_ref_close(branch);
13390 if (wt_branch)
13391 got_ref_close(wt_branch);
13392 if (worktree)
13393 got_worktree_close(worktree);
13394 if (repo) {
13395 const struct got_error *close_err = got_repo_close(repo);
13396 if (error == NULL)
13397 error = close_err;
13399 if (pack_fds) {
13400 const struct got_error *pack_err =
13401 got_repo_pack_fds_close(pack_fds);
13402 if (error == NULL)
13403 error = pack_err;
13405 return error;
13408 __dead static void
13409 usage_stage(void)
13411 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13412 "[path ...]\n", getprogname());
13413 exit(1);
13416 static const struct got_error *
13417 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13418 const char *path, struct got_object_id *blob_id,
13419 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13420 int dirfd, const char *de_name)
13422 const struct got_error *err = NULL;
13423 char *id_str = NULL;
13425 if (staged_status != GOT_STATUS_ADD &&
13426 staged_status != GOT_STATUS_MODIFY &&
13427 staged_status != GOT_STATUS_DELETE)
13428 return NULL;
13430 if (staged_status == GOT_STATUS_ADD ||
13431 staged_status == GOT_STATUS_MODIFY)
13432 err = got_object_id_str(&id_str, staged_blob_id);
13433 else
13434 err = got_object_id_str(&id_str, blob_id);
13435 if (err)
13436 return err;
13438 printf("%s %c %s\n", id_str, staged_status, path);
13439 free(id_str);
13440 return NULL;
13443 static const struct got_error *
13444 cmd_stage(int argc, char *argv[])
13446 const struct got_error *error = NULL;
13447 struct got_repository *repo = NULL;
13448 struct got_worktree *worktree = NULL;
13449 char *cwd = NULL;
13450 struct got_pathlist_head paths;
13451 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13452 FILE *patch_script_file = NULL;
13453 const char *patch_script_path = NULL;
13454 struct choose_patch_arg cpa;
13455 int *pack_fds = NULL;
13457 TAILQ_INIT(&paths);
13459 #ifndef PROFILE
13460 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13461 "unveil", NULL) == -1)
13462 err(1, "pledge");
13463 #endif
13465 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13466 switch (ch) {
13467 case 'F':
13468 patch_script_path = optarg;
13469 break;
13470 case 'l':
13471 list_stage = 1;
13472 break;
13473 case 'p':
13474 pflag = 1;
13475 break;
13476 case 'S':
13477 allow_bad_symlinks = 1;
13478 break;
13479 default:
13480 usage_stage();
13481 /* NOTREACHED */
13485 argc -= optind;
13486 argv += optind;
13488 if (list_stage && (pflag || patch_script_path))
13489 errx(1, "-l option cannot be used with other options");
13490 if (patch_script_path && !pflag)
13491 errx(1, "-F option can only be used together with -p option");
13493 cwd = getcwd(NULL, 0);
13494 if (cwd == NULL) {
13495 error = got_error_from_errno("getcwd");
13496 goto done;
13499 error = got_repo_pack_fds_open(&pack_fds);
13500 if (error != NULL)
13501 goto done;
13503 error = got_worktree_open(&worktree, cwd);
13504 if (error) {
13505 if (error->code == GOT_ERR_NOT_WORKTREE)
13506 error = wrap_not_worktree_error(error, "stage", cwd);
13507 goto done;
13510 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13511 NULL, pack_fds);
13512 if (error != NULL)
13513 goto done;
13515 if (patch_script_path) {
13516 patch_script_file = fopen(patch_script_path, "re");
13517 if (patch_script_file == NULL) {
13518 error = got_error_from_errno2("fopen",
13519 patch_script_path);
13520 goto done;
13523 error = apply_unveil(got_repo_get_path(repo), 0,
13524 got_worktree_get_root_path(worktree));
13525 if (error)
13526 goto done;
13528 error = check_merge_in_progress(worktree, repo);
13529 if (error)
13530 goto done;
13532 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13533 if (error)
13534 goto done;
13536 if (list_stage)
13537 error = got_worktree_status(worktree, &paths, repo, 0,
13538 print_stage, NULL, check_cancelled, NULL);
13539 else {
13540 cpa.patch_script_file = patch_script_file;
13541 cpa.action = "stage";
13542 error = got_worktree_stage(worktree, &paths,
13543 pflag ? NULL : print_status, NULL,
13544 pflag ? choose_patch : NULL, &cpa,
13545 allow_bad_symlinks, repo);
13547 done:
13548 if (patch_script_file && fclose(patch_script_file) == EOF &&
13549 error == NULL)
13550 error = got_error_from_errno2("fclose", patch_script_path);
13551 if (repo) {
13552 const struct got_error *close_err = got_repo_close(repo);
13553 if (error == NULL)
13554 error = close_err;
13556 if (worktree)
13557 got_worktree_close(worktree);
13558 if (pack_fds) {
13559 const struct got_error *pack_err =
13560 got_repo_pack_fds_close(pack_fds);
13561 if (error == NULL)
13562 error = pack_err;
13564 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13565 free(cwd);
13566 return error;
13569 __dead static void
13570 usage_unstage(void)
13572 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13573 "[path ...]\n", getprogname());
13574 exit(1);
13578 static const struct got_error *
13579 cmd_unstage(int argc, char *argv[])
13581 const struct got_error *error = NULL;
13582 struct got_repository *repo = NULL;
13583 struct got_worktree *worktree = NULL;
13584 char *cwd = NULL;
13585 struct got_pathlist_head paths;
13586 int ch, pflag = 0;
13587 struct got_update_progress_arg upa;
13588 FILE *patch_script_file = NULL;
13589 const char *patch_script_path = NULL;
13590 struct choose_patch_arg cpa;
13591 int *pack_fds = NULL;
13593 TAILQ_INIT(&paths);
13595 #ifndef PROFILE
13596 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13597 "unveil", NULL) == -1)
13598 err(1, "pledge");
13599 #endif
13601 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13602 switch (ch) {
13603 case 'F':
13604 patch_script_path = optarg;
13605 break;
13606 case 'p':
13607 pflag = 1;
13608 break;
13609 default:
13610 usage_unstage();
13611 /* NOTREACHED */
13615 argc -= optind;
13616 argv += optind;
13618 if (patch_script_path && !pflag)
13619 errx(1, "-F option can only be used together with -p option");
13621 cwd = getcwd(NULL, 0);
13622 if (cwd == NULL) {
13623 error = got_error_from_errno("getcwd");
13624 goto done;
13627 error = got_repo_pack_fds_open(&pack_fds);
13628 if (error != NULL)
13629 goto done;
13631 error = got_worktree_open(&worktree, cwd);
13632 if (error) {
13633 if (error->code == GOT_ERR_NOT_WORKTREE)
13634 error = wrap_not_worktree_error(error, "unstage", cwd);
13635 goto done;
13638 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13639 NULL, pack_fds);
13640 if (error != NULL)
13641 goto done;
13643 if (patch_script_path) {
13644 patch_script_file = fopen(patch_script_path, "re");
13645 if (patch_script_file == NULL) {
13646 error = got_error_from_errno2("fopen",
13647 patch_script_path);
13648 goto done;
13652 error = apply_unveil(got_repo_get_path(repo), 0,
13653 got_worktree_get_root_path(worktree));
13654 if (error)
13655 goto done;
13657 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13658 if (error)
13659 goto done;
13661 cpa.patch_script_file = patch_script_file;
13662 cpa.action = "unstage";
13663 memset(&upa, 0, sizeof(upa));
13664 error = got_worktree_unstage(worktree, &paths, update_progress,
13665 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13666 if (!error)
13667 print_merge_progress_stats(&upa);
13668 done:
13669 if (patch_script_file && fclose(patch_script_file) == EOF &&
13670 error == NULL)
13671 error = got_error_from_errno2("fclose", patch_script_path);
13672 if (repo) {
13673 const struct got_error *close_err = got_repo_close(repo);
13674 if (error == NULL)
13675 error = close_err;
13677 if (worktree)
13678 got_worktree_close(worktree);
13679 if (pack_fds) {
13680 const struct got_error *pack_err =
13681 got_repo_pack_fds_close(pack_fds);
13682 if (error == NULL)
13683 error = pack_err;
13685 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13686 free(cwd);
13687 return error;
13690 __dead static void
13691 usage_cat(void)
13693 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13694 "arg ...\n", getprogname());
13695 exit(1);
13698 static const struct got_error *
13699 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13701 const struct got_error *err;
13702 struct got_blob_object *blob;
13703 int fd = -1;
13705 fd = got_opentempfd();
13706 if (fd == -1)
13707 return got_error_from_errno("got_opentempfd");
13709 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13710 if (err)
13711 goto done;
13713 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13714 done:
13715 if (fd != -1 && close(fd) == -1 && err == NULL)
13716 err = got_error_from_errno("close");
13717 if (blob)
13718 got_object_blob_close(blob);
13719 return err;
13722 static const struct got_error *
13723 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13725 const struct got_error *err;
13726 struct got_tree_object *tree;
13727 int nentries, i;
13729 err = got_object_open_as_tree(&tree, repo, id);
13730 if (err)
13731 return err;
13733 nentries = got_object_tree_get_nentries(tree);
13734 for (i = 0; i < nentries; i++) {
13735 struct got_tree_entry *te;
13736 char *id_str;
13737 if (sigint_received || sigpipe_received)
13738 break;
13739 te = got_object_tree_get_entry(tree, i);
13740 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13741 if (err)
13742 break;
13743 fprintf(outfile, "%s %.7o %s\n", id_str,
13744 got_tree_entry_get_mode(te),
13745 got_tree_entry_get_name(te));
13746 free(id_str);
13749 got_object_tree_close(tree);
13750 return err;
13753 static const struct got_error *
13754 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13756 const struct got_error *err;
13757 struct got_commit_object *commit;
13758 const struct got_object_id_queue *parent_ids;
13759 struct got_object_qid *pid;
13760 char *id_str = NULL;
13761 const char *logmsg = NULL;
13762 char gmtoff[6];
13764 err = got_object_open_as_commit(&commit, repo, id);
13765 if (err)
13766 return err;
13768 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13769 if (err)
13770 goto done;
13772 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13773 parent_ids = got_object_commit_get_parent_ids(commit);
13774 fprintf(outfile, "numparents %d\n",
13775 got_object_commit_get_nparents(commit));
13776 STAILQ_FOREACH(pid, parent_ids, entry) {
13777 char *pid_str;
13778 err = got_object_id_str(&pid_str, &pid->id);
13779 if (err)
13780 goto done;
13781 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13782 free(pid_str);
13784 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13785 got_object_commit_get_author_gmtoff(commit));
13786 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13787 got_object_commit_get_author(commit),
13788 (long long)got_object_commit_get_author_time(commit),
13789 gmtoff);
13791 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13792 got_object_commit_get_committer_gmtoff(commit));
13793 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13794 got_object_commit_get_committer(commit),
13795 (long long)got_object_commit_get_committer_time(commit),
13796 gmtoff);
13798 logmsg = got_object_commit_get_logmsg_raw(commit);
13799 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13800 fprintf(outfile, "%s", logmsg);
13801 done:
13802 free(id_str);
13803 got_object_commit_close(commit);
13804 return err;
13807 static const struct got_error *
13808 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13810 const struct got_error *err;
13811 struct got_tag_object *tag;
13812 char *id_str = NULL;
13813 const char *tagmsg = NULL;
13814 char gmtoff[6];
13816 err = got_object_open_as_tag(&tag, repo, id);
13817 if (err)
13818 return err;
13820 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13821 if (err)
13822 goto done;
13824 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13826 switch (got_object_tag_get_object_type(tag)) {
13827 case GOT_OBJ_TYPE_BLOB:
13828 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13829 GOT_OBJ_LABEL_BLOB);
13830 break;
13831 case GOT_OBJ_TYPE_TREE:
13832 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13833 GOT_OBJ_LABEL_TREE);
13834 break;
13835 case GOT_OBJ_TYPE_COMMIT:
13836 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13837 GOT_OBJ_LABEL_COMMIT);
13838 break;
13839 case GOT_OBJ_TYPE_TAG:
13840 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13841 GOT_OBJ_LABEL_TAG);
13842 break;
13843 default:
13844 break;
13847 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13848 got_object_tag_get_name(tag));
13850 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13851 got_object_tag_get_tagger_gmtoff(tag));
13852 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13853 got_object_tag_get_tagger(tag),
13854 (long long)got_object_tag_get_tagger_time(tag),
13855 gmtoff);
13857 tagmsg = got_object_tag_get_message(tag);
13858 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13859 fprintf(outfile, "%s", tagmsg);
13860 done:
13861 free(id_str);
13862 got_object_tag_close(tag);
13863 return err;
13866 static const struct got_error *
13867 cmd_cat(int argc, char *argv[])
13869 const struct got_error *error;
13870 struct got_repository *repo = NULL;
13871 struct got_worktree *worktree = NULL;
13872 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13873 const char *commit_id_str = NULL;
13874 struct got_object_id *id = NULL, *commit_id = NULL;
13875 struct got_commit_object *commit = NULL;
13876 int ch, obj_type, i, force_path = 0;
13877 struct got_reflist_head refs;
13878 int *pack_fds = NULL;
13880 TAILQ_INIT(&refs);
13882 #ifndef PROFILE
13883 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13884 NULL) == -1)
13885 err(1, "pledge");
13886 #endif
13888 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13889 switch (ch) {
13890 case 'c':
13891 commit_id_str = optarg;
13892 break;
13893 case 'P':
13894 force_path = 1;
13895 break;
13896 case 'r':
13897 repo_path = realpath(optarg, NULL);
13898 if (repo_path == NULL)
13899 return got_error_from_errno2("realpath",
13900 optarg);
13901 got_path_strip_trailing_slashes(repo_path);
13902 break;
13903 default:
13904 usage_cat();
13905 /* NOTREACHED */
13909 argc -= optind;
13910 argv += optind;
13912 cwd = getcwd(NULL, 0);
13913 if (cwd == NULL) {
13914 error = got_error_from_errno("getcwd");
13915 goto done;
13918 error = got_repo_pack_fds_open(&pack_fds);
13919 if (error != NULL)
13920 goto done;
13922 if (repo_path == NULL) {
13923 error = got_worktree_open(&worktree, cwd);
13924 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13925 goto done;
13926 if (worktree) {
13927 repo_path = strdup(
13928 got_worktree_get_repo_path(worktree));
13929 if (repo_path == NULL) {
13930 error = got_error_from_errno("strdup");
13931 goto done;
13934 /* Release work tree lock. */
13935 got_worktree_close(worktree);
13936 worktree = NULL;
13940 if (repo_path == NULL) {
13941 repo_path = strdup(cwd);
13942 if (repo_path == NULL)
13943 return got_error_from_errno("strdup");
13946 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13947 free(repo_path);
13948 if (error != NULL)
13949 goto done;
13951 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13952 if (error)
13953 goto done;
13955 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13956 if (error)
13957 goto done;
13959 if (commit_id_str == NULL)
13960 commit_id_str = GOT_REF_HEAD;
13961 error = got_repo_match_object_id(&commit_id, NULL,
13962 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13963 if (error)
13964 goto done;
13966 error = got_object_open_as_commit(&commit, repo, commit_id);
13967 if (error)
13968 goto done;
13970 for (i = 0; i < argc; i++) {
13971 if (force_path) {
13972 error = got_object_id_by_path(&id, repo, commit,
13973 argv[i]);
13974 if (error)
13975 break;
13976 } else {
13977 error = got_repo_match_object_id(&id, &label, argv[i],
13978 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13979 repo);
13980 if (error) {
13981 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13982 error->code != GOT_ERR_NOT_REF)
13983 break;
13984 error = got_object_id_by_path(&id, repo,
13985 commit, argv[i]);
13986 if (error)
13987 break;
13991 error = got_object_get_type(&obj_type, repo, id);
13992 if (error)
13993 break;
13995 switch (obj_type) {
13996 case GOT_OBJ_TYPE_BLOB:
13997 error = cat_blob(id, repo, stdout);
13998 break;
13999 case GOT_OBJ_TYPE_TREE:
14000 error = cat_tree(id, repo, stdout);
14001 break;
14002 case GOT_OBJ_TYPE_COMMIT:
14003 error = cat_commit(id, repo, stdout);
14004 break;
14005 case GOT_OBJ_TYPE_TAG:
14006 error = cat_tag(id, repo, stdout);
14007 break;
14008 default:
14009 error = got_error(GOT_ERR_OBJ_TYPE);
14010 break;
14012 if (error)
14013 break;
14014 free(label);
14015 label = NULL;
14016 free(id);
14017 id = NULL;
14019 done:
14020 free(label);
14021 free(id);
14022 free(commit_id);
14023 if (commit)
14024 got_object_commit_close(commit);
14025 if (worktree)
14026 got_worktree_close(worktree);
14027 if (repo) {
14028 const struct got_error *close_err = got_repo_close(repo);
14029 if (error == NULL)
14030 error = close_err;
14032 if (pack_fds) {
14033 const struct got_error *pack_err =
14034 got_repo_pack_fds_close(pack_fds);
14035 if (error == NULL)
14036 error = pack_err;
14039 got_ref_list_free(&refs);
14040 return error;
14043 __dead static void
14044 usage_info(void)
14046 fprintf(stderr, "usage: %s info [path ...]\n",
14047 getprogname());
14048 exit(1);
14051 static const struct got_error *
14052 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14053 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14054 struct got_object_id *commit_id)
14056 const struct got_error *err = NULL;
14057 char *id_str = NULL;
14058 char datebuf[128];
14059 struct tm mytm, *tm;
14060 struct got_pathlist_head *paths = arg;
14061 struct got_pathlist_entry *pe;
14064 * Clear error indication from any of the path arguments which
14065 * would cause this file index entry to be displayed.
14067 TAILQ_FOREACH(pe, paths, entry) {
14068 if (got_path_cmp(path, pe->path, strlen(path),
14069 pe->path_len) == 0 ||
14070 got_path_is_child(path, pe->path, pe->path_len))
14071 pe->data = NULL; /* no error */
14074 printf(GOT_COMMIT_SEP_STR);
14075 if (S_ISLNK(mode))
14076 printf("symlink: %s\n", path);
14077 else if (S_ISREG(mode)) {
14078 printf("file: %s\n", path);
14079 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14080 } else if (S_ISDIR(mode))
14081 printf("directory: %s\n", path);
14082 else
14083 printf("something: %s\n", path);
14085 tm = localtime_r(&mtime, &mytm);
14086 if (tm == NULL)
14087 return NULL;
14088 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14089 return got_error(GOT_ERR_NO_SPACE);
14090 printf("timestamp: %s\n", datebuf);
14092 if (blob_id) {
14093 err = got_object_id_str(&id_str, blob_id);
14094 if (err)
14095 return err;
14096 printf("based on blob: %s\n", id_str);
14097 free(id_str);
14100 if (staged_blob_id) {
14101 err = got_object_id_str(&id_str, staged_blob_id);
14102 if (err)
14103 return err;
14104 printf("based on staged blob: %s\n", id_str);
14105 free(id_str);
14108 if (commit_id) {
14109 err = got_object_id_str(&id_str, commit_id);
14110 if (err)
14111 return err;
14112 printf("based on commit: %s\n", id_str);
14113 free(id_str);
14116 return NULL;
14119 static const struct got_error *
14120 cmd_info(int argc, char *argv[])
14122 const struct got_error *error = NULL;
14123 struct got_worktree *worktree = NULL;
14124 char *cwd = NULL, *id_str = NULL;
14125 struct got_pathlist_head paths;
14126 char *uuidstr = NULL;
14127 int ch, show_files = 0;
14129 TAILQ_INIT(&paths);
14131 #ifndef PROFILE
14132 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14133 NULL) == -1)
14134 err(1, "pledge");
14135 #endif
14137 while ((ch = getopt(argc, argv, "")) != -1) {
14138 switch (ch) {
14139 default:
14140 usage_info();
14141 /* NOTREACHED */
14145 argc -= optind;
14146 argv += optind;
14148 cwd = getcwd(NULL, 0);
14149 if (cwd == NULL) {
14150 error = got_error_from_errno("getcwd");
14151 goto done;
14154 error = got_worktree_open(&worktree, cwd);
14155 if (error) {
14156 if (error->code == GOT_ERR_NOT_WORKTREE)
14157 error = wrap_not_worktree_error(error, "info", cwd);
14158 goto done;
14161 #ifndef PROFILE
14162 /* Remove "wpath cpath proc exec sendfd" promises. */
14163 if (pledge("stdio rpath flock unveil", NULL) == -1)
14164 err(1, "pledge");
14165 #endif
14166 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14167 if (error)
14168 goto done;
14170 if (argc >= 1) {
14171 error = get_worktree_paths_from_argv(&paths, argc, argv,
14172 worktree);
14173 if (error)
14174 goto done;
14175 show_files = 1;
14178 error = got_object_id_str(&id_str,
14179 got_worktree_get_base_commit_id(worktree));
14180 if (error)
14181 goto done;
14183 error = got_worktree_get_uuid(&uuidstr, worktree);
14184 if (error)
14185 goto done;
14187 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14188 printf("work tree base commit: %s\n", id_str);
14189 printf("work tree path prefix: %s\n",
14190 got_worktree_get_path_prefix(worktree));
14191 printf("work tree branch reference: %s\n",
14192 got_worktree_get_head_ref_name(worktree));
14193 printf("work tree UUID: %s\n", uuidstr);
14194 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14196 if (show_files) {
14197 struct got_pathlist_entry *pe;
14198 TAILQ_FOREACH(pe, &paths, entry) {
14199 if (pe->path_len == 0)
14200 continue;
14202 * Assume this path will fail. This will be corrected
14203 * in print_path_info() in case the path does suceeed.
14205 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14207 error = got_worktree_path_info(worktree, &paths,
14208 print_path_info, &paths, check_cancelled, NULL);
14209 if (error)
14210 goto done;
14211 TAILQ_FOREACH(pe, &paths, entry) {
14212 if (pe->data != NULL) {
14213 const struct got_error *perr;
14215 perr = pe->data;
14216 error = got_error_fmt(perr->code, "%s",
14217 pe->path);
14218 break;
14222 done:
14223 if (worktree)
14224 got_worktree_close(worktree);
14225 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14226 free(cwd);
14227 free(id_str);
14228 free(uuidstr);
14229 return error;