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 struct got_patch_progress_arg {
8169 int did_something;
8170 int conflicts;
8171 int rejects;
8174 static const struct got_error *
8175 patch_progress(void *arg, const char *old, const char *new,
8176 unsigned char status, const struct got_error *error, int old_from,
8177 int old_lines, int new_from, int new_lines, int offset,
8178 int ws_mangled, const struct got_error *hunk_err)
8180 const char *path = new == NULL ? old : new;
8181 struct got_patch_progress_arg *a = arg;
8183 while (*path == '/')
8184 path++;
8186 if (status != GOT_STATUS_NO_CHANGE &&
8187 status != 0 /* per-hunk progress */) {
8188 printf("%c %s\n", status, path);
8189 a->did_something = 1;
8192 if (hunk_err == NULL) {
8193 if (status == GOT_STATUS_CANNOT_UPDATE)
8194 a->rejects++;
8195 else if (status == GOT_STATUS_CONFLICT)
8196 a->conflicts++;
8199 if (error != NULL)
8200 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8202 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8203 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8204 old_lines, new_from, new_lines);
8205 if (hunk_err != NULL)
8206 printf("%s\n", hunk_err->msg);
8207 else if (offset != 0)
8208 printf("applied with offset %d\n", offset);
8209 else
8210 printf("hunk contains mangled whitespace\n");
8213 return NULL;
8216 static void
8217 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8219 if (!ppa->did_something)
8220 return;
8222 if (ppa->conflicts > 0)
8223 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8225 if (ppa->rejects > 0) {
8226 printf("Files where patch failed to apply: %d\n",
8227 ppa->rejects);
8231 static const struct got_error *
8232 cmd_patch(int argc, char *argv[])
8234 const struct got_error *error = NULL, *close_error = NULL;
8235 struct got_worktree *worktree = NULL;
8236 struct got_repository *repo = NULL;
8237 struct got_reflist_head refs;
8238 struct got_object_id *commit_id = NULL;
8239 const char *commit_id_str = NULL;
8240 struct stat sb;
8241 const char *errstr;
8242 char *cwd = NULL;
8243 int ch, nop = 0, strip = -1, reverse = 0;
8244 int patchfd;
8245 int *pack_fds = NULL;
8246 struct got_patch_progress_arg ppa;
8248 TAILQ_INIT(&refs);
8250 #ifndef PROFILE
8251 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8252 "unveil", NULL) == -1)
8253 err(1, "pledge");
8254 #endif
8256 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8257 switch (ch) {
8258 case 'c':
8259 commit_id_str = optarg;
8260 break;
8261 case 'n':
8262 nop = 1;
8263 break;
8264 case 'p':
8265 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8266 if (errstr != NULL)
8267 errx(1, "pathname strip count is %s: %s",
8268 errstr, optarg);
8269 break;
8270 case 'R':
8271 reverse = 1;
8272 break;
8273 default:
8274 usage_patch();
8275 /* NOTREACHED */
8279 argc -= optind;
8280 argv += optind;
8282 if (argc == 0) {
8283 error = patch_from_stdin(&patchfd);
8284 if (error)
8285 return error;
8286 } else if (argc == 1) {
8287 patchfd = open(argv[0], O_RDONLY);
8288 if (patchfd == -1) {
8289 error = got_error_from_errno2("open", argv[0]);
8290 return error;
8292 if (fstat(patchfd, &sb) == -1) {
8293 error = got_error_from_errno2("fstat", argv[0]);
8294 goto done;
8296 if (!S_ISREG(sb.st_mode)) {
8297 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8298 goto done;
8300 } else
8301 usage_patch();
8303 if ((cwd = getcwd(NULL, 0)) == NULL) {
8304 error = got_error_from_errno("getcwd");
8305 goto done;
8308 error = got_repo_pack_fds_open(&pack_fds);
8309 if (error != NULL)
8310 goto done;
8312 error = got_worktree_open(&worktree, cwd);
8313 if (error != NULL)
8314 goto done;
8316 const char *repo_path = got_worktree_get_repo_path(worktree);
8317 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8318 if (error != NULL)
8319 goto done;
8321 error = apply_unveil(got_repo_get_path(repo), 0,
8322 got_worktree_get_root_path(worktree));
8323 if (error != NULL)
8324 goto done;
8326 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8327 if (error)
8328 goto done;
8330 if (commit_id_str != NULL) {
8331 error = got_repo_match_object_id(&commit_id, NULL,
8332 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8333 if (error)
8334 goto done;
8337 memset(&ppa, 0, sizeof(ppa));
8338 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8339 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8340 print_patch_progress_stats(&ppa);
8341 done:
8342 got_ref_list_free(&refs);
8343 free(commit_id);
8344 if (repo) {
8345 close_error = got_repo_close(repo);
8346 if (error == NULL)
8347 error = close_error;
8349 if (worktree != NULL) {
8350 close_error = got_worktree_close(worktree);
8351 if (error == NULL)
8352 error = close_error;
8354 if (pack_fds) {
8355 const struct got_error *pack_err =
8356 got_repo_pack_fds_close(pack_fds);
8357 if (error == NULL)
8358 error = pack_err;
8360 free(cwd);
8361 return error;
8364 __dead static void
8365 usage_revert(void)
8367 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8368 getprogname());
8369 exit(1);
8372 static const struct got_error *
8373 revert_progress(void *arg, unsigned char status, const char *path)
8375 if (status == GOT_STATUS_UNVERSIONED)
8376 return NULL;
8378 while (path[0] == '/')
8379 path++;
8380 printf("%c %s\n", status, path);
8381 return NULL;
8384 struct choose_patch_arg {
8385 FILE *patch_script_file;
8386 const char *action;
8389 static const struct got_error *
8390 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8391 int nchanges, const char *action)
8393 const struct got_error *err;
8394 char *line = NULL;
8395 size_t linesize = 0;
8396 ssize_t linelen;
8398 switch (status) {
8399 case GOT_STATUS_ADD:
8400 printf("A %s\n%s this addition? [y/n] ", path, action);
8401 break;
8402 case GOT_STATUS_DELETE:
8403 printf("D %s\n%s this deletion? [y/n] ", path, action);
8404 break;
8405 case GOT_STATUS_MODIFY:
8406 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8407 return got_error_from_errno("fseek");
8408 printf(GOT_COMMIT_SEP_STR);
8409 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8410 printf("%s", line);
8411 if (linelen == -1 && ferror(patch_file)) {
8412 err = got_error_from_errno("getline");
8413 free(line);
8414 return err;
8416 free(line);
8417 printf(GOT_COMMIT_SEP_STR);
8418 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8419 path, n, nchanges, action);
8420 break;
8421 default:
8422 return got_error_path(path, GOT_ERR_FILE_STATUS);
8425 fflush(stdout);
8426 return NULL;
8429 static const struct got_error *
8430 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8431 FILE *patch_file, int n, int nchanges)
8433 const struct got_error *err = NULL;
8434 char *line = NULL;
8435 size_t linesize = 0;
8436 ssize_t linelen;
8437 int resp = ' ';
8438 struct choose_patch_arg *a = arg;
8440 *choice = GOT_PATCH_CHOICE_NONE;
8442 if (a->patch_script_file) {
8443 char *nl;
8444 err = show_change(status, path, patch_file, n, nchanges,
8445 a->action);
8446 if (err)
8447 return err;
8448 linelen = getline(&line, &linesize, a->patch_script_file);
8449 if (linelen == -1) {
8450 if (ferror(a->patch_script_file))
8451 return got_error_from_errno("getline");
8452 return NULL;
8454 nl = strchr(line, '\n');
8455 if (nl)
8456 *nl = '\0';
8457 if (strcmp(line, "y") == 0) {
8458 *choice = GOT_PATCH_CHOICE_YES;
8459 printf("y\n");
8460 } else if (strcmp(line, "n") == 0) {
8461 *choice = GOT_PATCH_CHOICE_NO;
8462 printf("n\n");
8463 } else if (strcmp(line, "q") == 0 &&
8464 status == GOT_STATUS_MODIFY) {
8465 *choice = GOT_PATCH_CHOICE_QUIT;
8466 printf("q\n");
8467 } else
8468 printf("invalid response '%s'\n", line);
8469 free(line);
8470 return NULL;
8473 while (resp != 'y' && resp != 'n' && resp != 'q') {
8474 err = show_change(status, path, patch_file, n, nchanges,
8475 a->action);
8476 if (err)
8477 return err;
8478 resp = getchar();
8479 if (resp == '\n')
8480 resp = getchar();
8481 if (status == GOT_STATUS_MODIFY) {
8482 if (resp != 'y' && resp != 'n' && resp != 'q') {
8483 printf("invalid response '%c'\n", resp);
8484 resp = ' ';
8486 } else if (resp != 'y' && resp != 'n') {
8487 printf("invalid response '%c'\n", resp);
8488 resp = ' ';
8492 if (resp == 'y')
8493 *choice = GOT_PATCH_CHOICE_YES;
8494 else if (resp == 'n')
8495 *choice = GOT_PATCH_CHOICE_NO;
8496 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8497 *choice = GOT_PATCH_CHOICE_QUIT;
8499 return NULL;
8502 struct wt_commitable_path_arg {
8503 struct got_pathlist_head *commit_paths;
8504 int *has_changes;
8508 * Shortcut work tree status callback to determine if the set of paths scanned
8509 * has at least one versioned path that is being modified and, if not NULL, is
8510 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8511 * soon as a path is passed with a status that satisfies this criteria.
8513 static const struct got_error *
8514 worktree_has_commitable_path(void *arg, unsigned char status,
8515 unsigned char staged_status, const char *path,
8516 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8517 struct got_object_id *commit_id, int dirfd, const char *de_name)
8519 struct wt_commitable_path_arg *a = arg;
8521 if (status == staged_status && (status == GOT_STATUS_DELETE))
8522 status = GOT_STATUS_NO_CHANGE;
8524 if (!(status == GOT_STATUS_NO_CHANGE ||
8525 status == GOT_STATUS_UNVERSIONED) ||
8526 staged_status != GOT_STATUS_NO_CHANGE) {
8527 if (a->commit_paths != NULL) {
8528 struct got_pathlist_entry *pe;
8530 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8531 if (strncmp(path, pe->path,
8532 pe->path_len) == 0) {
8533 *a->has_changes = 1;
8534 break;
8537 } else
8538 *a->has_changes = 1;
8540 if (*a->has_changes)
8541 return got_error(GOT_ERR_FILE_MODIFIED);
8544 return NULL;
8548 * Check that the changeset of the commit identified by id is
8549 * comprised of at least one modified path that is being committed.
8551 static const struct got_error *
8552 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8553 struct got_object_id *id, struct got_worktree *worktree,
8554 struct got_repository *repo)
8556 const struct got_error *err;
8557 struct got_pathlist_head paths;
8558 struct got_commit_object *commit = NULL, *pcommit = NULL;
8559 struct got_tree_object *tree = NULL, *ptree = NULL;
8560 struct got_object_qid *pid;
8562 TAILQ_INIT(&paths);
8564 err = got_object_open_as_commit(&commit, repo, id);
8565 if (err)
8566 goto done;
8568 err = got_object_open_as_tree(&tree, repo,
8569 got_object_commit_get_tree_id(commit));
8570 if (err)
8571 goto done;
8573 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8574 if (pid != NULL) {
8575 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8576 if (err)
8577 goto done;
8579 err = got_object_open_as_tree(&ptree, repo,
8580 got_object_commit_get_tree_id(pcommit));
8581 if (err)
8582 goto done;
8585 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8586 got_diff_tree_collect_changed_paths, &paths, 0);
8587 if (err)
8588 goto done;
8590 err = got_worktree_status(worktree, &paths, repo, 0,
8591 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8592 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8594 * At least one changed path in the referenced commit is
8595 * modified in the work tree, that's all we need to know!
8597 err = NULL;
8600 done:
8601 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8602 if (commit)
8603 got_object_commit_close(commit);
8604 if (pcommit)
8605 got_object_commit_close(pcommit);
8606 if (tree)
8607 got_object_tree_close(tree);
8608 if (ptree)
8609 got_object_tree_close(ptree);
8610 return err;
8614 * Remove any "logmsg" reference comprised entirely of paths that have
8615 * been reverted in this work tree. If any path in the logmsg ref changeset
8616 * remains in a changed state in the worktree, do not remove the reference.
8618 static const struct got_error *
8619 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8621 const struct got_error *err;
8622 struct got_reflist_head refs;
8623 struct got_reflist_entry *re;
8624 struct got_commit_object *commit = NULL;
8625 struct got_object_id *commit_id = NULL;
8626 struct wt_commitable_path_arg wcpa;
8627 char *uuidstr = NULL;
8629 TAILQ_INIT(&refs);
8631 err = got_worktree_get_uuid(&uuidstr, worktree);
8632 if (err)
8633 goto done;
8635 err = got_ref_list(&refs, repo, "refs/got/worktree",
8636 got_ref_cmp_by_name, repo);
8637 if (err)
8638 goto done;
8640 TAILQ_FOREACH(re, &refs, entry) {
8641 const char *refname;
8642 int has_changes = 0;
8644 refname = got_ref_get_name(re->ref);
8646 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8647 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8648 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8649 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8650 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8651 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8652 else
8653 continue;
8655 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8656 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8657 else
8658 continue;
8660 err = got_repo_match_object_id(&commit_id, NULL, refname,
8661 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8662 if (err)
8663 goto done;
8665 err = got_object_open_as_commit(&commit, repo, commit_id);
8666 if (err)
8667 goto done;
8669 wcpa.commit_paths = NULL;
8670 wcpa.has_changes = &has_changes;
8672 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8673 worktree, repo);
8674 if (err)
8675 goto done;
8677 if (!has_changes) {
8678 err = got_ref_delete(re->ref, repo);
8679 if (err)
8680 goto done;
8683 got_object_commit_close(commit);
8684 commit = NULL;
8685 free(commit_id);
8686 commit_id = NULL;
8689 done:
8690 free(uuidstr);
8691 free(commit_id);
8692 got_ref_list_free(&refs);
8693 if (commit)
8694 got_object_commit_close(commit);
8695 return err;
8698 static const struct got_error *
8699 cmd_revert(int argc, char *argv[])
8701 const struct got_error *error = NULL;
8702 struct got_worktree *worktree = NULL;
8703 struct got_repository *repo = NULL;
8704 char *cwd = NULL, *path = NULL;
8705 struct got_pathlist_head paths;
8706 struct got_pathlist_entry *pe;
8707 int ch, can_recurse = 0, pflag = 0;
8708 FILE *patch_script_file = NULL;
8709 const char *patch_script_path = NULL;
8710 struct choose_patch_arg cpa;
8711 int *pack_fds = NULL;
8713 TAILQ_INIT(&paths);
8715 #ifndef PROFILE
8716 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8717 "unveil", NULL) == -1)
8718 err(1, "pledge");
8719 #endif
8721 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8722 switch (ch) {
8723 case 'F':
8724 patch_script_path = optarg;
8725 break;
8726 case 'p':
8727 pflag = 1;
8728 break;
8729 case 'R':
8730 can_recurse = 1;
8731 break;
8732 default:
8733 usage_revert();
8734 /* NOTREACHED */
8738 argc -= optind;
8739 argv += optind;
8741 if (argc < 1)
8742 usage_revert();
8743 if (patch_script_path && !pflag)
8744 errx(1, "-F option can only be used together with -p option");
8746 cwd = getcwd(NULL, 0);
8747 if (cwd == NULL) {
8748 error = got_error_from_errno("getcwd");
8749 goto done;
8752 error = got_repo_pack_fds_open(&pack_fds);
8753 if (error != NULL)
8754 goto done;
8756 error = got_worktree_open(&worktree, cwd);
8757 if (error) {
8758 if (error->code == GOT_ERR_NOT_WORKTREE)
8759 error = wrap_not_worktree_error(error, "revert", cwd);
8760 goto done;
8763 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8764 NULL, pack_fds);
8765 if (error != NULL)
8766 goto done;
8768 if (patch_script_path) {
8769 patch_script_file = fopen(patch_script_path, "re");
8770 if (patch_script_file == NULL) {
8771 error = got_error_from_errno2("fopen",
8772 patch_script_path);
8773 goto done;
8778 * XXX "c" perm needed on repo dir to delete merge references.
8780 error = apply_unveil(got_repo_get_path(repo), 0,
8781 got_worktree_get_root_path(worktree));
8782 if (error)
8783 goto done;
8785 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8786 if (error)
8787 goto done;
8789 if (!can_recurse) {
8790 char *ondisk_path;
8791 struct stat sb;
8792 TAILQ_FOREACH(pe, &paths, entry) {
8793 if (asprintf(&ondisk_path, "%s/%s",
8794 got_worktree_get_root_path(worktree),
8795 pe->path) == -1) {
8796 error = got_error_from_errno("asprintf");
8797 goto done;
8799 if (lstat(ondisk_path, &sb) == -1) {
8800 if (errno == ENOENT) {
8801 free(ondisk_path);
8802 continue;
8804 error = got_error_from_errno2("lstat",
8805 ondisk_path);
8806 free(ondisk_path);
8807 goto done;
8809 free(ondisk_path);
8810 if (S_ISDIR(sb.st_mode)) {
8811 error = got_error_msg(GOT_ERR_BAD_PATH,
8812 "reverting directories requires -R option");
8813 goto done;
8818 cpa.patch_script_file = patch_script_file;
8819 cpa.action = "revert";
8820 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8821 pflag ? choose_patch : NULL, &cpa, repo);
8823 error = rm_logmsg_ref(worktree, repo);
8824 done:
8825 if (patch_script_file && fclose(patch_script_file) == EOF &&
8826 error == NULL)
8827 error = got_error_from_errno2("fclose", patch_script_path);
8828 if (repo) {
8829 const struct got_error *close_err = got_repo_close(repo);
8830 if (error == NULL)
8831 error = close_err;
8833 if (worktree)
8834 got_worktree_close(worktree);
8835 if (pack_fds) {
8836 const struct got_error *pack_err =
8837 got_repo_pack_fds_close(pack_fds);
8838 if (error == NULL)
8839 error = pack_err;
8841 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8842 free(path);
8843 free(cwd);
8844 return error;
8847 __dead static void
8848 usage_commit(void)
8850 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8851 "[-m message] [path ...]\n", getprogname());
8852 exit(1);
8855 struct collect_commit_logmsg_arg {
8856 const char *cmdline_log;
8857 const char *prepared_log;
8858 const char *merged_log;
8859 int non_interactive;
8860 const char *editor;
8861 const char *worktree_path;
8862 const char *branch_name;
8863 const char *repo_path;
8864 char *logmsg_path;
8868 static const struct got_error *
8869 read_prepared_logmsg(char **logmsg, const char *path)
8871 const struct got_error *err = NULL;
8872 FILE *f = NULL;
8873 struct stat sb;
8874 size_t r;
8876 *logmsg = NULL;
8877 memset(&sb, 0, sizeof(sb));
8879 f = fopen(path, "re");
8880 if (f == NULL)
8881 return got_error_from_errno2("fopen", path);
8883 if (fstat(fileno(f), &sb) == -1) {
8884 err = got_error_from_errno2("fstat", path);
8885 goto done;
8887 if (sb.st_size == 0) {
8888 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8889 goto done;
8892 *logmsg = malloc(sb.st_size + 1);
8893 if (*logmsg == NULL) {
8894 err = got_error_from_errno("malloc");
8895 goto done;
8898 r = fread(*logmsg, 1, sb.st_size, f);
8899 if (r != sb.st_size) {
8900 if (ferror(f))
8901 err = got_error_from_errno2("fread", path);
8902 else
8903 err = got_error(GOT_ERR_IO);
8904 goto done;
8906 (*logmsg)[sb.st_size] = '\0';
8907 done:
8908 if (fclose(f) == EOF && err == NULL)
8909 err = got_error_from_errno2("fclose", path);
8910 if (err) {
8911 free(*logmsg);
8912 *logmsg = NULL;
8914 return err;
8917 static const struct got_error *
8918 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8919 const char *diff_path, char **logmsg, void *arg)
8921 char *initial_content = NULL;
8922 struct got_pathlist_entry *pe;
8923 const struct got_error *err = NULL;
8924 char *template = NULL;
8925 char *prepared_msg = NULL, *merged_msg = NULL;
8926 struct collect_commit_logmsg_arg *a = arg;
8927 int initial_content_len;
8928 int fd = -1;
8929 size_t len;
8931 /* if a message was specified on the command line, just use it */
8932 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8933 len = strlen(a->cmdline_log) + 1;
8934 *logmsg = malloc(len + 1);
8935 if (*logmsg == NULL)
8936 return got_error_from_errno("malloc");
8937 strlcpy(*logmsg, a->cmdline_log, len);
8938 return NULL;
8939 } else if (a->prepared_log != NULL && a->non_interactive)
8940 return read_prepared_logmsg(logmsg, a->prepared_log);
8942 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8943 return got_error_from_errno("asprintf");
8945 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8946 if (err)
8947 goto done;
8949 if (a->prepared_log) {
8950 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8951 if (err)
8952 goto done;
8953 } else if (a->merged_log) {
8954 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8955 if (err)
8956 goto done;
8959 initial_content_len = asprintf(&initial_content,
8960 "%s%s\n# changes to be committed on branch %s:\n",
8961 prepared_msg ? prepared_msg : "",
8962 merged_msg ? merged_msg : "", a->branch_name);
8963 if (initial_content_len == -1) {
8964 err = got_error_from_errno("asprintf");
8965 goto done;
8968 if (write(fd, initial_content, initial_content_len) == -1) {
8969 err = got_error_from_errno2("write", a->logmsg_path);
8970 goto done;
8973 TAILQ_FOREACH(pe, commitable_paths, entry) {
8974 struct got_commitable *ct = pe->data;
8975 dprintf(fd, "# %c %s\n",
8976 got_commitable_get_status(ct),
8977 got_commitable_get_path(ct));
8980 if (diff_path) {
8981 dprintf(fd, "# detailed changes can be viewed in %s\n",
8982 diff_path);
8985 if (close(fd) == -1) {
8986 err = got_error_from_errno2("close", a->logmsg_path);
8987 goto done;
8989 fd = -1;
8991 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8992 initial_content_len, a->prepared_log ? 0 : 1);
8993 done:
8994 free(initial_content);
8995 free(template);
8996 free(prepared_msg);
8997 free(merged_msg);
8999 if (fd != -1 && close(fd) == -1 && err == NULL)
9000 err = got_error_from_errno2("close", a->logmsg_path);
9002 /* Editor is done; we can now apply unveil(2) */
9003 if (err == NULL)
9004 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9005 if (err) {
9006 free(*logmsg);
9007 *logmsg = NULL;
9009 return err;
9012 static const struct got_error *
9013 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9014 const char *type, int has_content)
9016 const struct got_error *err = NULL;
9017 char *logmsg = NULL;
9019 err = got_object_commit_get_logmsg(&logmsg, commit);
9020 if (err)
9021 return err;
9023 if (fprintf(f, "%s# log message of %s commit %s:%s",
9024 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9025 err = got_ferror(f, GOT_ERR_IO);
9027 free(logmsg);
9028 return err;
9032 * Lookup "logmsg" references of backed-out and cherrypicked commits
9033 * belonging to the current work tree. If found, and the worktree has
9034 * at least one modified file that was changed in the referenced commit,
9035 * add its log message to a new temporary file at *logmsg_path.
9036 * Add all refs found to matched_refs to be scheduled for removal on
9037 * successful commit.
9039 static const struct got_error *
9040 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9041 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9042 struct got_repository *repo)
9044 const struct got_error *err;
9045 struct got_commit_object *commit = NULL;
9046 struct got_object_id *id = NULL;
9047 struct got_reflist_head refs;
9048 struct got_reflist_entry *re, *re_match;
9049 FILE *f = NULL;
9050 char *uuidstr = NULL;
9051 int added_logmsg = 0;
9053 TAILQ_INIT(&refs);
9055 *logmsg_path = NULL;
9057 err = got_worktree_get_uuid(&uuidstr, worktree);
9058 if (err)
9059 goto done;
9061 err = got_ref_list(&refs, repo, "refs/got/worktree",
9062 got_ref_cmp_by_name, repo);
9063 if (err)
9064 goto done;
9066 TAILQ_FOREACH(re, &refs, entry) {
9067 const char *refname, *type;
9068 struct wt_commitable_path_arg wcpa;
9069 int add_logmsg = 0;
9071 refname = got_ref_get_name(re->ref);
9073 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9074 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9075 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9076 type = "cherrypicked";
9077 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9078 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9079 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9080 type = "backed-out";
9081 } else
9082 continue;
9084 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9085 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9086 else
9087 continue;
9089 err = got_repo_match_object_id(&id, NULL, refname,
9090 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9091 if (err)
9092 goto done;
9094 err = got_object_open_as_commit(&commit, repo, id);
9095 if (err)
9096 goto done;
9098 wcpa.commit_paths = paths;
9099 wcpa.has_changes = &add_logmsg;
9101 err = commit_path_changed_in_worktree(&wcpa, id,
9102 worktree, repo);
9103 if (err)
9104 goto done;
9106 if (add_logmsg) {
9107 if (f == NULL) {
9108 err = got_opentemp_named(logmsg_path, &f,
9109 "got-commit-logmsg", "");
9110 if (err)
9111 goto done;
9113 err = cat_logmsg(f, commit, refname, type,
9114 added_logmsg);
9115 if (err)
9116 goto done;
9117 if (!added_logmsg)
9118 ++added_logmsg;
9120 err = got_reflist_entry_dup(&re_match, re);
9121 if (err)
9122 goto done;
9123 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9126 got_object_commit_close(commit);
9127 commit = NULL;
9128 free(id);
9129 id = NULL;
9132 done:
9133 free(id);
9134 free(uuidstr);
9135 got_ref_list_free(&refs);
9136 if (commit)
9137 got_object_commit_close(commit);
9138 if (f && fclose(f) == EOF && err == NULL)
9139 err = got_error_from_errno("fclose");
9140 if (!added_logmsg) {
9141 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9142 err = got_error_from_errno2("unlink", *logmsg_path);
9143 *logmsg_path = NULL;
9145 return err;
9148 static const struct got_error *
9149 cmd_commit(int argc, char *argv[])
9151 const struct got_error *error = NULL;
9152 struct got_worktree *worktree = NULL;
9153 struct got_repository *repo = NULL;
9154 char *cwd = NULL, *id_str = NULL;
9155 struct got_object_id *id = NULL;
9156 const char *logmsg = NULL;
9157 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9158 struct collect_commit_logmsg_arg cl_arg;
9159 const char *author = NULL;
9160 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9161 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9162 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9163 int show_diff = 1, commit_conflicts = 0;
9164 struct got_pathlist_head paths;
9165 struct got_reflist_head refs;
9166 struct got_reflist_entry *re;
9167 int *pack_fds = NULL;
9169 TAILQ_INIT(&refs);
9170 TAILQ_INIT(&paths);
9171 cl_arg.logmsg_path = NULL;
9173 #ifndef PROFILE
9174 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9175 "unveil", NULL) == -1)
9176 err(1, "pledge");
9177 #endif
9179 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9180 switch (ch) {
9181 case 'A':
9182 author = optarg;
9183 error = valid_author(author);
9184 if (error)
9185 return error;
9186 break;
9187 case 'C':
9188 commit_conflicts = 1;
9189 break;
9190 case 'F':
9191 if (logmsg != NULL)
9192 option_conflict('F', 'm');
9193 prepared_logmsg = realpath(optarg, NULL);
9194 if (prepared_logmsg == NULL)
9195 return got_error_from_errno2("realpath",
9196 optarg);
9197 break;
9198 case 'm':
9199 if (prepared_logmsg)
9200 option_conflict('m', 'F');
9201 logmsg = optarg;
9202 break;
9203 case 'N':
9204 non_interactive = 1;
9205 break;
9206 case 'n':
9207 show_diff = 0;
9208 break;
9209 case 'S':
9210 allow_bad_symlinks = 1;
9211 break;
9212 default:
9213 usage_commit();
9214 /* NOTREACHED */
9218 argc -= optind;
9219 argv += optind;
9221 cwd = getcwd(NULL, 0);
9222 if (cwd == NULL) {
9223 error = got_error_from_errno("getcwd");
9224 goto done;
9227 error = got_repo_pack_fds_open(&pack_fds);
9228 if (error != NULL)
9229 goto done;
9231 error = got_worktree_open(&worktree, cwd);
9232 if (error) {
9233 if (error->code == GOT_ERR_NOT_WORKTREE)
9234 error = wrap_not_worktree_error(error, "commit", cwd);
9235 goto done;
9238 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9239 if (error)
9240 goto done;
9241 if (rebase_in_progress) {
9242 error = got_error(GOT_ERR_REBASING);
9243 goto done;
9246 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9247 worktree);
9248 if (error)
9249 goto done;
9251 error = get_gitconfig_path(&gitconfig_path);
9252 if (error)
9253 goto done;
9254 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9255 gitconfig_path, pack_fds);
9256 if (error != NULL)
9257 goto done;
9259 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9260 if (error)
9261 goto done;
9262 if (merge_in_progress) {
9263 error = got_error(GOT_ERR_MERGE_BUSY);
9264 goto done;
9267 error = get_author(&committer, repo, worktree);
9268 if (error)
9269 goto done;
9271 if (author == NULL)
9272 author = committer;
9275 * unveil(2) traverses exec(2); if an editor is used we have
9276 * to apply unveil after the log message has been written.
9278 if (logmsg == NULL || strlen(logmsg) == 0)
9279 error = get_editor(&editor);
9280 else
9281 error = apply_unveil(got_repo_get_path(repo), 0,
9282 got_worktree_get_root_path(worktree));
9283 if (error)
9284 goto done;
9286 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9287 if (error)
9288 goto done;
9290 if (prepared_logmsg == NULL) {
9291 error = lookup_logmsg_ref(&merged_logmsg,
9292 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9293 if (error)
9294 goto done;
9297 cl_arg.editor = editor;
9298 cl_arg.cmdline_log = logmsg;
9299 cl_arg.prepared_log = prepared_logmsg;
9300 cl_arg.merged_log = merged_logmsg;
9301 cl_arg.non_interactive = non_interactive;
9302 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9303 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9304 if (!histedit_in_progress) {
9305 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9306 error = got_error(GOT_ERR_COMMIT_BRANCH);
9307 goto done;
9309 cl_arg.branch_name += 11;
9311 cl_arg.repo_path = got_repo_get_path(repo);
9312 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9313 allow_bad_symlinks, show_diff, commit_conflicts,
9314 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9315 if (error) {
9316 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9317 cl_arg.logmsg_path != NULL)
9318 preserve_logmsg = 1;
9319 goto done;
9322 error = got_object_id_str(&id_str, id);
9323 if (error)
9324 goto done;
9325 printf("Created commit %s\n", id_str);
9327 TAILQ_FOREACH(re, &refs, entry) {
9328 error = got_ref_delete(re->ref, repo);
9329 if (error)
9330 goto done;
9333 done:
9334 if (preserve_logmsg) {
9335 fprintf(stderr, "%s: log message preserved in %s\n",
9336 getprogname(), cl_arg.logmsg_path);
9337 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9338 error == NULL)
9339 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9340 free(cl_arg.logmsg_path);
9341 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9342 error = got_error_from_errno2("unlink", merged_logmsg);
9343 free(merged_logmsg);
9344 if (repo) {
9345 const struct got_error *close_err = got_repo_close(repo);
9346 if (error == NULL)
9347 error = close_err;
9349 if (worktree)
9350 got_worktree_close(worktree);
9351 if (pack_fds) {
9352 const struct got_error *pack_err =
9353 got_repo_pack_fds_close(pack_fds);
9354 if (error == NULL)
9355 error = pack_err;
9357 got_ref_list_free(&refs);
9358 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9359 free(cwd);
9360 free(id_str);
9361 free(gitconfig_path);
9362 free(editor);
9363 free(committer);
9364 free(prepared_logmsg);
9365 return error;
9368 __dead static void
9369 usage_send(void)
9371 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9372 "[-r repository-path] [-t tag] [remote-repository]\n",
9373 getprogname());
9374 exit(1);
9377 static void
9378 print_load_info(int print_colored, int print_found, int print_trees,
9379 int ncolored, int nfound, int ntrees)
9381 if (print_colored) {
9382 printf("%d commit%s colored", ncolored,
9383 ncolored == 1 ? "" : "s");
9385 if (print_found) {
9386 printf("%s%d object%s found",
9387 ncolored > 0 ? "; " : "",
9388 nfound, nfound == 1 ? "" : "s");
9390 if (print_trees) {
9391 printf("; %d tree%s scanned", ntrees,
9392 ntrees == 1 ? "" : "s");
9396 struct got_send_progress_arg {
9397 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9398 int verbosity;
9399 int last_ncolored;
9400 int last_nfound;
9401 int last_ntrees;
9402 int loading_done;
9403 int last_ncommits;
9404 int last_nobj_total;
9405 int last_p_deltify;
9406 int last_p_written;
9407 int last_p_sent;
9408 int printed_something;
9409 int sent_something;
9410 struct got_pathlist_head *delete_branches;
9413 static const struct got_error *
9414 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9415 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9416 int nobj_written, off_t bytes_sent, const char *refname,
9417 const char *errmsg, int success)
9419 struct got_send_progress_arg *a = arg;
9420 char scaled_packsize[FMT_SCALED_STRSIZE];
9421 char scaled_sent[FMT_SCALED_STRSIZE];
9422 int p_deltify = 0, p_written = 0, p_sent = 0;
9423 int print_colored = 0, print_found = 0, print_trees = 0;
9424 int print_searching = 0, print_total = 0;
9425 int print_deltify = 0, print_written = 0, print_sent = 0;
9427 if (a->verbosity < 0)
9428 return NULL;
9430 if (refname) {
9431 const char *status = success ? "accepted" : "rejected";
9433 if (success) {
9434 struct got_pathlist_entry *pe;
9435 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9436 const char *branchname = pe->path;
9437 if (got_path_cmp(branchname, refname,
9438 strlen(branchname), strlen(refname)) == 0) {
9439 status = "deleted";
9440 a->sent_something = 1;
9441 break;
9446 if (a->printed_something)
9447 putchar('\n');
9448 printf("Server has %s %s", status, refname);
9449 if (errmsg)
9450 printf(": %s", errmsg);
9451 a->printed_something = 1;
9452 return NULL;
9455 if (a->last_ncolored != ncolored) {
9456 print_colored = 1;
9457 a->last_ncolored = ncolored;
9460 if (a->last_nfound != nfound) {
9461 print_colored = 1;
9462 print_found = 1;
9463 a->last_nfound = nfound;
9466 if (a->last_ntrees != ntrees) {
9467 print_colored = 1;
9468 print_found = 1;
9469 print_trees = 1;
9470 a->last_ntrees = ntrees;
9473 if ((print_colored || print_found || print_trees) &&
9474 !a->loading_done) {
9475 printf("\r");
9476 print_load_info(print_colored, print_found, print_trees,
9477 ncolored, nfound, ntrees);
9478 a->printed_something = 1;
9479 fflush(stdout);
9480 return NULL;
9481 } else if (!a->loading_done) {
9482 printf("\r");
9483 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9484 printf("\n");
9485 a->loading_done = 1;
9488 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9489 return got_error_from_errno("fmt_scaled");
9490 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9491 return got_error_from_errno("fmt_scaled");
9493 if (a->last_ncommits != ncommits) {
9494 print_searching = 1;
9495 a->last_ncommits = ncommits;
9498 if (a->last_nobj_total != nobj_total) {
9499 print_searching = 1;
9500 print_total = 1;
9501 a->last_nobj_total = nobj_total;
9504 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9505 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9506 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9507 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9508 return got_error(GOT_ERR_NO_SPACE);
9511 if (nobj_deltify > 0 || nobj_written > 0) {
9512 if (nobj_deltify > 0) {
9513 p_deltify = (nobj_deltify * 100) / nobj_total;
9514 if (p_deltify != a->last_p_deltify) {
9515 a->last_p_deltify = p_deltify;
9516 print_searching = 1;
9517 print_total = 1;
9518 print_deltify = 1;
9521 if (nobj_written > 0) {
9522 p_written = (nobj_written * 100) / nobj_total;
9523 if (p_written != a->last_p_written) {
9524 a->last_p_written = p_written;
9525 print_searching = 1;
9526 print_total = 1;
9527 print_deltify = 1;
9528 print_written = 1;
9533 if (bytes_sent > 0) {
9534 p_sent = (bytes_sent * 100) / packfile_size;
9535 if (p_sent != a->last_p_sent) {
9536 a->last_p_sent = p_sent;
9537 print_searching = 1;
9538 print_total = 1;
9539 print_deltify = 1;
9540 print_written = 1;
9541 print_sent = 1;
9543 a->sent_something = 1;
9546 if (print_searching || print_total || print_deltify || print_written ||
9547 print_sent)
9548 printf("\r");
9549 if (print_searching)
9550 printf("packing %d reference%s", ncommits,
9551 ncommits == 1 ? "" : "s");
9552 if (print_total)
9553 printf("; %d object%s", nobj_total,
9554 nobj_total == 1 ? "" : "s");
9555 if (print_deltify)
9556 printf("; deltify: %d%%", p_deltify);
9557 if (print_sent)
9558 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9559 scaled_packsize, p_sent);
9560 else if (print_written)
9561 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9562 scaled_packsize, p_written);
9563 if (print_searching || print_total || print_deltify ||
9564 print_written || print_sent) {
9565 a->printed_something = 1;
9566 fflush(stdout);
9568 return NULL;
9571 static const struct got_error *
9572 cmd_send(int argc, char *argv[])
9574 const struct got_error *error = NULL;
9575 char *cwd = NULL, *repo_path = NULL;
9576 const char *remote_name;
9577 char *proto = NULL, *host = NULL, *port = NULL;
9578 char *repo_name = NULL, *server_path = NULL;
9579 const struct got_remote_repo *remotes, *remote = NULL;
9580 int nremotes, nbranches = 0, ndelete_branches = 0;
9581 struct got_repository *repo = NULL;
9582 struct got_worktree *worktree = NULL;
9583 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9584 struct got_pathlist_head branches;
9585 struct got_pathlist_head tags;
9586 struct got_reflist_head all_branches;
9587 struct got_reflist_head all_tags;
9588 struct got_pathlist_head delete_args;
9589 struct got_pathlist_head delete_branches;
9590 struct got_reflist_entry *re;
9591 struct got_pathlist_entry *pe;
9592 int i, ch, sendfd = -1, sendstatus;
9593 pid_t sendpid = -1;
9594 struct got_send_progress_arg spa;
9595 int verbosity = 0, overwrite_refs = 0;
9596 int send_all_branches = 0, send_all_tags = 0;
9597 struct got_reference *ref = NULL;
9598 int *pack_fds = NULL;
9600 TAILQ_INIT(&branches);
9601 TAILQ_INIT(&tags);
9602 TAILQ_INIT(&all_branches);
9603 TAILQ_INIT(&all_tags);
9604 TAILQ_INIT(&delete_args);
9605 TAILQ_INIT(&delete_branches);
9607 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9608 switch (ch) {
9609 case 'a':
9610 send_all_branches = 1;
9611 break;
9612 case 'b':
9613 error = got_pathlist_append(&branches, optarg, NULL);
9614 if (error)
9615 return error;
9616 nbranches++;
9617 break;
9618 case 'd':
9619 error = got_pathlist_append(&delete_args, optarg, NULL);
9620 if (error)
9621 return error;
9622 break;
9623 case 'f':
9624 overwrite_refs = 1;
9625 break;
9626 case 'q':
9627 verbosity = -1;
9628 break;
9629 case 'r':
9630 repo_path = realpath(optarg, NULL);
9631 if (repo_path == NULL)
9632 return got_error_from_errno2("realpath",
9633 optarg);
9634 got_path_strip_trailing_slashes(repo_path);
9635 break;
9636 case 'T':
9637 send_all_tags = 1;
9638 break;
9639 case 't':
9640 error = got_pathlist_append(&tags, optarg, NULL);
9641 if (error)
9642 return error;
9643 break;
9644 case 'v':
9645 if (verbosity < 0)
9646 verbosity = 0;
9647 else if (verbosity < 3)
9648 verbosity++;
9649 break;
9650 default:
9651 usage_send();
9652 /* NOTREACHED */
9655 argc -= optind;
9656 argv += optind;
9658 if (send_all_branches && !TAILQ_EMPTY(&branches))
9659 option_conflict('a', 'b');
9660 if (send_all_tags && !TAILQ_EMPTY(&tags))
9661 option_conflict('T', 't');
9664 if (argc == 0)
9665 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9666 else if (argc == 1)
9667 remote_name = argv[0];
9668 else
9669 usage_send();
9671 cwd = getcwd(NULL, 0);
9672 if (cwd == NULL) {
9673 error = got_error_from_errno("getcwd");
9674 goto done;
9677 error = got_repo_pack_fds_open(&pack_fds);
9678 if (error != NULL)
9679 goto done;
9681 if (repo_path == NULL) {
9682 error = got_worktree_open(&worktree, cwd);
9683 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9684 goto done;
9685 else
9686 error = NULL;
9687 if (worktree) {
9688 repo_path =
9689 strdup(got_worktree_get_repo_path(worktree));
9690 if (repo_path == NULL)
9691 error = got_error_from_errno("strdup");
9692 if (error)
9693 goto done;
9694 } else {
9695 repo_path = strdup(cwd);
9696 if (repo_path == NULL) {
9697 error = got_error_from_errno("strdup");
9698 goto done;
9703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9704 if (error)
9705 goto done;
9707 if (worktree) {
9708 worktree_conf = got_worktree_get_gotconfig(worktree);
9709 if (worktree_conf) {
9710 got_gotconfig_get_remotes(&nremotes, &remotes,
9711 worktree_conf);
9712 for (i = 0; i < nremotes; i++) {
9713 if (strcmp(remotes[i].name, remote_name) == 0) {
9714 remote = &remotes[i];
9715 break;
9720 if (remote == NULL) {
9721 repo_conf = got_repo_get_gotconfig(repo);
9722 if (repo_conf) {
9723 got_gotconfig_get_remotes(&nremotes, &remotes,
9724 repo_conf);
9725 for (i = 0; i < nremotes; i++) {
9726 if (strcmp(remotes[i].name, remote_name) == 0) {
9727 remote = &remotes[i];
9728 break;
9733 if (remote == NULL) {
9734 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9735 for (i = 0; i < nremotes; i++) {
9736 if (strcmp(remotes[i].name, remote_name) == 0) {
9737 remote = &remotes[i];
9738 break;
9742 if (remote == NULL) {
9743 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9744 goto done;
9747 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9748 &repo_name, remote->send_url);
9749 if (error)
9750 goto done;
9752 if (strcmp(proto, "git") == 0) {
9753 #ifndef PROFILE
9754 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9755 "sendfd dns inet unveil", NULL) == -1)
9756 err(1, "pledge");
9757 #endif
9758 } else if (strcmp(proto, "git+ssh") == 0 ||
9759 strcmp(proto, "ssh") == 0) {
9760 #ifndef PROFILE
9761 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9762 "sendfd unveil", NULL) == -1)
9763 err(1, "pledge");
9764 #endif
9765 } else if (strcmp(proto, "http") == 0 ||
9766 strcmp(proto, "git+http") == 0) {
9767 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9768 goto done;
9769 } else {
9770 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9771 goto done;
9774 error = got_dial_apply_unveil(proto);
9775 if (error)
9776 goto done;
9778 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9779 if (error)
9780 goto done;
9782 if (send_all_branches) {
9783 error = got_ref_list(&all_branches, repo, "refs/heads",
9784 got_ref_cmp_by_name, NULL);
9785 if (error)
9786 goto done;
9787 TAILQ_FOREACH(re, &all_branches, entry) {
9788 const char *branchname = got_ref_get_name(re->ref);
9789 error = got_pathlist_append(&branches,
9790 branchname, NULL);
9791 if (error)
9792 goto done;
9793 nbranches++;
9795 } else if (nbranches == 0) {
9796 for (i = 0; i < remote->nsend_branches; i++) {
9797 error = got_pathlist_append(&branches,
9798 remote->send_branches[i], NULL);
9799 if (error)
9800 goto done;
9804 if (send_all_tags) {
9805 error = got_ref_list(&all_tags, repo, "refs/tags",
9806 got_ref_cmp_by_name, NULL);
9807 if (error)
9808 goto done;
9809 TAILQ_FOREACH(re, &all_tags, entry) {
9810 const char *tagname = got_ref_get_name(re->ref);
9811 error = got_pathlist_append(&tags,
9812 tagname, NULL);
9813 if (error)
9814 goto done;
9819 * To prevent accidents only branches in refs/heads/ can be deleted
9820 * with 'got send -d'.
9821 * Deleting anything else requires local repository access or Git.
9823 TAILQ_FOREACH(pe, &delete_args, entry) {
9824 const char *branchname = pe->path;
9825 char *s;
9826 struct got_pathlist_entry *new;
9827 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9828 s = strdup(branchname);
9829 if (s == NULL) {
9830 error = got_error_from_errno("strdup");
9831 goto done;
9833 } else {
9834 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9835 error = got_error_from_errno("asprintf");
9836 goto done;
9839 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9840 if (error || new == NULL /* duplicate */)
9841 free(s);
9842 if (error)
9843 goto done;
9844 ndelete_branches++;
9847 if (nbranches == 0 && ndelete_branches == 0) {
9848 struct got_reference *head_ref;
9849 if (worktree)
9850 error = got_ref_open(&head_ref, repo,
9851 got_worktree_get_head_ref_name(worktree), 0);
9852 else
9853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9854 if (error)
9855 goto done;
9856 if (got_ref_is_symbolic(head_ref)) {
9857 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9858 got_ref_close(head_ref);
9859 if (error)
9860 goto done;
9861 } else
9862 ref = head_ref;
9863 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9864 NULL);
9865 if (error)
9866 goto done;
9867 nbranches++;
9870 if (verbosity >= 0) {
9871 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9872 remote->name, proto, host,
9873 port ? ":" : "", port ? port : "",
9874 *server_path == '/' ? "" : "/", server_path);
9877 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9878 server_path, verbosity);
9879 if (error)
9880 goto done;
9882 memset(&spa, 0, sizeof(spa));
9883 spa.last_scaled_packsize[0] = '\0';
9884 spa.last_p_deltify = -1;
9885 spa.last_p_written = -1;
9886 spa.verbosity = verbosity;
9887 spa.delete_branches = &delete_branches;
9888 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9889 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9890 check_cancelled, NULL);
9891 if (spa.printed_something)
9892 putchar('\n');
9893 if (error)
9894 goto done;
9895 if (!spa.sent_something && verbosity >= 0)
9896 printf("Already up-to-date\n");
9897 done:
9898 if (sendpid > 0) {
9899 if (kill(sendpid, SIGTERM) == -1)
9900 error = got_error_from_errno("kill");
9901 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9902 error = got_error_from_errno("waitpid");
9904 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9905 error = got_error_from_errno("close");
9906 if (repo) {
9907 const struct got_error *close_err = got_repo_close(repo);
9908 if (error == NULL)
9909 error = close_err;
9911 if (worktree)
9912 got_worktree_close(worktree);
9913 if (pack_fds) {
9914 const struct got_error *pack_err =
9915 got_repo_pack_fds_close(pack_fds);
9916 if (error == NULL)
9917 error = pack_err;
9919 if (ref)
9920 got_ref_close(ref);
9921 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9922 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9923 got_ref_list_free(&all_branches);
9924 got_ref_list_free(&all_tags);
9925 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9926 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9927 free(cwd);
9928 free(repo_path);
9929 free(proto);
9930 free(host);
9931 free(port);
9932 free(server_path);
9933 free(repo_name);
9934 return error;
9938 * Print and if delete is set delete all ref_prefix references.
9939 * If wanted_ref is not NULL, only print or delete this reference.
9941 static const struct got_error *
9942 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9943 const char *wanted_ref, int delete, struct got_worktree *worktree,
9944 struct got_repository *repo)
9946 const struct got_error *err;
9947 struct got_pathlist_head paths;
9948 struct got_reflist_head refs;
9949 struct got_reflist_entry *re;
9950 struct got_reflist_object_id_map *refs_idmap = NULL;
9951 struct got_commit_object *commit = NULL;
9952 struct got_object_id *id = NULL;
9953 const char *header_prefix;
9954 char *uuidstr = NULL;
9955 int found = 0;
9957 TAILQ_INIT(&refs);
9958 TAILQ_INIT(&paths);
9960 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9961 if (err)
9962 goto done;
9964 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9965 if (err)
9966 goto done;
9968 if (worktree != NULL) {
9969 err = got_worktree_get_uuid(&uuidstr, worktree);
9970 if (err)
9971 goto done;
9974 if (wanted_ref) {
9975 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9976 wanted_ref += 11;
9979 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9980 header_prefix = "backout";
9981 else
9982 header_prefix = "cherrypick";
9984 TAILQ_FOREACH(re, &refs, entry) {
9985 const char *refname, *wt;
9987 refname = got_ref_get_name(re->ref);
9989 err = check_cancelled(NULL);
9990 if (err)
9991 goto done;
9993 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9994 refname += prefix_len + 1; /* skip '-' delimiter */
9995 else
9996 continue;
9998 wt = refname;
10000 if (worktree == NULL || strncmp(refname, uuidstr,
10001 GOT_WORKTREE_UUID_STRLEN) == 0)
10002 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10003 else
10004 continue;
10006 err = got_repo_match_object_id(&id, NULL, refname,
10007 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10008 if (err)
10009 goto done;
10011 err = got_object_open_as_commit(&commit, repo, id);
10012 if (err)
10013 goto done;
10015 if (wanted_ref)
10016 found = strncmp(wanted_ref, refname,
10017 strlen(wanted_ref)) == 0;
10018 if (wanted_ref && !found) {
10019 struct got_reflist_head *ci_refs;
10021 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10022 id);
10024 if (ci_refs) {
10025 char *refs_str = NULL;
10026 char const *r = NULL;
10028 err = build_refs_str(&refs_str, ci_refs, id,
10029 repo, 1);
10030 if (err)
10031 goto done;
10033 r = refs_str;
10034 while (r) {
10035 if (strncmp(r, wanted_ref,
10036 strlen(wanted_ref)) == 0) {
10037 found = 1;
10038 break;
10040 r = strchr(r, ' ');
10041 if (r)
10042 ++r;
10044 free(refs_str);
10048 if (wanted_ref == NULL || found) {
10049 if (delete) {
10050 err = got_ref_delete(re->ref, repo);
10051 if (err)
10052 goto done;
10053 printf("Deleted: ");
10054 err = print_commit_oneline(commit, id, repo,
10055 refs_idmap);
10056 } else {
10058 * Print paths modified by commit to help
10059 * associate commits with worktree changes.
10061 err = get_changed_paths(&paths, commit,
10062 repo, NULL);
10063 if (err)
10064 goto done;
10066 err = print_commit(commit, id, repo, NULL,
10067 &paths, NULL, 0, 0, refs_idmap, NULL,
10068 header_prefix);
10069 got_pathlist_free(&paths,
10070 GOT_PATHLIST_FREE_ALL);
10072 if (worktree == NULL)
10073 printf("work tree: %.*s\n\n",
10074 GOT_WORKTREE_UUID_STRLEN, wt);
10076 if (err || found)
10077 goto done;
10080 got_object_commit_close(commit);
10081 commit = NULL;
10082 free(id);
10083 id = NULL;
10086 if (wanted_ref != NULL && !found)
10087 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10089 done:
10090 free(id);
10091 free(uuidstr);
10092 got_ref_list_free(&refs);
10093 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10094 if (refs_idmap)
10095 got_reflist_object_id_map_free(refs_idmap);
10096 if (commit)
10097 got_object_commit_close(commit);
10098 return err;
10102 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10103 * identified by id for log messages to prepopulate the editor on commit.
10105 static const struct got_error *
10106 logmsg_ref(struct got_object_id *id, const char *prefix,
10107 struct got_worktree *worktree, struct got_repository *repo)
10109 const struct got_error *err = NULL;
10110 char *idstr, *ref = NULL, *refname = NULL;
10111 int histedit_in_progress;
10112 int rebase_in_progress, merge_in_progress;
10115 * Silenty refuse to create merge reference if any histedit, merge,
10116 * or rebase operation is in progress.
10118 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10119 worktree);
10120 if (err)
10121 return err;
10122 if (histedit_in_progress)
10123 return NULL;
10125 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10126 if (err)
10127 return err;
10128 if (rebase_in_progress)
10129 return NULL;
10131 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10132 repo);
10133 if (err)
10134 return err;
10135 if (merge_in_progress)
10136 return NULL;
10138 err = got_object_id_str(&idstr, id);
10139 if (err)
10140 return err;
10142 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10143 if (err)
10144 goto done;
10146 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10147 err = got_error_from_errno("asprintf");
10148 goto done;
10151 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10152 -1, repo);
10153 done:
10154 free(ref);
10155 free(idstr);
10156 free(refname);
10157 return err;
10160 __dead static void
10161 usage_cherrypick(void)
10163 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10164 getprogname());
10165 exit(1);
10168 static const struct got_error *
10169 cmd_cherrypick(int argc, char *argv[])
10171 const struct got_error *error = NULL;
10172 struct got_worktree *worktree = NULL;
10173 struct got_repository *repo = NULL;
10174 char *cwd = NULL, *commit_id_str = NULL;
10175 struct got_object_id *commit_id = NULL;
10176 struct got_commit_object *commit = NULL;
10177 struct got_object_qid *pid;
10178 int ch, list_refs = 0, remove_refs = 0;
10179 struct got_update_progress_arg upa;
10180 int *pack_fds = NULL;
10182 #ifndef PROFILE
10183 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10184 "unveil", NULL) == -1)
10185 err(1, "pledge");
10186 #endif
10188 while ((ch = getopt(argc, argv, "lX")) != -1) {
10189 switch (ch) {
10190 case 'l':
10191 list_refs = 1;
10192 break;
10193 case 'X':
10194 remove_refs = 1;
10195 break;
10196 default:
10197 usage_cherrypick();
10198 /* NOTREACHED */
10202 argc -= optind;
10203 argv += optind;
10205 if (list_refs || remove_refs) {
10206 if (argc != 0 && argc != 1)
10207 usage_cherrypick();
10208 } else if (argc != 1)
10209 usage_cherrypick();
10210 if (list_refs && remove_refs)
10211 option_conflict('l', 'X');
10213 cwd = getcwd(NULL, 0);
10214 if (cwd == NULL) {
10215 error = got_error_from_errno("getcwd");
10216 goto done;
10219 error = got_repo_pack_fds_open(&pack_fds);
10220 if (error != NULL)
10221 goto done;
10223 error = got_worktree_open(&worktree, cwd);
10224 if (error) {
10225 if (list_refs || remove_refs) {
10226 if (error->code != GOT_ERR_NOT_WORKTREE)
10227 goto done;
10228 } else {
10229 if (error->code == GOT_ERR_NOT_WORKTREE)
10230 error = wrap_not_worktree_error(error,
10231 "cherrypick", cwd);
10232 goto done;
10236 error = got_repo_open(&repo,
10237 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10238 NULL, pack_fds);
10239 if (error != NULL)
10240 goto done;
10242 error = apply_unveil(got_repo_get_path(repo), 0,
10243 worktree ? got_worktree_get_root_path(worktree) : NULL);
10244 if (error)
10245 goto done;
10247 if (list_refs || remove_refs) {
10248 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10249 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10250 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10251 goto done;
10254 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10255 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10256 if (error)
10257 goto done;
10258 error = got_object_id_str(&commit_id_str, commit_id);
10259 if (error)
10260 goto done;
10262 error = got_object_open_as_commit(&commit, repo, commit_id);
10263 if (error)
10264 goto done;
10265 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10266 memset(&upa, 0, sizeof(upa));
10267 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10268 commit_id, repo, update_progress, &upa, check_cancelled,
10269 NULL);
10270 if (error != NULL)
10271 goto done;
10273 if (upa.did_something) {
10274 error = logmsg_ref(commit_id,
10275 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10276 if (error)
10277 goto done;
10278 printf("Merged commit %s\n", commit_id_str);
10280 print_merge_progress_stats(&upa);
10281 done:
10282 free(cwd);
10283 if (commit)
10284 got_object_commit_close(commit);
10285 free(commit_id_str);
10286 if (worktree)
10287 got_worktree_close(worktree);
10288 if (repo) {
10289 const struct got_error *close_err = got_repo_close(repo);
10290 if (error == NULL)
10291 error = close_err;
10293 if (pack_fds) {
10294 const struct got_error *pack_err =
10295 got_repo_pack_fds_close(pack_fds);
10296 if (error == NULL)
10297 error = pack_err;
10300 return error;
10303 __dead static void
10304 usage_backout(void)
10306 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10307 exit(1);
10310 static const struct got_error *
10311 cmd_backout(int argc, char *argv[])
10313 const struct got_error *error = NULL;
10314 struct got_worktree *worktree = NULL;
10315 struct got_repository *repo = NULL;
10316 char *cwd = NULL, *commit_id_str = NULL;
10317 struct got_object_id *commit_id = NULL;
10318 struct got_commit_object *commit = NULL;
10319 struct got_object_qid *pid;
10320 int ch, list_refs = 0, remove_refs = 0;
10321 struct got_update_progress_arg upa;
10322 int *pack_fds = NULL;
10324 #ifndef PROFILE
10325 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10326 "unveil", NULL) == -1)
10327 err(1, "pledge");
10328 #endif
10330 while ((ch = getopt(argc, argv, "lX")) != -1) {
10331 switch (ch) {
10332 case 'l':
10333 list_refs = 1;
10334 break;
10335 case 'X':
10336 remove_refs = 1;
10337 break;
10338 default:
10339 usage_backout();
10340 /* NOTREACHED */
10344 argc -= optind;
10345 argv += optind;
10347 if (list_refs || remove_refs) {
10348 if (argc != 0 && argc != 1)
10349 usage_backout();
10350 } else if (argc != 1)
10351 usage_backout();
10352 if (list_refs && remove_refs)
10353 option_conflict('l', 'X');
10355 cwd = getcwd(NULL, 0);
10356 if (cwd == NULL) {
10357 error = got_error_from_errno("getcwd");
10358 goto done;
10361 error = got_repo_pack_fds_open(&pack_fds);
10362 if (error != NULL)
10363 goto done;
10365 error = got_worktree_open(&worktree, cwd);
10366 if (error) {
10367 if (list_refs || remove_refs) {
10368 if (error->code != GOT_ERR_NOT_WORKTREE)
10369 goto done;
10370 } else {
10371 if (error->code == GOT_ERR_NOT_WORKTREE)
10372 error = wrap_not_worktree_error(error,
10373 "backout", cwd);
10374 goto done;
10378 error = got_repo_open(&repo,
10379 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10380 NULL, pack_fds);
10381 if (error != NULL)
10382 goto done;
10384 error = apply_unveil(got_repo_get_path(repo), 0,
10385 worktree ? got_worktree_get_root_path(worktree) : NULL);
10386 if (error)
10387 goto done;
10389 if (list_refs || remove_refs) {
10390 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10391 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10392 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10393 goto done;
10396 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10397 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10398 if (error)
10399 goto done;
10400 error = got_object_id_str(&commit_id_str, commit_id);
10401 if (error)
10402 goto done;
10404 error = got_object_open_as_commit(&commit, repo, commit_id);
10405 if (error)
10406 goto done;
10407 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10408 if (pid == NULL) {
10409 error = got_error(GOT_ERR_ROOT_COMMIT);
10410 goto done;
10413 memset(&upa, 0, sizeof(upa));
10414 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10415 repo, update_progress, &upa, check_cancelled, NULL);
10416 if (error != NULL)
10417 goto done;
10419 if (upa.did_something) {
10420 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10421 worktree, repo);
10422 if (error)
10423 goto done;
10424 printf("Backed out commit %s\n", commit_id_str);
10426 print_merge_progress_stats(&upa);
10427 done:
10428 free(cwd);
10429 if (commit)
10430 got_object_commit_close(commit);
10431 free(commit_id_str);
10432 if (worktree)
10433 got_worktree_close(worktree);
10434 if (repo) {
10435 const struct got_error *close_err = got_repo_close(repo);
10436 if (error == NULL)
10437 error = close_err;
10439 if (pack_fds) {
10440 const struct got_error *pack_err =
10441 got_repo_pack_fds_close(pack_fds);
10442 if (error == NULL)
10443 error = pack_err;
10445 return error;
10448 __dead static void
10449 usage_rebase(void)
10451 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10452 exit(1);
10455 static void
10456 trim_logmsg(char *logmsg, int limit)
10458 char *nl;
10459 size_t len;
10461 len = strlen(logmsg);
10462 if (len > limit)
10463 len = limit;
10464 logmsg[len] = '\0';
10465 nl = strchr(logmsg, '\n');
10466 if (nl)
10467 *nl = '\0';
10470 static const struct got_error *
10471 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10473 const struct got_error *err;
10474 char *logmsg0 = NULL;
10475 const char *s;
10477 err = got_object_commit_get_logmsg(&logmsg0, commit);
10478 if (err)
10479 return err;
10481 s = logmsg0;
10482 while (isspace((unsigned char)s[0]))
10483 s++;
10485 *logmsg = strdup(s);
10486 if (*logmsg == NULL) {
10487 err = got_error_from_errno("strdup");
10488 goto done;
10491 trim_logmsg(*logmsg, limit);
10492 done:
10493 free(logmsg0);
10494 return err;
10497 static const struct got_error *
10498 show_rebase_merge_conflict(struct got_object_id *id,
10499 struct got_repository *repo)
10501 const struct got_error *err;
10502 struct got_commit_object *commit = NULL;
10503 char *id_str = NULL, *logmsg = NULL;
10505 err = got_object_open_as_commit(&commit, repo, id);
10506 if (err)
10507 return err;
10509 err = got_object_id_str(&id_str, id);
10510 if (err)
10511 goto done;
10513 id_str[12] = '\0';
10515 err = get_short_logmsg(&logmsg, 42, commit);
10516 if (err)
10517 goto done;
10519 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10520 done:
10521 free(id_str);
10522 got_object_commit_close(commit);
10523 free(logmsg);
10524 return err;
10527 static const struct got_error *
10528 show_rebase_progress(struct got_commit_object *commit,
10529 struct got_object_id *old_id, struct got_object_id *new_id)
10531 const struct got_error *err;
10532 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10534 err = got_object_id_str(&old_id_str, old_id);
10535 if (err)
10536 goto done;
10538 if (new_id) {
10539 err = got_object_id_str(&new_id_str, new_id);
10540 if (err)
10541 goto done;
10544 old_id_str[12] = '\0';
10545 if (new_id_str)
10546 new_id_str[12] = '\0';
10548 err = get_short_logmsg(&logmsg, 42, commit);
10549 if (err)
10550 goto done;
10552 printf("%s -> %s: %s\n", old_id_str,
10553 new_id_str ? new_id_str : "no-op change", logmsg);
10554 done:
10555 free(old_id_str);
10556 free(new_id_str);
10557 free(logmsg);
10558 return err;
10561 static const struct got_error *
10562 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10563 struct got_reference *branch, struct got_reference *tmp_branch,
10564 struct got_repository *repo, int create_backup)
10566 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10567 return got_worktree_rebase_complete(worktree, fileindex,
10568 tmp_branch, branch, repo, create_backup);
10571 static const struct got_error *
10572 rebase_commit(struct got_pathlist_head *merged_paths,
10573 struct got_worktree *worktree, struct got_fileindex *fileindex,
10574 struct got_reference *tmp_branch, const char *committer,
10575 struct got_object_id *commit_id, int allow_conflict,
10576 struct got_repository *repo)
10578 const struct got_error *error;
10579 struct got_commit_object *commit;
10580 struct got_object_id *new_commit_id;
10582 error = got_object_open_as_commit(&commit, repo, commit_id);
10583 if (error)
10584 return error;
10586 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10587 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10588 allow_conflict, repo);
10589 if (error) {
10590 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10591 goto done;
10592 error = show_rebase_progress(commit, commit_id, NULL);
10593 } else {
10594 error = show_rebase_progress(commit, commit_id, new_commit_id);
10595 free(new_commit_id);
10597 done:
10598 got_object_commit_close(commit);
10599 return error;
10602 struct check_path_prefix_arg {
10603 const char *path_prefix;
10604 size_t len;
10605 int errcode;
10608 static const struct got_error *
10609 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10610 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10611 struct got_object_id *id1, struct got_object_id *id2,
10612 const char *path1, const char *path2,
10613 mode_t mode1, mode_t mode2, struct got_repository *repo)
10615 struct check_path_prefix_arg *a = arg;
10617 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10618 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10619 return got_error(a->errcode);
10621 return NULL;
10624 static const struct got_error *
10625 check_path_prefix(struct got_object_id *parent_id,
10626 struct got_object_id *commit_id, const char *path_prefix,
10627 int errcode, struct got_repository *repo)
10629 const struct got_error *err;
10630 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10631 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10632 struct check_path_prefix_arg cpp_arg;
10634 if (got_path_is_root_dir(path_prefix))
10635 return NULL;
10637 err = got_object_open_as_commit(&commit, repo, commit_id);
10638 if (err)
10639 goto done;
10641 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10642 if (err)
10643 goto done;
10645 err = got_object_open_as_tree(&tree1, repo,
10646 got_object_commit_get_tree_id(parent_commit));
10647 if (err)
10648 goto done;
10650 err = got_object_open_as_tree(&tree2, repo,
10651 got_object_commit_get_tree_id(commit));
10652 if (err)
10653 goto done;
10655 cpp_arg.path_prefix = path_prefix;
10656 while (cpp_arg.path_prefix[0] == '/')
10657 cpp_arg.path_prefix++;
10658 cpp_arg.len = strlen(cpp_arg.path_prefix);
10659 cpp_arg.errcode = errcode;
10660 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10661 check_path_prefix_in_diff, &cpp_arg, 0);
10662 done:
10663 if (tree1)
10664 got_object_tree_close(tree1);
10665 if (tree2)
10666 got_object_tree_close(tree2);
10667 if (commit)
10668 got_object_commit_close(commit);
10669 if (parent_commit)
10670 got_object_commit_close(parent_commit);
10671 return err;
10674 static const struct got_error *
10675 collect_commits(struct got_object_id_queue *commits,
10676 struct got_object_id *initial_commit_id,
10677 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10678 const char *path_prefix, int path_prefix_errcode,
10679 struct got_repository *repo)
10681 const struct got_error *err = NULL;
10682 struct got_commit_graph *graph = NULL;
10683 struct got_object_id parent_id, commit_id;
10684 struct got_object_qid *qid;
10686 err = got_commit_graph_open(&graph, "/", 1);
10687 if (err)
10688 return err;
10690 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10691 check_cancelled, NULL);
10692 if (err)
10693 goto done;
10695 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10696 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10697 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10698 check_cancelled, NULL);
10699 if (err) {
10700 if (err->code == GOT_ERR_ITER_COMPLETED) {
10701 err = got_error_msg(GOT_ERR_ANCESTRY,
10702 "ran out of commits to rebase before "
10703 "youngest common ancestor commit has "
10704 "been reached?!?");
10706 goto done;
10707 } else {
10708 err = check_path_prefix(&parent_id, &commit_id,
10709 path_prefix, path_prefix_errcode, repo);
10710 if (err)
10711 goto done;
10713 err = got_object_qid_alloc(&qid, &commit_id);
10714 if (err)
10715 goto done;
10716 STAILQ_INSERT_HEAD(commits, qid, entry);
10718 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10721 done:
10722 got_commit_graph_close(graph);
10723 return err;
10726 static const struct got_error *
10727 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10729 const struct got_error *err = NULL;
10730 time_t committer_time;
10731 struct tm tm;
10732 char datebuf[11]; /* YYYY-MM-DD + NUL */
10733 char *author0 = NULL, *author, *smallerthan;
10734 char *logmsg0 = NULL, *logmsg, *newline;
10736 committer_time = got_object_commit_get_committer_time(commit);
10737 if (gmtime_r(&committer_time, &tm) == NULL)
10738 return got_error_from_errno("gmtime_r");
10739 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10740 return got_error(GOT_ERR_NO_SPACE);
10742 author0 = strdup(got_object_commit_get_author(commit));
10743 if (author0 == NULL)
10744 return got_error_from_errno("strdup");
10745 author = author0;
10746 smallerthan = strchr(author, '<');
10747 if (smallerthan && smallerthan[1] != '\0')
10748 author = smallerthan + 1;
10749 author[strcspn(author, "@>")] = '\0';
10751 err = got_object_commit_get_logmsg(&logmsg0, commit);
10752 if (err)
10753 goto done;
10754 logmsg = logmsg0;
10755 while (*logmsg == '\n')
10756 logmsg++;
10757 newline = strchr(logmsg, '\n');
10758 if (newline)
10759 *newline = '\0';
10761 if (asprintf(brief_str, "%s %s %s",
10762 datebuf, author, logmsg) == -1)
10763 err = got_error_from_errno("asprintf");
10764 done:
10765 free(author0);
10766 free(logmsg0);
10767 return err;
10770 static const struct got_error *
10771 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10772 struct got_repository *repo)
10774 const struct got_error *err;
10775 char *id_str;
10777 err = got_object_id_str(&id_str, id);
10778 if (err)
10779 return err;
10781 err = got_ref_delete(ref, repo);
10782 if (err)
10783 goto done;
10785 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10786 done:
10787 free(id_str);
10788 return err;
10791 static const struct got_error *
10792 print_backup_ref(const char *branch_name, const char *new_id_str,
10793 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10794 struct got_reflist_object_id_map *refs_idmap,
10795 struct got_repository *repo)
10797 const struct got_error *err = NULL;
10798 struct got_reflist_head *refs;
10799 char *refs_str = NULL;
10800 struct got_object_id *new_commit_id = NULL;
10801 struct got_commit_object *new_commit = NULL;
10802 char *new_commit_brief_str = NULL;
10803 struct got_object_id *yca_id = NULL;
10804 struct got_commit_object *yca_commit = NULL;
10805 char *yca_id_str = NULL, *yca_brief_str = NULL;
10806 char *custom_refs_str;
10808 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10809 return got_error_from_errno("asprintf");
10811 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10812 0, 0, refs_idmap, custom_refs_str, NULL);
10813 if (err)
10814 goto done;
10816 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10817 if (err)
10818 goto done;
10820 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10821 if (refs) {
10822 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10823 if (err)
10824 goto done;
10827 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10828 if (err)
10829 goto done;
10831 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10832 if (err)
10833 goto done;
10835 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10836 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10837 if (err)
10838 goto done;
10840 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10841 refs_str ? " (" : "", refs_str ? refs_str : "",
10842 refs_str ? ")" : "", new_commit_brief_str);
10843 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10844 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10845 free(refs_str);
10846 refs_str = NULL;
10848 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10849 if (err)
10850 goto done;
10852 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10853 if (err)
10854 goto done;
10856 err = got_object_id_str(&yca_id_str, yca_id);
10857 if (err)
10858 goto done;
10860 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10861 if (refs) {
10862 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10863 if (err)
10864 goto done;
10866 printf("history forked at %s%s%s%s\n %s\n",
10867 yca_id_str,
10868 refs_str ? " (" : "", refs_str ? refs_str : "",
10869 refs_str ? ")" : "", yca_brief_str);
10871 done:
10872 free(custom_refs_str);
10873 free(new_commit_id);
10874 free(refs_str);
10875 free(yca_id);
10876 free(yca_id_str);
10877 free(yca_brief_str);
10878 if (new_commit)
10879 got_object_commit_close(new_commit);
10880 if (yca_commit)
10881 got_object_commit_close(yca_commit);
10883 return err;
10886 static const struct got_error *
10887 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10888 struct got_repository *repo)
10890 const struct got_error *err;
10891 struct got_reflist_head refs;
10892 struct got_reflist_entry *re;
10893 char *uuidstr = NULL;
10894 static char msg[160];
10896 TAILQ_INIT(&refs);
10898 err = got_worktree_get_uuid(&uuidstr, worktree);
10899 if (err)
10900 goto done;
10902 err = got_ref_list(&refs, repo, "refs/got/worktree",
10903 got_ref_cmp_by_name, repo);
10904 if (err)
10905 goto done;
10907 TAILQ_FOREACH(re, &refs, entry) {
10908 const char *cmd, *refname, *type;
10910 refname = got_ref_get_name(re->ref);
10912 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10913 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10914 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10915 cmd = "cherrypick";
10916 type = "cherrypicked";
10917 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10918 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10919 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10920 cmd = "backout";
10921 type = "backed-out";
10922 } else
10923 continue;
10925 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10926 continue;
10928 snprintf(msg, sizeof(msg),
10929 "work tree has references created by %s commits which "
10930 "must be removed with 'got %s -X' before running the %s "
10931 "command", type, cmd, caller);
10932 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10933 goto done;
10936 done:
10937 free(uuidstr);
10938 got_ref_list_free(&refs);
10939 return err;
10942 static const struct got_error *
10943 process_backup_refs(const char *backup_ref_prefix,
10944 const char *wanted_branch_name,
10945 int delete, struct got_repository *repo)
10947 const struct got_error *err;
10948 struct got_reflist_head refs, backup_refs;
10949 struct got_reflist_entry *re;
10950 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10951 struct got_object_id *old_commit_id = NULL;
10952 char *branch_name = NULL;
10953 struct got_commit_object *old_commit = NULL;
10954 struct got_reflist_object_id_map *refs_idmap = NULL;
10955 int wanted_branch_found = 0;
10957 TAILQ_INIT(&refs);
10958 TAILQ_INIT(&backup_refs);
10960 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10961 if (err)
10962 return err;
10964 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10965 if (err)
10966 goto done;
10968 if (wanted_branch_name) {
10969 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10970 wanted_branch_name += 11;
10973 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10974 got_ref_cmp_by_commit_timestamp_descending, repo);
10975 if (err)
10976 goto done;
10978 TAILQ_FOREACH(re, &backup_refs, entry) {
10979 const char *refname = got_ref_get_name(re->ref);
10980 char *slash;
10982 err = check_cancelled(NULL);
10983 if (err)
10984 break;
10986 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10987 if (err)
10988 break;
10990 err = got_object_open_as_commit(&old_commit, repo,
10991 old_commit_id);
10992 if (err)
10993 break;
10995 if (strncmp(backup_ref_prefix, refname,
10996 backup_ref_prefix_len) == 0)
10997 refname += backup_ref_prefix_len;
10999 while (refname[0] == '/')
11000 refname++;
11002 branch_name = strdup(refname);
11003 if (branch_name == NULL) {
11004 err = got_error_from_errno("strdup");
11005 break;
11007 slash = strrchr(branch_name, '/');
11008 if (slash) {
11009 *slash = '\0';
11010 refname += strlen(branch_name) + 1;
11013 if (wanted_branch_name == NULL ||
11014 strcmp(wanted_branch_name, branch_name) == 0) {
11015 wanted_branch_found = 1;
11016 if (delete) {
11017 err = delete_backup_ref(re->ref,
11018 old_commit_id, repo);
11019 } else {
11020 err = print_backup_ref(branch_name, refname,
11021 old_commit_id, old_commit, refs_idmap,
11022 repo);
11024 if (err)
11025 break;
11028 free(old_commit_id);
11029 old_commit_id = NULL;
11030 free(branch_name);
11031 branch_name = NULL;
11032 got_object_commit_close(old_commit);
11033 old_commit = NULL;
11036 if (wanted_branch_name && !wanted_branch_found) {
11037 err = got_error_fmt(GOT_ERR_NOT_REF,
11038 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11040 done:
11041 if (refs_idmap)
11042 got_reflist_object_id_map_free(refs_idmap);
11043 got_ref_list_free(&refs);
11044 got_ref_list_free(&backup_refs);
11045 free(old_commit_id);
11046 free(branch_name);
11047 if (old_commit)
11048 got_object_commit_close(old_commit);
11049 return err;
11052 static const struct got_error *
11053 abort_progress(void *arg, unsigned char status, const char *path)
11056 * Unversioned files should not clutter progress output when
11057 * an operation is aborted.
11059 if (status == GOT_STATUS_UNVERSIONED)
11060 return NULL;
11062 return update_progress(arg, status, path);
11065 static const struct got_error *
11066 cmd_rebase(int argc, char *argv[])
11068 const struct got_error *error = NULL;
11069 struct got_worktree *worktree = NULL;
11070 struct got_repository *repo = NULL;
11071 struct got_fileindex *fileindex = NULL;
11072 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11073 struct got_reference *branch = NULL;
11074 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11075 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11076 struct got_object_id *resume_commit_id = NULL;
11077 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11078 struct got_object_id *head_commit_id = NULL;
11079 struct got_reference *head_ref = NULL;
11080 struct got_commit_object *commit = NULL;
11081 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11082 int histedit_in_progress = 0, merge_in_progress = 0;
11083 int create_backup = 1, list_backups = 0, delete_backups = 0;
11084 int allow_conflict = 0;
11085 struct got_object_id_queue commits;
11086 struct got_pathlist_head merged_paths;
11087 const struct got_object_id_queue *parent_ids;
11088 struct got_object_qid *qid, *pid;
11089 struct got_update_progress_arg upa;
11090 int *pack_fds = NULL;
11092 STAILQ_INIT(&commits);
11093 TAILQ_INIT(&merged_paths);
11094 memset(&upa, 0, sizeof(upa));
11096 #ifndef PROFILE
11097 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11098 "unveil", NULL) == -1)
11099 err(1, "pledge");
11100 #endif
11102 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11103 switch (ch) {
11104 case 'a':
11105 abort_rebase = 1;
11106 break;
11107 case 'C':
11108 allow_conflict = 1;
11109 break;
11110 case 'c':
11111 continue_rebase = 1;
11112 break;
11113 case 'l':
11114 list_backups = 1;
11115 break;
11116 case 'X':
11117 delete_backups = 1;
11118 break;
11119 default:
11120 usage_rebase();
11121 /* NOTREACHED */
11125 argc -= optind;
11126 argv += optind;
11128 if (list_backups) {
11129 if (abort_rebase)
11130 option_conflict('l', 'a');
11131 if (allow_conflict)
11132 option_conflict('l', 'C');
11133 if (continue_rebase)
11134 option_conflict('l', 'c');
11135 if (delete_backups)
11136 option_conflict('l', 'X');
11137 if (argc != 0 && argc != 1)
11138 usage_rebase();
11139 } else if (delete_backups) {
11140 if (abort_rebase)
11141 option_conflict('X', 'a');
11142 if (allow_conflict)
11143 option_conflict('X', 'C');
11144 if (continue_rebase)
11145 option_conflict('X', 'c');
11146 if (list_backups)
11147 option_conflict('l', 'X');
11148 if (argc != 0 && argc != 1)
11149 usage_rebase();
11150 } else if (allow_conflict) {
11151 if (abort_rebase)
11152 option_conflict('C', 'a');
11153 if (!continue_rebase)
11154 errx(1, "-C option requires -c");
11155 } else {
11156 if (abort_rebase && continue_rebase)
11157 usage_rebase();
11158 else if (abort_rebase || continue_rebase) {
11159 if (argc != 0)
11160 usage_rebase();
11161 } else if (argc != 1)
11162 usage_rebase();
11165 cwd = getcwd(NULL, 0);
11166 if (cwd == NULL) {
11167 error = got_error_from_errno("getcwd");
11168 goto done;
11171 error = got_repo_pack_fds_open(&pack_fds);
11172 if (error != NULL)
11173 goto done;
11175 error = got_worktree_open(&worktree, cwd);
11176 if (error) {
11177 if (list_backups || delete_backups) {
11178 if (error->code != GOT_ERR_NOT_WORKTREE)
11179 goto done;
11180 } else {
11181 if (error->code == GOT_ERR_NOT_WORKTREE)
11182 error = wrap_not_worktree_error(error,
11183 "rebase", cwd);
11184 goto done;
11188 error = get_gitconfig_path(&gitconfig_path);
11189 if (error)
11190 goto done;
11191 error = got_repo_open(&repo,
11192 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11193 gitconfig_path, pack_fds);
11194 if (error != NULL)
11195 goto done;
11197 if (worktree != NULL && !list_backups && !delete_backups) {
11198 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11199 if (error)
11200 goto done;
11203 error = get_author(&committer, repo, worktree);
11204 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11205 goto done;
11207 error = apply_unveil(got_repo_get_path(repo), 0,
11208 worktree ? got_worktree_get_root_path(worktree) : NULL);
11209 if (error)
11210 goto done;
11212 if (list_backups || delete_backups) {
11213 error = process_backup_refs(
11214 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11215 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11216 goto done; /* nothing else to do */
11219 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11220 worktree);
11221 if (error)
11222 goto done;
11223 if (histedit_in_progress) {
11224 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11225 goto done;
11228 error = got_worktree_merge_in_progress(&merge_in_progress,
11229 worktree, repo);
11230 if (error)
11231 goto done;
11232 if (merge_in_progress) {
11233 error = got_error(GOT_ERR_MERGE_BUSY);
11234 goto done;
11237 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11238 if (error)
11239 goto done;
11241 if (abort_rebase) {
11242 if (!rebase_in_progress) {
11243 error = got_error(GOT_ERR_NOT_REBASING);
11244 goto done;
11246 error = got_worktree_rebase_continue(&resume_commit_id,
11247 &new_base_branch, &tmp_branch, &branch, &fileindex,
11248 worktree, repo);
11249 if (error)
11250 goto done;
11251 printf("Switching work tree to %s\n",
11252 got_ref_get_symref_target(new_base_branch));
11253 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11254 new_base_branch, abort_progress, &upa);
11255 if (error)
11256 goto done;
11257 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11258 print_merge_progress_stats(&upa);
11259 goto done; /* nothing else to do */
11262 if (continue_rebase) {
11263 if (!rebase_in_progress) {
11264 error = got_error(GOT_ERR_NOT_REBASING);
11265 goto done;
11267 error = got_worktree_rebase_continue(&resume_commit_id,
11268 &new_base_branch, &tmp_branch, &branch, &fileindex,
11269 worktree, repo);
11270 if (error)
11271 goto done;
11273 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11274 committer, resume_commit_id, allow_conflict, repo);
11275 if (error)
11276 goto done;
11278 yca_id = got_object_id_dup(resume_commit_id);
11279 if (yca_id == NULL) {
11280 error = got_error_from_errno("got_object_id_dup");
11281 goto done;
11283 } else {
11284 error = got_ref_open(&branch, repo, argv[0], 0);
11285 if (error != NULL)
11286 goto done;
11287 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11288 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11289 "will not rebase a branch which lives outside "
11290 "the \"refs/heads/\" reference namespace");
11291 goto done;
11295 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11296 if (error)
11297 goto done;
11299 if (!continue_rebase) {
11300 struct got_object_id *base_commit_id;
11302 error = got_ref_open(&head_ref, repo,
11303 got_worktree_get_head_ref_name(worktree), 0);
11304 if (error)
11305 goto done;
11306 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11307 if (error)
11308 goto done;
11309 base_commit_id = got_worktree_get_base_commit_id(worktree);
11310 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11311 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11312 goto done;
11315 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11316 base_commit_id, branch_head_commit_id, 1, repo,
11317 check_cancelled, NULL);
11318 if (error) {
11319 if (error->code == GOT_ERR_ANCESTRY) {
11320 error = got_error_msg(GOT_ERR_ANCESTRY,
11321 "specified branch shares no common "
11322 "ancestry with work tree's branch");
11324 goto done;
11327 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11328 if (error) {
11329 if (error->code != GOT_ERR_ANCESTRY)
11330 goto done;
11331 error = NULL;
11332 } else {
11333 struct got_pathlist_head paths;
11334 printf("%s is already based on %s\n",
11335 got_ref_get_name(branch),
11336 got_worktree_get_head_ref_name(worktree));
11337 error = switch_head_ref(branch, branch_head_commit_id,
11338 worktree, repo);
11339 if (error)
11340 goto done;
11341 error = got_worktree_set_base_commit_id(worktree, repo,
11342 branch_head_commit_id);
11343 if (error)
11344 goto done;
11345 TAILQ_INIT(&paths);
11346 error = got_pathlist_append(&paths, "", NULL);
11347 if (error)
11348 goto done;
11349 error = got_worktree_checkout_files(worktree,
11350 &paths, repo, update_progress, &upa,
11351 check_cancelled, NULL);
11352 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11353 if (error)
11354 goto done;
11355 if (upa.did_something) {
11356 char *id_str;
11357 error = got_object_id_str(&id_str,
11358 branch_head_commit_id);
11359 if (error)
11360 goto done;
11361 printf("Updated to %s: %s\n",
11362 got_worktree_get_head_ref_name(worktree),
11363 id_str);
11364 free(id_str);
11365 } else
11366 printf("Already up-to-date\n");
11367 print_update_progress_stats(&upa);
11368 goto done;
11372 commit_id = branch_head_commit_id;
11373 error = got_object_open_as_commit(&commit, repo, commit_id);
11374 if (error)
11375 goto done;
11377 parent_ids = got_object_commit_get_parent_ids(commit);
11378 pid = STAILQ_FIRST(parent_ids);
11379 if (pid) {
11380 error = collect_commits(&commits, commit_id, &pid->id,
11381 yca_id, got_worktree_get_path_prefix(worktree),
11382 GOT_ERR_REBASE_PATH, repo);
11383 if (error)
11384 goto done;
11387 got_object_commit_close(commit);
11388 commit = NULL;
11390 if (!continue_rebase) {
11391 error = got_worktree_rebase_prepare(&new_base_branch,
11392 &tmp_branch, &fileindex, worktree, branch, repo);
11393 if (error)
11394 goto done;
11397 if (STAILQ_EMPTY(&commits)) {
11398 if (continue_rebase) {
11399 error = rebase_complete(worktree, fileindex,
11400 branch, tmp_branch, repo, create_backup);
11401 goto done;
11402 } else {
11403 /* Fast-forward the reference of the branch. */
11404 struct got_object_id *new_head_commit_id;
11405 char *id_str;
11406 error = got_ref_resolve(&new_head_commit_id, repo,
11407 new_base_branch);
11408 if (error)
11409 goto done;
11410 error = got_object_id_str(&id_str, new_head_commit_id);
11411 if (error)
11412 goto done;
11413 printf("Forwarding %s to commit %s\n",
11414 got_ref_get_name(branch), id_str);
11415 free(id_str);
11416 error = got_ref_change_ref(branch,
11417 new_head_commit_id);
11418 if (error)
11419 goto done;
11420 /* No backup needed since objects did not change. */
11421 create_backup = 0;
11425 pid = NULL;
11426 STAILQ_FOREACH(qid, &commits, entry) {
11428 commit_id = &qid->id;
11429 parent_id = pid ? &pid->id : yca_id;
11430 pid = qid;
11432 memset(&upa, 0, sizeof(upa));
11433 error = got_worktree_rebase_merge_files(&merged_paths,
11434 worktree, fileindex, parent_id, commit_id, repo,
11435 update_progress, &upa, check_cancelled, NULL);
11436 if (error)
11437 goto done;
11439 print_merge_progress_stats(&upa);
11440 if (upa.conflicts > 0 || upa.missing > 0 ||
11441 upa.not_deleted > 0 || upa.unversioned > 0) {
11442 if (upa.conflicts > 0) {
11443 error = show_rebase_merge_conflict(&qid->id,
11444 repo);
11445 if (error)
11446 goto done;
11448 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11449 break;
11452 error = rebase_commit(&merged_paths, worktree, fileindex,
11453 tmp_branch, committer, commit_id, 0, repo);
11454 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11455 if (error)
11456 goto done;
11459 if (upa.conflicts > 0 || upa.missing > 0 ||
11460 upa.not_deleted > 0 || upa.unversioned > 0) {
11461 error = got_worktree_rebase_postpone(worktree, fileindex);
11462 if (error)
11463 goto done;
11464 if (upa.conflicts > 0 && upa.missing == 0 &&
11465 upa.not_deleted == 0 && upa.unversioned == 0) {
11466 error = got_error_msg(GOT_ERR_CONFLICTS,
11467 "conflicts must be resolved before rebasing "
11468 "can continue");
11469 } else if (upa.conflicts > 0) {
11470 error = got_error_msg(GOT_ERR_CONFLICTS,
11471 "conflicts must be resolved before rebasing "
11472 "can continue; changes destined for some "
11473 "files were not yet merged and should be "
11474 "merged manually if required before the "
11475 "rebase operation is continued");
11476 } else {
11477 error = got_error_msg(GOT_ERR_CONFLICTS,
11478 "changes destined for some files were not "
11479 "yet merged and should be merged manually "
11480 "if required before the rebase operation "
11481 "is continued");
11483 } else
11484 error = rebase_complete(worktree, fileindex, branch,
11485 tmp_branch, repo, create_backup);
11486 done:
11487 free(cwd);
11488 free(committer);
11489 free(gitconfig_path);
11490 got_object_id_queue_free(&commits);
11491 free(branch_head_commit_id);
11492 free(resume_commit_id);
11493 free(head_commit_id);
11494 free(yca_id);
11495 if (commit)
11496 got_object_commit_close(commit);
11497 if (branch)
11498 got_ref_close(branch);
11499 if (new_base_branch)
11500 got_ref_close(new_base_branch);
11501 if (tmp_branch)
11502 got_ref_close(tmp_branch);
11503 if (head_ref)
11504 got_ref_close(head_ref);
11505 if (worktree)
11506 got_worktree_close(worktree);
11507 if (repo) {
11508 const struct got_error *close_err = got_repo_close(repo);
11509 if (error == NULL)
11510 error = close_err;
11512 if (pack_fds) {
11513 const struct got_error *pack_err =
11514 got_repo_pack_fds_close(pack_fds);
11515 if (error == NULL)
11516 error = pack_err;
11518 return error;
11521 __dead static void
11522 usage_histedit(void)
11524 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11525 "[branch]\n", getprogname());
11526 exit(1);
11529 #define GOT_HISTEDIT_PICK 'p'
11530 #define GOT_HISTEDIT_EDIT 'e'
11531 #define GOT_HISTEDIT_FOLD 'f'
11532 #define GOT_HISTEDIT_DROP 'd'
11533 #define GOT_HISTEDIT_MESG 'm'
11535 static const struct got_histedit_cmd {
11536 unsigned char code;
11537 const char *name;
11538 const char *desc;
11539 } got_histedit_cmds[] = {
11540 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11541 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11542 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11543 "be used" },
11544 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11545 { GOT_HISTEDIT_MESG, "mesg",
11546 "single-line log message for commit above (open editor if empty)" },
11549 struct got_histedit_list_entry {
11550 TAILQ_ENTRY(got_histedit_list_entry) entry;
11551 struct got_object_id *commit_id;
11552 const struct got_histedit_cmd *cmd;
11553 char *logmsg;
11555 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11557 static const struct got_error *
11558 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11559 FILE *f, struct got_repository *repo)
11561 const struct got_error *err = NULL;
11562 char *logmsg = NULL, *id_str = NULL;
11563 struct got_commit_object *commit = NULL;
11564 int n;
11566 err = got_object_open_as_commit(&commit, repo, commit_id);
11567 if (err)
11568 goto done;
11570 err = get_short_logmsg(&logmsg, 34, commit);
11571 if (err)
11572 goto done;
11574 err = got_object_id_str(&id_str, commit_id);
11575 if (err)
11576 goto done;
11578 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11579 if (n < 0)
11580 err = got_ferror(f, GOT_ERR_IO);
11581 done:
11582 if (commit)
11583 got_object_commit_close(commit);
11584 free(id_str);
11585 free(logmsg);
11586 return err;
11589 static const struct got_error *
11590 histedit_write_commit_list(struct got_object_id_queue *commits,
11591 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11592 int edit_only, struct got_repository *repo)
11594 const struct got_error *err = NULL;
11595 struct got_object_qid *qid;
11596 const char *histedit_cmd = NULL;
11598 if (STAILQ_EMPTY(commits))
11599 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11601 STAILQ_FOREACH(qid, commits, entry) {
11602 histedit_cmd = got_histedit_cmds[0].name;
11603 if (drop_only)
11604 histedit_cmd = "drop";
11605 else if (edit_only)
11606 histedit_cmd = "edit";
11607 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11608 histedit_cmd = "fold";
11609 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11610 if (err)
11611 break;
11612 if (edit_logmsg_only) {
11613 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11614 if (n < 0) {
11615 err = got_ferror(f, GOT_ERR_IO);
11616 break;
11621 return err;
11624 static const struct got_error *
11625 write_cmd_list(FILE *f, const char *branch_name,
11626 struct got_object_id_queue *commits)
11628 const struct got_error *err = NULL;
11629 size_t i;
11630 int n;
11631 char *id_str;
11632 struct got_object_qid *qid;
11634 qid = STAILQ_FIRST(commits);
11635 err = got_object_id_str(&id_str, &qid->id);
11636 if (err)
11637 return err;
11639 n = fprintf(f,
11640 "# Editing the history of branch '%s' starting at\n"
11641 "# commit %s\n"
11642 "# Commits will be processed in order from top to "
11643 "bottom of this file.\n", branch_name, id_str);
11644 if (n < 0) {
11645 err = got_ferror(f, GOT_ERR_IO);
11646 goto done;
11649 n = fprintf(f, "# Available histedit commands:\n");
11650 if (n < 0) {
11651 err = got_ferror(f, GOT_ERR_IO);
11652 goto done;
11655 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11656 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11657 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11658 cmd->desc);
11659 if (n < 0) {
11660 err = got_ferror(f, GOT_ERR_IO);
11661 break;
11664 done:
11665 free(id_str);
11666 return err;
11669 static const struct got_error *
11670 histedit_syntax_error(int lineno)
11672 static char msg[42];
11673 int ret;
11675 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11676 lineno);
11677 if (ret < 0 || (size_t)ret >= sizeof(msg))
11678 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11680 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11683 static const struct got_error *
11684 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11685 char *logmsg, struct got_repository *repo)
11687 const struct got_error *err;
11688 struct got_commit_object *folded_commit = NULL;
11689 char *id_str, *folded_logmsg = NULL;
11691 err = got_object_id_str(&id_str, hle->commit_id);
11692 if (err)
11693 return err;
11695 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11696 if (err)
11697 goto done;
11699 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11700 if (err)
11701 goto done;
11702 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11703 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11704 folded_logmsg) == -1) {
11705 err = got_error_from_errno("asprintf");
11707 done:
11708 if (folded_commit)
11709 got_object_commit_close(folded_commit);
11710 free(id_str);
11711 free(folded_logmsg);
11712 return err;
11715 static struct got_histedit_list_entry *
11716 get_folded_commits(struct got_histedit_list_entry *hle)
11718 struct got_histedit_list_entry *prev, *folded = NULL;
11720 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11721 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11722 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11723 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11724 folded = prev;
11725 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11728 return folded;
11731 static const struct got_error *
11732 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11733 struct got_repository *repo)
11735 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11736 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11737 const struct got_error *err = NULL;
11738 struct got_commit_object *commit = NULL;
11739 int logmsg_len;
11740 int fd = -1;
11741 struct got_histedit_list_entry *folded = NULL;
11743 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11744 if (err)
11745 return err;
11747 folded = get_folded_commits(hle);
11748 if (folded) {
11749 while (folded != hle) {
11750 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11751 folded = TAILQ_NEXT(folded, entry);
11752 continue;
11754 err = append_folded_commit_msg(&new_msg, folded,
11755 logmsg, repo);
11756 if (err)
11757 goto done;
11758 free(logmsg);
11759 logmsg = new_msg;
11760 folded = TAILQ_NEXT(folded, entry);
11764 err = got_object_id_str(&id_str, hle->commit_id);
11765 if (err)
11766 goto done;
11767 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11768 if (err)
11769 goto done;
11770 logmsg_len = asprintf(&new_msg,
11771 "%s\n# original log message of commit %s: %s",
11772 logmsg ? logmsg : "", id_str, orig_logmsg);
11773 if (logmsg_len == -1) {
11774 err = got_error_from_errno("asprintf");
11775 goto done;
11777 free(logmsg);
11778 logmsg = new_msg;
11780 err = got_object_id_str(&id_str, hle->commit_id);
11781 if (err)
11782 goto done;
11784 err = got_opentemp_named_fd(&logmsg_path, &fd,
11785 GOT_TMPDIR_STR "/got-logmsg", "");
11786 if (err)
11787 goto done;
11789 if (write(fd, logmsg, logmsg_len) == -1) {
11790 err = got_error_from_errno2("write", logmsg_path);
11791 goto done;
11793 if (close(fd) == -1) {
11794 err = got_error_from_errno2("close", logmsg_path);
11795 goto done;
11797 fd = -1;
11799 err = get_editor(&editor);
11800 if (err)
11801 goto done;
11803 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11804 logmsg_len, 0);
11805 if (err) {
11806 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11807 goto done;
11808 err = NULL;
11809 hle->logmsg = strdup(new_msg);
11810 if (hle->logmsg == NULL)
11811 err = got_error_from_errno("strdup");
11813 done:
11814 if (fd != -1 && close(fd) == -1 && err == NULL)
11815 err = got_error_from_errno2("close", logmsg_path);
11816 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11817 err = got_error_from_errno2("unlink", logmsg_path);
11818 free(logmsg_path);
11819 free(logmsg);
11820 free(orig_logmsg);
11821 free(editor);
11822 if (commit)
11823 got_object_commit_close(commit);
11824 return err;
11827 static const struct got_error *
11828 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11829 FILE *f, struct got_repository *repo)
11831 const struct got_error *err = NULL;
11832 char *line = NULL, *p, *end;
11833 size_t i, linesize = 0;
11834 ssize_t linelen;
11835 int lineno = 0, lastcmd = -1;
11836 const struct got_histedit_cmd *cmd;
11837 struct got_object_id *commit_id = NULL;
11838 struct got_histedit_list_entry *hle = NULL;
11840 for (;;) {
11841 linelen = getline(&line, &linesize, f);
11842 if (linelen == -1) {
11843 const struct got_error *getline_err;
11844 if (feof(f))
11845 break;
11846 getline_err = got_error_from_errno("getline");
11847 err = got_ferror(f, getline_err->code);
11848 break;
11850 lineno++;
11851 p = line;
11852 while (isspace((unsigned char)p[0]))
11853 p++;
11854 if (p[0] == '#' || p[0] == '\0')
11855 continue;
11856 cmd = NULL;
11857 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11858 cmd = &got_histedit_cmds[i];
11859 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11860 isspace((unsigned char)p[strlen(cmd->name)])) {
11861 p += strlen(cmd->name);
11862 break;
11864 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11865 p++;
11866 break;
11869 if (i == nitems(got_histedit_cmds)) {
11870 err = histedit_syntax_error(lineno);
11871 break;
11873 while (isspace((unsigned char)p[0]))
11874 p++;
11875 if (cmd->code == GOT_HISTEDIT_MESG) {
11876 if (lastcmd != GOT_HISTEDIT_PICK &&
11877 lastcmd != GOT_HISTEDIT_EDIT) {
11878 err = got_error(GOT_ERR_HISTEDIT_CMD);
11879 break;
11881 if (p[0] == '\0') {
11882 err = histedit_edit_logmsg(hle, repo);
11883 if (err)
11884 break;
11885 } else {
11886 hle->logmsg = strdup(p);
11887 if (hle->logmsg == NULL) {
11888 err = got_error_from_errno("strdup");
11889 break;
11892 lastcmd = cmd->code;
11893 continue;
11894 } else {
11895 end = p;
11896 while (end[0] && !isspace((unsigned char)end[0]))
11897 end++;
11898 *end = '\0';
11900 err = got_object_resolve_id_str(&commit_id, repo, p);
11901 if (err) {
11902 /* override error code */
11903 err = histedit_syntax_error(lineno);
11904 break;
11907 hle = malloc(sizeof(*hle));
11908 if (hle == NULL) {
11909 err = got_error_from_errno("malloc");
11910 break;
11912 hle->cmd = cmd;
11913 hle->commit_id = commit_id;
11914 hle->logmsg = NULL;
11915 commit_id = NULL;
11916 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11917 lastcmd = cmd->code;
11920 free(line);
11921 free(commit_id);
11922 return err;
11925 static const struct got_error *
11926 histedit_check_script(struct got_histedit_list *histedit_cmds,
11927 struct got_object_id_queue *commits, struct got_repository *repo)
11929 const struct got_error *err = NULL;
11930 struct got_object_qid *qid;
11931 struct got_histedit_list_entry *hle;
11932 static char msg[92];
11933 char *id_str;
11935 if (TAILQ_EMPTY(histedit_cmds))
11936 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11937 "histedit script contains no commands");
11938 if (STAILQ_EMPTY(commits))
11939 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11941 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11942 struct got_histedit_list_entry *hle2;
11943 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11944 if (hle == hle2)
11945 continue;
11946 if (got_object_id_cmp(hle->commit_id,
11947 hle2->commit_id) != 0)
11948 continue;
11949 err = got_object_id_str(&id_str, hle->commit_id);
11950 if (err)
11951 return err;
11952 snprintf(msg, sizeof(msg), "commit %s is listed "
11953 "more than once in histedit script", id_str);
11954 free(id_str);
11955 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11959 STAILQ_FOREACH(qid, commits, entry) {
11960 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11961 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11962 break;
11964 if (hle == NULL) {
11965 err = got_object_id_str(&id_str, &qid->id);
11966 if (err)
11967 return err;
11968 snprintf(msg, sizeof(msg),
11969 "commit %s missing from histedit script", id_str);
11970 free(id_str);
11971 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11975 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11976 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11977 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11978 "last commit in histedit script cannot be folded");
11980 return NULL;
11983 static const struct got_error *
11984 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11985 const char *path, struct got_object_id_queue *commits,
11986 struct got_repository *repo)
11988 const struct got_error *err = NULL;
11989 char *editor;
11990 FILE *f = NULL;
11992 err = get_editor(&editor);
11993 if (err)
11994 return err;
11996 if (spawn_editor(editor, path) == -1) {
11997 err = got_error_from_errno("failed spawning editor");
11998 goto done;
12001 f = fopen(path, "re");
12002 if (f == NULL) {
12003 err = got_error_from_errno("fopen");
12004 goto done;
12006 err = histedit_parse_list(histedit_cmds, f, repo);
12007 if (err)
12008 goto done;
12010 err = histedit_check_script(histedit_cmds, commits, repo);
12011 done:
12012 if (f && fclose(f) == EOF && err == NULL)
12013 err = got_error_from_errno("fclose");
12014 free(editor);
12015 return err;
12018 static const struct got_error *
12019 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12020 struct got_object_id_queue *, const char *, const char *,
12021 struct got_repository *);
12023 static const struct got_error *
12024 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12025 struct got_object_id_queue *commits, const char *branch_name,
12026 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12027 struct got_repository *repo)
12029 const struct got_error *err;
12030 FILE *f = NULL;
12031 char *path = NULL;
12033 err = got_opentemp_named(&path, &f, "got-histedit", "");
12034 if (err)
12035 return err;
12037 err = write_cmd_list(f, branch_name, commits);
12038 if (err)
12039 goto done;
12041 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12042 fold_only, drop_only, edit_only, repo);
12043 if (err)
12044 goto done;
12046 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12047 rewind(f);
12048 err = histedit_parse_list(histedit_cmds, f, repo);
12049 } else {
12050 if (fclose(f) == EOF) {
12051 err = got_error_from_errno("fclose");
12052 goto done;
12054 f = NULL;
12055 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12056 if (err) {
12057 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12058 err->code != GOT_ERR_HISTEDIT_CMD)
12059 goto done;
12060 err = histedit_edit_list_retry(histedit_cmds, err,
12061 commits, path, branch_name, repo);
12064 done:
12065 if (f && fclose(f) == EOF && err == NULL)
12066 err = got_error_from_errno("fclose");
12067 if (path && unlink(path) != 0 && err == NULL)
12068 err = got_error_from_errno2("unlink", path);
12069 free(path);
12070 return err;
12073 static const struct got_error *
12074 histedit_save_list(struct got_histedit_list *histedit_cmds,
12075 struct got_worktree *worktree, struct got_repository *repo)
12077 const struct got_error *err = NULL;
12078 char *path = NULL;
12079 FILE *f = NULL;
12080 struct got_histedit_list_entry *hle;
12081 struct got_commit_object *commit = NULL;
12083 err = got_worktree_get_histedit_script_path(&path, worktree);
12084 if (err)
12085 return err;
12087 f = fopen(path, "we");
12088 if (f == NULL) {
12089 err = got_error_from_errno2("fopen", path);
12090 goto done;
12092 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12093 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12094 repo);
12095 if (err)
12096 break;
12098 if (hle->logmsg) {
12099 int n = fprintf(f, "%c %s\n",
12100 GOT_HISTEDIT_MESG, hle->logmsg);
12101 if (n < 0) {
12102 err = got_ferror(f, GOT_ERR_IO);
12103 break;
12107 done:
12108 if (f && fclose(f) == EOF && err == NULL)
12109 err = got_error_from_errno("fclose");
12110 free(path);
12111 if (commit)
12112 got_object_commit_close(commit);
12113 return err;
12116 static void
12117 histedit_free_list(struct got_histedit_list *histedit_cmds)
12119 struct got_histedit_list_entry *hle;
12121 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12122 TAILQ_REMOVE(histedit_cmds, hle, entry);
12123 free(hle);
12127 static const struct got_error *
12128 histedit_load_list(struct got_histedit_list *histedit_cmds,
12129 const char *path, struct got_repository *repo)
12131 const struct got_error *err = NULL;
12132 FILE *f = NULL;
12134 f = fopen(path, "re");
12135 if (f == NULL) {
12136 err = got_error_from_errno2("fopen", path);
12137 goto done;
12140 err = histedit_parse_list(histedit_cmds, f, repo);
12141 done:
12142 if (f && fclose(f) == EOF && err == NULL)
12143 err = got_error_from_errno("fclose");
12144 return err;
12147 static const struct got_error *
12148 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12149 const struct got_error *edit_err, struct got_object_id_queue *commits,
12150 const char *path, const char *branch_name, struct got_repository *repo)
12152 const struct got_error *err = NULL, *prev_err = edit_err;
12153 int resp = ' ';
12155 while (resp != 'c' && resp != 'r' && resp != 'a') {
12156 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12157 "or (a)bort: ", getprogname(), prev_err->msg);
12158 resp = getchar();
12159 if (resp == '\n')
12160 resp = getchar();
12161 if (resp == 'c') {
12162 histedit_free_list(histedit_cmds);
12163 err = histedit_run_editor(histedit_cmds, path, commits,
12164 repo);
12165 if (err) {
12166 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12167 err->code != GOT_ERR_HISTEDIT_CMD)
12168 break;
12169 prev_err = err;
12170 resp = ' ';
12171 continue;
12173 break;
12174 } else if (resp == 'r') {
12175 histedit_free_list(histedit_cmds);
12176 err = histedit_edit_script(histedit_cmds,
12177 commits, branch_name, 0, 0, 0, 0, repo);
12178 if (err) {
12179 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12180 err->code != GOT_ERR_HISTEDIT_CMD)
12181 break;
12182 prev_err = err;
12183 resp = ' ';
12184 continue;
12186 break;
12187 } else if (resp == 'a') {
12188 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12189 break;
12190 } else
12191 printf("invalid response '%c'\n", resp);
12194 return err;
12197 static const struct got_error *
12198 histedit_complete(struct got_worktree *worktree,
12199 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12200 struct got_reference *branch, struct got_repository *repo)
12202 printf("Switching work tree to %s\n",
12203 got_ref_get_symref_target(branch));
12204 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12205 branch, repo);
12208 static const struct got_error *
12209 show_histedit_progress(struct got_commit_object *commit,
12210 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12212 const struct got_error *err;
12213 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12215 err = got_object_id_str(&old_id_str, hle->commit_id);
12216 if (err)
12217 goto done;
12219 if (new_id) {
12220 err = got_object_id_str(&new_id_str, new_id);
12221 if (err)
12222 goto done;
12225 old_id_str[12] = '\0';
12226 if (new_id_str)
12227 new_id_str[12] = '\0';
12229 if (hle->logmsg) {
12230 logmsg = strdup(hle->logmsg);
12231 if (logmsg == NULL) {
12232 err = got_error_from_errno("strdup");
12233 goto done;
12235 trim_logmsg(logmsg, 42);
12236 } else {
12237 err = get_short_logmsg(&logmsg, 42, commit);
12238 if (err)
12239 goto done;
12242 switch (hle->cmd->code) {
12243 case GOT_HISTEDIT_PICK:
12244 case GOT_HISTEDIT_EDIT:
12245 printf("%s -> %s: %s\n", old_id_str,
12246 new_id_str ? new_id_str : "no-op change", logmsg);
12247 break;
12248 case GOT_HISTEDIT_DROP:
12249 case GOT_HISTEDIT_FOLD:
12250 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12251 logmsg);
12252 break;
12253 default:
12254 break;
12256 done:
12257 free(old_id_str);
12258 free(new_id_str);
12259 return err;
12262 static const struct got_error *
12263 histedit_commit(struct got_pathlist_head *merged_paths,
12264 struct got_worktree *worktree, struct got_fileindex *fileindex,
12265 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12266 const char *committer, int allow_conflict, struct got_repository *repo)
12268 const struct got_error *err;
12269 struct got_commit_object *commit;
12270 struct got_object_id *new_commit_id;
12272 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12273 && hle->logmsg == NULL) {
12274 err = histedit_edit_logmsg(hle, repo);
12275 if (err)
12276 return err;
12279 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12280 if (err)
12281 return err;
12283 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12284 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12285 hle->logmsg, allow_conflict, repo);
12286 if (err) {
12287 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12288 goto done;
12289 err = show_histedit_progress(commit, hle, NULL);
12290 } else {
12291 err = show_histedit_progress(commit, hle, new_commit_id);
12292 free(new_commit_id);
12294 done:
12295 got_object_commit_close(commit);
12296 return err;
12299 static const struct got_error *
12300 histedit_skip_commit(struct got_histedit_list_entry *hle,
12301 struct got_worktree *worktree, struct got_repository *repo)
12303 const struct got_error *error;
12304 struct got_commit_object *commit;
12306 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12307 repo);
12308 if (error)
12309 return error;
12311 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12312 if (error)
12313 return error;
12315 error = show_histedit_progress(commit, hle, NULL);
12316 got_object_commit_close(commit);
12317 return error;
12320 static const struct got_error *
12321 check_local_changes(void *arg, unsigned char status,
12322 unsigned char staged_status, const char *path,
12323 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12324 struct got_object_id *commit_id, int dirfd, const char *de_name)
12326 int *have_local_changes = arg;
12328 switch (status) {
12329 case GOT_STATUS_ADD:
12330 case GOT_STATUS_DELETE:
12331 case GOT_STATUS_MODIFY:
12332 case GOT_STATUS_CONFLICT:
12333 *have_local_changes = 1;
12334 return got_error(GOT_ERR_CANCELLED);
12335 default:
12336 break;
12339 switch (staged_status) {
12340 case GOT_STATUS_ADD:
12341 case GOT_STATUS_DELETE:
12342 case GOT_STATUS_MODIFY:
12343 *have_local_changes = 1;
12344 return got_error(GOT_ERR_CANCELLED);
12345 default:
12346 break;
12349 return NULL;
12352 static const struct got_error *
12353 cmd_histedit(int argc, char *argv[])
12355 const struct got_error *error = NULL;
12356 struct got_worktree *worktree = NULL;
12357 struct got_fileindex *fileindex = NULL;
12358 struct got_repository *repo = NULL;
12359 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12360 struct got_reference *branch = NULL;
12361 struct got_reference *tmp_branch = NULL;
12362 struct got_object_id *resume_commit_id = NULL;
12363 struct got_object_id *base_commit_id = NULL;
12364 struct got_object_id *head_commit_id = NULL;
12365 struct got_commit_object *commit = NULL;
12366 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12367 struct got_update_progress_arg upa;
12368 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12369 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12370 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12371 const char *edit_script_path = NULL;
12372 struct got_object_id_queue commits;
12373 struct got_pathlist_head merged_paths;
12374 const struct got_object_id_queue *parent_ids;
12375 struct got_object_qid *pid;
12376 struct got_histedit_list histedit_cmds;
12377 struct got_histedit_list_entry *hle;
12378 int *pack_fds = NULL;
12380 STAILQ_INIT(&commits);
12381 TAILQ_INIT(&histedit_cmds);
12382 TAILQ_INIT(&merged_paths);
12383 memset(&upa, 0, sizeof(upa));
12385 #ifndef PROFILE
12386 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12387 "unveil", NULL) == -1)
12388 err(1, "pledge");
12389 #endif
12391 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12392 switch (ch) {
12393 case 'a':
12394 abort_edit = 1;
12395 break;
12396 case 'C':
12397 allow_conflict = 1;
12398 break;
12399 case 'c':
12400 continue_edit = 1;
12401 break;
12402 case 'd':
12403 drop_only = 1;
12404 break;
12405 case 'e':
12406 edit_only = 1;
12407 break;
12408 case 'F':
12409 edit_script_path = optarg;
12410 break;
12411 case 'f':
12412 fold_only = 1;
12413 break;
12414 case 'l':
12415 list_backups = 1;
12416 break;
12417 case 'm':
12418 edit_logmsg_only = 1;
12419 break;
12420 case 'X':
12421 delete_backups = 1;
12422 break;
12423 default:
12424 usage_histedit();
12425 /* NOTREACHED */
12429 argc -= optind;
12430 argv += optind;
12432 if (abort_edit && allow_conflict)
12433 option_conflict('a', 'C');
12434 if (abort_edit && continue_edit)
12435 option_conflict('a', 'c');
12436 if (edit_script_path && allow_conflict)
12437 option_conflict('F', 'C');
12438 if (edit_script_path && edit_logmsg_only)
12439 option_conflict('F', 'm');
12440 if (abort_edit && edit_logmsg_only)
12441 option_conflict('a', 'm');
12442 if (edit_logmsg_only && allow_conflict)
12443 option_conflict('m', 'C');
12444 if (continue_edit && edit_logmsg_only)
12445 option_conflict('c', 'm');
12446 if (abort_edit && fold_only)
12447 option_conflict('a', 'f');
12448 if (fold_only && allow_conflict)
12449 option_conflict('f', 'C');
12450 if (continue_edit && fold_only)
12451 option_conflict('c', 'f');
12452 if (fold_only && edit_logmsg_only)
12453 option_conflict('f', 'm');
12454 if (edit_script_path && fold_only)
12455 option_conflict('F', 'f');
12456 if (abort_edit && edit_only)
12457 option_conflict('a', 'e');
12458 if (continue_edit && edit_only)
12459 option_conflict('c', 'e');
12460 if (edit_only && edit_logmsg_only)
12461 option_conflict('e', 'm');
12462 if (edit_script_path && edit_only)
12463 option_conflict('F', 'e');
12464 if (fold_only && edit_only)
12465 option_conflict('f', 'e');
12466 if (drop_only && abort_edit)
12467 option_conflict('d', 'a');
12468 if (drop_only && allow_conflict)
12469 option_conflict('d', 'C');
12470 if (drop_only && continue_edit)
12471 option_conflict('d', 'c');
12472 if (drop_only && edit_logmsg_only)
12473 option_conflict('d', 'm');
12474 if (drop_only && edit_only)
12475 option_conflict('d', 'e');
12476 if (drop_only && edit_script_path)
12477 option_conflict('d', 'F');
12478 if (drop_only && fold_only)
12479 option_conflict('d', 'f');
12480 if (list_backups) {
12481 if (abort_edit)
12482 option_conflict('l', 'a');
12483 if (allow_conflict)
12484 option_conflict('l', 'C');
12485 if (continue_edit)
12486 option_conflict('l', 'c');
12487 if (edit_script_path)
12488 option_conflict('l', 'F');
12489 if (edit_logmsg_only)
12490 option_conflict('l', 'm');
12491 if (drop_only)
12492 option_conflict('l', 'd');
12493 if (fold_only)
12494 option_conflict('l', 'f');
12495 if (edit_only)
12496 option_conflict('l', 'e');
12497 if (delete_backups)
12498 option_conflict('l', 'X');
12499 if (argc != 0 && argc != 1)
12500 usage_histedit();
12501 } else if (delete_backups) {
12502 if (abort_edit)
12503 option_conflict('X', 'a');
12504 if (allow_conflict)
12505 option_conflict('X', 'C');
12506 if (continue_edit)
12507 option_conflict('X', 'c');
12508 if (drop_only)
12509 option_conflict('X', 'd');
12510 if (edit_script_path)
12511 option_conflict('X', 'F');
12512 if (edit_logmsg_only)
12513 option_conflict('X', 'm');
12514 if (fold_only)
12515 option_conflict('X', 'f');
12516 if (edit_only)
12517 option_conflict('X', 'e');
12518 if (list_backups)
12519 option_conflict('X', 'l');
12520 if (argc != 0 && argc != 1)
12521 usage_histedit();
12522 } else if (allow_conflict && !continue_edit)
12523 errx(1, "-C option requires -c");
12524 else if (argc != 0)
12525 usage_histedit();
12528 * This command cannot apply unveil(2) in all cases because the
12529 * user may choose to run an editor to edit the histedit script
12530 * and to edit individual commit log messages.
12531 * unveil(2) traverses exec(2); if an editor is used we have to
12532 * apply unveil after edit script and log messages have been written.
12533 * XXX TODO: Make use of unveil(2) where possible.
12536 cwd = getcwd(NULL, 0);
12537 if (cwd == NULL) {
12538 error = got_error_from_errno("getcwd");
12539 goto done;
12542 error = got_repo_pack_fds_open(&pack_fds);
12543 if (error != NULL)
12544 goto done;
12546 error = got_worktree_open(&worktree, cwd);
12547 if (error) {
12548 if (list_backups || delete_backups) {
12549 if (error->code != GOT_ERR_NOT_WORKTREE)
12550 goto done;
12551 } else {
12552 if (error->code == GOT_ERR_NOT_WORKTREE)
12553 error = wrap_not_worktree_error(error,
12554 "histedit", cwd);
12555 goto done;
12559 if (list_backups || delete_backups) {
12560 error = got_repo_open(&repo,
12561 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12562 NULL, pack_fds);
12563 if (error != NULL)
12564 goto done;
12565 error = apply_unveil(got_repo_get_path(repo), 0,
12566 worktree ? got_worktree_get_root_path(worktree) : NULL);
12567 if (error)
12568 goto done;
12569 error = process_backup_refs(
12570 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12571 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12572 goto done; /* nothing else to do */
12575 error = get_gitconfig_path(&gitconfig_path);
12576 if (error)
12577 goto done;
12578 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12579 gitconfig_path, pack_fds);
12580 if (error != NULL)
12581 goto done;
12583 if (worktree != NULL && !list_backups && !delete_backups) {
12584 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12585 if (error)
12586 goto done;
12589 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12590 if (error)
12591 goto done;
12592 if (rebase_in_progress) {
12593 error = got_error(GOT_ERR_REBASING);
12594 goto done;
12597 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12598 repo);
12599 if (error)
12600 goto done;
12601 if (merge_in_progress) {
12602 error = got_error(GOT_ERR_MERGE_BUSY);
12603 goto done;
12606 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12607 if (error)
12608 goto done;
12610 if (edit_in_progress && edit_logmsg_only) {
12611 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12612 "histedit operation is in progress in this "
12613 "work tree and must be continued or aborted "
12614 "before the -m option can be used");
12615 goto done;
12617 if (edit_in_progress && drop_only) {
12618 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12619 "histedit operation is in progress in this "
12620 "work tree and must be continued or aborted "
12621 "before the -d option can be used");
12622 goto done;
12624 if (edit_in_progress && fold_only) {
12625 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12626 "histedit operation is in progress in this "
12627 "work tree and must be continued or aborted "
12628 "before the -f option can be used");
12629 goto done;
12631 if (edit_in_progress && edit_only) {
12632 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12633 "histedit operation is in progress in this "
12634 "work tree and must be continued or aborted "
12635 "before the -e option can be used");
12636 goto done;
12639 if (edit_in_progress && abort_edit) {
12640 error = got_worktree_histedit_continue(&resume_commit_id,
12641 &tmp_branch, &branch, &base_commit_id, &fileindex,
12642 worktree, repo);
12643 if (error)
12644 goto done;
12645 printf("Switching work tree to %s\n",
12646 got_ref_get_symref_target(branch));
12647 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12648 branch, base_commit_id, abort_progress, &upa);
12649 if (error)
12650 goto done;
12651 printf("Histedit of %s aborted\n",
12652 got_ref_get_symref_target(branch));
12653 print_merge_progress_stats(&upa);
12654 goto done; /* nothing else to do */
12655 } else if (abort_edit) {
12656 error = got_error(GOT_ERR_NOT_HISTEDIT);
12657 goto done;
12660 error = get_author(&committer, repo, worktree);
12661 if (error)
12662 goto done;
12664 if (continue_edit) {
12665 char *path;
12667 if (!edit_in_progress) {
12668 error = got_error(GOT_ERR_NOT_HISTEDIT);
12669 goto done;
12672 error = got_worktree_get_histedit_script_path(&path, worktree);
12673 if (error)
12674 goto done;
12676 error = histedit_load_list(&histedit_cmds, path, repo);
12677 free(path);
12678 if (error)
12679 goto done;
12681 error = got_worktree_histedit_continue(&resume_commit_id,
12682 &tmp_branch, &branch, &base_commit_id, &fileindex,
12683 worktree, repo);
12684 if (error)
12685 goto done;
12687 error = got_ref_resolve(&head_commit_id, repo, branch);
12688 if (error)
12689 goto done;
12691 error = got_object_open_as_commit(&commit, repo,
12692 head_commit_id);
12693 if (error)
12694 goto done;
12695 parent_ids = got_object_commit_get_parent_ids(commit);
12696 pid = STAILQ_FIRST(parent_ids);
12697 if (pid == NULL) {
12698 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12699 goto done;
12701 error = collect_commits(&commits, head_commit_id, &pid->id,
12702 base_commit_id, got_worktree_get_path_prefix(worktree),
12703 GOT_ERR_HISTEDIT_PATH, repo);
12704 got_object_commit_close(commit);
12705 commit = NULL;
12706 if (error)
12707 goto done;
12708 } else {
12709 if (edit_in_progress) {
12710 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12711 goto done;
12714 error = got_ref_open(&branch, repo,
12715 got_worktree_get_head_ref_name(worktree), 0);
12716 if (error != NULL)
12717 goto done;
12719 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12720 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12721 "will not edit commit history of a branch outside "
12722 "the \"refs/heads/\" reference namespace");
12723 goto done;
12726 error = got_ref_resolve(&head_commit_id, repo, branch);
12727 got_ref_close(branch);
12728 branch = NULL;
12729 if (error)
12730 goto done;
12732 error = got_object_open_as_commit(&commit, repo,
12733 head_commit_id);
12734 if (error)
12735 goto done;
12736 parent_ids = got_object_commit_get_parent_ids(commit);
12737 pid = STAILQ_FIRST(parent_ids);
12738 if (pid == NULL) {
12739 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12740 goto done;
12742 error = collect_commits(&commits, head_commit_id, &pid->id,
12743 got_worktree_get_base_commit_id(worktree),
12744 got_worktree_get_path_prefix(worktree),
12745 GOT_ERR_HISTEDIT_PATH, repo);
12746 got_object_commit_close(commit);
12747 commit = NULL;
12748 if (error)
12749 goto done;
12751 if (STAILQ_EMPTY(&commits)) {
12752 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12753 goto done;
12756 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12757 &base_commit_id, &fileindex, worktree, repo);
12758 if (error)
12759 goto done;
12761 if (edit_script_path) {
12762 error = histedit_load_list(&histedit_cmds,
12763 edit_script_path, repo);
12764 if (error) {
12765 got_worktree_histedit_abort(worktree, fileindex,
12766 repo, branch, base_commit_id,
12767 abort_progress, &upa);
12768 print_merge_progress_stats(&upa);
12769 goto done;
12771 } else {
12772 const char *branch_name;
12773 branch_name = got_ref_get_symref_target(branch);
12774 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12775 branch_name += 11;
12776 error = histedit_edit_script(&histedit_cmds, &commits,
12777 branch_name, edit_logmsg_only, fold_only,
12778 drop_only, edit_only, repo);
12779 if (error) {
12780 got_worktree_histedit_abort(worktree, fileindex,
12781 repo, branch, base_commit_id,
12782 abort_progress, &upa);
12783 print_merge_progress_stats(&upa);
12784 goto done;
12789 error = histedit_save_list(&histedit_cmds, worktree,
12790 repo);
12791 if (error) {
12792 got_worktree_histedit_abort(worktree, fileindex,
12793 repo, branch, base_commit_id,
12794 abort_progress, &upa);
12795 print_merge_progress_stats(&upa);
12796 goto done;
12801 error = histedit_check_script(&histedit_cmds, &commits, repo);
12802 if (error)
12803 goto done;
12805 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12806 if (resume_commit_id) {
12807 if (got_object_id_cmp(hle->commit_id,
12808 resume_commit_id) != 0)
12809 continue;
12811 resume_commit_id = NULL;
12812 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12813 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12814 error = histedit_skip_commit(hle, worktree,
12815 repo);
12816 if (error)
12817 goto done;
12818 } else {
12819 struct got_pathlist_head paths;
12820 int have_changes = 0;
12822 TAILQ_INIT(&paths);
12823 error = got_pathlist_append(&paths, "", NULL);
12824 if (error)
12825 goto done;
12826 error = got_worktree_status(worktree, &paths,
12827 repo, 0, check_local_changes, &have_changes,
12828 check_cancelled, NULL);
12829 got_pathlist_free(&paths,
12830 GOT_PATHLIST_FREE_NONE);
12831 if (error) {
12832 if (error->code != GOT_ERR_CANCELLED)
12833 goto done;
12834 if (sigint_received || sigpipe_received)
12835 goto done;
12837 if (have_changes) {
12838 error = histedit_commit(NULL, worktree,
12839 fileindex, tmp_branch, hle,
12840 committer, allow_conflict, repo);
12841 if (error)
12842 goto done;
12843 } else {
12844 error = got_object_open_as_commit(
12845 &commit, repo, hle->commit_id);
12846 if (error)
12847 goto done;
12848 error = show_histedit_progress(commit,
12849 hle, NULL);
12850 got_object_commit_close(commit);
12851 commit = NULL;
12852 if (error)
12853 goto done;
12856 continue;
12859 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12860 error = histedit_skip_commit(hle, worktree, repo);
12861 if (error)
12862 goto done;
12863 continue;
12866 error = got_object_open_as_commit(&commit, repo,
12867 hle->commit_id);
12868 if (error)
12869 goto done;
12870 parent_ids = got_object_commit_get_parent_ids(commit);
12871 pid = STAILQ_FIRST(parent_ids);
12873 error = got_worktree_histedit_merge_files(&merged_paths,
12874 worktree, fileindex, &pid->id, hle->commit_id, repo,
12875 update_progress, &upa, check_cancelled, NULL);
12876 if (error)
12877 goto done;
12878 got_object_commit_close(commit);
12879 commit = NULL;
12881 print_merge_progress_stats(&upa);
12882 if (upa.conflicts > 0 || upa.missing > 0 ||
12883 upa.not_deleted > 0 || upa.unversioned > 0) {
12884 if (upa.conflicts > 0) {
12885 error = show_rebase_merge_conflict(
12886 hle->commit_id, repo);
12887 if (error)
12888 goto done;
12890 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12891 break;
12894 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12895 char *id_str;
12896 error = got_object_id_str(&id_str, hle->commit_id);
12897 if (error)
12898 goto done;
12899 printf("Stopping histedit for amending commit %s\n",
12900 id_str);
12901 free(id_str);
12902 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12903 error = got_worktree_histedit_postpone(worktree,
12904 fileindex);
12905 goto done;
12908 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12909 error = histedit_skip_commit(hle, worktree, repo);
12910 if (error)
12911 goto done;
12912 continue;
12915 error = histedit_commit(&merged_paths, worktree, fileindex,
12916 tmp_branch, hle, committer, allow_conflict, repo);
12917 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12918 if (error)
12919 goto done;
12922 if (upa.conflicts > 0 || upa.missing > 0 ||
12923 upa.not_deleted > 0 || upa.unversioned > 0) {
12924 error = got_worktree_histedit_postpone(worktree, fileindex);
12925 if (error)
12926 goto done;
12927 if (upa.conflicts > 0 && upa.missing == 0 &&
12928 upa.not_deleted == 0 && upa.unversioned == 0) {
12929 error = got_error_msg(GOT_ERR_CONFLICTS,
12930 "conflicts must be resolved before histedit "
12931 "can continue");
12932 } else if (upa.conflicts > 0) {
12933 error = got_error_msg(GOT_ERR_CONFLICTS,
12934 "conflicts must be resolved before histedit "
12935 "can continue; changes destined for some "
12936 "files were not yet merged and should be "
12937 "merged manually if required before the "
12938 "histedit operation is continued");
12939 } else {
12940 error = got_error_msg(GOT_ERR_CONFLICTS,
12941 "changes destined for some files were not "
12942 "yet merged and should be merged manually "
12943 "if required before the histedit operation "
12944 "is continued");
12946 } else
12947 error = histedit_complete(worktree, fileindex, tmp_branch,
12948 branch, repo);
12949 done:
12950 free(cwd);
12951 free(committer);
12952 free(gitconfig_path);
12953 got_object_id_queue_free(&commits);
12954 histedit_free_list(&histedit_cmds);
12955 free(head_commit_id);
12956 free(base_commit_id);
12957 free(resume_commit_id);
12958 if (commit)
12959 got_object_commit_close(commit);
12960 if (branch)
12961 got_ref_close(branch);
12962 if (tmp_branch)
12963 got_ref_close(tmp_branch);
12964 if (worktree)
12965 got_worktree_close(worktree);
12966 if (repo) {
12967 const struct got_error *close_err = got_repo_close(repo);
12968 if (error == NULL)
12969 error = close_err;
12971 if (pack_fds) {
12972 const struct got_error *pack_err =
12973 got_repo_pack_fds_close(pack_fds);
12974 if (error == NULL)
12975 error = pack_err;
12977 return error;
12980 __dead static void
12981 usage_integrate(void)
12983 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12984 exit(1);
12987 static const struct got_error *
12988 cmd_integrate(int argc, char *argv[])
12990 const struct got_error *error = NULL;
12991 struct got_repository *repo = NULL;
12992 struct got_worktree *worktree = NULL;
12993 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12994 const char *branch_arg = NULL;
12995 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12996 struct got_fileindex *fileindex = NULL;
12997 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12998 int ch;
12999 struct got_update_progress_arg upa;
13000 int *pack_fds = NULL;
13002 #ifndef PROFILE
13003 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13004 "unveil", NULL) == -1)
13005 err(1, "pledge");
13006 #endif
13008 while ((ch = getopt(argc, argv, "")) != -1) {
13009 switch (ch) {
13010 default:
13011 usage_integrate();
13012 /* NOTREACHED */
13016 argc -= optind;
13017 argv += optind;
13019 if (argc != 1)
13020 usage_integrate();
13021 branch_arg = argv[0];
13023 cwd = getcwd(NULL, 0);
13024 if (cwd == NULL) {
13025 error = got_error_from_errno("getcwd");
13026 goto done;
13029 error = got_repo_pack_fds_open(&pack_fds);
13030 if (error != NULL)
13031 goto done;
13033 error = got_worktree_open(&worktree, cwd);
13034 if (error) {
13035 if (error->code == GOT_ERR_NOT_WORKTREE)
13036 error = wrap_not_worktree_error(error, "integrate",
13037 cwd);
13038 goto done;
13041 error = check_rebase_or_histedit_in_progress(worktree);
13042 if (error)
13043 goto done;
13045 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13046 NULL, pack_fds);
13047 if (error != NULL)
13048 goto done;
13050 error = apply_unveil(got_repo_get_path(repo), 0,
13051 got_worktree_get_root_path(worktree));
13052 if (error)
13053 goto done;
13055 error = check_merge_in_progress(worktree, repo);
13056 if (error)
13057 goto done;
13059 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13060 error = got_error_from_errno("asprintf");
13061 goto done;
13064 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13065 &base_branch_ref, worktree, refname, repo);
13066 if (error)
13067 goto done;
13069 refname = strdup(got_ref_get_name(branch_ref));
13070 if (refname == NULL) {
13071 error = got_error_from_errno("strdup");
13072 got_worktree_integrate_abort(worktree, fileindex, repo,
13073 branch_ref, base_branch_ref);
13074 goto done;
13076 base_refname = strdup(got_ref_get_name(base_branch_ref));
13077 if (base_refname == NULL) {
13078 error = got_error_from_errno("strdup");
13079 got_worktree_integrate_abort(worktree, fileindex, repo,
13080 branch_ref, base_branch_ref);
13081 goto done;
13083 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13084 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13085 got_worktree_integrate_abort(worktree, fileindex, repo,
13086 branch_ref, base_branch_ref);
13087 goto done;
13090 error = got_ref_resolve(&commit_id, repo, branch_ref);
13091 if (error)
13092 goto done;
13094 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13095 if (error)
13096 goto done;
13098 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13099 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13100 "specified branch has already been integrated");
13101 got_worktree_integrate_abort(worktree, fileindex, repo,
13102 branch_ref, base_branch_ref);
13103 goto done;
13106 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13107 if (error) {
13108 if (error->code == GOT_ERR_ANCESTRY)
13109 error = got_error(GOT_ERR_REBASE_REQUIRED);
13110 got_worktree_integrate_abort(worktree, fileindex, repo,
13111 branch_ref, base_branch_ref);
13112 goto done;
13115 memset(&upa, 0, sizeof(upa));
13116 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13117 branch_ref, base_branch_ref, update_progress, &upa,
13118 check_cancelled, NULL);
13119 if (error)
13120 goto done;
13122 printf("Integrated %s into %s\n", refname, base_refname);
13123 print_update_progress_stats(&upa);
13124 done:
13125 if (repo) {
13126 const struct got_error *close_err = got_repo_close(repo);
13127 if (error == NULL)
13128 error = close_err;
13130 if (worktree)
13131 got_worktree_close(worktree);
13132 if (pack_fds) {
13133 const struct got_error *pack_err =
13134 got_repo_pack_fds_close(pack_fds);
13135 if (error == NULL)
13136 error = pack_err;
13138 free(cwd);
13139 free(base_commit_id);
13140 free(commit_id);
13141 free(refname);
13142 free(base_refname);
13143 return error;
13146 __dead static void
13147 usage_merge(void)
13149 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13150 exit(1);
13153 static const struct got_error *
13154 cmd_merge(int argc, char *argv[])
13156 const struct got_error *error = NULL;
13157 struct got_worktree *worktree = NULL;
13158 struct got_repository *repo = NULL;
13159 struct got_fileindex *fileindex = NULL;
13160 char *cwd = NULL, *id_str = NULL, *author = NULL;
13161 char *gitconfig_path = NULL;
13162 struct got_reference *branch = NULL, *wt_branch = NULL;
13163 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13164 struct got_object_id *wt_branch_tip = NULL;
13165 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13166 int allow_conflict = 0, interrupt_merge = 0;
13167 struct got_update_progress_arg upa;
13168 struct got_object_id *merge_commit_id = NULL;
13169 char *branch_name = NULL;
13170 int *pack_fds = NULL;
13172 memset(&upa, 0, sizeof(upa));
13174 #ifndef PROFILE
13175 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13176 "unveil", NULL) == -1)
13177 err(1, "pledge");
13178 #endif
13180 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13181 switch (ch) {
13182 case 'a':
13183 abort_merge = 1;
13184 break;
13185 case 'C':
13186 allow_conflict = 1;
13187 case 'c':
13188 continue_merge = 1;
13189 break;
13190 case 'n':
13191 interrupt_merge = 1;
13192 break;
13193 default:
13194 usage_merge();
13195 /* NOTREACHED */
13199 argc -= optind;
13200 argv += optind;
13202 if (allow_conflict) {
13203 if (abort_merge)
13204 option_conflict('a', 'C');
13205 if (!continue_merge)
13206 errx(1, "-C option requires -c");
13208 if (abort_merge && continue_merge)
13209 option_conflict('a', 'c');
13210 if (abort_merge || continue_merge) {
13211 if (argc != 0)
13212 usage_merge();
13213 } else if (argc != 1)
13214 usage_merge();
13216 cwd = getcwd(NULL, 0);
13217 if (cwd == NULL) {
13218 error = got_error_from_errno("getcwd");
13219 goto done;
13222 error = got_repo_pack_fds_open(&pack_fds);
13223 if (error != NULL)
13224 goto done;
13226 error = got_worktree_open(&worktree, cwd);
13227 if (error) {
13228 if (error->code == GOT_ERR_NOT_WORKTREE)
13229 error = wrap_not_worktree_error(error,
13230 "merge", cwd);
13231 goto done;
13234 error = get_gitconfig_path(&gitconfig_path);
13235 if (error)
13236 goto done;
13237 error = got_repo_open(&repo,
13238 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13239 gitconfig_path, pack_fds);
13240 if (error != NULL)
13241 goto done;
13243 if (worktree != NULL) {
13244 error = worktree_has_logmsg_ref("merge", worktree, repo);
13245 if (error)
13246 goto done;
13249 error = apply_unveil(got_repo_get_path(repo), 0,
13250 worktree ? got_worktree_get_root_path(worktree) : NULL);
13251 if (error)
13252 goto done;
13254 error = check_rebase_or_histedit_in_progress(worktree);
13255 if (error)
13256 goto done;
13258 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13259 repo);
13260 if (error)
13261 goto done;
13263 if (abort_merge) {
13264 if (!merge_in_progress) {
13265 error = got_error(GOT_ERR_NOT_MERGING);
13266 goto done;
13268 error = got_worktree_merge_continue(&branch_name,
13269 &branch_tip, &fileindex, worktree, repo);
13270 if (error)
13271 goto done;
13272 error = got_worktree_merge_abort(worktree, fileindex, repo,
13273 abort_progress, &upa);
13274 if (error)
13275 goto done;
13276 printf("Merge of %s aborted\n", branch_name);
13277 goto done; /* nothing else to do */
13280 error = get_author(&author, repo, worktree);
13281 if (error)
13282 goto done;
13284 if (continue_merge) {
13285 if (!merge_in_progress) {
13286 error = got_error(GOT_ERR_NOT_MERGING);
13287 goto done;
13289 error = got_worktree_merge_continue(&branch_name,
13290 &branch_tip, &fileindex, worktree, repo);
13291 if (error)
13292 goto done;
13293 } else {
13294 error = got_ref_open(&branch, repo, argv[0], 0);
13295 if (error != NULL)
13296 goto done;
13297 branch_name = strdup(got_ref_get_name(branch));
13298 if (branch_name == NULL) {
13299 error = got_error_from_errno("strdup");
13300 goto done;
13302 error = got_ref_resolve(&branch_tip, repo, branch);
13303 if (error)
13304 goto done;
13307 error = got_ref_open(&wt_branch, repo,
13308 got_worktree_get_head_ref_name(worktree), 0);
13309 if (error)
13310 goto done;
13311 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13312 if (error)
13313 goto done;
13314 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13315 wt_branch_tip, branch_tip, 0, repo,
13316 check_cancelled, NULL);
13317 if (error && error->code != GOT_ERR_ANCESTRY)
13318 goto done;
13320 if (!continue_merge) {
13321 error = check_path_prefix(wt_branch_tip, branch_tip,
13322 got_worktree_get_path_prefix(worktree),
13323 GOT_ERR_MERGE_PATH, repo);
13324 if (error)
13325 goto done;
13326 if (yca_id) {
13327 error = check_same_branch(wt_branch_tip, branch,
13328 yca_id, repo);
13329 if (error) {
13330 if (error->code != GOT_ERR_ANCESTRY)
13331 goto done;
13332 error = NULL;
13333 } else {
13334 static char msg[512];
13335 snprintf(msg, sizeof(msg),
13336 "cannot create a merge commit because "
13337 "%s is based on %s; %s can be integrated "
13338 "with 'got integrate' instead", branch_name,
13339 got_worktree_get_head_ref_name(worktree),
13340 branch_name);
13341 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13342 goto done;
13345 error = got_worktree_merge_prepare(&fileindex, worktree,
13346 branch, repo);
13347 if (error)
13348 goto done;
13350 error = got_worktree_merge_branch(worktree, fileindex,
13351 yca_id, branch_tip, repo, update_progress, &upa,
13352 check_cancelled, NULL);
13353 if (error)
13354 goto done;
13355 print_merge_progress_stats(&upa);
13356 if (!upa.did_something) {
13357 error = got_worktree_merge_abort(worktree, fileindex,
13358 repo, abort_progress, &upa);
13359 if (error)
13360 goto done;
13361 printf("Already up-to-date\n");
13362 goto done;
13366 if (interrupt_merge) {
13367 error = got_worktree_merge_postpone(worktree, fileindex);
13368 if (error)
13369 goto done;
13370 printf("Merge of %s interrupted on request\n", branch_name);
13371 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13372 upa.not_deleted > 0 || upa.unversioned > 0) {
13373 error = got_worktree_merge_postpone(worktree, fileindex);
13374 if (error)
13375 goto done;
13376 if (upa.conflicts > 0 && upa.missing == 0 &&
13377 upa.not_deleted == 0 && upa.unversioned == 0) {
13378 error = got_error_msg(GOT_ERR_CONFLICTS,
13379 "conflicts must be resolved before merging "
13380 "can continue");
13381 } else if (upa.conflicts > 0) {
13382 error = got_error_msg(GOT_ERR_CONFLICTS,
13383 "conflicts must be resolved before merging "
13384 "can continue; changes destined for some "
13385 "files were not yet merged and "
13386 "should be merged manually if required before the "
13387 "merge operation is continued");
13388 } else {
13389 error = got_error_msg(GOT_ERR_CONFLICTS,
13390 "changes destined for some "
13391 "files were not yet merged and should be "
13392 "merged manually if required before the "
13393 "merge operation is continued");
13395 goto done;
13396 } else {
13397 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13398 fileindex, author, NULL, 1, branch_tip, branch_name,
13399 allow_conflict, repo, continue_merge ? print_status : NULL,
13400 NULL);
13401 if (error)
13402 goto done;
13403 error = got_worktree_merge_complete(worktree, fileindex, repo);
13404 if (error)
13405 goto done;
13406 error = got_object_id_str(&id_str, merge_commit_id);
13407 if (error)
13408 goto done;
13409 printf("Merged %s into %s: %s\n", branch_name,
13410 got_worktree_get_head_ref_name(worktree),
13411 id_str);
13414 done:
13415 free(gitconfig_path);
13416 free(id_str);
13417 free(merge_commit_id);
13418 free(author);
13419 free(branch_tip);
13420 free(branch_name);
13421 free(yca_id);
13422 if (branch)
13423 got_ref_close(branch);
13424 if (wt_branch)
13425 got_ref_close(wt_branch);
13426 if (worktree)
13427 got_worktree_close(worktree);
13428 if (repo) {
13429 const struct got_error *close_err = got_repo_close(repo);
13430 if (error == NULL)
13431 error = close_err;
13433 if (pack_fds) {
13434 const struct got_error *pack_err =
13435 got_repo_pack_fds_close(pack_fds);
13436 if (error == NULL)
13437 error = pack_err;
13439 return error;
13442 __dead static void
13443 usage_stage(void)
13445 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13446 "[path ...]\n", getprogname());
13447 exit(1);
13450 static const struct got_error *
13451 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13452 const char *path, struct got_object_id *blob_id,
13453 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13454 int dirfd, const char *de_name)
13456 const struct got_error *err = NULL;
13457 char *id_str = NULL;
13459 if (staged_status != GOT_STATUS_ADD &&
13460 staged_status != GOT_STATUS_MODIFY &&
13461 staged_status != GOT_STATUS_DELETE)
13462 return NULL;
13464 if (staged_status == GOT_STATUS_ADD ||
13465 staged_status == GOT_STATUS_MODIFY)
13466 err = got_object_id_str(&id_str, staged_blob_id);
13467 else
13468 err = got_object_id_str(&id_str, blob_id);
13469 if (err)
13470 return err;
13472 printf("%s %c %s\n", id_str, staged_status, path);
13473 free(id_str);
13474 return NULL;
13477 static const struct got_error *
13478 cmd_stage(int argc, char *argv[])
13480 const struct got_error *error = NULL;
13481 struct got_repository *repo = NULL;
13482 struct got_worktree *worktree = NULL;
13483 char *cwd = NULL;
13484 struct got_pathlist_head paths;
13485 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13486 FILE *patch_script_file = NULL;
13487 const char *patch_script_path = NULL;
13488 struct choose_patch_arg cpa;
13489 int *pack_fds = NULL;
13491 TAILQ_INIT(&paths);
13493 #ifndef PROFILE
13494 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13495 "unveil", NULL) == -1)
13496 err(1, "pledge");
13497 #endif
13499 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13500 switch (ch) {
13501 case 'F':
13502 patch_script_path = optarg;
13503 break;
13504 case 'l':
13505 list_stage = 1;
13506 break;
13507 case 'p':
13508 pflag = 1;
13509 break;
13510 case 'S':
13511 allow_bad_symlinks = 1;
13512 break;
13513 default:
13514 usage_stage();
13515 /* NOTREACHED */
13519 argc -= optind;
13520 argv += optind;
13522 if (list_stage && (pflag || patch_script_path))
13523 errx(1, "-l option cannot be used with other options");
13524 if (patch_script_path && !pflag)
13525 errx(1, "-F option can only be used together with -p option");
13527 cwd = getcwd(NULL, 0);
13528 if (cwd == NULL) {
13529 error = got_error_from_errno("getcwd");
13530 goto done;
13533 error = got_repo_pack_fds_open(&pack_fds);
13534 if (error != NULL)
13535 goto done;
13537 error = got_worktree_open(&worktree, cwd);
13538 if (error) {
13539 if (error->code == GOT_ERR_NOT_WORKTREE)
13540 error = wrap_not_worktree_error(error, "stage", cwd);
13541 goto done;
13544 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13545 NULL, pack_fds);
13546 if (error != NULL)
13547 goto done;
13549 if (patch_script_path) {
13550 patch_script_file = fopen(patch_script_path, "re");
13551 if (patch_script_file == NULL) {
13552 error = got_error_from_errno2("fopen",
13553 patch_script_path);
13554 goto done;
13557 error = apply_unveil(got_repo_get_path(repo), 0,
13558 got_worktree_get_root_path(worktree));
13559 if (error)
13560 goto done;
13562 error = check_merge_in_progress(worktree, repo);
13563 if (error)
13564 goto done;
13566 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13567 if (error)
13568 goto done;
13570 if (list_stage)
13571 error = got_worktree_status(worktree, &paths, repo, 0,
13572 print_stage, NULL, check_cancelled, NULL);
13573 else {
13574 cpa.patch_script_file = patch_script_file;
13575 cpa.action = "stage";
13576 error = got_worktree_stage(worktree, &paths,
13577 pflag ? NULL : print_status, NULL,
13578 pflag ? choose_patch : NULL, &cpa,
13579 allow_bad_symlinks, repo);
13581 done:
13582 if (patch_script_file && fclose(patch_script_file) == EOF &&
13583 error == NULL)
13584 error = got_error_from_errno2("fclose", patch_script_path);
13585 if (repo) {
13586 const struct got_error *close_err = got_repo_close(repo);
13587 if (error == NULL)
13588 error = close_err;
13590 if (worktree)
13591 got_worktree_close(worktree);
13592 if (pack_fds) {
13593 const struct got_error *pack_err =
13594 got_repo_pack_fds_close(pack_fds);
13595 if (error == NULL)
13596 error = pack_err;
13598 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13599 free(cwd);
13600 return error;
13603 __dead static void
13604 usage_unstage(void)
13606 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13607 "[path ...]\n", getprogname());
13608 exit(1);
13612 static const struct got_error *
13613 cmd_unstage(int argc, char *argv[])
13615 const struct got_error *error = NULL;
13616 struct got_repository *repo = NULL;
13617 struct got_worktree *worktree = NULL;
13618 char *cwd = NULL;
13619 struct got_pathlist_head paths;
13620 int ch, pflag = 0;
13621 struct got_update_progress_arg upa;
13622 FILE *patch_script_file = NULL;
13623 const char *patch_script_path = NULL;
13624 struct choose_patch_arg cpa;
13625 int *pack_fds = NULL;
13627 TAILQ_INIT(&paths);
13629 #ifndef PROFILE
13630 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13631 "unveil", NULL) == -1)
13632 err(1, "pledge");
13633 #endif
13635 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13636 switch (ch) {
13637 case 'F':
13638 patch_script_path = optarg;
13639 break;
13640 case 'p':
13641 pflag = 1;
13642 break;
13643 default:
13644 usage_unstage();
13645 /* NOTREACHED */
13649 argc -= optind;
13650 argv += optind;
13652 if (patch_script_path && !pflag)
13653 errx(1, "-F option can only be used together with -p option");
13655 cwd = getcwd(NULL, 0);
13656 if (cwd == NULL) {
13657 error = got_error_from_errno("getcwd");
13658 goto done;
13661 error = got_repo_pack_fds_open(&pack_fds);
13662 if (error != NULL)
13663 goto done;
13665 error = got_worktree_open(&worktree, cwd);
13666 if (error) {
13667 if (error->code == GOT_ERR_NOT_WORKTREE)
13668 error = wrap_not_worktree_error(error, "unstage", cwd);
13669 goto done;
13672 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13673 NULL, pack_fds);
13674 if (error != NULL)
13675 goto done;
13677 if (patch_script_path) {
13678 patch_script_file = fopen(patch_script_path, "re");
13679 if (patch_script_file == NULL) {
13680 error = got_error_from_errno2("fopen",
13681 patch_script_path);
13682 goto done;
13686 error = apply_unveil(got_repo_get_path(repo), 0,
13687 got_worktree_get_root_path(worktree));
13688 if (error)
13689 goto done;
13691 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13692 if (error)
13693 goto done;
13695 cpa.patch_script_file = patch_script_file;
13696 cpa.action = "unstage";
13697 memset(&upa, 0, sizeof(upa));
13698 error = got_worktree_unstage(worktree, &paths, update_progress,
13699 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13700 if (!error)
13701 print_merge_progress_stats(&upa);
13702 done:
13703 if (patch_script_file && fclose(patch_script_file) == EOF &&
13704 error == NULL)
13705 error = got_error_from_errno2("fclose", patch_script_path);
13706 if (repo) {
13707 const struct got_error *close_err = got_repo_close(repo);
13708 if (error == NULL)
13709 error = close_err;
13711 if (worktree)
13712 got_worktree_close(worktree);
13713 if (pack_fds) {
13714 const struct got_error *pack_err =
13715 got_repo_pack_fds_close(pack_fds);
13716 if (error == NULL)
13717 error = pack_err;
13719 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13720 free(cwd);
13721 return error;
13724 __dead static void
13725 usage_cat(void)
13727 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13728 "arg ...\n", getprogname());
13729 exit(1);
13732 static const struct got_error *
13733 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13735 const struct got_error *err;
13736 struct got_blob_object *blob;
13737 int fd = -1;
13739 fd = got_opentempfd();
13740 if (fd == -1)
13741 return got_error_from_errno("got_opentempfd");
13743 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13744 if (err)
13745 goto done;
13747 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13748 done:
13749 if (fd != -1 && close(fd) == -1 && err == NULL)
13750 err = got_error_from_errno("close");
13751 if (blob)
13752 got_object_blob_close(blob);
13753 return err;
13756 static const struct got_error *
13757 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13759 const struct got_error *err;
13760 struct got_tree_object *tree;
13761 int nentries, i;
13763 err = got_object_open_as_tree(&tree, repo, id);
13764 if (err)
13765 return err;
13767 nentries = got_object_tree_get_nentries(tree);
13768 for (i = 0; i < nentries; i++) {
13769 struct got_tree_entry *te;
13770 char *id_str;
13771 if (sigint_received || sigpipe_received)
13772 break;
13773 te = got_object_tree_get_entry(tree, i);
13774 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13775 if (err)
13776 break;
13777 fprintf(outfile, "%s %.7o %s\n", id_str,
13778 got_tree_entry_get_mode(te),
13779 got_tree_entry_get_name(te));
13780 free(id_str);
13783 got_object_tree_close(tree);
13784 return err;
13787 static const struct got_error *
13788 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13790 const struct got_error *err;
13791 struct got_commit_object *commit;
13792 const struct got_object_id_queue *parent_ids;
13793 struct got_object_qid *pid;
13794 char *id_str = NULL;
13795 const char *logmsg = NULL;
13796 char gmtoff[6];
13798 err = got_object_open_as_commit(&commit, repo, id);
13799 if (err)
13800 return err;
13802 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13803 if (err)
13804 goto done;
13806 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13807 parent_ids = got_object_commit_get_parent_ids(commit);
13808 fprintf(outfile, "numparents %d\n",
13809 got_object_commit_get_nparents(commit));
13810 STAILQ_FOREACH(pid, parent_ids, entry) {
13811 char *pid_str;
13812 err = got_object_id_str(&pid_str, &pid->id);
13813 if (err)
13814 goto done;
13815 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13816 free(pid_str);
13818 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13819 got_object_commit_get_author_gmtoff(commit));
13820 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13821 got_object_commit_get_author(commit),
13822 (long long)got_object_commit_get_author_time(commit),
13823 gmtoff);
13825 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13826 got_object_commit_get_committer_gmtoff(commit));
13827 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13828 got_object_commit_get_committer(commit),
13829 (long long)got_object_commit_get_committer_time(commit),
13830 gmtoff);
13832 logmsg = got_object_commit_get_logmsg_raw(commit);
13833 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13834 fprintf(outfile, "%s", logmsg);
13835 done:
13836 free(id_str);
13837 got_object_commit_close(commit);
13838 return err;
13841 static const struct got_error *
13842 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13844 const struct got_error *err;
13845 struct got_tag_object *tag;
13846 char *id_str = NULL;
13847 const char *tagmsg = NULL;
13848 char gmtoff[6];
13850 err = got_object_open_as_tag(&tag, repo, id);
13851 if (err)
13852 return err;
13854 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13855 if (err)
13856 goto done;
13858 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13860 switch (got_object_tag_get_object_type(tag)) {
13861 case GOT_OBJ_TYPE_BLOB:
13862 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13863 GOT_OBJ_LABEL_BLOB);
13864 break;
13865 case GOT_OBJ_TYPE_TREE:
13866 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13867 GOT_OBJ_LABEL_TREE);
13868 break;
13869 case GOT_OBJ_TYPE_COMMIT:
13870 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13871 GOT_OBJ_LABEL_COMMIT);
13872 break;
13873 case GOT_OBJ_TYPE_TAG:
13874 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13875 GOT_OBJ_LABEL_TAG);
13876 break;
13877 default:
13878 break;
13881 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13882 got_object_tag_get_name(tag));
13884 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13885 got_object_tag_get_tagger_gmtoff(tag));
13886 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13887 got_object_tag_get_tagger(tag),
13888 (long long)got_object_tag_get_tagger_time(tag),
13889 gmtoff);
13891 tagmsg = got_object_tag_get_message(tag);
13892 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13893 fprintf(outfile, "%s", tagmsg);
13894 done:
13895 free(id_str);
13896 got_object_tag_close(tag);
13897 return err;
13900 static const struct got_error *
13901 cmd_cat(int argc, char *argv[])
13903 const struct got_error *error;
13904 struct got_repository *repo = NULL;
13905 struct got_worktree *worktree = NULL;
13906 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13907 const char *commit_id_str = NULL;
13908 struct got_object_id *id = NULL, *commit_id = NULL;
13909 struct got_commit_object *commit = NULL;
13910 int ch, obj_type, i, force_path = 0;
13911 struct got_reflist_head refs;
13912 int *pack_fds = NULL;
13914 TAILQ_INIT(&refs);
13916 #ifndef PROFILE
13917 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13918 NULL) == -1)
13919 err(1, "pledge");
13920 #endif
13922 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13923 switch (ch) {
13924 case 'c':
13925 commit_id_str = optarg;
13926 break;
13927 case 'P':
13928 force_path = 1;
13929 break;
13930 case 'r':
13931 repo_path = realpath(optarg, NULL);
13932 if (repo_path == NULL)
13933 return got_error_from_errno2("realpath",
13934 optarg);
13935 got_path_strip_trailing_slashes(repo_path);
13936 break;
13937 default:
13938 usage_cat();
13939 /* NOTREACHED */
13943 argc -= optind;
13944 argv += optind;
13946 cwd = getcwd(NULL, 0);
13947 if (cwd == NULL) {
13948 error = got_error_from_errno("getcwd");
13949 goto done;
13952 error = got_repo_pack_fds_open(&pack_fds);
13953 if (error != NULL)
13954 goto done;
13956 if (repo_path == NULL) {
13957 error = got_worktree_open(&worktree, cwd);
13958 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13959 goto done;
13960 if (worktree) {
13961 repo_path = strdup(
13962 got_worktree_get_repo_path(worktree));
13963 if (repo_path == NULL) {
13964 error = got_error_from_errno("strdup");
13965 goto done;
13968 /* Release work tree lock. */
13969 got_worktree_close(worktree);
13970 worktree = NULL;
13974 if (repo_path == NULL) {
13975 repo_path = strdup(cwd);
13976 if (repo_path == NULL)
13977 return got_error_from_errno("strdup");
13980 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13981 free(repo_path);
13982 if (error != NULL)
13983 goto done;
13985 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13986 if (error)
13987 goto done;
13989 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13990 if (error)
13991 goto done;
13993 if (commit_id_str == NULL)
13994 commit_id_str = GOT_REF_HEAD;
13995 error = got_repo_match_object_id(&commit_id, NULL,
13996 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13997 if (error)
13998 goto done;
14000 error = got_object_open_as_commit(&commit, repo, commit_id);
14001 if (error)
14002 goto done;
14004 for (i = 0; i < argc; i++) {
14005 if (force_path) {
14006 error = got_object_id_by_path(&id, repo, commit,
14007 argv[i]);
14008 if (error)
14009 break;
14010 } else {
14011 error = got_repo_match_object_id(&id, &label, argv[i],
14012 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14013 repo);
14014 if (error) {
14015 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14016 error->code != GOT_ERR_NOT_REF)
14017 break;
14018 error = got_object_id_by_path(&id, repo,
14019 commit, argv[i]);
14020 if (error)
14021 break;
14025 error = got_object_get_type(&obj_type, repo, id);
14026 if (error)
14027 break;
14029 switch (obj_type) {
14030 case GOT_OBJ_TYPE_BLOB:
14031 error = cat_blob(id, repo, stdout);
14032 break;
14033 case GOT_OBJ_TYPE_TREE:
14034 error = cat_tree(id, repo, stdout);
14035 break;
14036 case GOT_OBJ_TYPE_COMMIT:
14037 error = cat_commit(id, repo, stdout);
14038 break;
14039 case GOT_OBJ_TYPE_TAG:
14040 error = cat_tag(id, repo, stdout);
14041 break;
14042 default:
14043 error = got_error(GOT_ERR_OBJ_TYPE);
14044 break;
14046 if (error)
14047 break;
14048 free(label);
14049 label = NULL;
14050 free(id);
14051 id = NULL;
14053 done:
14054 free(label);
14055 free(id);
14056 free(commit_id);
14057 if (commit)
14058 got_object_commit_close(commit);
14059 if (worktree)
14060 got_worktree_close(worktree);
14061 if (repo) {
14062 const struct got_error *close_err = got_repo_close(repo);
14063 if (error == NULL)
14064 error = close_err;
14066 if (pack_fds) {
14067 const struct got_error *pack_err =
14068 got_repo_pack_fds_close(pack_fds);
14069 if (error == NULL)
14070 error = pack_err;
14073 got_ref_list_free(&refs);
14074 return error;
14077 __dead static void
14078 usage_info(void)
14080 fprintf(stderr, "usage: %s info [path ...]\n",
14081 getprogname());
14082 exit(1);
14085 static const struct got_error *
14086 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14087 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14088 struct got_object_id *commit_id)
14090 const struct got_error *err = NULL;
14091 char *id_str = NULL;
14092 char datebuf[128];
14093 struct tm mytm, *tm;
14094 struct got_pathlist_head *paths = arg;
14095 struct got_pathlist_entry *pe;
14098 * Clear error indication from any of the path arguments which
14099 * would cause this file index entry to be displayed.
14101 TAILQ_FOREACH(pe, paths, entry) {
14102 if (got_path_cmp(path, pe->path, strlen(path),
14103 pe->path_len) == 0 ||
14104 got_path_is_child(path, pe->path, pe->path_len))
14105 pe->data = NULL; /* no error */
14108 printf(GOT_COMMIT_SEP_STR);
14109 if (S_ISLNK(mode))
14110 printf("symlink: %s\n", path);
14111 else if (S_ISREG(mode)) {
14112 printf("file: %s\n", path);
14113 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14114 } else if (S_ISDIR(mode))
14115 printf("directory: %s\n", path);
14116 else
14117 printf("something: %s\n", path);
14119 tm = localtime_r(&mtime, &mytm);
14120 if (tm == NULL)
14121 return NULL;
14122 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14123 return got_error(GOT_ERR_NO_SPACE);
14124 printf("timestamp: %s\n", datebuf);
14126 if (blob_id) {
14127 err = got_object_id_str(&id_str, blob_id);
14128 if (err)
14129 return err;
14130 printf("based on blob: %s\n", id_str);
14131 free(id_str);
14134 if (staged_blob_id) {
14135 err = got_object_id_str(&id_str, staged_blob_id);
14136 if (err)
14137 return err;
14138 printf("based on staged blob: %s\n", id_str);
14139 free(id_str);
14142 if (commit_id) {
14143 err = got_object_id_str(&id_str, commit_id);
14144 if (err)
14145 return err;
14146 printf("based on commit: %s\n", id_str);
14147 free(id_str);
14150 return NULL;
14153 static const struct got_error *
14154 cmd_info(int argc, char *argv[])
14156 const struct got_error *error = NULL;
14157 struct got_worktree *worktree = NULL;
14158 char *cwd = NULL, *id_str = NULL;
14159 struct got_pathlist_head paths;
14160 char *uuidstr = NULL;
14161 int ch, show_files = 0;
14163 TAILQ_INIT(&paths);
14165 #ifndef PROFILE
14166 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14167 NULL) == -1)
14168 err(1, "pledge");
14169 #endif
14171 while ((ch = getopt(argc, argv, "")) != -1) {
14172 switch (ch) {
14173 default:
14174 usage_info();
14175 /* NOTREACHED */
14179 argc -= optind;
14180 argv += optind;
14182 cwd = getcwd(NULL, 0);
14183 if (cwd == NULL) {
14184 error = got_error_from_errno("getcwd");
14185 goto done;
14188 error = got_worktree_open(&worktree, cwd);
14189 if (error) {
14190 if (error->code == GOT_ERR_NOT_WORKTREE)
14191 error = wrap_not_worktree_error(error, "info", cwd);
14192 goto done;
14195 #ifndef PROFILE
14196 /* Remove "wpath cpath proc exec sendfd" promises. */
14197 if (pledge("stdio rpath flock unveil", NULL) == -1)
14198 err(1, "pledge");
14199 #endif
14200 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14201 if (error)
14202 goto done;
14204 if (argc >= 1) {
14205 error = get_worktree_paths_from_argv(&paths, argc, argv,
14206 worktree);
14207 if (error)
14208 goto done;
14209 show_files = 1;
14212 error = got_object_id_str(&id_str,
14213 got_worktree_get_base_commit_id(worktree));
14214 if (error)
14215 goto done;
14217 error = got_worktree_get_uuid(&uuidstr, worktree);
14218 if (error)
14219 goto done;
14221 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14222 printf("work tree base commit: %s\n", id_str);
14223 printf("work tree path prefix: %s\n",
14224 got_worktree_get_path_prefix(worktree));
14225 printf("work tree branch reference: %s\n",
14226 got_worktree_get_head_ref_name(worktree));
14227 printf("work tree UUID: %s\n", uuidstr);
14228 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14230 if (show_files) {
14231 struct got_pathlist_entry *pe;
14232 TAILQ_FOREACH(pe, &paths, entry) {
14233 if (pe->path_len == 0)
14234 continue;
14236 * Assume this path will fail. This will be corrected
14237 * in print_path_info() in case the path does suceeed.
14239 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14241 error = got_worktree_path_info(worktree, &paths,
14242 print_path_info, &paths, check_cancelled, NULL);
14243 if (error)
14244 goto done;
14245 TAILQ_FOREACH(pe, &paths, entry) {
14246 if (pe->data != NULL) {
14247 const struct got_error *perr;
14249 perr = pe->data;
14250 error = got_error_fmt(perr->code, "%s",
14251 pe->path);
14252 break;
14256 done:
14257 if (worktree)
14258 got_worktree_close(worktree);
14259 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14260 free(cwd);
14261 free(id_str);
14262 free(uuidstr);
14263 return error;