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 || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3110 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3111 goto done;
3113 error = got_worktree_open(&worktree, worktree_path);
3114 if (error != NULL)
3115 goto done;
3117 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3118 path_prefix);
3119 if (error != NULL)
3120 goto done;
3121 if (!same_path_prefix) {
3122 error = got_error(GOT_ERR_PATH_PREFIX);
3123 goto done;
3126 if (commit_id_str) {
3127 struct got_reflist_head refs;
3128 TAILQ_INIT(&refs);
3129 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3130 NULL);
3131 if (error)
3132 goto done;
3133 error = got_repo_match_object_id(&commit_id, NULL,
3134 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3135 got_ref_list_free(&refs);
3136 if (error)
3137 goto done;
3138 error = check_linear_ancestry(commit_id,
3139 got_worktree_get_base_commit_id(worktree), 0, repo);
3140 if (error != NULL) {
3141 if (error->code == GOT_ERR_ANCESTRY) {
3142 error = checkout_ancestry_error(
3143 head_ref, commit_id_str);
3145 goto done;
3147 error = check_same_branch(commit_id, head_ref, repo);
3148 if (error) {
3149 if (error->code == GOT_ERR_ANCESTRY) {
3150 error = checkout_ancestry_error(
3151 head_ref, commit_id_str);
3153 goto done;
3155 error = got_worktree_set_base_commit_id(worktree, repo,
3156 commit_id);
3157 if (error)
3158 goto done;
3159 /* Expand potentially abbreviated commit ID string. */
3160 free(commit_id_str);
3161 error = got_object_id_str(&commit_id_str, commit_id);
3162 if (error)
3163 goto done;
3164 } else {
3165 commit_id = got_object_id_dup(
3166 got_worktree_get_base_commit_id(worktree));
3167 if (commit_id == NULL) {
3168 error = got_error_from_errno("got_object_id_dup");
3169 goto done;
3171 error = got_object_id_str(&commit_id_str, commit_id);
3172 if (error)
3173 goto done;
3176 error = got_pathlist_append(&paths, "", NULL);
3177 if (error)
3178 goto done;
3179 cpa.worktree_path = worktree_path;
3180 cpa.had_base_commit_ref_error = 0;
3181 cpa.verbosity = verbosity;
3182 error = got_worktree_checkout_files(worktree, &paths, repo,
3183 checkout_progress, &cpa, check_cancelled, NULL);
3184 if (error != NULL)
3185 goto done;
3187 if (got_ref_is_symbolic(head_ref)) {
3188 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3189 if (error)
3190 goto done;
3191 refname = got_ref_get_name(ref);
3192 } else
3193 refname = got_ref_get_name(head_ref);
3194 printf("Checked out %s: %s\n", refname, commit_id_str);
3195 printf("Now shut up and hack\n");
3196 if (cpa.had_base_commit_ref_error)
3197 show_worktree_base_ref_warning();
3198 done:
3199 if (pack_fds) {
3200 const struct got_error *pack_err =
3201 got_repo_pack_fds_close(pack_fds);
3202 if (error == NULL)
3203 error = pack_err;
3205 if (head_ref)
3206 got_ref_close(head_ref);
3207 if (ref)
3208 got_ref_close(ref);
3209 if (repo) {
3210 const struct got_error *close_err = got_repo_close(repo);
3211 if (error == NULL)
3212 error = close_err;
3214 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3215 free(commit_id_str);
3216 free(commit_id);
3217 free(repo_path);
3218 free(worktree_path);
3219 free(cwd);
3220 return error;
3223 struct got_update_progress_arg {
3224 int did_something;
3225 int conflicts;
3226 int obstructed;
3227 int not_updated;
3228 int missing;
3229 int not_deleted;
3230 int unversioned;
3231 int verbosity;
3234 static void
3235 print_update_progress_stats(struct got_update_progress_arg *upa)
3237 if (!upa->did_something)
3238 return;
3240 if (upa->conflicts > 0)
3241 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3242 if (upa->obstructed > 0)
3243 printf("File paths obstructed by a non-regular file: %d\n",
3244 upa->obstructed);
3245 if (upa->not_updated > 0)
3246 printf("Files not updated because of existing merge "
3247 "conflicts: %d\n", upa->not_updated);
3251 * The meaning of some status codes differs between merge-style operations and
3252 * update operations. For example, the ! status code means "file was missing"
3253 * if changes were merged into the work tree, and "missing file was restored"
3254 * if the work tree was updated. This function should be used by any operation
3255 * which merges changes into the work tree without updating the work tree.
3257 static void
3258 print_merge_progress_stats(struct got_update_progress_arg *upa)
3260 if (!upa->did_something)
3261 return;
3263 if (upa->conflicts > 0)
3264 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3265 if (upa->obstructed > 0)
3266 printf("File paths obstructed by a non-regular file: %d\n",
3267 upa->obstructed);
3268 if (upa->missing > 0)
3269 printf("Files which had incoming changes but could not be "
3270 "found in the work tree: %d\n", upa->missing);
3271 if (upa->not_deleted > 0)
3272 printf("Files not deleted due to differences in deleted "
3273 "content: %d\n", upa->not_deleted);
3274 if (upa->unversioned > 0)
3275 printf("Files not merged because an unversioned file was "
3276 "found in the work tree: %d\n", upa->unversioned);
3279 __dead static void
3280 usage_update(void)
3282 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3283 "[path ...]\n", getprogname());
3284 exit(1);
3287 static const struct got_error *
3288 update_progress(void *arg, unsigned char status, const char *path)
3290 struct got_update_progress_arg *upa = arg;
3292 if (status == GOT_STATUS_EXISTS ||
3293 status == GOT_STATUS_BASE_REF_ERR)
3294 return NULL;
3296 upa->did_something = 1;
3298 /* Base commit bump happens silently. */
3299 if (status == GOT_STATUS_BUMP_BASE)
3300 return NULL;
3302 if (status == GOT_STATUS_CONFLICT)
3303 upa->conflicts++;
3304 if (status == GOT_STATUS_OBSTRUCTED)
3305 upa->obstructed++;
3306 if (status == GOT_STATUS_CANNOT_UPDATE)
3307 upa->not_updated++;
3308 if (status == GOT_STATUS_MISSING)
3309 upa->missing++;
3310 if (status == GOT_STATUS_CANNOT_DELETE)
3311 upa->not_deleted++;
3312 if (status == GOT_STATUS_UNVERSIONED)
3313 upa->unversioned++;
3315 while (path[0] == '/')
3316 path++;
3317 if (upa->verbosity >= 0)
3318 printf("%c %s\n", status, path);
3320 return NULL;
3323 static const struct got_error *
3324 switch_head_ref(struct got_reference *head_ref,
3325 struct got_object_id *commit_id, struct got_worktree *worktree,
3326 struct got_repository *repo)
3328 const struct got_error *err = NULL;
3329 char *base_id_str;
3330 int ref_has_moved = 0;
3332 /* Trivial case: switching between two different references. */
3333 if (strcmp(got_ref_get_name(head_ref),
3334 got_worktree_get_head_ref_name(worktree)) != 0) {
3335 printf("Switching work tree from %s to %s\n",
3336 got_worktree_get_head_ref_name(worktree),
3337 got_ref_get_name(head_ref));
3338 return got_worktree_set_head_ref(worktree, head_ref);
3341 err = check_linear_ancestry(commit_id,
3342 got_worktree_get_base_commit_id(worktree), 0, repo);
3343 if (err) {
3344 if (err->code != GOT_ERR_ANCESTRY)
3345 return err;
3346 ref_has_moved = 1;
3348 if (!ref_has_moved)
3349 return NULL;
3351 /* Switching to a rebased branch with the same reference name. */
3352 err = got_object_id_str(&base_id_str,
3353 got_worktree_get_base_commit_id(worktree));
3354 if (err)
3355 return err;
3356 printf("Reference %s now points at a different branch\n",
3357 got_worktree_get_head_ref_name(worktree));
3358 printf("Switching work tree from %s to %s\n", base_id_str,
3359 got_worktree_get_head_ref_name(worktree));
3360 return NULL;
3363 static const struct got_error *
3364 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3366 const struct got_error *err;
3367 int in_progress;
3369 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3370 if (err)
3371 return err;
3372 if (in_progress)
3373 return got_error(GOT_ERR_REBASING);
3375 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3376 if (err)
3377 return err;
3378 if (in_progress)
3379 return got_error(GOT_ERR_HISTEDIT_BUSY);
3381 return NULL;
3384 static const struct got_error *
3385 check_merge_in_progress(struct got_worktree *worktree,
3386 struct got_repository *repo)
3388 const struct got_error *err;
3389 int in_progress;
3391 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3392 if (err)
3393 return err;
3394 if (in_progress)
3395 return got_error(GOT_ERR_MERGE_BUSY);
3397 return NULL;
3400 static const struct got_error *
3401 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3402 char *argv[], struct got_worktree *worktree)
3404 const struct got_error *err = NULL;
3405 char *path;
3406 struct got_pathlist_entry *new;
3407 int i;
3409 if (argc == 0) {
3410 path = strdup("");
3411 if (path == NULL)
3412 return got_error_from_errno("strdup");
3413 return got_pathlist_append(paths, path, NULL);
3416 for (i = 0; i < argc; i++) {
3417 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3418 if (err)
3419 break;
3420 err = got_pathlist_insert(&new, paths, path, NULL);
3421 if (err || new == NULL /* duplicate */) {
3422 free(path);
3423 if (err)
3424 break;
3428 return err;
3431 static const struct got_error *
3432 wrap_not_worktree_error(const struct got_error *orig_err,
3433 const char *cmdname, const char *path)
3435 const struct got_error *err;
3436 struct got_repository *repo;
3437 static char msg[512];
3438 int *pack_fds = NULL;
3440 err = got_repo_pack_fds_open(&pack_fds);
3441 if (err)
3442 return err;
3444 err = got_repo_open(&repo, path, NULL, pack_fds);
3445 if (err)
3446 return orig_err;
3448 snprintf(msg, sizeof(msg),
3449 "'got %s' needs a work tree in addition to a git repository\n"
3450 "Work trees can be checked out from this Git repository with "
3451 "'got checkout'.\n"
3452 "The got(1) manual page contains more information.", cmdname);
3453 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3454 if (repo) {
3455 const struct got_error *close_err = got_repo_close(repo);
3456 if (err == NULL)
3457 err = close_err;
3459 if (pack_fds) {
3460 const struct got_error *pack_err =
3461 got_repo_pack_fds_close(pack_fds);
3462 if (err == NULL)
3463 err = pack_err;
3465 return err;
3468 static const struct got_error *
3469 cmd_update(int argc, char *argv[])
3471 const struct got_error *error = NULL;
3472 struct got_repository *repo = NULL;
3473 struct got_worktree *worktree = NULL;
3474 char *worktree_path = NULL;
3475 struct got_object_id *commit_id = NULL;
3476 char *commit_id_str = NULL;
3477 const char *branch_name = NULL;
3478 struct got_reference *head_ref = NULL;
3479 struct got_pathlist_head paths;
3480 struct got_pathlist_entry *pe;
3481 int ch, verbosity = 0;
3482 struct got_update_progress_arg upa;
3483 int *pack_fds = NULL;
3485 TAILQ_INIT(&paths);
3487 #ifndef PROFILE
3488 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3489 "unveil", NULL) == -1)
3490 err(1, "pledge");
3491 #endif
3493 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3494 switch (ch) {
3495 case 'b':
3496 branch_name = optarg;
3497 break;
3498 case 'c':
3499 commit_id_str = strdup(optarg);
3500 if (commit_id_str == NULL)
3501 return got_error_from_errno("strdup");
3502 break;
3503 case 'q':
3504 verbosity = -1;
3505 break;
3506 default:
3507 usage_update();
3508 /* NOTREACHED */
3512 argc -= optind;
3513 argv += optind;
3515 worktree_path = getcwd(NULL, 0);
3516 if (worktree_path == NULL) {
3517 error = got_error_from_errno("getcwd");
3518 goto done;
3521 error = got_repo_pack_fds_open(&pack_fds);
3522 if (error != NULL)
3523 goto done;
3525 error = got_worktree_open(&worktree, worktree_path);
3526 if (error) {
3527 if (error->code == GOT_ERR_NOT_WORKTREE)
3528 error = wrap_not_worktree_error(error, "update",
3529 worktree_path);
3530 goto done;
3533 error = check_rebase_or_histedit_in_progress(worktree);
3534 if (error)
3535 goto done;
3537 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3538 NULL, pack_fds);
3539 if (error != NULL)
3540 goto done;
3542 error = apply_unveil(got_repo_get_path(repo), 0,
3543 got_worktree_get_root_path(worktree));
3544 if (error)
3545 goto done;
3547 error = check_merge_in_progress(worktree, repo);
3548 if (error)
3549 goto done;
3551 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3552 if (error)
3553 goto done;
3555 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3556 got_worktree_get_head_ref_name(worktree), 0);
3557 if (error != NULL)
3558 goto done;
3559 if (commit_id_str == NULL) {
3560 error = got_ref_resolve(&commit_id, repo, head_ref);
3561 if (error != NULL)
3562 goto done;
3563 error = got_object_id_str(&commit_id_str, commit_id);
3564 if (error != NULL)
3565 goto done;
3566 } else {
3567 struct got_reflist_head refs;
3568 TAILQ_INIT(&refs);
3569 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3570 NULL);
3571 if (error)
3572 goto done;
3573 error = got_repo_match_object_id(&commit_id, NULL,
3574 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3575 got_ref_list_free(&refs);
3576 free(commit_id_str);
3577 commit_id_str = NULL;
3578 if (error)
3579 goto done;
3580 error = got_object_id_str(&commit_id_str, commit_id);
3581 if (error)
3582 goto done;
3585 if (branch_name) {
3586 struct got_object_id *head_commit_id;
3587 TAILQ_FOREACH(pe, &paths, entry) {
3588 if (pe->path_len == 0)
3589 continue;
3590 error = got_error_msg(GOT_ERR_BAD_PATH,
3591 "switching between branches requires that "
3592 "the entire work tree gets updated");
3593 goto done;
3595 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3596 if (error)
3597 goto done;
3598 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3599 repo);
3600 free(head_commit_id);
3601 if (error != NULL)
3602 goto done;
3603 error = check_same_branch(commit_id, head_ref, repo);
3604 if (error)
3605 goto done;
3606 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3607 if (error)
3608 goto done;
3609 } else {
3610 error = check_linear_ancestry(commit_id,
3611 got_worktree_get_base_commit_id(worktree), 0, repo);
3612 if (error != NULL) {
3613 if (error->code == GOT_ERR_ANCESTRY)
3614 error = got_error(GOT_ERR_BRANCH_MOVED);
3615 goto done;
3617 error = check_same_branch(commit_id, head_ref, repo);
3618 if (error)
3619 goto done;
3622 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3623 commit_id) != 0) {
3624 error = got_worktree_set_base_commit_id(worktree, repo,
3625 commit_id);
3626 if (error)
3627 goto done;
3630 memset(&upa, 0, sizeof(upa));
3631 upa.verbosity = verbosity;
3632 error = got_worktree_checkout_files(worktree, &paths, repo,
3633 update_progress, &upa, check_cancelled, NULL);
3634 if (error != NULL)
3635 goto done;
3637 if (upa.did_something) {
3638 printf("Updated to %s: %s\n",
3639 got_worktree_get_head_ref_name(worktree), commit_id_str);
3640 } else
3641 printf("Already up-to-date\n");
3643 print_update_progress_stats(&upa);
3644 done:
3645 if (pack_fds) {
3646 const struct got_error *pack_err =
3647 got_repo_pack_fds_close(pack_fds);
3648 if (error == NULL)
3649 error = pack_err;
3651 if (repo) {
3652 const struct got_error *close_err = got_repo_close(repo);
3653 if (error == NULL)
3654 error = close_err;
3656 free(worktree_path);
3657 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3658 free(commit_id);
3659 free(commit_id_str);
3660 return error;
3663 static const struct got_error *
3664 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3665 const char *path, int diff_context, int ignore_whitespace,
3666 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3667 struct got_repository *repo, FILE *outfile)
3669 const struct got_error *err = NULL;
3670 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3671 FILE *f1 = NULL, *f2 = NULL;
3672 int fd1 = -1, fd2 = -1;
3674 fd1 = got_opentempfd();
3675 if (fd1 == -1)
3676 return got_error_from_errno("got_opentempfd");
3677 fd2 = got_opentempfd();
3678 if (fd2 == -1) {
3679 err = got_error_from_errno("got_opentempfd");
3680 goto done;
3683 if (blob_id1) {
3684 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3685 fd1);
3686 if (err)
3687 goto done;
3690 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3691 if (err)
3692 goto done;
3694 f1 = got_opentemp();
3695 if (f1 == NULL) {
3696 err = got_error_from_errno("got_opentemp");
3697 goto done;
3699 f2 = got_opentemp();
3700 if (f2 == NULL) {
3701 err = got_error_from_errno("got_opentemp");
3702 goto done;
3705 while (path[0] == '/')
3706 path++;
3707 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3708 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3709 force_text_diff, dsa, outfile);
3710 done:
3711 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3712 err = got_error_from_errno("close");
3713 if (blob1)
3714 got_object_blob_close(blob1);
3715 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3716 err = got_error_from_errno("close");
3717 if (blob2)
3718 got_object_blob_close(blob2);
3719 if (f1 && fclose(f1) == EOF && err == NULL)
3720 err = got_error_from_errno("fclose");
3721 if (f2 && fclose(f2) == EOF && err == NULL)
3722 err = got_error_from_errno("fclose");
3723 return err;
3726 static const struct got_error *
3727 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3728 const char *path, int diff_context, int ignore_whitespace,
3729 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3730 struct got_repository *repo, FILE *outfile)
3732 const struct got_error *err = NULL;
3733 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3734 struct got_diff_blob_output_unidiff_arg arg;
3735 FILE *f1 = NULL, *f2 = NULL;
3736 int fd1 = -1, fd2 = -1;
3738 if (tree_id1) {
3739 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3740 if (err)
3741 goto done;
3742 fd1 = got_opentempfd();
3743 if (fd1 == -1) {
3744 err = got_error_from_errno("got_opentempfd");
3745 goto done;
3749 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3750 if (err)
3751 goto done;
3753 f1 = got_opentemp();
3754 if (f1 == NULL) {
3755 err = got_error_from_errno("got_opentemp");
3756 goto done;
3759 f2 = got_opentemp();
3760 if (f2 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3764 fd2 = got_opentempfd();
3765 if (fd2 == -1) {
3766 err = got_error_from_errno("got_opentempfd");
3767 goto done;
3769 arg.diff_context = diff_context;
3770 arg.ignore_whitespace = ignore_whitespace;
3771 arg.force_text_diff = force_text_diff;
3772 arg.diffstat = dsa;
3773 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3774 arg.outfile = outfile;
3775 arg.lines = NULL;
3776 arg.nlines = 0;
3777 while (path[0] == '/')
3778 path++;
3779 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3780 got_diff_blob_output_unidiff, &arg, 1);
3781 done:
3782 if (tree1)
3783 got_object_tree_close(tree1);
3784 if (tree2)
3785 got_object_tree_close(tree2);
3786 if (f1 && fclose(f1) == EOF && err == NULL)
3787 err = got_error_from_errno("fclose");
3788 if (f2 && fclose(f2) == EOF && err == NULL)
3789 err = got_error_from_errno("fclose");
3790 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3791 err = got_error_from_errno("close");
3792 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3793 err = got_error_from_errno("close");
3794 return err;
3797 static const struct got_error *
3798 get_changed_paths(struct got_pathlist_head *paths,
3799 struct got_commit_object *commit, struct got_repository *repo,
3800 struct got_diffstat_cb_arg *dsa)
3802 const struct got_error *err = NULL;
3803 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3804 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3805 struct got_object_qid *qid;
3806 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3807 FILE *f1 = NULL, *f2 = NULL;
3808 int fd1 = -1, fd2 = -1;
3810 if (dsa) {
3811 cb = got_diff_tree_compute_diffstat;
3813 f1 = got_opentemp();
3814 if (f1 == NULL) {
3815 err = got_error_from_errno("got_opentemp");
3816 goto done;
3818 f2 = got_opentemp();
3819 if (f2 == NULL) {
3820 err = got_error_from_errno("got_opentemp");
3821 goto done;
3823 fd1 = got_opentempfd();
3824 if (fd1 == -1) {
3825 err = got_error_from_errno("got_opentempfd");
3826 goto done;
3828 fd2 = got_opentempfd();
3829 if (fd2 == -1) {
3830 err = got_error_from_errno("got_opentempfd");
3831 goto done;
3835 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3836 if (qid != NULL) {
3837 struct got_commit_object *pcommit;
3838 err = got_object_open_as_commit(&pcommit, repo,
3839 &qid->id);
3840 if (err)
3841 return err;
3843 tree_id1 = got_object_id_dup(
3844 got_object_commit_get_tree_id(pcommit));
3845 if (tree_id1 == NULL) {
3846 got_object_commit_close(pcommit);
3847 return got_error_from_errno("got_object_id_dup");
3849 got_object_commit_close(pcommit);
3853 if (tree_id1) {
3854 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3855 if (err)
3856 goto done;
3859 tree_id2 = got_object_commit_get_tree_id(commit);
3860 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3861 if (err)
3862 goto done;
3864 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3865 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3866 done:
3867 if (tree1)
3868 got_object_tree_close(tree1);
3869 if (tree2)
3870 got_object_tree_close(tree2);
3871 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3872 err = got_error_from_errno("close");
3873 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3874 err = got_error_from_errno("close");
3875 if (f1 && fclose(f1) == EOF && err == NULL)
3876 err = got_error_from_errno("fclose");
3877 if (f2 && fclose(f2) == EOF && err == NULL)
3878 err = got_error_from_errno("fclose");
3879 free(tree_id1);
3880 return err;
3883 static const struct got_error *
3884 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3885 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3886 struct got_repository *repo, FILE *outfile)
3888 const struct got_error *err = NULL;
3889 struct got_commit_object *pcommit = NULL;
3890 char *id_str1 = NULL, *id_str2 = NULL;
3891 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3892 struct got_object_qid *qid;
3894 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3895 if (qid != NULL) {
3896 err = got_object_open_as_commit(&pcommit, repo,
3897 &qid->id);
3898 if (err)
3899 return err;
3900 err = got_object_id_str(&id_str1, &qid->id);
3901 if (err)
3902 goto done;
3905 err = got_object_id_str(&id_str2, id);
3906 if (err)
3907 goto done;
3909 if (path && path[0] != '\0') {
3910 int obj_type;
3911 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3912 if (err)
3913 goto done;
3914 if (pcommit) {
3915 err = got_object_id_by_path(&obj_id1, repo,
3916 pcommit, path);
3917 if (err) {
3918 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3919 free(obj_id2);
3920 goto done;
3924 err = got_object_get_type(&obj_type, repo, obj_id2);
3925 if (err) {
3926 free(obj_id2);
3927 goto done;
3929 fprintf(outfile,
3930 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3931 fprintf(outfile, "commit - %s\n",
3932 id_str1 ? id_str1 : "/dev/null");
3933 fprintf(outfile, "commit + %s\n", id_str2);
3934 switch (obj_type) {
3935 case GOT_OBJ_TYPE_BLOB:
3936 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3937 0, 0, dsa, repo, outfile);
3938 break;
3939 case GOT_OBJ_TYPE_TREE:
3940 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3941 0, 0, dsa, repo, outfile);
3942 break;
3943 default:
3944 err = got_error(GOT_ERR_OBJ_TYPE);
3945 break;
3947 free(obj_id1);
3948 free(obj_id2);
3949 } else {
3950 obj_id2 = got_object_commit_get_tree_id(commit);
3951 if (pcommit)
3952 obj_id1 = got_object_commit_get_tree_id(pcommit);
3953 fprintf(outfile,
3954 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3955 fprintf(outfile, "commit - %s\n",
3956 id_str1 ? id_str1 : "/dev/null");
3957 fprintf(outfile, "commit + %s\n", id_str2);
3958 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3959 dsa, repo, outfile);
3961 done:
3962 free(id_str1);
3963 free(id_str2);
3964 if (pcommit)
3965 got_object_commit_close(pcommit);
3966 return err;
3969 static char *
3970 get_datestr(time_t *time, char *datebuf)
3972 struct tm mytm, *tm;
3973 char *p, *s;
3975 tm = gmtime_r(time, &mytm);
3976 if (tm == NULL)
3977 return NULL;
3978 s = asctime_r(tm, datebuf);
3979 if (s == NULL)
3980 return NULL;
3981 p = strchr(s, '\n');
3982 if (p)
3983 *p = '\0';
3984 return s;
3987 static const struct got_error *
3988 match_commit(int *have_match, struct got_object_id *id,
3989 struct got_commit_object *commit, regex_t *regex)
3991 const struct got_error *err = NULL;
3992 regmatch_t regmatch;
3993 char *id_str = NULL, *logmsg = NULL;
3995 *have_match = 0;
3997 err = got_object_id_str(&id_str, id);
3998 if (err)
3999 return err;
4001 err = got_object_commit_get_logmsg(&logmsg, commit);
4002 if (err)
4003 goto done;
4005 if (regexec(regex, got_object_commit_get_author(commit), 1,
4006 &regmatch, 0) == 0 ||
4007 regexec(regex, got_object_commit_get_committer(commit), 1,
4008 &regmatch, 0) == 0 ||
4009 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4010 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4011 *have_match = 1;
4012 done:
4013 free(id_str);
4014 free(logmsg);
4015 return err;
4018 static void
4019 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4020 regex_t *regex)
4022 regmatch_t regmatch;
4023 struct got_pathlist_entry *pe;
4025 *have_match = 0;
4027 TAILQ_FOREACH(pe, changed_paths, entry) {
4028 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4029 *have_match = 1;
4030 break;
4035 static const struct got_error *
4036 match_patch(int *have_match, struct got_commit_object *commit,
4037 struct got_object_id *id, const char *path, int diff_context,
4038 struct got_repository *repo, regex_t *regex, FILE *f)
4040 const struct got_error *err = NULL;
4041 char *line = NULL;
4042 size_t linesize = 0;
4043 regmatch_t regmatch;
4045 *have_match = 0;
4047 err = got_opentemp_truncate(f);
4048 if (err)
4049 return err;
4051 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4052 if (err)
4053 goto done;
4055 if (fseeko(f, 0L, SEEK_SET) == -1) {
4056 err = got_error_from_errno("fseeko");
4057 goto done;
4060 while (getline(&line, &linesize, f) != -1) {
4061 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4062 *have_match = 1;
4063 break;
4066 done:
4067 free(line);
4068 return err;
4071 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4073 static const struct got_error*
4074 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4075 struct got_object_id *id, struct got_repository *repo,
4076 int local_only)
4078 static const struct got_error *err = NULL;
4079 struct got_reflist_entry *re;
4080 char *s;
4081 const char *name;
4083 *refs_str = NULL;
4085 TAILQ_FOREACH(re, refs, entry) {
4086 struct got_tag_object *tag = NULL;
4087 struct got_object_id *ref_id;
4088 int cmp;
4090 name = got_ref_get_name(re->ref);
4091 if (strcmp(name, GOT_REF_HEAD) == 0)
4092 continue;
4093 if (strncmp(name, "refs/", 5) == 0)
4094 name += 5;
4095 if (strncmp(name, "got/", 4) == 0)
4096 continue;
4097 if (strncmp(name, "heads/", 6) == 0)
4098 name += 6;
4099 if (strncmp(name, "remotes/", 8) == 0) {
4100 if (local_only)
4101 continue;
4102 name += 8;
4103 s = strstr(name, "/" GOT_REF_HEAD);
4104 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4105 continue;
4107 err = got_ref_resolve(&ref_id, repo, re->ref);
4108 if (err)
4109 break;
4110 if (strncmp(name, "tags/", 5) == 0) {
4111 err = got_object_open_as_tag(&tag, repo, ref_id);
4112 if (err) {
4113 if (err->code != GOT_ERR_OBJ_TYPE) {
4114 free(ref_id);
4115 break;
4117 /* Ref points at something other than a tag. */
4118 err = NULL;
4119 tag = NULL;
4122 cmp = got_object_id_cmp(tag ?
4123 got_object_tag_get_object_id(tag) : ref_id, id);
4124 free(ref_id);
4125 if (tag)
4126 got_object_tag_close(tag);
4127 if (cmp != 0)
4128 continue;
4129 s = *refs_str;
4130 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4131 s ? ", " : "", name) == -1) {
4132 err = got_error_from_errno("asprintf");
4133 free(s);
4134 *refs_str = NULL;
4135 break;
4137 free(s);
4140 return err;
4143 static const struct got_error *
4144 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4145 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4147 const struct got_error *err = NULL;
4148 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4149 char *comma, *s, *nl;
4150 struct got_reflist_head *refs;
4151 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4152 struct tm tm;
4153 time_t committer_time;
4155 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4156 if (refs) {
4157 err = build_refs_str(&ref_str, refs, id, repo, 1);
4158 if (err)
4159 return err;
4161 /* Display the first matching ref only. */
4162 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4163 *comma = '\0';
4166 if (ref_str == NULL) {
4167 err = got_object_id_str(&id_str, id);
4168 if (err)
4169 return err;
4172 committer_time = got_object_commit_get_committer_time(commit);
4173 if (gmtime_r(&committer_time, &tm) == NULL) {
4174 err = got_error_from_errno("gmtime_r");
4175 goto done;
4177 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4178 err = got_error(GOT_ERR_NO_SPACE);
4179 goto done;
4182 err = got_object_commit_get_logmsg(&logmsg0, commit);
4183 if (err)
4184 goto done;
4186 s = logmsg0;
4187 while (isspace((unsigned char)s[0]))
4188 s++;
4190 nl = strchr(s, '\n');
4191 if (nl) {
4192 *nl = '\0';
4195 if (ref_str)
4196 printf("%s%-7s %s\n", datebuf, ref_str, s);
4197 else
4198 printf("%s%.7s %s\n", datebuf, id_str, s);
4200 if (fflush(stdout) != 0 && err == NULL)
4201 err = got_error_from_errno("fflush");
4202 done:
4203 free(id_str);
4204 free(ref_str);
4205 free(logmsg0);
4206 return err;
4209 static const struct got_error *
4210 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4212 struct got_pathlist_entry *pe;
4214 if (header != NULL)
4215 printf("%s\n", header);
4217 TAILQ_FOREACH(pe, dsa->paths, entry) {
4218 struct got_diff_changed_path *cp = pe->data;
4219 int pad = dsa->max_path_len - pe->path_len + 1;
4221 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4222 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4224 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4225 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4226 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4228 if (fflush(stdout) != 0)
4229 return got_error_from_errno("fflush");
4231 return NULL;
4234 static const struct got_error *
4235 printfile(FILE *f)
4237 char buf[8192];
4238 size_t r;
4240 if (fseeko(f, 0L, SEEK_SET) == -1)
4241 return got_error_from_errno("fseek");
4243 for (;;) {
4244 r = fread(buf, 1, sizeof(buf), f);
4245 if (r == 0) {
4246 if (ferror(f))
4247 return got_error_from_errno("fread");
4248 if (feof(f))
4249 break;
4251 if (fwrite(buf, 1, r, stdout) != r)
4252 return got_ferror(stdout, GOT_ERR_IO);
4255 return NULL;
4258 static const struct got_error *
4259 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4260 struct got_repository *repo, const char *path,
4261 struct got_pathlist_head *changed_paths,
4262 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4263 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4264 const char *prefix)
4266 const struct got_error *err = NULL;
4267 FILE *f = NULL;
4268 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4269 char datebuf[26];
4270 time_t committer_time;
4271 const char *author, *committer;
4272 char *refs_str = NULL;
4274 err = got_object_id_str(&id_str, id);
4275 if (err)
4276 return err;
4278 if (custom_refs_str == NULL) {
4279 struct got_reflist_head *refs;
4280 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4281 if (refs) {
4282 err = build_refs_str(&refs_str, refs, id, repo, 0);
4283 if (err)
4284 goto done;
4288 printf(GOT_COMMIT_SEP_STR);
4289 if (custom_refs_str)
4290 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4291 custom_refs_str);
4292 else
4293 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4294 refs_str ? " (" : "", refs_str ? refs_str : "",
4295 refs_str ? ")" : "");
4296 free(id_str);
4297 id_str = NULL;
4298 free(refs_str);
4299 refs_str = NULL;
4300 printf("from: %s\n", got_object_commit_get_author(commit));
4301 author = got_object_commit_get_author(commit);
4302 committer = got_object_commit_get_committer(commit);
4303 if (strcmp(author, committer) != 0)
4304 printf("via: %s\n", committer);
4305 committer_time = got_object_commit_get_committer_time(commit);
4306 datestr = get_datestr(&committer_time, datebuf);
4307 if (datestr)
4308 printf("date: %s UTC\n", datestr);
4309 if (got_object_commit_get_nparents(commit) > 1) {
4310 const struct got_object_id_queue *parent_ids;
4311 struct got_object_qid *qid;
4312 int n = 1;
4313 parent_ids = got_object_commit_get_parent_ids(commit);
4314 STAILQ_FOREACH(qid, parent_ids, entry) {
4315 err = got_object_id_str(&id_str, &qid->id);
4316 if (err)
4317 goto done;
4318 printf("parent %d: %s\n", n++, id_str);
4319 free(id_str);
4320 id_str = NULL;
4324 err = got_object_commit_get_logmsg(&logmsg0, commit);
4325 if (err)
4326 goto done;
4328 logmsg = logmsg0;
4329 do {
4330 line = strsep(&logmsg, "\n");
4331 if (line)
4332 printf(" %s\n", line);
4333 } while (line);
4334 free(logmsg0);
4336 if (changed_paths && diffstat == NULL) {
4337 struct got_pathlist_entry *pe;
4339 TAILQ_FOREACH(pe, changed_paths, entry) {
4340 struct got_diff_changed_path *cp = pe->data;
4342 printf(" %c %s\n", cp->status, pe->path);
4344 printf("\n");
4346 if (show_patch) {
4347 if (diffstat) {
4348 f = got_opentemp();
4349 if (f == NULL) {
4350 err = got_error_from_errno("got_opentemp");
4351 goto done;
4355 err = print_patch(commit, id, path, diff_context, diffstat,
4356 repo, diffstat == NULL ? stdout : f);
4357 if (err)
4358 goto done;
4360 if (diffstat) {
4361 err = print_diffstat(diffstat, NULL);
4362 if (err)
4363 goto done;
4364 if (show_patch) {
4365 err = printfile(f);
4366 if (err)
4367 goto done;
4370 if (show_patch)
4371 printf("\n");
4373 if (fflush(stdout) != 0 && err == NULL)
4374 err = got_error_from_errno("fflush");
4375 done:
4376 if (f && fclose(f) == EOF && err == NULL)
4377 err = got_error_from_errno("fclose");
4378 free(id_str);
4379 free(refs_str);
4380 return err;
4383 static const struct got_error *
4384 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4385 struct got_repository *repo, const char *path, int show_changed_paths,
4386 int show_diffstat, int show_patch, const char *search_pattern,
4387 int diff_context, int limit, int log_branches, int reverse_display_order,
4388 struct got_reflist_object_id_map *refs_idmap, int one_line,
4389 FILE *tmpfile)
4391 const struct got_error *err;
4392 struct got_commit_graph *graph;
4393 regex_t regex;
4394 int have_match;
4395 struct got_object_id_queue reversed_commits;
4396 struct got_object_qid *qid;
4397 struct got_commit_object *commit;
4398 struct got_pathlist_head changed_paths;
4400 STAILQ_INIT(&reversed_commits);
4401 TAILQ_INIT(&changed_paths);
4403 if (search_pattern && regcomp(&regex, search_pattern,
4404 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4405 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4407 err = got_commit_graph_open(&graph, path, !log_branches);
4408 if (err)
4409 return err;
4410 err = got_commit_graph_iter_start(graph, root_id, repo,
4411 check_cancelled, NULL);
4412 if (err)
4413 goto done;
4414 for (;;) {
4415 struct got_object_id id;
4416 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4417 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4419 if (sigint_received || sigpipe_received)
4420 break;
4422 err = got_commit_graph_iter_next(&id, graph, repo,
4423 check_cancelled, NULL);
4424 if (err) {
4425 if (err->code == GOT_ERR_ITER_COMPLETED)
4426 err = NULL;
4427 break;
4430 err = got_object_open_as_commit(&commit, repo, &id);
4431 if (err)
4432 break;
4434 if ((show_changed_paths || (show_diffstat && !show_patch))
4435 && !reverse_display_order) {
4436 err = get_changed_paths(&changed_paths, commit, repo,
4437 show_diffstat ? &dsa : NULL);
4438 if (err)
4439 break;
4442 if (search_pattern) {
4443 err = match_commit(&have_match, &id, commit, &regex);
4444 if (err) {
4445 got_object_commit_close(commit);
4446 break;
4448 if (have_match == 0 && show_changed_paths)
4449 match_changed_paths(&have_match,
4450 &changed_paths, &regex);
4451 if (have_match == 0 && show_patch) {
4452 err = match_patch(&have_match, commit, &id,
4453 path, diff_context, repo, &regex, tmpfile);
4454 if (err)
4455 break;
4457 if (have_match == 0) {
4458 got_object_commit_close(commit);
4459 got_pathlist_free(&changed_paths,
4460 GOT_PATHLIST_FREE_ALL);
4461 continue;
4465 if (reverse_display_order) {
4466 err = got_object_qid_alloc(&qid, &id);
4467 if (err)
4468 break;
4469 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4470 got_object_commit_close(commit);
4471 } else {
4472 if (one_line)
4473 err = print_commit_oneline(commit, &id,
4474 repo, refs_idmap);
4475 else
4476 err = print_commit(commit, &id, repo, path,
4477 (show_changed_paths || show_diffstat) ?
4478 &changed_paths : NULL,
4479 show_diffstat ? &dsa : NULL, show_patch,
4480 diff_context, refs_idmap, NULL, NULL);
4481 got_object_commit_close(commit);
4482 if (err)
4483 break;
4485 if ((limit && --limit == 0) ||
4486 (end_id && got_object_id_cmp(&id, end_id) == 0))
4487 break;
4489 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4491 if (reverse_display_order) {
4492 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4493 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4494 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4496 err = got_object_open_as_commit(&commit, repo,
4497 &qid->id);
4498 if (err)
4499 break;
4500 if (show_changed_paths ||
4501 (show_diffstat && !show_patch)) {
4502 err = get_changed_paths(&changed_paths, commit,
4503 repo, show_diffstat ? &dsa : NULL);
4504 if (err)
4505 break;
4507 if (one_line)
4508 err = print_commit_oneline(commit, &qid->id,
4509 repo, refs_idmap);
4510 else
4511 err = print_commit(commit, &qid->id, repo, path,
4512 (show_changed_paths || show_diffstat) ?
4513 &changed_paths : NULL,
4514 show_diffstat ? &dsa : NULL, show_patch,
4515 diff_context, refs_idmap, NULL, NULL);
4516 got_object_commit_close(commit);
4517 if (err)
4518 break;
4519 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4522 done:
4523 while (!STAILQ_EMPTY(&reversed_commits)) {
4524 qid = STAILQ_FIRST(&reversed_commits);
4525 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4526 got_object_qid_free(qid);
4528 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4529 if (search_pattern)
4530 regfree(&regex);
4531 got_commit_graph_close(graph);
4532 return err;
4535 __dead static void
4536 usage_log(void)
4538 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4539 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4540 "[path]\n", getprogname());
4541 exit(1);
4544 static int
4545 get_default_log_limit(void)
4547 const char *got_default_log_limit;
4548 long long n;
4549 const char *errstr;
4551 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4552 if (got_default_log_limit == NULL)
4553 return 0;
4554 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4555 if (errstr != NULL)
4556 return 0;
4557 return n;
4560 static const struct got_error *
4561 cmd_log(int argc, char *argv[])
4563 const struct got_error *error;
4564 struct got_repository *repo = NULL;
4565 struct got_worktree *worktree = NULL;
4566 struct got_object_id *start_id = NULL, *end_id = NULL;
4567 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4568 const char *start_commit = NULL, *end_commit = NULL;
4569 const char *search_pattern = NULL;
4570 int diff_context = -1, ch;
4571 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4572 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4573 const char *errstr;
4574 struct got_reflist_head refs;
4575 struct got_reflist_object_id_map *refs_idmap = NULL;
4576 FILE *tmpfile = NULL;
4577 int *pack_fds = NULL;
4579 TAILQ_INIT(&refs);
4581 #ifndef PROFILE
4582 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4583 NULL)
4584 == -1)
4585 err(1, "pledge");
4586 #endif
4588 limit = get_default_log_limit();
4590 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4591 switch (ch) {
4592 case 'b':
4593 log_branches = 1;
4594 break;
4595 case 'C':
4596 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4597 &errstr);
4598 if (errstr != NULL)
4599 errx(1, "number of context lines is %s: %s",
4600 errstr, optarg);
4601 break;
4602 case 'c':
4603 start_commit = optarg;
4604 break;
4605 case 'd':
4606 show_diffstat = 1;
4607 break;
4608 case 'l':
4609 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4610 if (errstr != NULL)
4611 errx(1, "number of commits is %s: %s",
4612 errstr, optarg);
4613 break;
4614 case 'P':
4615 show_changed_paths = 1;
4616 break;
4617 case 'p':
4618 show_patch = 1;
4619 break;
4620 case 'R':
4621 reverse_display_order = 1;
4622 break;
4623 case 'r':
4624 repo_path = realpath(optarg, NULL);
4625 if (repo_path == NULL)
4626 return got_error_from_errno2("realpath",
4627 optarg);
4628 got_path_strip_trailing_slashes(repo_path);
4629 break;
4630 case 'S':
4631 search_pattern = optarg;
4632 break;
4633 case 's':
4634 one_line = 1;
4635 break;
4636 case 'x':
4637 end_commit = optarg;
4638 break;
4639 default:
4640 usage_log();
4641 /* NOTREACHED */
4645 argc -= optind;
4646 argv += optind;
4648 if (diff_context == -1)
4649 diff_context = 3;
4650 else if (!show_patch)
4651 errx(1, "-C requires -p");
4653 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4654 errx(1, "cannot use -s with -d, -p or -P");
4656 cwd = getcwd(NULL, 0);
4657 if (cwd == NULL) {
4658 error = got_error_from_errno("getcwd");
4659 goto done;
4662 error = got_repo_pack_fds_open(&pack_fds);
4663 if (error != NULL)
4664 goto done;
4666 if (repo_path == NULL) {
4667 error = got_worktree_open(&worktree, cwd);
4668 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4669 goto done;
4670 error = NULL;
4673 if (argc == 1) {
4674 if (worktree) {
4675 error = got_worktree_resolve_path(&path, worktree,
4676 argv[0]);
4677 if (error)
4678 goto done;
4679 } else {
4680 path = strdup(argv[0]);
4681 if (path == NULL) {
4682 error = got_error_from_errno("strdup");
4683 goto done;
4686 } else if (argc != 0)
4687 usage_log();
4689 if (repo_path == NULL) {
4690 repo_path = worktree ?
4691 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4693 if (repo_path == NULL) {
4694 error = got_error_from_errno("strdup");
4695 goto done;
4698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4699 if (error != NULL)
4700 goto done;
4702 error = apply_unveil(got_repo_get_path(repo), 1,
4703 worktree ? got_worktree_get_root_path(worktree) : NULL);
4704 if (error)
4705 goto done;
4707 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4708 if (error)
4709 goto done;
4711 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4712 if (error)
4713 goto done;
4715 if (start_commit == NULL) {
4716 struct got_reference *head_ref;
4717 struct got_commit_object *commit = NULL;
4718 error = got_ref_open(&head_ref, repo,
4719 worktree ? got_worktree_get_head_ref_name(worktree)
4720 : GOT_REF_HEAD, 0);
4721 if (error != NULL)
4722 goto done;
4723 error = got_ref_resolve(&start_id, repo, head_ref);
4724 got_ref_close(head_ref);
4725 if (error != NULL)
4726 goto done;
4727 error = got_object_open_as_commit(&commit, repo,
4728 start_id);
4729 if (error != NULL)
4730 goto done;
4731 got_object_commit_close(commit);
4732 } else {
4733 error = got_repo_match_object_id(&start_id, NULL,
4734 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4735 if (error != NULL)
4736 goto done;
4738 if (end_commit != NULL) {
4739 error = got_repo_match_object_id(&end_id, NULL,
4740 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4741 if (error != NULL)
4742 goto done;
4745 if (worktree) {
4747 * If a path was specified on the command line it was resolved
4748 * to a path in the work tree above. Prepend the work tree's
4749 * path prefix to obtain the corresponding in-repository path.
4751 if (path) {
4752 const char *prefix;
4753 prefix = got_worktree_get_path_prefix(worktree);
4754 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4755 (path[0] != '\0') ? "/" : "", path) == -1) {
4756 error = got_error_from_errno("asprintf");
4757 goto done;
4760 } else
4761 error = got_repo_map_path(&in_repo_path, repo,
4762 path ? path : "");
4763 if (error != NULL)
4764 goto done;
4765 if (in_repo_path) {
4766 free(path);
4767 path = in_repo_path;
4770 if (worktree) {
4771 /* Release work tree lock. */
4772 got_worktree_close(worktree);
4773 worktree = NULL;
4776 if (search_pattern && show_patch) {
4777 tmpfile = got_opentemp();
4778 if (tmpfile == NULL) {
4779 error = got_error_from_errno("got_opentemp");
4780 goto done;
4784 error = print_commits(start_id, end_id, repo, path ? path : "",
4785 show_changed_paths, show_diffstat, show_patch, search_pattern,
4786 diff_context, limit, log_branches, reverse_display_order,
4787 refs_idmap, one_line, tmpfile);
4788 done:
4789 free(path);
4790 free(repo_path);
4791 free(cwd);
4792 free(start_id);
4793 free(end_id);
4794 if (worktree)
4795 got_worktree_close(worktree);
4796 if (repo) {
4797 const struct got_error *close_err = got_repo_close(repo);
4798 if (error == NULL)
4799 error = close_err;
4801 if (pack_fds) {
4802 const struct got_error *pack_err =
4803 got_repo_pack_fds_close(pack_fds);
4804 if (error == NULL)
4805 error = pack_err;
4807 if (refs_idmap)
4808 got_reflist_object_id_map_free(refs_idmap);
4809 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4810 error = got_error_from_errno("fclose");
4811 got_ref_list_free(&refs);
4812 return error;
4815 __dead static void
4816 usage_diff(void)
4818 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4819 "[-r repository-path] [object1 object2 | path ...]\n",
4820 getprogname());
4821 exit(1);
4824 struct print_diff_arg {
4825 struct got_repository *repo;
4826 struct got_worktree *worktree;
4827 struct got_diffstat_cb_arg *diffstat;
4828 int diff_context;
4829 const char *id_str;
4830 int header_shown;
4831 int diff_staged;
4832 enum got_diff_algorithm diff_algo;
4833 int ignore_whitespace;
4834 int force_text_diff;
4835 FILE *f1;
4836 FILE *f2;
4837 FILE *outfile;
4841 * Create a file which contains the target path of a symlink so we can feed
4842 * it as content to the diff engine.
4844 static const struct got_error *
4845 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4846 const char *abspath)
4848 const struct got_error *err = NULL;
4849 char target_path[PATH_MAX];
4850 ssize_t target_len, outlen;
4852 *fd = -1;
4854 if (dirfd != -1) {
4855 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4856 if (target_len == -1)
4857 return got_error_from_errno2("readlinkat", abspath);
4858 } else {
4859 target_len = readlink(abspath, target_path, PATH_MAX);
4860 if (target_len == -1)
4861 return got_error_from_errno2("readlink", abspath);
4864 *fd = got_opentempfd();
4865 if (*fd == -1)
4866 return got_error_from_errno("got_opentempfd");
4868 outlen = write(*fd, target_path, target_len);
4869 if (outlen == -1) {
4870 err = got_error_from_errno("got_opentempfd");
4871 goto done;
4874 if (lseek(*fd, 0, SEEK_SET) == -1) {
4875 err = got_error_from_errno2("lseek", abspath);
4876 goto done;
4878 done:
4879 if (err) {
4880 close(*fd);
4881 *fd = -1;
4883 return err;
4886 static const struct got_error *
4887 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4888 const char *path, struct got_object_id *blob_id,
4889 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4890 int dirfd, const char *de_name)
4892 struct print_diff_arg *a = arg;
4893 const struct got_error *err = NULL;
4894 struct got_blob_object *blob1 = NULL;
4895 int fd = -1, fd1 = -1, fd2 = -1;
4896 FILE *f2 = NULL;
4897 char *abspath = NULL, *label1 = NULL;
4898 struct stat sb;
4899 off_t size1 = 0;
4900 int f2_exists = 0;
4902 memset(&sb, 0, sizeof(sb));
4904 if (a->diff_staged) {
4905 if (staged_status != GOT_STATUS_MODIFY &&
4906 staged_status != GOT_STATUS_ADD &&
4907 staged_status != GOT_STATUS_DELETE)
4908 return NULL;
4909 } else {
4910 if (staged_status == GOT_STATUS_DELETE)
4911 return NULL;
4912 if (status == GOT_STATUS_NONEXISTENT)
4913 return got_error_set_errno(ENOENT, path);
4914 if (status != GOT_STATUS_MODIFY &&
4915 status != GOT_STATUS_ADD &&
4916 status != GOT_STATUS_DELETE &&
4917 status != GOT_STATUS_CONFLICT)
4918 return NULL;
4921 err = got_opentemp_truncate(a->f1);
4922 if (err)
4923 return got_error_from_errno("got_opentemp_truncate");
4924 err = got_opentemp_truncate(a->f2);
4925 if (err)
4926 return got_error_from_errno("got_opentemp_truncate");
4928 if (!a->header_shown) {
4929 if (fprintf(a->outfile, "diff %s%s\n",
4930 a->diff_staged ? "-s " : "",
4931 got_worktree_get_root_path(a->worktree)) < 0) {
4932 err = got_error_from_errno("fprintf");
4933 goto done;
4935 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4936 err = got_error_from_errno("fprintf");
4937 goto done;
4939 if (fprintf(a->outfile, "path + %s%s\n",
4940 got_worktree_get_root_path(a->worktree),
4941 a->diff_staged ? " (staged changes)" : "") < 0) {
4942 err = got_error_from_errno("fprintf");
4943 goto done;
4945 a->header_shown = 1;
4948 if (a->diff_staged) {
4949 const char *label1 = NULL, *label2 = NULL;
4950 switch (staged_status) {
4951 case GOT_STATUS_MODIFY:
4952 label1 = path;
4953 label2 = path;
4954 break;
4955 case GOT_STATUS_ADD:
4956 label2 = path;
4957 break;
4958 case GOT_STATUS_DELETE:
4959 label1 = path;
4960 break;
4961 default:
4962 return got_error(GOT_ERR_FILE_STATUS);
4964 fd1 = got_opentempfd();
4965 if (fd1 == -1) {
4966 err = got_error_from_errno("got_opentempfd");
4967 goto done;
4969 fd2 = got_opentempfd();
4970 if (fd2 == -1) {
4971 err = got_error_from_errno("got_opentempfd");
4972 goto done;
4974 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4975 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4976 a->diff_algo, a->diff_context, a->ignore_whitespace,
4977 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4978 goto done;
4981 fd1 = got_opentempfd();
4982 if (fd1 == -1) {
4983 err = got_error_from_errno("got_opentempfd");
4984 goto done;
4987 if (staged_status == GOT_STATUS_ADD ||
4988 staged_status == GOT_STATUS_MODIFY) {
4989 char *id_str;
4990 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4991 8192, fd1);
4992 if (err)
4993 goto done;
4994 err = got_object_id_str(&id_str, staged_blob_id);
4995 if (err)
4996 goto done;
4997 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4998 err = got_error_from_errno("asprintf");
4999 free(id_str);
5000 goto done;
5002 free(id_str);
5003 } else if (status != GOT_STATUS_ADD) {
5004 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5005 fd1);
5006 if (err)
5007 goto done;
5010 if (status != GOT_STATUS_DELETE) {
5011 if (asprintf(&abspath, "%s/%s",
5012 got_worktree_get_root_path(a->worktree), path) == -1) {
5013 err = got_error_from_errno("asprintf");
5014 goto done;
5017 if (dirfd != -1) {
5018 fd = openat(dirfd, de_name,
5019 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5020 if (fd == -1) {
5021 if (!got_err_open_nofollow_on_symlink()) {
5022 err = got_error_from_errno2("openat",
5023 abspath);
5024 goto done;
5026 err = get_symlink_target_file(&fd, dirfd,
5027 de_name, abspath);
5028 if (err)
5029 goto done;
5031 } else {
5032 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5033 if (fd == -1) {
5034 if (!got_err_open_nofollow_on_symlink()) {
5035 err = got_error_from_errno2("open",
5036 abspath);
5037 goto done;
5039 err = get_symlink_target_file(&fd, dirfd,
5040 de_name, abspath);
5041 if (err)
5042 goto done;
5045 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5046 err = got_error_from_errno2("fstatat", abspath);
5047 goto done;
5049 f2 = fdopen(fd, "r");
5050 if (f2 == NULL) {
5051 err = got_error_from_errno2("fdopen", abspath);
5052 goto done;
5054 fd = -1;
5055 f2_exists = 1;
5058 if (blob1) {
5059 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5060 a->f1, blob1);
5061 if (err)
5062 goto done;
5065 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5066 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5067 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5068 done:
5069 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5070 err = got_error_from_errno("close");
5071 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5072 err = got_error_from_errno("close");
5073 if (blob1)
5074 got_object_blob_close(blob1);
5075 if (fd != -1 && close(fd) == -1 && err == NULL)
5076 err = got_error_from_errno("close");
5077 if (f2 && fclose(f2) == EOF && err == NULL)
5078 err = got_error_from_errno("fclose");
5079 free(abspath);
5080 return err;
5083 static const struct got_error *
5084 cmd_diff(int argc, char *argv[])
5086 const struct got_error *error;
5087 struct got_repository *repo = NULL;
5088 struct got_worktree *worktree = NULL;
5089 char *cwd = NULL, *repo_path = NULL;
5090 const char *commit_args[2] = { NULL, NULL };
5091 int ncommit_args = 0;
5092 struct got_object_id *ids[2] = { NULL, NULL };
5093 char *labels[2] = { NULL, NULL };
5094 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5095 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5096 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5097 const char *errstr;
5098 struct got_reflist_head refs;
5099 struct got_pathlist_head diffstat_paths, paths;
5100 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5101 int fd1 = -1, fd2 = -1;
5102 int *pack_fds = NULL;
5103 struct got_diffstat_cb_arg dsa;
5105 memset(&dsa, 0, sizeof(dsa));
5107 TAILQ_INIT(&refs);
5108 TAILQ_INIT(&paths);
5109 TAILQ_INIT(&diffstat_paths);
5111 #ifndef PROFILE
5112 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5113 NULL) == -1)
5114 err(1, "pledge");
5115 #endif
5117 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5118 switch (ch) {
5119 case 'a':
5120 force_text_diff = 1;
5121 break;
5122 case 'C':
5123 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5124 &errstr);
5125 if (errstr != NULL)
5126 errx(1, "number of context lines is %s: %s",
5127 errstr, optarg);
5128 break;
5129 case 'c':
5130 if (ncommit_args >= 2)
5131 errx(1, "too many -c options used");
5132 commit_args[ncommit_args++] = optarg;
5133 break;
5134 case 'd':
5135 show_diffstat = 1;
5136 break;
5137 case 'P':
5138 force_path = 1;
5139 break;
5140 case 'r':
5141 repo_path = realpath(optarg, NULL);
5142 if (repo_path == NULL)
5143 return got_error_from_errno2("realpath",
5144 optarg);
5145 got_path_strip_trailing_slashes(repo_path);
5146 rflag = 1;
5147 break;
5148 case 's':
5149 diff_staged = 1;
5150 break;
5151 case 'w':
5152 ignore_whitespace = 1;
5153 break;
5154 default:
5155 usage_diff();
5156 /* NOTREACHED */
5160 argc -= optind;
5161 argv += optind;
5163 cwd = getcwd(NULL, 0);
5164 if (cwd == NULL) {
5165 error = got_error_from_errno("getcwd");
5166 goto done;
5169 error = got_repo_pack_fds_open(&pack_fds);
5170 if (error != NULL)
5171 goto done;
5173 if (repo_path == NULL) {
5174 error = got_worktree_open(&worktree, cwd);
5175 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5176 goto done;
5177 else
5178 error = NULL;
5179 if (worktree) {
5180 repo_path =
5181 strdup(got_worktree_get_repo_path(worktree));
5182 if (repo_path == NULL) {
5183 error = got_error_from_errno("strdup");
5184 goto done;
5186 } else {
5187 repo_path = strdup(cwd);
5188 if (repo_path == NULL) {
5189 error = got_error_from_errno("strdup");
5190 goto done;
5195 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5196 free(repo_path);
5197 if (error != NULL)
5198 goto done;
5200 if (show_diffstat) {
5201 dsa.paths = &diffstat_paths;
5202 dsa.force_text = force_text_diff;
5203 dsa.ignore_ws = ignore_whitespace;
5204 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5207 if (rflag || worktree == NULL || ncommit_args > 0) {
5208 if (force_path) {
5209 error = got_error_msg(GOT_ERR_NOT_IMPL,
5210 "-P option can only be used when diffing "
5211 "a work tree");
5212 goto done;
5214 if (diff_staged) {
5215 error = got_error_msg(GOT_ERR_NOT_IMPL,
5216 "-s option can only be used when diffing "
5217 "a work tree");
5218 goto done;
5222 error = apply_unveil(got_repo_get_path(repo), 1,
5223 worktree ? got_worktree_get_root_path(worktree) : NULL);
5224 if (error)
5225 goto done;
5227 if ((!force_path && argc == 2) || ncommit_args > 0) {
5228 int obj_type = (ncommit_args > 0 ?
5229 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5230 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5231 NULL);
5232 if (error)
5233 goto done;
5234 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5235 const char *arg;
5236 if (ncommit_args > 0)
5237 arg = commit_args[i];
5238 else
5239 arg = argv[i];
5240 error = got_repo_match_object_id(&ids[i], &labels[i],
5241 arg, obj_type, &refs, repo);
5242 if (error) {
5243 if (error->code != GOT_ERR_NOT_REF &&
5244 error->code != GOT_ERR_NO_OBJ)
5245 goto done;
5246 if (ncommit_args > 0)
5247 goto done;
5248 error = NULL;
5249 break;
5254 f1 = got_opentemp();
5255 if (f1 == NULL) {
5256 error = got_error_from_errno("got_opentemp");
5257 goto done;
5260 f2 = got_opentemp();
5261 if (f2 == NULL) {
5262 error = got_error_from_errno("got_opentemp");
5263 goto done;
5266 outfile = got_opentemp();
5267 if (outfile == NULL) {
5268 error = got_error_from_errno("got_opentemp");
5269 goto done;
5272 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5273 struct print_diff_arg arg;
5274 char *id_str;
5276 if (worktree == NULL) {
5277 if (argc == 2 && ids[0] == NULL) {
5278 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5279 goto done;
5280 } else if (argc == 2 && ids[1] == NULL) {
5281 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5282 goto done;
5283 } else if (argc > 0) {
5284 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5285 "%s", "specified paths cannot be resolved");
5286 goto done;
5287 } else {
5288 error = got_error(GOT_ERR_NOT_WORKTREE);
5289 goto done;
5293 error = get_worktree_paths_from_argv(&paths, argc, argv,
5294 worktree);
5295 if (error)
5296 goto done;
5298 error = got_object_id_str(&id_str,
5299 got_worktree_get_base_commit_id(worktree));
5300 if (error)
5301 goto done;
5302 arg.repo = repo;
5303 arg.worktree = worktree;
5304 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5305 arg.diff_context = diff_context;
5306 arg.id_str = id_str;
5307 arg.header_shown = 0;
5308 arg.diff_staged = diff_staged;
5309 arg.ignore_whitespace = ignore_whitespace;
5310 arg.force_text_diff = force_text_diff;
5311 arg.diffstat = show_diffstat ? &dsa : NULL;
5312 arg.f1 = f1;
5313 arg.f2 = f2;
5314 arg.outfile = outfile;
5316 error = got_worktree_status(worktree, &paths, repo, 0,
5317 print_diff, &arg, check_cancelled, NULL);
5318 free(id_str);
5319 if (error)
5320 goto done;
5322 if (show_diffstat && dsa.nfiles > 0) {
5323 char *header;
5325 if (asprintf(&header, "diffstat %s%s",
5326 diff_staged ? "-s " : "",
5327 got_worktree_get_root_path(worktree)) == -1) {
5328 error = got_error_from_errno("asprintf");
5329 goto done;
5332 error = print_diffstat(&dsa, header);
5333 free(header);
5334 if (error)
5335 goto done;
5338 error = printfile(outfile);
5339 goto done;
5342 if (ncommit_args == 1) {
5343 struct got_commit_object *commit;
5344 error = got_object_open_as_commit(&commit, repo, ids[0]);
5345 if (error)
5346 goto done;
5348 labels[1] = labels[0];
5349 ids[1] = ids[0];
5350 if (got_object_commit_get_nparents(commit) > 0) {
5351 const struct got_object_id_queue *pids;
5352 struct got_object_qid *pid;
5353 pids = got_object_commit_get_parent_ids(commit);
5354 pid = STAILQ_FIRST(pids);
5355 ids[0] = got_object_id_dup(&pid->id);
5356 if (ids[0] == NULL) {
5357 error = got_error_from_errno(
5358 "got_object_id_dup");
5359 got_object_commit_close(commit);
5360 goto done;
5362 error = got_object_id_str(&labels[0], ids[0]);
5363 if (error) {
5364 got_object_commit_close(commit);
5365 goto done;
5367 } else {
5368 ids[0] = NULL;
5369 labels[0] = strdup("/dev/null");
5370 if (labels[0] == NULL) {
5371 error = got_error_from_errno("strdup");
5372 got_object_commit_close(commit);
5373 goto done;
5377 got_object_commit_close(commit);
5380 if (ncommit_args == 0 && argc > 2) {
5381 error = got_error_msg(GOT_ERR_BAD_PATH,
5382 "path arguments cannot be used when diffing two objects");
5383 goto done;
5386 if (ids[0]) {
5387 error = got_object_get_type(&type1, repo, ids[0]);
5388 if (error)
5389 goto done;
5392 error = got_object_get_type(&type2, repo, ids[1]);
5393 if (error)
5394 goto done;
5395 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5396 error = got_error(GOT_ERR_OBJ_TYPE);
5397 goto done;
5399 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5400 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5401 "path arguments cannot be used when diffing blobs");
5402 goto done;
5405 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5406 char *in_repo_path;
5407 struct got_pathlist_entry *new;
5408 if (worktree) {
5409 const char *prefix;
5410 char *p;
5411 error = got_worktree_resolve_path(&p, worktree,
5412 argv[i]);
5413 if (error)
5414 goto done;
5415 prefix = got_worktree_get_path_prefix(worktree);
5416 while (prefix[0] == '/')
5417 prefix++;
5418 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5419 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5420 p) == -1) {
5421 error = got_error_from_errno("asprintf");
5422 free(p);
5423 goto done;
5425 free(p);
5426 } else {
5427 char *mapped_path, *s;
5428 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5429 if (error)
5430 goto done;
5431 s = mapped_path;
5432 while (s[0] == '/')
5433 s++;
5434 in_repo_path = strdup(s);
5435 if (in_repo_path == NULL) {
5436 error = got_error_from_errno("asprintf");
5437 free(mapped_path);
5438 goto done;
5440 free(mapped_path);
5443 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5444 if (error || new == NULL /* duplicate */)
5445 free(in_repo_path);
5446 if (error)
5447 goto done;
5450 if (worktree) {
5451 /* Release work tree lock. */
5452 got_worktree_close(worktree);
5453 worktree = NULL;
5456 fd1 = got_opentempfd();
5457 if (fd1 == -1) {
5458 error = got_error_from_errno("got_opentempfd");
5459 goto done;
5462 fd2 = got_opentempfd();
5463 if (fd2 == -1) {
5464 error = got_error_from_errno("got_opentempfd");
5465 goto done;
5468 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5469 case GOT_OBJ_TYPE_BLOB:
5470 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5471 fd1, fd2, ids[0], ids[1], NULL, NULL,
5472 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5473 ignore_whitespace, force_text_diff,
5474 show_diffstat ? &dsa : NULL, repo, outfile);
5475 break;
5476 case GOT_OBJ_TYPE_TREE:
5477 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5478 ids[0], ids[1], &paths, "", "",
5479 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5480 ignore_whitespace, force_text_diff,
5481 show_diffstat ? &dsa : NULL, repo, outfile);
5482 break;
5483 case GOT_OBJ_TYPE_COMMIT:
5484 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5485 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5486 fd1, fd2, ids[0], ids[1], &paths,
5487 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5488 ignore_whitespace, force_text_diff,
5489 show_diffstat ? &dsa : NULL, repo, outfile);
5490 break;
5491 default:
5492 error = got_error(GOT_ERR_OBJ_TYPE);
5494 if (error)
5495 goto done;
5497 if (show_diffstat && dsa.nfiles > 0) {
5498 char *header = NULL;
5500 if (asprintf(&header, "diffstat %s %s",
5501 labels[0], labels[1]) == -1) {
5502 error = got_error_from_errno("asprintf");
5503 goto done;
5506 error = print_diffstat(&dsa, header);
5507 free(header);
5508 if (error)
5509 goto done;
5512 error = printfile(outfile);
5514 done:
5515 free(labels[0]);
5516 free(labels[1]);
5517 free(ids[0]);
5518 free(ids[1]);
5519 if (worktree)
5520 got_worktree_close(worktree);
5521 if (repo) {
5522 const struct got_error *close_err = got_repo_close(repo);
5523 if (error == NULL)
5524 error = close_err;
5526 if (pack_fds) {
5527 const struct got_error *pack_err =
5528 got_repo_pack_fds_close(pack_fds);
5529 if (error == NULL)
5530 error = pack_err;
5532 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5533 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5534 got_ref_list_free(&refs);
5535 if (outfile && fclose(outfile) == EOF && error == NULL)
5536 error = got_error_from_errno("fclose");
5537 if (f1 && fclose(f1) == EOF && error == NULL)
5538 error = got_error_from_errno("fclose");
5539 if (f2 && fclose(f2) == EOF && error == NULL)
5540 error = got_error_from_errno("fclose");
5541 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5542 error = got_error_from_errno("close");
5543 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5544 error = got_error_from_errno("close");
5545 return error;
5548 __dead static void
5549 usage_blame(void)
5551 fprintf(stderr,
5552 "usage: %s blame [-c commit] [-r repository-path] path\n",
5553 getprogname());
5554 exit(1);
5557 struct blame_line {
5558 int annotated;
5559 char *id_str;
5560 char *committer;
5561 char datebuf[11]; /* YYYY-MM-DD + NUL */
5564 struct blame_cb_args {
5565 struct blame_line *lines;
5566 int nlines;
5567 int nlines_prec;
5568 int lineno_cur;
5569 off_t *line_offsets;
5570 FILE *f;
5571 struct got_repository *repo;
5574 static const struct got_error *
5575 blame_cb(void *arg, int nlines, int lineno,
5576 struct got_commit_object *commit, struct got_object_id *id)
5578 const struct got_error *err = NULL;
5579 struct blame_cb_args *a = arg;
5580 struct blame_line *bline;
5581 char *line = NULL;
5582 size_t linesize = 0;
5583 off_t offset;
5584 struct tm tm;
5585 time_t committer_time;
5587 if (nlines != a->nlines ||
5588 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5589 return got_error(GOT_ERR_RANGE);
5591 if (sigint_received)
5592 return got_error(GOT_ERR_ITER_COMPLETED);
5594 if (lineno == -1)
5595 return NULL; /* no change in this commit */
5597 /* Annotate this line. */
5598 bline = &a->lines[lineno - 1];
5599 if (bline->annotated)
5600 return NULL;
5601 err = got_object_id_str(&bline->id_str, id);
5602 if (err)
5603 return err;
5605 bline->committer = strdup(got_object_commit_get_committer(commit));
5606 if (bline->committer == NULL) {
5607 err = got_error_from_errno("strdup");
5608 goto done;
5611 committer_time = got_object_commit_get_committer_time(commit);
5612 if (gmtime_r(&committer_time, &tm) == NULL)
5613 return got_error_from_errno("gmtime_r");
5614 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5615 &tm) == 0) {
5616 err = got_error(GOT_ERR_NO_SPACE);
5617 goto done;
5619 bline->annotated = 1;
5621 /* Print lines annotated so far. */
5622 bline = &a->lines[a->lineno_cur - 1];
5623 if (!bline->annotated)
5624 goto done;
5626 offset = a->line_offsets[a->lineno_cur - 1];
5627 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5628 err = got_error_from_errno("fseeko");
5629 goto done;
5632 while (a->lineno_cur <= a->nlines && bline->annotated) {
5633 char *smallerthan, *at, *nl, *committer;
5634 size_t len;
5636 if (getline(&line, &linesize, a->f) == -1) {
5637 if (ferror(a->f))
5638 err = got_error_from_errno("getline");
5639 break;
5642 committer = bline->committer;
5643 smallerthan = strchr(committer, '<');
5644 if (smallerthan && smallerthan[1] != '\0')
5645 committer = smallerthan + 1;
5646 at = strchr(committer, '@');
5647 if (at)
5648 *at = '\0';
5649 len = strlen(committer);
5650 if (len >= 9)
5651 committer[8] = '\0';
5653 nl = strchr(line, '\n');
5654 if (nl)
5655 *nl = '\0';
5656 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5657 bline->id_str, bline->datebuf, committer, line);
5659 a->lineno_cur++;
5660 bline = &a->lines[a->lineno_cur - 1];
5662 done:
5663 free(line);
5664 return err;
5667 static const struct got_error *
5668 cmd_blame(int argc, char *argv[])
5670 const struct got_error *error;
5671 struct got_repository *repo = NULL;
5672 struct got_worktree *worktree = NULL;
5673 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5674 char *link_target = NULL;
5675 struct got_object_id *obj_id = NULL;
5676 struct got_object_id *commit_id = NULL;
5677 struct got_commit_object *commit = NULL;
5678 struct got_blob_object *blob = NULL;
5679 char *commit_id_str = NULL;
5680 struct blame_cb_args bca;
5681 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5682 off_t filesize;
5683 int *pack_fds = NULL;
5684 FILE *f1 = NULL, *f2 = NULL;
5686 fd1 = got_opentempfd();
5687 if (fd1 == -1)
5688 return got_error_from_errno("got_opentempfd");
5690 memset(&bca, 0, sizeof(bca));
5692 #ifndef PROFILE
5693 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5694 NULL) == -1)
5695 err(1, "pledge");
5696 #endif
5698 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5699 switch (ch) {
5700 case 'c':
5701 commit_id_str = optarg;
5702 break;
5703 case 'r':
5704 repo_path = realpath(optarg, NULL);
5705 if (repo_path == NULL)
5706 return got_error_from_errno2("realpath",
5707 optarg);
5708 got_path_strip_trailing_slashes(repo_path);
5709 break;
5710 default:
5711 usage_blame();
5712 /* NOTREACHED */
5716 argc -= optind;
5717 argv += optind;
5719 if (argc == 1)
5720 path = argv[0];
5721 else
5722 usage_blame();
5724 cwd = getcwd(NULL, 0);
5725 if (cwd == NULL) {
5726 error = got_error_from_errno("getcwd");
5727 goto done;
5730 error = got_repo_pack_fds_open(&pack_fds);
5731 if (error != NULL)
5732 goto done;
5734 if (repo_path == NULL) {
5735 error = got_worktree_open(&worktree, cwd);
5736 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5737 goto done;
5738 else
5739 error = NULL;
5740 if (worktree) {
5741 repo_path =
5742 strdup(got_worktree_get_repo_path(worktree));
5743 if (repo_path == NULL) {
5744 error = got_error_from_errno("strdup");
5745 if (error)
5746 goto done;
5748 } else {
5749 repo_path = strdup(cwd);
5750 if (repo_path == NULL) {
5751 error = got_error_from_errno("strdup");
5752 goto done;
5757 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5758 if (error != NULL)
5759 goto done;
5761 if (worktree) {
5762 const char *prefix = got_worktree_get_path_prefix(worktree);
5763 char *p;
5765 error = got_worktree_resolve_path(&p, worktree, path);
5766 if (error)
5767 goto done;
5768 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5769 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5770 p) == -1) {
5771 error = got_error_from_errno("asprintf");
5772 free(p);
5773 goto done;
5775 free(p);
5776 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5777 } else {
5778 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5779 if (error)
5780 goto done;
5781 error = got_repo_map_path(&in_repo_path, repo, path);
5783 if (error)
5784 goto done;
5786 if (commit_id_str == NULL) {
5787 struct got_reference *head_ref;
5788 error = got_ref_open(&head_ref, repo, worktree ?
5789 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5790 if (error != NULL)
5791 goto done;
5792 error = got_ref_resolve(&commit_id, repo, head_ref);
5793 got_ref_close(head_ref);
5794 if (error != NULL)
5795 goto done;
5796 } else {
5797 struct got_reflist_head refs;
5798 TAILQ_INIT(&refs);
5799 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5800 NULL);
5801 if (error)
5802 goto done;
5803 error = got_repo_match_object_id(&commit_id, NULL,
5804 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5805 got_ref_list_free(&refs);
5806 if (error)
5807 goto done;
5810 if (worktree) {
5811 /* Release work tree lock. */
5812 got_worktree_close(worktree);
5813 worktree = NULL;
5816 error = got_object_open_as_commit(&commit, repo, commit_id);
5817 if (error)
5818 goto done;
5820 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5821 commit, repo);
5822 if (error)
5823 goto done;
5825 error = got_object_id_by_path(&obj_id, repo, commit,
5826 link_target ? link_target : in_repo_path);
5827 if (error)
5828 goto done;
5830 error = got_object_get_type(&obj_type, repo, obj_id);
5831 if (error)
5832 goto done;
5834 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5835 error = got_error_path(link_target ? link_target : in_repo_path,
5836 GOT_ERR_OBJ_TYPE);
5837 goto done;
5840 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5841 if (error)
5842 goto done;
5843 bca.f = got_opentemp();
5844 if (bca.f == NULL) {
5845 error = got_error_from_errno("got_opentemp");
5846 goto done;
5848 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5849 &bca.line_offsets, bca.f, blob);
5850 if (error || bca.nlines == 0)
5851 goto done;
5853 /* Don't include \n at EOF in the blame line count. */
5854 if (bca.line_offsets[bca.nlines - 1] == filesize)
5855 bca.nlines--;
5857 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5858 if (bca.lines == NULL) {
5859 error = got_error_from_errno("calloc");
5860 goto done;
5862 bca.lineno_cur = 1;
5863 bca.nlines_prec = 0;
5864 i = bca.nlines;
5865 while (i > 0) {
5866 i /= 10;
5867 bca.nlines_prec++;
5869 bca.repo = repo;
5871 fd2 = got_opentempfd();
5872 if (fd2 == -1) {
5873 error = got_error_from_errno("got_opentempfd");
5874 goto done;
5876 fd3 = got_opentempfd();
5877 if (fd3 == -1) {
5878 error = got_error_from_errno("got_opentempfd");
5879 goto done;
5881 f1 = got_opentemp();
5882 if (f1 == NULL) {
5883 error = got_error_from_errno("got_opentemp");
5884 goto done;
5886 f2 = got_opentemp();
5887 if (f2 == NULL) {
5888 error = got_error_from_errno("got_opentemp");
5889 goto done;
5891 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5892 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5893 check_cancelled, NULL, fd2, fd3, f1, f2);
5894 done:
5895 free(in_repo_path);
5896 free(link_target);
5897 free(repo_path);
5898 free(cwd);
5899 free(commit_id);
5900 free(obj_id);
5901 if (commit)
5902 got_object_commit_close(commit);
5904 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5905 error = got_error_from_errno("close");
5906 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5907 error = got_error_from_errno("close");
5908 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5909 error = got_error_from_errno("close");
5910 if (f1 && fclose(f1) == EOF && error == NULL)
5911 error = got_error_from_errno("fclose");
5912 if (f2 && fclose(f2) == EOF && error == NULL)
5913 error = got_error_from_errno("fclose");
5915 if (blob)
5916 got_object_blob_close(blob);
5917 if (worktree)
5918 got_worktree_close(worktree);
5919 if (repo) {
5920 const struct got_error *close_err = got_repo_close(repo);
5921 if (error == NULL)
5922 error = close_err;
5924 if (pack_fds) {
5925 const struct got_error *pack_err =
5926 got_repo_pack_fds_close(pack_fds);
5927 if (error == NULL)
5928 error = pack_err;
5930 if (bca.lines) {
5931 for (i = 0; i < bca.nlines; i++) {
5932 struct blame_line *bline = &bca.lines[i];
5933 free(bline->id_str);
5934 free(bline->committer);
5936 free(bca.lines);
5938 free(bca.line_offsets);
5939 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5940 error = got_error_from_errno("fclose");
5941 return error;
5944 __dead static void
5945 usage_tree(void)
5947 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5948 "[path]\n", getprogname());
5949 exit(1);
5952 static const struct got_error *
5953 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5954 const char *root_path, struct got_repository *repo)
5956 const struct got_error *err = NULL;
5957 int is_root_path = (strcmp(path, root_path) == 0);
5958 const char *modestr = "";
5959 mode_t mode = got_tree_entry_get_mode(te);
5960 char *link_target = NULL;
5962 path += strlen(root_path);
5963 while (path[0] == '/')
5964 path++;
5966 if (got_object_tree_entry_is_submodule(te))
5967 modestr = "$";
5968 else if (S_ISLNK(mode)) {
5969 int i;
5971 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5972 if (err)
5973 return err;
5974 for (i = 0; link_target[i] != '\0'; i++) {
5975 if (!isprint((unsigned char)link_target[i]))
5976 link_target[i] = '?';
5979 modestr = "@";
5981 else if (S_ISDIR(mode))
5982 modestr = "/";
5983 else if (mode & S_IXUSR)
5984 modestr = "*";
5986 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5987 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5988 link_target ? " -> ": "", link_target ? link_target : "");
5990 free(link_target);
5991 return NULL;
5994 static const struct got_error *
5995 print_tree(const char *path, struct got_commit_object *commit,
5996 int show_ids, int recurse, const char *root_path,
5997 struct got_repository *repo)
5999 const struct got_error *err = NULL;
6000 struct got_object_id *tree_id = NULL;
6001 struct got_tree_object *tree = NULL;
6002 int nentries, i;
6004 err = got_object_id_by_path(&tree_id, repo, commit, path);
6005 if (err)
6006 goto done;
6008 err = got_object_open_as_tree(&tree, repo, tree_id);
6009 if (err)
6010 goto done;
6011 nentries = got_object_tree_get_nentries(tree);
6012 for (i = 0; i < nentries; i++) {
6013 struct got_tree_entry *te;
6014 char *id = NULL;
6016 if (sigint_received || sigpipe_received)
6017 break;
6019 te = got_object_tree_get_entry(tree, i);
6020 if (show_ids) {
6021 char *id_str;
6022 err = got_object_id_str(&id_str,
6023 got_tree_entry_get_id(te));
6024 if (err)
6025 goto done;
6026 if (asprintf(&id, "%s ", id_str) == -1) {
6027 err = got_error_from_errno("asprintf");
6028 free(id_str);
6029 goto done;
6031 free(id_str);
6033 err = print_entry(te, id, path, root_path, repo);
6034 free(id);
6035 if (err)
6036 goto done;
6038 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6039 char *child_path;
6040 if (asprintf(&child_path, "%s%s%s", path,
6041 path[0] == '/' && path[1] == '\0' ? "" : "/",
6042 got_tree_entry_get_name(te)) == -1) {
6043 err = got_error_from_errno("asprintf");
6044 goto done;
6046 err = print_tree(child_path, commit, show_ids, 1,
6047 root_path, repo);
6048 free(child_path);
6049 if (err)
6050 goto done;
6053 done:
6054 if (tree)
6055 got_object_tree_close(tree);
6056 free(tree_id);
6057 return err;
6060 static const struct got_error *
6061 cmd_tree(int argc, char *argv[])
6063 const struct got_error *error;
6064 struct got_repository *repo = NULL;
6065 struct got_worktree *worktree = NULL;
6066 const char *path, *refname = NULL;
6067 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6068 struct got_object_id *commit_id = NULL;
6069 struct got_commit_object *commit = NULL;
6070 char *commit_id_str = NULL;
6071 int show_ids = 0, recurse = 0;
6072 int ch;
6073 int *pack_fds = NULL;
6075 #ifndef PROFILE
6076 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6077 NULL) == -1)
6078 err(1, "pledge");
6079 #endif
6081 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6082 switch (ch) {
6083 case 'c':
6084 commit_id_str = optarg;
6085 break;
6086 case 'i':
6087 show_ids = 1;
6088 break;
6089 case 'R':
6090 recurse = 1;
6091 break;
6092 case 'r':
6093 repo_path = realpath(optarg, NULL);
6094 if (repo_path == NULL)
6095 return got_error_from_errno2("realpath",
6096 optarg);
6097 got_path_strip_trailing_slashes(repo_path);
6098 break;
6099 default:
6100 usage_tree();
6101 /* NOTREACHED */
6105 argc -= optind;
6106 argv += optind;
6108 if (argc == 1)
6109 path = argv[0];
6110 else if (argc > 1)
6111 usage_tree();
6112 else
6113 path = NULL;
6115 cwd = getcwd(NULL, 0);
6116 if (cwd == NULL) {
6117 error = got_error_from_errno("getcwd");
6118 goto done;
6121 error = got_repo_pack_fds_open(&pack_fds);
6122 if (error != NULL)
6123 goto done;
6125 if (repo_path == NULL) {
6126 error = got_worktree_open(&worktree, cwd);
6127 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6128 goto done;
6129 else
6130 error = NULL;
6131 if (worktree) {
6132 repo_path =
6133 strdup(got_worktree_get_repo_path(worktree));
6134 if (repo_path == NULL)
6135 error = got_error_from_errno("strdup");
6136 if (error)
6137 goto done;
6138 } else {
6139 repo_path = strdup(cwd);
6140 if (repo_path == NULL) {
6141 error = got_error_from_errno("strdup");
6142 goto done;
6147 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6148 if (error != NULL)
6149 goto done;
6151 if (worktree) {
6152 const char *prefix = got_worktree_get_path_prefix(worktree);
6153 char *p;
6155 if (path == NULL || got_path_is_root_dir(path))
6156 path = "";
6157 error = got_worktree_resolve_path(&p, worktree, path);
6158 if (error)
6159 goto done;
6160 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6161 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6162 p) == -1) {
6163 error = got_error_from_errno("asprintf");
6164 free(p);
6165 goto done;
6167 free(p);
6168 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6169 if (error)
6170 goto done;
6171 } else {
6172 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6173 if (error)
6174 goto done;
6175 if (path == NULL)
6176 path = "/";
6177 error = got_repo_map_path(&in_repo_path, repo, path);
6178 if (error != NULL)
6179 goto done;
6182 if (commit_id_str == NULL) {
6183 struct got_reference *head_ref;
6184 if (worktree)
6185 refname = got_worktree_get_head_ref_name(worktree);
6186 else
6187 refname = GOT_REF_HEAD;
6188 error = got_ref_open(&head_ref, repo, refname, 0);
6189 if (error != NULL)
6190 goto done;
6191 error = got_ref_resolve(&commit_id, repo, head_ref);
6192 got_ref_close(head_ref);
6193 if (error != NULL)
6194 goto done;
6195 } else {
6196 struct got_reflist_head refs;
6197 TAILQ_INIT(&refs);
6198 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6199 NULL);
6200 if (error)
6201 goto done;
6202 error = got_repo_match_object_id(&commit_id, NULL,
6203 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6204 got_ref_list_free(&refs);
6205 if (error)
6206 goto done;
6209 if (worktree) {
6210 /* Release work tree lock. */
6211 got_worktree_close(worktree);
6212 worktree = NULL;
6215 error = got_object_open_as_commit(&commit, repo, commit_id);
6216 if (error)
6217 goto done;
6219 error = print_tree(in_repo_path, commit, show_ids, recurse,
6220 in_repo_path, repo);
6221 done:
6222 free(in_repo_path);
6223 free(repo_path);
6224 free(cwd);
6225 free(commit_id);
6226 if (commit)
6227 got_object_commit_close(commit);
6228 if (worktree)
6229 got_worktree_close(worktree);
6230 if (repo) {
6231 const struct got_error *close_err = got_repo_close(repo);
6232 if (error == NULL)
6233 error = close_err;
6235 if (pack_fds) {
6236 const struct got_error *pack_err =
6237 got_repo_pack_fds_close(pack_fds);
6238 if (error == NULL)
6239 error = pack_err;
6241 return error;
6244 __dead static void
6245 usage_status(void)
6247 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6248 "[-s status-codes] [path ...]\n", getprogname());
6249 exit(1);
6252 struct got_status_arg {
6253 char *status_codes;
6254 int suppress;
6257 static const struct got_error *
6258 print_status(void *arg, unsigned char status, unsigned char staged_status,
6259 const char *path, struct got_object_id *blob_id,
6260 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6261 int dirfd, const char *de_name)
6263 struct got_status_arg *st = arg;
6265 if (status == staged_status && (status == GOT_STATUS_DELETE))
6266 status = GOT_STATUS_NO_CHANGE;
6267 if (st != NULL && st->status_codes) {
6268 size_t ncodes = strlen(st->status_codes);
6269 int i, j = 0;
6271 for (i = 0; i < ncodes ; i++) {
6272 if (st->suppress) {
6273 if (status == st->status_codes[i] ||
6274 staged_status == st->status_codes[i]) {
6275 j++;
6276 continue;
6278 } else {
6279 if (status == st->status_codes[i] ||
6280 staged_status == st->status_codes[i])
6281 break;
6285 if (st->suppress && j == 0)
6286 goto print;
6288 if (i == ncodes)
6289 return NULL;
6291 print:
6292 printf("%c%c %s\n", status, staged_status, path);
6293 return NULL;
6296 static const struct got_error *
6297 cmd_status(int argc, char *argv[])
6299 const struct got_error *error = NULL;
6300 struct got_repository *repo = NULL;
6301 struct got_worktree *worktree = NULL;
6302 struct got_status_arg st;
6303 char *cwd = NULL;
6304 struct got_pathlist_head paths;
6305 int ch, i, no_ignores = 0;
6306 int *pack_fds = NULL;
6308 TAILQ_INIT(&paths);
6310 memset(&st, 0, sizeof(st));
6311 st.status_codes = NULL;
6312 st.suppress = 0;
6314 #ifndef PROFILE
6315 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6316 NULL) == -1)
6317 err(1, "pledge");
6318 #endif
6320 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6321 switch (ch) {
6322 case 'I':
6323 no_ignores = 1;
6324 break;
6325 case 'S':
6326 if (st.status_codes != NULL && st.suppress == 0)
6327 option_conflict('S', 's');
6328 st.suppress = 1;
6329 /* fallthrough */
6330 case 's':
6331 for (i = 0; optarg[i] != '\0'; i++) {
6332 switch (optarg[i]) {
6333 case GOT_STATUS_MODIFY:
6334 case GOT_STATUS_ADD:
6335 case GOT_STATUS_DELETE:
6336 case GOT_STATUS_CONFLICT:
6337 case GOT_STATUS_MISSING:
6338 case GOT_STATUS_OBSTRUCTED:
6339 case GOT_STATUS_UNVERSIONED:
6340 case GOT_STATUS_MODE_CHANGE:
6341 case GOT_STATUS_NONEXISTENT:
6342 break;
6343 default:
6344 errx(1, "invalid status code '%c'",
6345 optarg[i]);
6348 if (ch == 's' && st.suppress)
6349 option_conflict('s', 'S');
6350 st.status_codes = optarg;
6351 break;
6352 default:
6353 usage_status();
6354 /* NOTREACHED */
6358 argc -= optind;
6359 argv += optind;
6361 cwd = getcwd(NULL, 0);
6362 if (cwd == NULL) {
6363 error = got_error_from_errno("getcwd");
6364 goto done;
6367 error = got_repo_pack_fds_open(&pack_fds);
6368 if (error != NULL)
6369 goto done;
6371 error = got_worktree_open(&worktree, cwd);
6372 if (error) {
6373 if (error->code == GOT_ERR_NOT_WORKTREE)
6374 error = wrap_not_worktree_error(error, "status", cwd);
6375 goto done;
6378 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6379 NULL, pack_fds);
6380 if (error != NULL)
6381 goto done;
6383 error = apply_unveil(got_repo_get_path(repo), 1,
6384 got_worktree_get_root_path(worktree));
6385 if (error)
6386 goto done;
6388 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6389 if (error)
6390 goto done;
6392 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6393 print_status, &st, check_cancelled, NULL);
6394 done:
6395 if (pack_fds) {
6396 const struct got_error *pack_err =
6397 got_repo_pack_fds_close(pack_fds);
6398 if (error == NULL)
6399 error = pack_err;
6401 if (repo) {
6402 const struct got_error *close_err = got_repo_close(repo);
6403 if (error == NULL)
6404 error = close_err;
6407 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6408 free(cwd);
6409 return error;
6412 __dead static void
6413 usage_ref(void)
6415 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6416 "[-s reference] [name]\n", getprogname());
6417 exit(1);
6420 static const struct got_error *
6421 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6423 static const struct got_error *err = NULL;
6424 struct got_reflist_head refs;
6425 struct got_reflist_entry *re;
6427 TAILQ_INIT(&refs);
6428 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6429 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6430 repo);
6431 if (err)
6432 return err;
6434 TAILQ_FOREACH(re, &refs, entry) {
6435 char *refstr;
6436 refstr = got_ref_to_str(re->ref);
6437 if (refstr == NULL) {
6438 err = got_error_from_errno("got_ref_to_str");
6439 break;
6441 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6442 free(refstr);
6445 got_ref_list_free(&refs);
6446 return err;
6449 static const struct got_error *
6450 delete_ref_by_name(struct got_repository *repo, const char *refname)
6452 const struct got_error *err;
6453 struct got_reference *ref;
6455 err = got_ref_open(&ref, repo, refname, 0);
6456 if (err)
6457 return err;
6459 err = delete_ref(repo, ref);
6460 got_ref_close(ref);
6461 return err;
6464 static const struct got_error *
6465 add_ref(struct got_repository *repo, const char *refname, const char *target)
6467 const struct got_error *err = NULL;
6468 struct got_object_id *id = NULL;
6469 struct got_reference *ref = NULL;
6470 struct got_reflist_head refs;
6473 * Don't let the user create a reference name with a leading '-'.
6474 * While technically a valid reference name, this case is usually
6475 * an unintended typo.
6477 if (refname[0] == '-')
6478 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6480 TAILQ_INIT(&refs);
6481 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6482 if (err)
6483 goto done;
6484 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6485 &refs, repo);
6486 got_ref_list_free(&refs);
6487 if (err)
6488 goto done;
6490 err = got_ref_alloc(&ref, refname, id);
6491 if (err)
6492 goto done;
6494 err = got_ref_write(ref, repo);
6495 done:
6496 if (ref)
6497 got_ref_close(ref);
6498 free(id);
6499 return err;
6502 static const struct got_error *
6503 add_symref(struct got_repository *repo, const char *refname, const char *target)
6505 const struct got_error *err = NULL;
6506 struct got_reference *ref = NULL;
6507 struct got_reference *target_ref = NULL;
6510 * Don't let the user create a reference name with a leading '-'.
6511 * While technically a valid reference name, this case is usually
6512 * an unintended typo.
6514 if (refname[0] == '-')
6515 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6517 err = got_ref_open(&target_ref, repo, target, 0);
6518 if (err)
6519 return err;
6521 err = got_ref_alloc_symref(&ref, refname, target_ref);
6522 if (err)
6523 goto done;
6525 err = got_ref_write(ref, repo);
6526 done:
6527 if (target_ref)
6528 got_ref_close(target_ref);
6529 if (ref)
6530 got_ref_close(ref);
6531 return err;
6534 static const struct got_error *
6535 cmd_ref(int argc, char *argv[])
6537 const struct got_error *error = NULL;
6538 struct got_repository *repo = NULL;
6539 struct got_worktree *worktree = NULL;
6540 char *cwd = NULL, *repo_path = NULL;
6541 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6542 const char *obj_arg = NULL, *symref_target= NULL;
6543 char *refname = NULL;
6544 int *pack_fds = NULL;
6546 #ifndef PROFILE
6547 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6548 "sendfd unveil", NULL) == -1)
6549 err(1, "pledge");
6550 #endif
6552 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6553 switch (ch) {
6554 case 'c':
6555 obj_arg = optarg;
6556 break;
6557 case 'd':
6558 do_delete = 1;
6559 break;
6560 case 'l':
6561 do_list = 1;
6562 break;
6563 case 'r':
6564 repo_path = realpath(optarg, NULL);
6565 if (repo_path == NULL)
6566 return got_error_from_errno2("realpath",
6567 optarg);
6568 got_path_strip_trailing_slashes(repo_path);
6569 break;
6570 case 's':
6571 symref_target = optarg;
6572 break;
6573 case 't':
6574 sort_by_time = 1;
6575 break;
6576 default:
6577 usage_ref();
6578 /* NOTREACHED */
6582 if (obj_arg && do_list)
6583 option_conflict('c', 'l');
6584 if (obj_arg && do_delete)
6585 option_conflict('c', 'd');
6586 if (obj_arg && symref_target)
6587 option_conflict('c', 's');
6588 if (symref_target && do_delete)
6589 option_conflict('s', 'd');
6590 if (symref_target && do_list)
6591 option_conflict('s', 'l');
6592 if (do_delete && do_list)
6593 option_conflict('d', 'l');
6594 if (sort_by_time && !do_list)
6595 errx(1, "-t option requires -l option");
6597 argc -= optind;
6598 argv += optind;
6600 if (do_list) {
6601 if (argc != 0 && argc != 1)
6602 usage_ref();
6603 if (argc == 1) {
6604 refname = strdup(argv[0]);
6605 if (refname == NULL) {
6606 error = got_error_from_errno("strdup");
6607 goto done;
6610 } else {
6611 if (argc != 1)
6612 usage_ref();
6613 refname = strdup(argv[0]);
6614 if (refname == NULL) {
6615 error = got_error_from_errno("strdup");
6616 goto done;
6620 if (refname)
6621 got_path_strip_trailing_slashes(refname);
6623 cwd = getcwd(NULL, 0);
6624 if (cwd == NULL) {
6625 error = got_error_from_errno("getcwd");
6626 goto done;
6629 error = got_repo_pack_fds_open(&pack_fds);
6630 if (error != NULL)
6631 goto done;
6633 if (repo_path == NULL) {
6634 error = got_worktree_open(&worktree, cwd);
6635 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6636 goto done;
6637 else
6638 error = NULL;
6639 if (worktree) {
6640 repo_path =
6641 strdup(got_worktree_get_repo_path(worktree));
6642 if (repo_path == NULL)
6643 error = got_error_from_errno("strdup");
6644 if (error)
6645 goto done;
6646 } else {
6647 repo_path = strdup(cwd);
6648 if (repo_path == NULL) {
6649 error = got_error_from_errno("strdup");
6650 goto done;
6655 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6656 if (error != NULL)
6657 goto done;
6659 #ifndef PROFILE
6660 if (do_list) {
6661 /* Remove "cpath" promise. */
6662 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6663 NULL) == -1)
6664 err(1, "pledge");
6666 #endif
6668 error = apply_unveil(got_repo_get_path(repo), do_list,
6669 worktree ? got_worktree_get_root_path(worktree) : NULL);
6670 if (error)
6671 goto done;
6673 if (do_list)
6674 error = list_refs(repo, refname, sort_by_time);
6675 else if (do_delete)
6676 error = delete_ref_by_name(repo, refname);
6677 else if (symref_target)
6678 error = add_symref(repo, refname, symref_target);
6679 else {
6680 if (obj_arg == NULL)
6681 usage_ref();
6682 error = add_ref(repo, refname, obj_arg);
6684 done:
6685 free(refname);
6686 if (repo) {
6687 const struct got_error *close_err = got_repo_close(repo);
6688 if (error == NULL)
6689 error = close_err;
6691 if (worktree)
6692 got_worktree_close(worktree);
6693 if (pack_fds) {
6694 const struct got_error *pack_err =
6695 got_repo_pack_fds_close(pack_fds);
6696 if (error == NULL)
6697 error = pack_err;
6699 free(cwd);
6700 free(repo_path);
6701 return error;
6704 __dead static void
6705 usage_branch(void)
6707 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6708 "[-r repository-path] [name]\n", getprogname());
6709 exit(1);
6712 static const struct got_error *
6713 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6714 struct got_reference *ref)
6716 const struct got_error *err = NULL;
6717 const char *refname, *marker = " ";
6718 char *refstr;
6720 refname = got_ref_get_name(ref);
6721 if (worktree && strcmp(refname,
6722 got_worktree_get_head_ref_name(worktree)) == 0) {
6723 struct got_object_id *id = NULL;
6725 err = got_ref_resolve(&id, repo, ref);
6726 if (err)
6727 return err;
6728 if (got_object_id_cmp(id,
6729 got_worktree_get_base_commit_id(worktree)) == 0)
6730 marker = "* ";
6731 else
6732 marker = "~ ";
6733 free(id);
6736 if (strncmp(refname, "refs/heads/", 11) == 0)
6737 refname += 11;
6738 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6739 refname += 18;
6740 if (strncmp(refname, "refs/remotes/", 13) == 0)
6741 refname += 13;
6743 refstr = got_ref_to_str(ref);
6744 if (refstr == NULL)
6745 return got_error_from_errno("got_ref_to_str");
6747 printf("%s%s: %s\n", marker, refname, refstr);
6748 free(refstr);
6749 return NULL;
6752 static const struct got_error *
6753 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6755 const char *refname;
6757 if (worktree == NULL)
6758 return got_error(GOT_ERR_NOT_WORKTREE);
6760 refname = got_worktree_get_head_ref_name(worktree);
6762 if (strncmp(refname, "refs/heads/", 11) == 0)
6763 refname += 11;
6764 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6765 refname += 18;
6767 printf("%s\n", refname);
6769 return NULL;
6772 static const struct got_error *
6773 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6774 int sort_by_time)
6776 static const struct got_error *err = NULL;
6777 struct got_reflist_head refs;
6778 struct got_reflist_entry *re;
6779 struct got_reference *temp_ref = NULL;
6780 int rebase_in_progress, histedit_in_progress;
6782 TAILQ_INIT(&refs);
6784 if (worktree) {
6785 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6786 worktree);
6787 if (err)
6788 return err;
6790 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6791 worktree);
6792 if (err)
6793 return err;
6795 if (rebase_in_progress || histedit_in_progress) {
6796 err = got_ref_open(&temp_ref, repo,
6797 got_worktree_get_head_ref_name(worktree), 0);
6798 if (err)
6799 return err;
6800 list_branch(repo, worktree, temp_ref);
6801 got_ref_close(temp_ref);
6805 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6806 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6807 repo);
6808 if (err)
6809 return err;
6811 TAILQ_FOREACH(re, &refs, entry)
6812 list_branch(repo, worktree, re->ref);
6814 got_ref_list_free(&refs);
6816 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6817 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6818 repo);
6819 if (err)
6820 return err;
6822 TAILQ_FOREACH(re, &refs, entry)
6823 list_branch(repo, worktree, re->ref);
6825 got_ref_list_free(&refs);
6827 return NULL;
6830 static const struct got_error *
6831 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6832 const char *branch_name)
6834 const struct got_error *err = NULL;
6835 struct got_reference *ref = NULL;
6836 char *refname, *remote_refname = NULL;
6838 if (strncmp(branch_name, "refs/", 5) == 0)
6839 branch_name += 5;
6840 if (strncmp(branch_name, "heads/", 6) == 0)
6841 branch_name += 6;
6842 else if (strncmp(branch_name, "remotes/", 8) == 0)
6843 branch_name += 8;
6845 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6846 return got_error_from_errno("asprintf");
6848 if (asprintf(&remote_refname, "refs/remotes/%s",
6849 branch_name) == -1) {
6850 err = got_error_from_errno("asprintf");
6851 goto done;
6854 err = got_ref_open(&ref, repo, refname, 0);
6855 if (err) {
6856 const struct got_error *err2;
6857 if (err->code != GOT_ERR_NOT_REF)
6858 goto done;
6860 * Keep 'err' intact such that if neither branch exists
6861 * we report "refs/heads" rather than "refs/remotes" in
6862 * our error message.
6864 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6865 if (err2)
6866 goto done;
6867 err = NULL;
6870 if (worktree &&
6871 strcmp(got_worktree_get_head_ref_name(worktree),
6872 got_ref_get_name(ref)) == 0) {
6873 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6874 "will not delete this work tree's current branch");
6875 goto done;
6878 err = delete_ref(repo, ref);
6879 done:
6880 if (ref)
6881 got_ref_close(ref);
6882 free(refname);
6883 free(remote_refname);
6884 return err;
6887 static const struct got_error *
6888 add_branch(struct got_repository *repo, const char *branch_name,
6889 struct got_object_id *base_commit_id)
6891 const struct got_error *err = NULL;
6892 struct got_reference *ref = NULL;
6893 char *refname = NULL;
6896 * Don't let the user create a branch name with a leading '-'.
6897 * While technically a valid reference name, this case is usually
6898 * an unintended typo.
6900 if (branch_name[0] == '-')
6901 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6903 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6904 branch_name += 11;
6906 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6907 err = got_error_from_errno("asprintf");
6908 goto done;
6911 err = got_ref_open(&ref, repo, refname, 0);
6912 if (err == NULL) {
6913 err = got_error(GOT_ERR_BRANCH_EXISTS);
6914 goto done;
6915 } else if (err->code != GOT_ERR_NOT_REF)
6916 goto done;
6918 err = got_ref_alloc(&ref, refname, base_commit_id);
6919 if (err)
6920 goto done;
6922 err = got_ref_write(ref, repo);
6923 done:
6924 if (ref)
6925 got_ref_close(ref);
6926 free(refname);
6927 return err;
6930 static const struct got_error *
6931 cmd_branch(int argc, char *argv[])
6933 const struct got_error *error = NULL;
6934 struct got_repository *repo = NULL;
6935 struct got_worktree *worktree = NULL;
6936 char *cwd = NULL, *repo_path = NULL;
6937 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6938 const char *delref = NULL, *commit_id_arg = NULL;
6939 struct got_reference *ref = NULL;
6940 struct got_pathlist_head paths;
6941 struct got_object_id *commit_id = NULL;
6942 char *commit_id_str = NULL;
6943 int *pack_fds = NULL;
6945 TAILQ_INIT(&paths);
6947 #ifndef PROFILE
6948 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6949 "sendfd unveil", NULL) == -1)
6950 err(1, "pledge");
6951 #endif
6953 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6954 switch (ch) {
6955 case 'c':
6956 commit_id_arg = optarg;
6957 break;
6958 case 'd':
6959 delref = optarg;
6960 break;
6961 case 'l':
6962 do_list = 1;
6963 break;
6964 case 'n':
6965 do_update = 0;
6966 break;
6967 case 'r':
6968 repo_path = realpath(optarg, NULL);
6969 if (repo_path == NULL)
6970 return got_error_from_errno2("realpath",
6971 optarg);
6972 got_path_strip_trailing_slashes(repo_path);
6973 break;
6974 case 't':
6975 sort_by_time = 1;
6976 break;
6977 default:
6978 usage_branch();
6979 /* NOTREACHED */
6983 if (do_list && delref)
6984 option_conflict('l', 'd');
6985 if (sort_by_time && !do_list)
6986 errx(1, "-t option requires -l option");
6988 argc -= optind;
6989 argv += optind;
6991 if (!do_list && !delref && argc == 0)
6992 do_show = 1;
6994 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6995 errx(1, "-c option can only be used when creating a branch");
6997 if (do_list || delref) {
6998 if (argc > 0)
6999 usage_branch();
7000 } else if (!do_show && argc != 1)
7001 usage_branch();
7003 cwd = getcwd(NULL, 0);
7004 if (cwd == NULL) {
7005 error = got_error_from_errno("getcwd");
7006 goto done;
7009 error = got_repo_pack_fds_open(&pack_fds);
7010 if (error != NULL)
7011 goto done;
7013 if (repo_path == NULL) {
7014 error = got_worktree_open(&worktree, cwd);
7015 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7016 goto done;
7017 else
7018 error = NULL;
7019 if (worktree) {
7020 repo_path =
7021 strdup(got_worktree_get_repo_path(worktree));
7022 if (repo_path == NULL)
7023 error = got_error_from_errno("strdup");
7024 if (error)
7025 goto done;
7026 } else {
7027 repo_path = strdup(cwd);
7028 if (repo_path == NULL) {
7029 error = got_error_from_errno("strdup");
7030 goto done;
7035 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7036 if (error != NULL)
7037 goto done;
7039 #ifndef PROFILE
7040 if (do_list || do_show) {
7041 /* Remove "cpath" promise. */
7042 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7043 NULL) == -1)
7044 err(1, "pledge");
7046 #endif
7048 error = apply_unveil(got_repo_get_path(repo), do_list,
7049 worktree ? got_worktree_get_root_path(worktree) : NULL);
7050 if (error)
7051 goto done;
7053 if (do_show)
7054 error = show_current_branch(repo, worktree);
7055 else if (do_list)
7056 error = list_branches(repo, worktree, sort_by_time);
7057 else if (delref)
7058 error = delete_branch(repo, worktree, delref);
7059 else {
7060 struct got_reflist_head refs;
7061 TAILQ_INIT(&refs);
7062 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7063 NULL);
7064 if (error)
7065 goto done;
7066 if (commit_id_arg == NULL)
7067 commit_id_arg = worktree ?
7068 got_worktree_get_head_ref_name(worktree) :
7069 GOT_REF_HEAD;
7070 error = got_repo_match_object_id(&commit_id, NULL,
7071 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7072 got_ref_list_free(&refs);
7073 if (error)
7074 goto done;
7075 error = add_branch(repo, argv[0], commit_id);
7076 if (error)
7077 goto done;
7078 if (worktree && do_update) {
7079 struct got_update_progress_arg upa;
7080 char *branch_refname = NULL;
7082 error = got_object_id_str(&commit_id_str, commit_id);
7083 if (error)
7084 goto done;
7085 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7086 worktree);
7087 if (error)
7088 goto done;
7089 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7090 == -1) {
7091 error = got_error_from_errno("asprintf");
7092 goto done;
7094 error = got_ref_open(&ref, repo, branch_refname, 0);
7095 free(branch_refname);
7096 if (error)
7097 goto done;
7098 error = switch_head_ref(ref, commit_id, worktree,
7099 repo);
7100 if (error)
7101 goto done;
7102 error = got_worktree_set_base_commit_id(worktree, repo,
7103 commit_id);
7104 if (error)
7105 goto done;
7106 memset(&upa, 0, sizeof(upa));
7107 error = got_worktree_checkout_files(worktree, &paths,
7108 repo, update_progress, &upa, check_cancelled,
7109 NULL);
7110 if (error)
7111 goto done;
7112 if (upa.did_something) {
7113 printf("Updated to %s: %s\n",
7114 got_worktree_get_head_ref_name(worktree),
7115 commit_id_str);
7117 print_update_progress_stats(&upa);
7120 done:
7121 if (ref)
7122 got_ref_close(ref);
7123 if (repo) {
7124 const struct got_error *close_err = got_repo_close(repo);
7125 if (error == NULL)
7126 error = close_err;
7128 if (worktree)
7129 got_worktree_close(worktree);
7130 if (pack_fds) {
7131 const struct got_error *pack_err =
7132 got_repo_pack_fds_close(pack_fds);
7133 if (error == NULL)
7134 error = pack_err;
7136 free(cwd);
7137 free(repo_path);
7138 free(commit_id);
7139 free(commit_id_str);
7140 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7141 return error;
7145 __dead static void
7146 usage_tag(void)
7148 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7149 "[-r repository-path] [-s signer-id] name\n", getprogname());
7150 exit(1);
7153 #if 0
7154 static const struct got_error *
7155 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7157 const struct got_error *err = NULL;
7158 struct got_reflist_entry *re, *se, *new;
7159 struct got_object_id *re_id, *se_id;
7160 struct got_tag_object *re_tag, *se_tag;
7161 time_t re_time, se_time;
7163 STAILQ_FOREACH(re, tags, entry) {
7164 se = STAILQ_FIRST(sorted);
7165 if (se == NULL) {
7166 err = got_reflist_entry_dup(&new, re);
7167 if (err)
7168 return err;
7169 STAILQ_INSERT_HEAD(sorted, new, entry);
7170 continue;
7171 } else {
7172 err = got_ref_resolve(&re_id, repo, re->ref);
7173 if (err)
7174 break;
7175 err = got_object_open_as_tag(&re_tag, repo, re_id);
7176 free(re_id);
7177 if (err)
7178 break;
7179 re_time = got_object_tag_get_tagger_time(re_tag);
7180 got_object_tag_close(re_tag);
7183 while (se) {
7184 err = got_ref_resolve(&se_id, repo, re->ref);
7185 if (err)
7186 break;
7187 err = got_object_open_as_tag(&se_tag, repo, se_id);
7188 free(se_id);
7189 if (err)
7190 break;
7191 se_time = got_object_tag_get_tagger_time(se_tag);
7192 got_object_tag_close(se_tag);
7194 if (se_time > re_time) {
7195 err = got_reflist_entry_dup(&new, re);
7196 if (err)
7197 return err;
7198 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7199 break;
7201 se = STAILQ_NEXT(se, entry);
7202 continue;
7205 done:
7206 return err;
7208 #endif
7210 static const struct got_error *
7211 get_tag_refname(char **refname, const char *tag_name)
7213 const struct got_error *err;
7215 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7216 *refname = strdup(tag_name);
7217 if (*refname == NULL)
7218 return got_error_from_errno("strdup");
7219 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7220 err = got_error_from_errno("asprintf");
7221 *refname = NULL;
7222 return err;
7225 return NULL;
7228 static const struct got_error *
7229 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7230 const char *allowed_signers, const char *revoked_signers, int verbosity)
7232 static const struct got_error *err = NULL;
7233 struct got_reflist_head refs;
7234 struct got_reflist_entry *re;
7235 char *wanted_refname = NULL;
7236 int bad_sigs = 0;
7238 TAILQ_INIT(&refs);
7240 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7241 if (err)
7242 return err;
7244 if (tag_name) {
7245 struct got_reference *ref;
7246 err = get_tag_refname(&wanted_refname, tag_name);
7247 if (err)
7248 goto done;
7249 /* Wanted tag reference should exist. */
7250 err = got_ref_open(&ref, repo, wanted_refname, 0);
7251 if (err)
7252 goto done;
7253 got_ref_close(ref);
7256 TAILQ_FOREACH(re, &refs, entry) {
7257 const char *refname;
7258 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7259 char datebuf[26];
7260 const char *tagger, *ssh_sig = NULL;
7261 char *sig_msg = NULL;
7262 time_t tagger_time;
7263 struct got_object_id *id;
7264 struct got_tag_object *tag;
7265 struct got_commit_object *commit = NULL;
7267 refname = got_ref_get_name(re->ref);
7268 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7269 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7270 continue;
7271 refname += 10;
7272 refstr = got_ref_to_str(re->ref);
7273 if (refstr == NULL) {
7274 err = got_error_from_errno("got_ref_to_str");
7275 break;
7278 err = got_ref_resolve(&id, repo, re->ref);
7279 if (err)
7280 break;
7281 err = got_object_open_as_tag(&tag, repo, id);
7282 if (err) {
7283 if (err->code != GOT_ERR_OBJ_TYPE) {
7284 free(id);
7285 break;
7287 /* "lightweight" tag */
7288 err = got_object_open_as_commit(&commit, repo, id);
7289 if (err) {
7290 free(id);
7291 break;
7293 tagger = got_object_commit_get_committer(commit);
7294 tagger_time =
7295 got_object_commit_get_committer_time(commit);
7296 err = got_object_id_str(&id_str, id);
7297 free(id);
7298 if (err)
7299 break;
7300 } else {
7301 free(id);
7302 tagger = got_object_tag_get_tagger(tag);
7303 tagger_time = got_object_tag_get_tagger_time(tag);
7304 err = got_object_id_str(&id_str,
7305 got_object_tag_get_object_id(tag));
7306 if (err)
7307 break;
7310 if (tag && verify_tags) {
7311 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7312 got_object_tag_get_message(tag));
7313 if (ssh_sig && allowed_signers == NULL) {
7314 err = got_error_msg(
7315 GOT_ERR_VERIFY_TAG_SIGNATURE,
7316 "SSH signature verification requires "
7317 "setting allowed_signers in "
7318 "got.conf(5)");
7319 break;
7323 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7324 free(refstr);
7325 printf("from: %s\n", tagger);
7326 datestr = get_datestr(&tagger_time, datebuf);
7327 if (datestr)
7328 printf("date: %s UTC\n", datestr);
7329 if (commit)
7330 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7331 else {
7332 switch (got_object_tag_get_object_type(tag)) {
7333 case GOT_OBJ_TYPE_BLOB:
7334 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7335 id_str);
7336 break;
7337 case GOT_OBJ_TYPE_TREE:
7338 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7339 id_str);
7340 break;
7341 case GOT_OBJ_TYPE_COMMIT:
7342 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7343 id_str);
7344 break;
7345 case GOT_OBJ_TYPE_TAG:
7346 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7347 id_str);
7348 break;
7349 default:
7350 break;
7353 free(id_str);
7355 if (ssh_sig) {
7356 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7357 allowed_signers, revoked_signers, verbosity);
7358 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7359 bad_sigs = 1;
7360 else if (err)
7361 break;
7362 printf("signature: %s", sig_msg);
7363 free(sig_msg);
7364 sig_msg = NULL;
7367 if (commit) {
7368 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7369 if (err)
7370 break;
7371 got_object_commit_close(commit);
7372 } else {
7373 tagmsg0 = strdup(got_object_tag_get_message(tag));
7374 got_object_tag_close(tag);
7375 if (tagmsg0 == NULL) {
7376 err = got_error_from_errno("strdup");
7377 break;
7381 tagmsg = tagmsg0;
7382 do {
7383 line = strsep(&tagmsg, "\n");
7384 if (line)
7385 printf(" %s\n", line);
7386 } while (line);
7387 free(tagmsg0);
7389 done:
7390 got_ref_list_free(&refs);
7391 free(wanted_refname);
7393 if (err == NULL && bad_sigs)
7394 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7395 return err;
7398 static const struct got_error *
7399 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7400 const char *tag_name, const char *repo_path)
7402 const struct got_error *err = NULL;
7403 char *template = NULL, *initial_content = NULL;
7404 char *editor = NULL;
7405 int initial_content_len;
7406 int fd = -1;
7408 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7409 err = got_error_from_errno("asprintf");
7410 goto done;
7413 initial_content_len = asprintf(&initial_content,
7414 "\n# tagging commit %s as %s\n",
7415 commit_id_str, tag_name);
7416 if (initial_content_len == -1) {
7417 err = got_error_from_errno("asprintf");
7418 goto done;
7421 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7422 if (err)
7423 goto done;
7425 if (write(fd, initial_content, initial_content_len) == -1) {
7426 err = got_error_from_errno2("write", *tagmsg_path);
7427 goto done;
7429 if (close(fd) == -1) {
7430 err = got_error_from_errno2("close", *tagmsg_path);
7431 goto done;
7433 fd = -1;
7435 err = get_editor(&editor);
7436 if (err)
7437 goto done;
7438 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7439 initial_content_len, 1);
7440 done:
7441 free(initial_content);
7442 free(template);
7443 free(editor);
7445 if (fd != -1 && close(fd) == -1 && err == NULL)
7446 err = got_error_from_errno2("close", *tagmsg_path);
7448 if (err) {
7449 free(*tagmsg);
7450 *tagmsg = NULL;
7452 return err;
7455 static const struct got_error *
7456 add_tag(struct got_repository *repo, const char *tagger,
7457 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7458 const char *signer_id, int verbosity)
7460 const struct got_error *err = NULL;
7461 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7462 char *label = NULL, *commit_id_str = NULL;
7463 struct got_reference *ref = NULL;
7464 char *refname = NULL, *tagmsg = NULL;
7465 char *tagmsg_path = NULL, *tag_id_str = NULL;
7466 int preserve_tagmsg = 0;
7467 struct got_reflist_head refs;
7469 TAILQ_INIT(&refs);
7472 * Don't let the user create a tag name with a leading '-'.
7473 * While technically a valid reference name, this case is usually
7474 * an unintended typo.
7476 if (tag_name[0] == '-')
7477 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7479 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7480 if (err)
7481 goto done;
7483 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7484 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7485 if (err)
7486 goto done;
7488 err = got_object_id_str(&commit_id_str, commit_id);
7489 if (err)
7490 goto done;
7492 err = get_tag_refname(&refname, tag_name);
7493 if (err)
7494 goto done;
7495 if (strncmp("refs/tags/", tag_name, 10) == 0)
7496 tag_name += 10;
7498 err = got_ref_open(&ref, repo, refname, 0);
7499 if (err == NULL) {
7500 err = got_error(GOT_ERR_TAG_EXISTS);
7501 goto done;
7502 } else if (err->code != GOT_ERR_NOT_REF)
7503 goto done;
7505 if (tagmsg_arg == NULL) {
7506 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7507 tag_name, got_repo_get_path(repo));
7508 if (err) {
7509 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7510 tagmsg_path != NULL)
7511 preserve_tagmsg = 1;
7512 goto done;
7514 /* Editor is done; we can now apply unveil(2) */
7515 err = got_sigs_apply_unveil();
7516 if (err)
7517 goto done;
7518 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7519 if (err)
7520 goto done;
7523 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7524 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7525 verbosity);
7526 if (err) {
7527 if (tagmsg_path)
7528 preserve_tagmsg = 1;
7529 goto done;
7532 err = got_ref_alloc(&ref, refname, tag_id);
7533 if (err) {
7534 if (tagmsg_path)
7535 preserve_tagmsg = 1;
7536 goto done;
7539 err = got_ref_write(ref, repo);
7540 if (err) {
7541 if (tagmsg_path)
7542 preserve_tagmsg = 1;
7543 goto done;
7546 err = got_object_id_str(&tag_id_str, tag_id);
7547 if (err) {
7548 if (tagmsg_path)
7549 preserve_tagmsg = 1;
7550 goto done;
7552 printf("Created tag %s\n", tag_id_str);
7553 done:
7554 if (preserve_tagmsg) {
7555 fprintf(stderr, "%s: tag message preserved in %s\n",
7556 getprogname(), tagmsg_path);
7557 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7558 err = got_error_from_errno2("unlink", tagmsg_path);
7559 free(tag_id_str);
7560 if (ref)
7561 got_ref_close(ref);
7562 free(commit_id);
7563 free(commit_id_str);
7564 free(refname);
7565 free(tagmsg);
7566 free(tagmsg_path);
7567 got_ref_list_free(&refs);
7568 return err;
7571 static const struct got_error *
7572 cmd_tag(int argc, char *argv[])
7574 const struct got_error *error = NULL;
7575 struct got_repository *repo = NULL;
7576 struct got_worktree *worktree = NULL;
7577 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7578 char *gitconfig_path = NULL, *tagger = NULL;
7579 char *allowed_signers = NULL, *revoked_signers = NULL;
7580 const char *signer_id = NULL;
7581 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7582 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7583 int *pack_fds = NULL;
7585 #ifndef PROFILE
7586 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7587 "sendfd unveil", NULL) == -1)
7588 err(1, "pledge");
7589 #endif
7591 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7592 switch (ch) {
7593 case 'c':
7594 commit_id_arg = optarg;
7595 break;
7596 case 'l':
7597 do_list = 1;
7598 break;
7599 case 'm':
7600 tagmsg = optarg;
7601 break;
7602 case 'r':
7603 repo_path = realpath(optarg, NULL);
7604 if (repo_path == NULL) {
7605 error = got_error_from_errno2("realpath",
7606 optarg);
7607 goto done;
7609 got_path_strip_trailing_slashes(repo_path);
7610 break;
7611 case 's':
7612 signer_id = optarg;
7613 break;
7614 case 'V':
7615 verify_tags = 1;
7616 break;
7617 case 'v':
7618 if (verbosity < 0)
7619 verbosity = 0;
7620 else if (verbosity < 3)
7621 verbosity++;
7622 break;
7623 default:
7624 usage_tag();
7625 /* NOTREACHED */
7629 argc -= optind;
7630 argv += optind;
7632 if (do_list || verify_tags) {
7633 if (commit_id_arg != NULL)
7634 errx(1,
7635 "-c option can only be used when creating a tag");
7636 if (tagmsg) {
7637 if (do_list)
7638 option_conflict('l', 'm');
7639 else
7640 option_conflict('V', 'm');
7642 if (signer_id) {
7643 if (do_list)
7644 option_conflict('l', 's');
7645 else
7646 option_conflict('V', 's');
7648 if (argc > 1)
7649 usage_tag();
7650 } else if (argc != 1)
7651 usage_tag();
7653 if (argc == 1)
7654 tag_name = argv[0];
7656 cwd = getcwd(NULL, 0);
7657 if (cwd == NULL) {
7658 error = got_error_from_errno("getcwd");
7659 goto done;
7662 error = got_repo_pack_fds_open(&pack_fds);
7663 if (error != NULL)
7664 goto done;
7666 if (repo_path == NULL) {
7667 error = got_worktree_open(&worktree, cwd);
7668 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7669 goto done;
7670 else
7671 error = NULL;
7672 if (worktree) {
7673 repo_path =
7674 strdup(got_worktree_get_repo_path(worktree));
7675 if (repo_path == NULL)
7676 error = got_error_from_errno("strdup");
7677 if (error)
7678 goto done;
7679 } else {
7680 repo_path = strdup(cwd);
7681 if (repo_path == NULL) {
7682 error = got_error_from_errno("strdup");
7683 goto done;
7688 if (do_list || verify_tags) {
7689 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7690 if (error != NULL)
7691 goto done;
7692 error = get_allowed_signers(&allowed_signers, repo, worktree);
7693 if (error)
7694 goto done;
7695 error = get_revoked_signers(&revoked_signers, repo, worktree);
7696 if (error)
7697 goto done;
7698 if (worktree) {
7699 /* Release work tree lock. */
7700 got_worktree_close(worktree);
7701 worktree = NULL;
7705 * Remove "cpath" promise unless needed for signature tmpfile
7706 * creation.
7708 if (verify_tags)
7709 got_sigs_apply_unveil();
7710 else {
7711 #ifndef PROFILE
7712 if (pledge("stdio rpath wpath flock proc exec sendfd "
7713 "unveil", NULL) == -1)
7714 err(1, "pledge");
7715 #endif
7717 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7718 if (error)
7719 goto done;
7720 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7721 revoked_signers, verbosity);
7722 } else {
7723 error = get_gitconfig_path(&gitconfig_path);
7724 if (error)
7725 goto done;
7726 error = got_repo_open(&repo, repo_path, gitconfig_path,
7727 pack_fds);
7728 if (error != NULL)
7729 goto done;
7731 error = get_author(&tagger, repo, worktree);
7732 if (error)
7733 goto done;
7734 if (signer_id == NULL)
7735 signer_id = get_signer_id(repo, worktree);
7737 if (tagmsg) {
7738 if (signer_id) {
7739 error = got_sigs_apply_unveil();
7740 if (error)
7741 goto done;
7743 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7744 if (error)
7745 goto done;
7748 if (commit_id_arg == NULL) {
7749 struct got_reference *head_ref;
7750 struct got_object_id *commit_id;
7751 error = got_ref_open(&head_ref, repo,
7752 worktree ? got_worktree_get_head_ref_name(worktree)
7753 : GOT_REF_HEAD, 0);
7754 if (error)
7755 goto done;
7756 error = got_ref_resolve(&commit_id, repo, head_ref);
7757 got_ref_close(head_ref);
7758 if (error)
7759 goto done;
7760 error = got_object_id_str(&commit_id_str, commit_id);
7761 free(commit_id);
7762 if (error)
7763 goto done;
7766 if (worktree) {
7767 /* Release work tree lock. */
7768 got_worktree_close(worktree);
7769 worktree = NULL;
7772 error = add_tag(repo, tagger, tag_name,
7773 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7774 signer_id, verbosity);
7776 done:
7777 if (repo) {
7778 const struct got_error *close_err = got_repo_close(repo);
7779 if (error == NULL)
7780 error = close_err;
7782 if (worktree)
7783 got_worktree_close(worktree);
7784 if (pack_fds) {
7785 const struct got_error *pack_err =
7786 got_repo_pack_fds_close(pack_fds);
7787 if (error == NULL)
7788 error = pack_err;
7790 free(cwd);
7791 free(repo_path);
7792 free(gitconfig_path);
7793 free(commit_id_str);
7794 free(tagger);
7795 free(allowed_signers);
7796 free(revoked_signers);
7797 return error;
7800 __dead static void
7801 usage_add(void)
7803 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7804 exit(1);
7807 static const struct got_error *
7808 add_progress(void *arg, unsigned char status, const char *path)
7810 while (path[0] == '/')
7811 path++;
7812 printf("%c %s\n", status, path);
7813 return NULL;
7816 static const struct got_error *
7817 cmd_add(int argc, char *argv[])
7819 const struct got_error *error = NULL;
7820 struct got_repository *repo = NULL;
7821 struct got_worktree *worktree = NULL;
7822 char *cwd = NULL;
7823 struct got_pathlist_head paths;
7824 struct got_pathlist_entry *pe;
7825 int ch, can_recurse = 0, no_ignores = 0;
7826 int *pack_fds = NULL;
7828 TAILQ_INIT(&paths);
7830 #ifndef PROFILE
7831 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7832 NULL) == -1)
7833 err(1, "pledge");
7834 #endif
7836 while ((ch = getopt(argc, argv, "IR")) != -1) {
7837 switch (ch) {
7838 case 'I':
7839 no_ignores = 1;
7840 break;
7841 case 'R':
7842 can_recurse = 1;
7843 break;
7844 default:
7845 usage_add();
7846 /* NOTREACHED */
7850 argc -= optind;
7851 argv += optind;
7853 if (argc < 1)
7854 usage_add();
7856 cwd = getcwd(NULL, 0);
7857 if (cwd == NULL) {
7858 error = got_error_from_errno("getcwd");
7859 goto done;
7862 error = got_repo_pack_fds_open(&pack_fds);
7863 if (error != NULL)
7864 goto done;
7866 error = got_worktree_open(&worktree, cwd);
7867 if (error) {
7868 if (error->code == GOT_ERR_NOT_WORKTREE)
7869 error = wrap_not_worktree_error(error, "add", cwd);
7870 goto done;
7873 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7874 NULL, pack_fds);
7875 if (error != NULL)
7876 goto done;
7878 error = apply_unveil(got_repo_get_path(repo), 1,
7879 got_worktree_get_root_path(worktree));
7880 if (error)
7881 goto done;
7883 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7884 if (error)
7885 goto done;
7887 if (!can_recurse) {
7888 char *ondisk_path;
7889 struct stat sb;
7890 TAILQ_FOREACH(pe, &paths, entry) {
7891 if (asprintf(&ondisk_path, "%s/%s",
7892 got_worktree_get_root_path(worktree),
7893 pe->path) == -1) {
7894 error = got_error_from_errno("asprintf");
7895 goto done;
7897 if (lstat(ondisk_path, &sb) == -1) {
7898 if (errno == ENOENT) {
7899 free(ondisk_path);
7900 continue;
7902 error = got_error_from_errno2("lstat",
7903 ondisk_path);
7904 free(ondisk_path);
7905 goto done;
7907 free(ondisk_path);
7908 if (S_ISDIR(sb.st_mode)) {
7909 error = got_error_msg(GOT_ERR_BAD_PATH,
7910 "adding directories requires -R option");
7911 goto done;
7916 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7917 NULL, repo, no_ignores);
7918 done:
7919 if (repo) {
7920 const struct got_error *close_err = got_repo_close(repo);
7921 if (error == NULL)
7922 error = close_err;
7924 if (worktree)
7925 got_worktree_close(worktree);
7926 if (pack_fds) {
7927 const struct got_error *pack_err =
7928 got_repo_pack_fds_close(pack_fds);
7929 if (error == NULL)
7930 error = pack_err;
7932 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7933 free(cwd);
7934 return error;
7937 __dead static void
7938 usage_remove(void)
7940 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7941 getprogname());
7942 exit(1);
7945 static const struct got_error *
7946 print_remove_status(void *arg, unsigned char status,
7947 unsigned char staged_status, const char *path)
7949 while (path[0] == '/')
7950 path++;
7951 if (status == GOT_STATUS_NONEXISTENT)
7952 return NULL;
7953 if (status == staged_status && (status == GOT_STATUS_DELETE))
7954 status = GOT_STATUS_NO_CHANGE;
7955 printf("%c%c %s\n", status, staged_status, path);
7956 return NULL;
7959 static const struct got_error *
7960 cmd_remove(int argc, char *argv[])
7962 const struct got_error *error = NULL;
7963 struct got_worktree *worktree = NULL;
7964 struct got_repository *repo = NULL;
7965 const char *status_codes = NULL;
7966 char *cwd = NULL;
7967 struct got_pathlist_head paths;
7968 struct got_pathlist_entry *pe;
7969 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7970 int ignore_missing_paths = 0;
7971 int *pack_fds = NULL;
7973 TAILQ_INIT(&paths);
7975 #ifndef PROFILE
7976 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7977 NULL) == -1)
7978 err(1, "pledge");
7979 #endif
7981 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7982 switch (ch) {
7983 case 'f':
7984 delete_local_mods = 1;
7985 ignore_missing_paths = 1;
7986 break;
7987 case 'k':
7988 keep_on_disk = 1;
7989 break;
7990 case 'R':
7991 can_recurse = 1;
7992 break;
7993 case 's':
7994 for (i = 0; optarg[i] != '\0'; i++) {
7995 switch (optarg[i]) {
7996 case GOT_STATUS_MODIFY:
7997 delete_local_mods = 1;
7998 break;
7999 case GOT_STATUS_MISSING:
8000 ignore_missing_paths = 1;
8001 break;
8002 default:
8003 errx(1, "invalid status code '%c'",
8004 optarg[i]);
8007 status_codes = optarg;
8008 break;
8009 default:
8010 usage_remove();
8011 /* NOTREACHED */
8015 argc -= optind;
8016 argv += optind;
8018 if (argc < 1)
8019 usage_remove();
8021 cwd = getcwd(NULL, 0);
8022 if (cwd == NULL) {
8023 error = got_error_from_errno("getcwd");
8024 goto done;
8027 error = got_repo_pack_fds_open(&pack_fds);
8028 if (error != NULL)
8029 goto done;
8031 error = got_worktree_open(&worktree, cwd);
8032 if (error) {
8033 if (error->code == GOT_ERR_NOT_WORKTREE)
8034 error = wrap_not_worktree_error(error, "remove", cwd);
8035 goto done;
8038 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8039 NULL, pack_fds);
8040 if (error)
8041 goto done;
8043 error = apply_unveil(got_repo_get_path(repo), 1,
8044 got_worktree_get_root_path(worktree));
8045 if (error)
8046 goto done;
8048 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8049 if (error)
8050 goto done;
8052 if (!can_recurse) {
8053 char *ondisk_path;
8054 struct stat sb;
8055 TAILQ_FOREACH(pe, &paths, entry) {
8056 if (asprintf(&ondisk_path, "%s/%s",
8057 got_worktree_get_root_path(worktree),
8058 pe->path) == -1) {
8059 error = got_error_from_errno("asprintf");
8060 goto done;
8062 if (lstat(ondisk_path, &sb) == -1) {
8063 if (errno == ENOENT) {
8064 free(ondisk_path);
8065 continue;
8067 error = got_error_from_errno2("lstat",
8068 ondisk_path);
8069 free(ondisk_path);
8070 goto done;
8072 free(ondisk_path);
8073 if (S_ISDIR(sb.st_mode)) {
8074 error = got_error_msg(GOT_ERR_BAD_PATH,
8075 "removing directories requires -R option");
8076 goto done;
8081 error = got_worktree_schedule_delete(worktree, &paths,
8082 delete_local_mods, status_codes, print_remove_status, NULL,
8083 repo, keep_on_disk, ignore_missing_paths);
8084 done:
8085 if (repo) {
8086 const struct got_error *close_err = got_repo_close(repo);
8087 if (error == NULL)
8088 error = close_err;
8090 if (worktree)
8091 got_worktree_close(worktree);
8092 if (pack_fds) {
8093 const struct got_error *pack_err =
8094 got_repo_pack_fds_close(pack_fds);
8095 if (error == NULL)
8096 error = pack_err;
8098 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8099 free(cwd);
8100 return error;
8103 __dead static void
8104 usage_patch(void)
8106 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8107 "[patchfile]\n", getprogname());
8108 exit(1);
8111 static const struct got_error *
8112 patch_from_stdin(int *patchfd)
8114 const struct got_error *err = NULL;
8115 ssize_t r;
8116 char buf[BUFSIZ];
8117 sig_t sighup, sigint, sigquit;
8119 *patchfd = got_opentempfd();
8120 if (*patchfd == -1)
8121 return got_error_from_errno("got_opentempfd");
8123 sighup = signal(SIGHUP, SIG_DFL);
8124 sigint = signal(SIGINT, SIG_DFL);
8125 sigquit = signal(SIGQUIT, SIG_DFL);
8127 for (;;) {
8128 r = read(0, buf, sizeof(buf));
8129 if (r == -1) {
8130 err = got_error_from_errno("read");
8131 break;
8133 if (r == 0)
8134 break;
8135 if (write(*patchfd, buf, r) == -1) {
8136 err = got_error_from_errno("write");
8137 break;
8141 signal(SIGHUP, sighup);
8142 signal(SIGINT, sigint);
8143 signal(SIGQUIT, sigquit);
8145 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8146 err = got_error_from_errno("lseek");
8148 if (err != NULL) {
8149 close(*patchfd);
8150 *patchfd = -1;
8153 return err;
8156 struct got_patch_progress_arg {
8157 int did_something;
8158 int conflicts;
8159 int rejects;
8162 static const struct got_error *
8163 patch_progress(void *arg, const char *old, const char *new,
8164 unsigned char status, const struct got_error *error, int old_from,
8165 int old_lines, int new_from, int new_lines, int offset,
8166 int ws_mangled, const struct got_error *hunk_err)
8168 const char *path = new == NULL ? old : new;
8169 struct got_patch_progress_arg *a = arg;
8171 while (*path == '/')
8172 path++;
8174 if (status != GOT_STATUS_NO_CHANGE &&
8175 status != 0 /* per-hunk progress */) {
8176 printf("%c %s\n", status, path);
8177 a->did_something = 1;
8180 if (hunk_err == NULL) {
8181 if (status == GOT_STATUS_CANNOT_UPDATE)
8182 a->rejects++;
8183 else if (status == GOT_STATUS_CONFLICT)
8184 a->conflicts++;
8187 if (error != NULL)
8188 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8190 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8191 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8192 old_lines, new_from, new_lines);
8193 if (hunk_err != NULL)
8194 printf("%s\n", hunk_err->msg);
8195 else if (offset != 0)
8196 printf("applied with offset %d\n", offset);
8197 else
8198 printf("hunk contains mangled whitespace\n");
8201 return NULL;
8204 static void
8205 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8207 if (!ppa->did_something)
8208 return;
8210 if (ppa->conflicts > 0)
8211 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8213 if (ppa->rejects > 0) {
8214 printf("Files where patch failed to apply: %d\n",
8215 ppa->rejects);
8219 static const struct got_error *
8220 cmd_patch(int argc, char *argv[])
8222 const struct got_error *error = NULL, *close_error = NULL;
8223 struct got_worktree *worktree = NULL;
8224 struct got_repository *repo = NULL;
8225 struct got_reflist_head refs;
8226 struct got_object_id *commit_id = NULL;
8227 const char *commit_id_str = NULL;
8228 struct stat sb;
8229 const char *errstr;
8230 char *cwd = NULL;
8231 int ch, nop = 0, strip = -1, reverse = 0;
8232 int patchfd;
8233 int *pack_fds = NULL;
8234 struct got_patch_progress_arg ppa;
8236 TAILQ_INIT(&refs);
8238 #ifndef PROFILE
8239 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8240 "unveil", NULL) == -1)
8241 err(1, "pledge");
8242 #endif
8244 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8245 switch (ch) {
8246 case 'c':
8247 commit_id_str = optarg;
8248 break;
8249 case 'n':
8250 nop = 1;
8251 break;
8252 case 'p':
8253 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8254 if (errstr != NULL)
8255 errx(1, "pathname strip count is %s: %s",
8256 errstr, optarg);
8257 break;
8258 case 'R':
8259 reverse = 1;
8260 break;
8261 default:
8262 usage_patch();
8263 /* NOTREACHED */
8267 argc -= optind;
8268 argv += optind;
8270 if (argc == 0) {
8271 error = patch_from_stdin(&patchfd);
8272 if (error)
8273 return error;
8274 } else if (argc == 1) {
8275 patchfd = open(argv[0], O_RDONLY);
8276 if (patchfd == -1) {
8277 error = got_error_from_errno2("open", argv[0]);
8278 return error;
8280 if (fstat(patchfd, &sb) == -1) {
8281 error = got_error_from_errno2("fstat", argv[0]);
8282 goto done;
8284 if (!S_ISREG(sb.st_mode)) {
8285 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8286 goto done;
8288 } else
8289 usage_patch();
8291 if ((cwd = getcwd(NULL, 0)) == NULL) {
8292 error = got_error_from_errno("getcwd");
8293 goto done;
8296 error = got_repo_pack_fds_open(&pack_fds);
8297 if (error != NULL)
8298 goto done;
8300 error = got_worktree_open(&worktree, cwd);
8301 if (error != NULL)
8302 goto done;
8304 const char *repo_path = got_worktree_get_repo_path(worktree);
8305 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8306 if (error != NULL)
8307 goto done;
8309 error = apply_unveil(got_repo_get_path(repo), 0,
8310 got_worktree_get_root_path(worktree));
8311 if (error != NULL)
8312 goto done;
8314 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8315 if (error)
8316 goto done;
8318 if (commit_id_str != NULL) {
8319 error = got_repo_match_object_id(&commit_id, NULL,
8320 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8321 if (error)
8322 goto done;
8325 memset(&ppa, 0, sizeof(ppa));
8326 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8327 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8328 print_patch_progress_stats(&ppa);
8329 done:
8330 got_ref_list_free(&refs);
8331 free(commit_id);
8332 if (repo) {
8333 close_error = got_repo_close(repo);
8334 if (error == NULL)
8335 error = close_error;
8337 if (worktree != NULL) {
8338 close_error = got_worktree_close(worktree);
8339 if (error == NULL)
8340 error = close_error;
8342 if (pack_fds) {
8343 const struct got_error *pack_err =
8344 got_repo_pack_fds_close(pack_fds);
8345 if (error == NULL)
8346 error = pack_err;
8348 free(cwd);
8349 return error;
8352 __dead static void
8353 usage_revert(void)
8355 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8356 getprogname());
8357 exit(1);
8360 static const struct got_error *
8361 revert_progress(void *arg, unsigned char status, const char *path)
8363 if (status == GOT_STATUS_UNVERSIONED)
8364 return NULL;
8366 while (path[0] == '/')
8367 path++;
8368 printf("%c %s\n", status, path);
8369 return NULL;
8372 struct choose_patch_arg {
8373 FILE *patch_script_file;
8374 const char *action;
8377 static const struct got_error *
8378 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8379 int nchanges, const char *action)
8381 const struct got_error *err;
8382 char *line = NULL;
8383 size_t linesize = 0;
8384 ssize_t linelen;
8386 switch (status) {
8387 case GOT_STATUS_ADD:
8388 printf("A %s\n%s this addition? [y/n] ", path, action);
8389 break;
8390 case GOT_STATUS_DELETE:
8391 printf("D %s\n%s this deletion? [y/n] ", path, action);
8392 break;
8393 case GOT_STATUS_MODIFY:
8394 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8395 return got_error_from_errno("fseek");
8396 printf(GOT_COMMIT_SEP_STR);
8397 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8398 printf("%s", line);
8399 if (linelen == -1 && ferror(patch_file)) {
8400 err = got_error_from_errno("getline");
8401 free(line);
8402 return err;
8404 free(line);
8405 printf(GOT_COMMIT_SEP_STR);
8406 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8407 path, n, nchanges, action);
8408 break;
8409 default:
8410 return got_error_path(path, GOT_ERR_FILE_STATUS);
8413 fflush(stdout);
8414 return NULL;
8417 static const struct got_error *
8418 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8419 FILE *patch_file, int n, int nchanges)
8421 const struct got_error *err = NULL;
8422 char *line = NULL;
8423 size_t linesize = 0;
8424 ssize_t linelen;
8425 int resp = ' ';
8426 struct choose_patch_arg *a = arg;
8428 *choice = GOT_PATCH_CHOICE_NONE;
8430 if (a->patch_script_file) {
8431 char *nl;
8432 err = show_change(status, path, patch_file, n, nchanges,
8433 a->action);
8434 if (err)
8435 return err;
8436 linelen = getline(&line, &linesize, a->patch_script_file);
8437 if (linelen == -1) {
8438 if (ferror(a->patch_script_file))
8439 return got_error_from_errno("getline");
8440 return NULL;
8442 nl = strchr(line, '\n');
8443 if (nl)
8444 *nl = '\0';
8445 if (strcmp(line, "y") == 0) {
8446 *choice = GOT_PATCH_CHOICE_YES;
8447 printf("y\n");
8448 } else if (strcmp(line, "n") == 0) {
8449 *choice = GOT_PATCH_CHOICE_NO;
8450 printf("n\n");
8451 } else if (strcmp(line, "q") == 0 &&
8452 status == GOT_STATUS_MODIFY) {
8453 *choice = GOT_PATCH_CHOICE_QUIT;
8454 printf("q\n");
8455 } else
8456 printf("invalid response '%s'\n", line);
8457 free(line);
8458 return NULL;
8461 while (resp != 'y' && resp != 'n' && resp != 'q') {
8462 err = show_change(status, path, patch_file, n, nchanges,
8463 a->action);
8464 if (err)
8465 return err;
8466 resp = getchar();
8467 if (resp == '\n')
8468 resp = getchar();
8469 if (status == GOT_STATUS_MODIFY) {
8470 if (resp != 'y' && resp != 'n' && resp != 'q') {
8471 printf("invalid response '%c'\n", resp);
8472 resp = ' ';
8474 } else if (resp != 'y' && resp != 'n') {
8475 printf("invalid response '%c'\n", resp);
8476 resp = ' ';
8480 if (resp == 'y')
8481 *choice = GOT_PATCH_CHOICE_YES;
8482 else if (resp == 'n')
8483 *choice = GOT_PATCH_CHOICE_NO;
8484 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8485 *choice = GOT_PATCH_CHOICE_QUIT;
8487 return NULL;
8490 struct wt_commitable_path_arg {
8491 struct got_pathlist_head *commit_paths;
8492 int *has_changes;
8496 * Shortcut work tree status callback to determine if the set of paths scanned
8497 * has at least one versioned path that is being modified and, if not NULL, is
8498 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8499 * soon as a path is passed with a status that satisfies this criteria.
8501 static const struct got_error *
8502 worktree_has_commitable_path(void *arg, unsigned char status,
8503 unsigned char staged_status, const char *path,
8504 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8505 struct got_object_id *commit_id, int dirfd, const char *de_name)
8507 struct wt_commitable_path_arg *a = arg;
8509 if (status == staged_status && (status == GOT_STATUS_DELETE))
8510 status = GOT_STATUS_NO_CHANGE;
8512 if (!(status == GOT_STATUS_NO_CHANGE ||
8513 status == GOT_STATUS_UNVERSIONED) ||
8514 staged_status != GOT_STATUS_NO_CHANGE) {
8515 if (a->commit_paths != NULL) {
8516 struct got_pathlist_entry *pe;
8518 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8519 if (strncmp(path, pe->path,
8520 pe->path_len) == 0) {
8521 *a->has_changes = 1;
8522 break;
8525 } else
8526 *a->has_changes = 1;
8528 if (*a->has_changes)
8529 return got_error(GOT_ERR_FILE_MODIFIED);
8532 return NULL;
8536 * Check that the changeset of the commit identified by id is
8537 * comprised of at least one modified path that is being committed.
8539 static const struct got_error *
8540 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8541 struct got_object_id *id, struct got_worktree *worktree,
8542 struct got_repository *repo)
8544 const struct got_error *err;
8545 struct got_pathlist_head paths;
8546 struct got_commit_object *commit = NULL, *pcommit = NULL;
8547 struct got_tree_object *tree = NULL, *ptree = NULL;
8548 struct got_object_qid *pid;
8550 TAILQ_INIT(&paths);
8552 err = got_object_open_as_commit(&commit, repo, id);
8553 if (err)
8554 goto done;
8556 err = got_object_open_as_tree(&tree, repo,
8557 got_object_commit_get_tree_id(commit));
8558 if (err)
8559 goto done;
8561 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8562 if (pid != NULL) {
8563 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8564 if (err)
8565 goto done;
8567 err = got_object_open_as_tree(&ptree, repo,
8568 got_object_commit_get_tree_id(pcommit));
8569 if (err)
8570 goto done;
8573 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8574 got_diff_tree_collect_changed_paths, &paths, 0);
8575 if (err)
8576 goto done;
8578 err = got_worktree_status(worktree, &paths, repo, 0,
8579 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8580 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8582 * At least one changed path in the referenced commit is
8583 * modified in the work tree, that's all we need to know!
8585 err = NULL;
8588 done:
8589 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8590 if (commit)
8591 got_object_commit_close(commit);
8592 if (pcommit)
8593 got_object_commit_close(pcommit);
8594 if (tree)
8595 got_object_tree_close(tree);
8596 if (ptree)
8597 got_object_tree_close(ptree);
8598 return err;
8602 * Remove any "logmsg" reference comprised entirely of paths that have
8603 * been reverted in this work tree. If any path in the logmsg ref changeset
8604 * remains in a changed state in the worktree, do not remove the reference.
8606 static const struct got_error *
8607 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8609 const struct got_error *err;
8610 struct got_reflist_head refs;
8611 struct got_reflist_entry *re;
8612 struct got_commit_object *commit = NULL;
8613 struct got_object_id *commit_id = NULL;
8614 struct wt_commitable_path_arg wcpa;
8615 char *uuidstr = NULL;
8617 TAILQ_INIT(&refs);
8619 err = got_worktree_get_uuid(&uuidstr, worktree);
8620 if (err)
8621 goto done;
8623 err = got_ref_list(&refs, repo, "refs/got/worktree",
8624 got_ref_cmp_by_name, repo);
8625 if (err)
8626 goto done;
8628 TAILQ_FOREACH(re, &refs, entry) {
8629 const char *refname;
8630 int has_changes = 0;
8632 refname = got_ref_get_name(re->ref);
8634 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8635 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8636 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8637 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8638 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8639 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8640 else
8641 continue;
8643 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8644 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8645 else
8646 continue;
8648 err = got_repo_match_object_id(&commit_id, NULL, refname,
8649 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8650 if (err)
8651 goto done;
8653 err = got_object_open_as_commit(&commit, repo, commit_id);
8654 if (err)
8655 goto done;
8657 wcpa.commit_paths = NULL;
8658 wcpa.has_changes = &has_changes;
8660 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8661 worktree, repo);
8662 if (err)
8663 goto done;
8665 if (!has_changes) {
8666 err = got_ref_delete(re->ref, repo);
8667 if (err)
8668 goto done;
8671 got_object_commit_close(commit);
8672 commit = NULL;
8673 free(commit_id);
8674 commit_id = NULL;
8677 done:
8678 free(uuidstr);
8679 free(commit_id);
8680 got_ref_list_free(&refs);
8681 if (commit)
8682 got_object_commit_close(commit);
8683 return err;
8686 static const struct got_error *
8687 cmd_revert(int argc, char *argv[])
8689 const struct got_error *error = NULL;
8690 struct got_worktree *worktree = NULL;
8691 struct got_repository *repo = NULL;
8692 char *cwd = NULL, *path = NULL;
8693 struct got_pathlist_head paths;
8694 struct got_pathlist_entry *pe;
8695 int ch, can_recurse = 0, pflag = 0;
8696 FILE *patch_script_file = NULL;
8697 const char *patch_script_path = NULL;
8698 struct choose_patch_arg cpa;
8699 int *pack_fds = NULL;
8701 TAILQ_INIT(&paths);
8703 #ifndef PROFILE
8704 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8705 "unveil", NULL) == -1)
8706 err(1, "pledge");
8707 #endif
8709 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8710 switch (ch) {
8711 case 'F':
8712 patch_script_path = optarg;
8713 break;
8714 case 'p':
8715 pflag = 1;
8716 break;
8717 case 'R':
8718 can_recurse = 1;
8719 break;
8720 default:
8721 usage_revert();
8722 /* NOTREACHED */
8726 argc -= optind;
8727 argv += optind;
8729 if (argc < 1)
8730 usage_revert();
8731 if (patch_script_path && !pflag)
8732 errx(1, "-F option can only be used together with -p option");
8734 cwd = getcwd(NULL, 0);
8735 if (cwd == NULL) {
8736 error = got_error_from_errno("getcwd");
8737 goto done;
8740 error = got_repo_pack_fds_open(&pack_fds);
8741 if (error != NULL)
8742 goto done;
8744 error = got_worktree_open(&worktree, cwd);
8745 if (error) {
8746 if (error->code == GOT_ERR_NOT_WORKTREE)
8747 error = wrap_not_worktree_error(error, "revert", cwd);
8748 goto done;
8751 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8752 NULL, pack_fds);
8753 if (error != NULL)
8754 goto done;
8756 if (patch_script_path) {
8757 patch_script_file = fopen(patch_script_path, "re");
8758 if (patch_script_file == NULL) {
8759 error = got_error_from_errno2("fopen",
8760 patch_script_path);
8761 goto done;
8766 * XXX "c" perm needed on repo dir to delete merge references.
8768 error = apply_unveil(got_repo_get_path(repo), 0,
8769 got_worktree_get_root_path(worktree));
8770 if (error)
8771 goto done;
8773 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8774 if (error)
8775 goto done;
8777 if (!can_recurse) {
8778 char *ondisk_path;
8779 struct stat sb;
8780 TAILQ_FOREACH(pe, &paths, entry) {
8781 if (asprintf(&ondisk_path, "%s/%s",
8782 got_worktree_get_root_path(worktree),
8783 pe->path) == -1) {
8784 error = got_error_from_errno("asprintf");
8785 goto done;
8787 if (lstat(ondisk_path, &sb) == -1) {
8788 if (errno == ENOENT) {
8789 free(ondisk_path);
8790 continue;
8792 error = got_error_from_errno2("lstat",
8793 ondisk_path);
8794 free(ondisk_path);
8795 goto done;
8797 free(ondisk_path);
8798 if (S_ISDIR(sb.st_mode)) {
8799 error = got_error_msg(GOT_ERR_BAD_PATH,
8800 "reverting directories requires -R option");
8801 goto done;
8806 cpa.patch_script_file = patch_script_file;
8807 cpa.action = "revert";
8808 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8809 pflag ? choose_patch : NULL, &cpa, repo);
8811 error = rm_logmsg_ref(worktree, repo);
8812 done:
8813 if (patch_script_file && fclose(patch_script_file) == EOF &&
8814 error == NULL)
8815 error = got_error_from_errno2("fclose", patch_script_path);
8816 if (repo) {
8817 const struct got_error *close_err = got_repo_close(repo);
8818 if (error == NULL)
8819 error = close_err;
8821 if (worktree)
8822 got_worktree_close(worktree);
8823 if (pack_fds) {
8824 const struct got_error *pack_err =
8825 got_repo_pack_fds_close(pack_fds);
8826 if (error == NULL)
8827 error = pack_err;
8829 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8830 free(path);
8831 free(cwd);
8832 return error;
8835 __dead static void
8836 usage_commit(void)
8838 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8839 "[-m message] [path ...]\n", getprogname());
8840 exit(1);
8843 struct collect_commit_logmsg_arg {
8844 const char *cmdline_log;
8845 const char *prepared_log;
8846 const char *merged_log;
8847 int non_interactive;
8848 const char *editor;
8849 const char *worktree_path;
8850 const char *branch_name;
8851 const char *repo_path;
8852 char *logmsg_path;
8856 static const struct got_error *
8857 read_prepared_logmsg(char **logmsg, const char *path)
8859 const struct got_error *err = NULL;
8860 FILE *f = NULL;
8861 struct stat sb;
8862 size_t r;
8864 *logmsg = NULL;
8865 memset(&sb, 0, sizeof(sb));
8867 f = fopen(path, "re");
8868 if (f == NULL)
8869 return got_error_from_errno2("fopen", path);
8871 if (fstat(fileno(f), &sb) == -1) {
8872 err = got_error_from_errno2("fstat", path);
8873 goto done;
8875 if (sb.st_size == 0) {
8876 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8877 goto done;
8880 *logmsg = malloc(sb.st_size + 1);
8881 if (*logmsg == NULL) {
8882 err = got_error_from_errno("malloc");
8883 goto done;
8886 r = fread(*logmsg, 1, sb.st_size, f);
8887 if (r != sb.st_size) {
8888 if (ferror(f))
8889 err = got_error_from_errno2("fread", path);
8890 else
8891 err = got_error(GOT_ERR_IO);
8892 goto done;
8894 (*logmsg)[sb.st_size] = '\0';
8895 done:
8896 if (fclose(f) == EOF && err == NULL)
8897 err = got_error_from_errno2("fclose", path);
8898 if (err) {
8899 free(*logmsg);
8900 *logmsg = NULL;
8902 return err;
8905 static const struct got_error *
8906 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8907 const char *diff_path, char **logmsg, void *arg)
8909 char *initial_content = NULL;
8910 struct got_pathlist_entry *pe;
8911 const struct got_error *err = NULL;
8912 char *template = NULL;
8913 char *prepared_msg = NULL, *merged_msg = NULL;
8914 struct collect_commit_logmsg_arg *a = arg;
8915 int initial_content_len;
8916 int fd = -1;
8917 size_t len;
8919 /* if a message was specified on the command line, just use it */
8920 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
8921 len = strlen(a->cmdline_log) + 1;
8922 *logmsg = malloc(len + 1);
8923 if (*logmsg == NULL)
8924 return got_error_from_errno("malloc");
8925 strlcpy(*logmsg, a->cmdline_log, len);
8926 return NULL;
8927 } else if (a->prepared_log != NULL && a->non_interactive)
8928 return read_prepared_logmsg(logmsg, a->prepared_log);
8930 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8931 return got_error_from_errno("asprintf");
8933 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8934 if (err)
8935 goto done;
8937 if (a->prepared_log) {
8938 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8939 if (err)
8940 goto done;
8941 } else if (a->merged_log) {
8942 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8943 if (err)
8944 goto done;
8947 initial_content_len = asprintf(&initial_content,
8948 "%s%s\n# changes to be committed on branch %s:\n",
8949 prepared_msg ? prepared_msg : "",
8950 merged_msg ? merged_msg : "", a->branch_name);
8951 if (initial_content_len == -1) {
8952 err = got_error_from_errno("asprintf");
8953 goto done;
8956 if (write(fd, initial_content, initial_content_len) == -1) {
8957 err = got_error_from_errno2("write", a->logmsg_path);
8958 goto done;
8961 TAILQ_FOREACH(pe, commitable_paths, entry) {
8962 struct got_commitable *ct = pe->data;
8963 dprintf(fd, "# %c %s\n",
8964 got_commitable_get_status(ct),
8965 got_commitable_get_path(ct));
8968 if (diff_path) {
8969 dprintf(fd, "# detailed changes can be viewed in %s\n",
8970 diff_path);
8973 if (close(fd) == -1) {
8974 err = got_error_from_errno2("close", a->logmsg_path);
8975 goto done;
8977 fd = -1;
8979 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8980 initial_content_len, a->prepared_log ? 0 : 1);
8981 done:
8982 free(initial_content);
8983 free(template);
8984 free(prepared_msg);
8985 free(merged_msg);
8987 if (fd != -1 && close(fd) == -1 && err == NULL)
8988 err = got_error_from_errno2("close", a->logmsg_path);
8990 /* Editor is done; we can now apply unveil(2) */
8991 if (err == NULL)
8992 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8993 if (err) {
8994 free(*logmsg);
8995 *logmsg = NULL;
8997 return err;
9000 static const struct got_error *
9001 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9002 const char *type, int has_content)
9004 const struct got_error *err = NULL;
9005 char *logmsg = NULL;
9007 err = got_object_commit_get_logmsg(&logmsg, commit);
9008 if (err)
9009 return err;
9011 if (fprintf(f, "%s# log message of %s commit %s:%s",
9012 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9013 err = got_ferror(f, GOT_ERR_IO);
9015 free(logmsg);
9016 return err;
9020 * Lookup "logmsg" references of backed-out and cherrypicked commits
9021 * belonging to the current work tree. If found, and the worktree has
9022 * at least one modified file that was changed in the referenced commit,
9023 * add its log message to a new temporary file at *logmsg_path.
9024 * Add all refs found to matched_refs to be scheduled for removal on
9025 * successful commit.
9027 static const struct got_error *
9028 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9029 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9030 struct got_repository *repo)
9032 const struct got_error *err;
9033 struct got_commit_object *commit = NULL;
9034 struct got_object_id *id = NULL;
9035 struct got_reflist_head refs;
9036 struct got_reflist_entry *re, *re_match;
9037 FILE *f = NULL;
9038 char *uuidstr = NULL;
9039 int added_logmsg = 0;
9041 TAILQ_INIT(&refs);
9043 *logmsg_path = NULL;
9045 err = got_worktree_get_uuid(&uuidstr, worktree);
9046 if (err)
9047 goto done;
9049 err = got_ref_list(&refs, repo, "refs/got/worktree",
9050 got_ref_cmp_by_name, repo);
9051 if (err)
9052 goto done;
9054 TAILQ_FOREACH(re, &refs, entry) {
9055 const char *refname, *type;
9056 struct wt_commitable_path_arg wcpa;
9057 int add_logmsg = 0;
9059 refname = got_ref_get_name(re->ref);
9061 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9062 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9063 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9064 type = "cherrypicked";
9065 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9066 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9067 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9068 type = "backed-out";
9069 } else
9070 continue;
9072 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9073 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9074 else
9075 continue;
9077 err = got_repo_match_object_id(&id, NULL, refname,
9078 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9079 if (err)
9080 goto done;
9082 err = got_object_open_as_commit(&commit, repo, id);
9083 if (err)
9084 goto done;
9086 wcpa.commit_paths = paths;
9087 wcpa.has_changes = &add_logmsg;
9089 err = commit_path_changed_in_worktree(&wcpa, id,
9090 worktree, repo);
9091 if (err)
9092 goto done;
9094 if (add_logmsg) {
9095 if (f == NULL) {
9096 err = got_opentemp_named(logmsg_path, &f,
9097 "got-commit-logmsg", "");
9098 if (err)
9099 goto done;
9101 err = cat_logmsg(f, commit, refname, type,
9102 added_logmsg);
9103 if (err)
9104 goto done;
9105 if (!added_logmsg)
9106 ++added_logmsg;
9108 err = got_reflist_entry_dup(&re_match, re);
9109 if (err)
9110 goto done;
9111 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9114 got_object_commit_close(commit);
9115 commit = NULL;
9116 free(id);
9117 id = NULL;
9120 done:
9121 free(id);
9122 free(uuidstr);
9123 got_ref_list_free(&refs);
9124 if (commit)
9125 got_object_commit_close(commit);
9126 if (f && fclose(f) == EOF && err == NULL)
9127 err = got_error_from_errno("fclose");
9128 if (!added_logmsg) {
9129 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9130 err = got_error_from_errno2("unlink", *logmsg_path);
9131 *logmsg_path = NULL;
9133 return err;
9136 static const struct got_error *
9137 cmd_commit(int argc, char *argv[])
9139 const struct got_error *error = NULL;
9140 struct got_worktree *worktree = NULL;
9141 struct got_repository *repo = NULL;
9142 char *cwd = NULL, *id_str = NULL;
9143 struct got_object_id *id = NULL;
9144 const char *logmsg = NULL;
9145 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9146 struct collect_commit_logmsg_arg cl_arg;
9147 const char *author = NULL;
9148 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9149 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9150 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9151 int show_diff = 1, commit_conflicts = 0;
9152 struct got_pathlist_head paths;
9153 struct got_reflist_head refs;
9154 struct got_reflist_entry *re;
9155 int *pack_fds = NULL;
9157 TAILQ_INIT(&refs);
9158 TAILQ_INIT(&paths);
9159 cl_arg.logmsg_path = NULL;
9161 #ifndef PROFILE
9162 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9163 "unveil", NULL) == -1)
9164 err(1, "pledge");
9165 #endif
9167 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9168 switch (ch) {
9169 case 'A':
9170 author = optarg;
9171 error = valid_author(author);
9172 if (error)
9173 return error;
9174 break;
9175 case 'C':
9176 commit_conflicts = 1;
9177 break;
9178 case 'F':
9179 if (logmsg != NULL)
9180 option_conflict('F', 'm');
9181 prepared_logmsg = realpath(optarg, NULL);
9182 if (prepared_logmsg == NULL)
9183 return got_error_from_errno2("realpath",
9184 optarg);
9185 break;
9186 case 'm':
9187 if (prepared_logmsg)
9188 option_conflict('m', 'F');
9189 logmsg = optarg;
9190 break;
9191 case 'N':
9192 non_interactive = 1;
9193 break;
9194 case 'n':
9195 show_diff = 0;
9196 break;
9197 case 'S':
9198 allow_bad_symlinks = 1;
9199 break;
9200 default:
9201 usage_commit();
9202 /* NOTREACHED */
9206 argc -= optind;
9207 argv += optind;
9209 cwd = getcwd(NULL, 0);
9210 if (cwd == NULL) {
9211 error = got_error_from_errno("getcwd");
9212 goto done;
9215 error = got_repo_pack_fds_open(&pack_fds);
9216 if (error != NULL)
9217 goto done;
9219 error = got_worktree_open(&worktree, cwd);
9220 if (error) {
9221 if (error->code == GOT_ERR_NOT_WORKTREE)
9222 error = wrap_not_worktree_error(error, "commit", cwd);
9223 goto done;
9226 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9227 if (error)
9228 goto done;
9229 if (rebase_in_progress) {
9230 error = got_error(GOT_ERR_REBASING);
9231 goto done;
9234 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9235 worktree);
9236 if (error)
9237 goto done;
9239 error = get_gitconfig_path(&gitconfig_path);
9240 if (error)
9241 goto done;
9242 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9243 gitconfig_path, pack_fds);
9244 if (error != NULL)
9245 goto done;
9247 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9248 if (error)
9249 goto done;
9250 if (merge_in_progress) {
9251 error = got_error(GOT_ERR_MERGE_BUSY);
9252 goto done;
9255 error = get_author(&committer, repo, worktree);
9256 if (error)
9257 goto done;
9259 if (author == NULL)
9260 author = committer;
9263 * unveil(2) traverses exec(2); if an editor is used we have
9264 * to apply unveil after the log message has been written.
9266 if (logmsg == NULL || strlen(logmsg) == 0)
9267 error = get_editor(&editor);
9268 else
9269 error = apply_unveil(got_repo_get_path(repo), 0,
9270 got_worktree_get_root_path(worktree));
9271 if (error)
9272 goto done;
9274 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9275 if (error)
9276 goto done;
9278 if (prepared_logmsg == NULL) {
9279 error = lookup_logmsg_ref(&merged_logmsg,
9280 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9281 if (error)
9282 goto done;
9285 cl_arg.editor = editor;
9286 cl_arg.cmdline_log = logmsg;
9287 cl_arg.prepared_log = prepared_logmsg;
9288 cl_arg.merged_log = merged_logmsg;
9289 cl_arg.non_interactive = non_interactive;
9290 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9291 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9292 if (!histedit_in_progress) {
9293 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9294 error = got_error(GOT_ERR_COMMIT_BRANCH);
9295 goto done;
9297 cl_arg.branch_name += 11;
9299 cl_arg.repo_path = got_repo_get_path(repo);
9300 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9301 allow_bad_symlinks, show_diff, commit_conflicts,
9302 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9303 if (error) {
9304 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9305 cl_arg.logmsg_path != NULL)
9306 preserve_logmsg = 1;
9307 goto done;
9310 error = got_object_id_str(&id_str, id);
9311 if (error)
9312 goto done;
9313 printf("Created commit %s\n", id_str);
9315 TAILQ_FOREACH(re, &refs, entry) {
9316 error = got_ref_delete(re->ref, repo);
9317 if (error)
9318 goto done;
9321 done:
9322 if (preserve_logmsg) {
9323 fprintf(stderr, "%s: log message preserved in %s\n",
9324 getprogname(), cl_arg.logmsg_path);
9325 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9326 error == NULL)
9327 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9328 free(cl_arg.logmsg_path);
9329 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9330 error = got_error_from_errno2("unlink", merged_logmsg);
9331 free(merged_logmsg);
9332 if (repo) {
9333 const struct got_error *close_err = got_repo_close(repo);
9334 if (error == NULL)
9335 error = close_err;
9337 if (worktree)
9338 got_worktree_close(worktree);
9339 if (pack_fds) {
9340 const struct got_error *pack_err =
9341 got_repo_pack_fds_close(pack_fds);
9342 if (error == NULL)
9343 error = pack_err;
9345 got_ref_list_free(&refs);
9346 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9347 free(cwd);
9348 free(id_str);
9349 free(gitconfig_path);
9350 free(editor);
9351 free(committer);
9352 free(prepared_logmsg);
9353 return error;
9356 __dead static void
9357 usage_send(void)
9359 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9360 "[-r repository-path] [-t tag] [remote-repository]\n",
9361 getprogname());
9362 exit(1);
9365 static void
9366 print_load_info(int print_colored, int print_found, int print_trees,
9367 int ncolored, int nfound, int ntrees)
9369 if (print_colored) {
9370 printf("%d commit%s colored", ncolored,
9371 ncolored == 1 ? "" : "s");
9373 if (print_found) {
9374 printf("%s%d object%s found",
9375 ncolored > 0 ? "; " : "",
9376 nfound, nfound == 1 ? "" : "s");
9378 if (print_trees) {
9379 printf("; %d tree%s scanned", ntrees,
9380 ntrees == 1 ? "" : "s");
9384 struct got_send_progress_arg {
9385 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9386 int verbosity;
9387 int last_ncolored;
9388 int last_nfound;
9389 int last_ntrees;
9390 int loading_done;
9391 int last_ncommits;
9392 int last_nobj_total;
9393 int last_p_deltify;
9394 int last_p_written;
9395 int last_p_sent;
9396 int printed_something;
9397 int sent_something;
9398 struct got_pathlist_head *delete_branches;
9401 static const struct got_error *
9402 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9403 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9404 int nobj_written, off_t bytes_sent, const char *refname,
9405 const char *errmsg, int success)
9407 struct got_send_progress_arg *a = arg;
9408 char scaled_packsize[FMT_SCALED_STRSIZE];
9409 char scaled_sent[FMT_SCALED_STRSIZE];
9410 int p_deltify = 0, p_written = 0, p_sent = 0;
9411 int print_colored = 0, print_found = 0, print_trees = 0;
9412 int print_searching = 0, print_total = 0;
9413 int print_deltify = 0, print_written = 0, print_sent = 0;
9415 if (a->verbosity < 0)
9416 return NULL;
9418 if (refname) {
9419 const char *status = success ? "accepted" : "rejected";
9421 if (success) {
9422 struct got_pathlist_entry *pe;
9423 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9424 const char *branchname = pe->path;
9425 if (got_path_cmp(branchname, refname,
9426 strlen(branchname), strlen(refname)) == 0) {
9427 status = "deleted";
9428 a->sent_something = 1;
9429 break;
9434 if (a->printed_something)
9435 putchar('\n');
9436 printf("Server has %s %s", status, refname);
9437 if (errmsg)
9438 printf(": %s", errmsg);
9439 a->printed_something = 1;
9440 return NULL;
9443 if (a->last_ncolored != ncolored) {
9444 print_colored = 1;
9445 a->last_ncolored = ncolored;
9448 if (a->last_nfound != nfound) {
9449 print_colored = 1;
9450 print_found = 1;
9451 a->last_nfound = nfound;
9454 if (a->last_ntrees != ntrees) {
9455 print_colored = 1;
9456 print_found = 1;
9457 print_trees = 1;
9458 a->last_ntrees = ntrees;
9461 if ((print_colored || print_found || print_trees) &&
9462 !a->loading_done) {
9463 printf("\r");
9464 print_load_info(print_colored, print_found, print_trees,
9465 ncolored, nfound, ntrees);
9466 a->printed_something = 1;
9467 fflush(stdout);
9468 return NULL;
9469 } else if (!a->loading_done) {
9470 printf("\r");
9471 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9472 printf("\n");
9473 a->loading_done = 1;
9476 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9477 return got_error_from_errno("fmt_scaled");
9478 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9479 return got_error_from_errno("fmt_scaled");
9481 if (a->last_ncommits != ncommits) {
9482 print_searching = 1;
9483 a->last_ncommits = ncommits;
9486 if (a->last_nobj_total != nobj_total) {
9487 print_searching = 1;
9488 print_total = 1;
9489 a->last_nobj_total = nobj_total;
9492 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9493 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9494 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9495 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9496 return got_error(GOT_ERR_NO_SPACE);
9499 if (nobj_deltify > 0 || nobj_written > 0) {
9500 if (nobj_deltify > 0) {
9501 p_deltify = (nobj_deltify * 100) / nobj_total;
9502 if (p_deltify != a->last_p_deltify) {
9503 a->last_p_deltify = p_deltify;
9504 print_searching = 1;
9505 print_total = 1;
9506 print_deltify = 1;
9509 if (nobj_written > 0) {
9510 p_written = (nobj_written * 100) / nobj_total;
9511 if (p_written != a->last_p_written) {
9512 a->last_p_written = p_written;
9513 print_searching = 1;
9514 print_total = 1;
9515 print_deltify = 1;
9516 print_written = 1;
9521 if (bytes_sent > 0) {
9522 p_sent = (bytes_sent * 100) / packfile_size;
9523 if (p_sent != a->last_p_sent) {
9524 a->last_p_sent = p_sent;
9525 print_searching = 1;
9526 print_total = 1;
9527 print_deltify = 1;
9528 print_written = 1;
9529 print_sent = 1;
9531 a->sent_something = 1;
9534 if (print_searching || print_total || print_deltify || print_written ||
9535 print_sent)
9536 printf("\r");
9537 if (print_searching)
9538 printf("packing %d reference%s", ncommits,
9539 ncommits == 1 ? "" : "s");
9540 if (print_total)
9541 printf("; %d object%s", nobj_total,
9542 nobj_total == 1 ? "" : "s");
9543 if (print_deltify)
9544 printf("; deltify: %d%%", p_deltify);
9545 if (print_sent)
9546 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9547 scaled_packsize, p_sent);
9548 else if (print_written)
9549 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9550 scaled_packsize, p_written);
9551 if (print_searching || print_total || print_deltify ||
9552 print_written || print_sent) {
9553 a->printed_something = 1;
9554 fflush(stdout);
9556 return NULL;
9559 static const struct got_error *
9560 cmd_send(int argc, char *argv[])
9562 const struct got_error *error = NULL;
9563 char *cwd = NULL, *repo_path = NULL;
9564 const char *remote_name;
9565 char *proto = NULL, *host = NULL, *port = NULL;
9566 char *repo_name = NULL, *server_path = NULL;
9567 const struct got_remote_repo *remotes, *remote = NULL;
9568 int nremotes, nbranches = 0, ndelete_branches = 0;
9569 struct got_repository *repo = NULL;
9570 struct got_worktree *worktree = NULL;
9571 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9572 struct got_pathlist_head branches;
9573 struct got_pathlist_head tags;
9574 struct got_reflist_head all_branches;
9575 struct got_reflist_head all_tags;
9576 struct got_pathlist_head delete_args;
9577 struct got_pathlist_head delete_branches;
9578 struct got_reflist_entry *re;
9579 struct got_pathlist_entry *pe;
9580 int i, ch, sendfd = -1, sendstatus;
9581 pid_t sendpid = -1;
9582 struct got_send_progress_arg spa;
9583 int verbosity = 0, overwrite_refs = 0;
9584 int send_all_branches = 0, send_all_tags = 0;
9585 struct got_reference *ref = NULL;
9586 int *pack_fds = NULL;
9588 TAILQ_INIT(&branches);
9589 TAILQ_INIT(&tags);
9590 TAILQ_INIT(&all_branches);
9591 TAILQ_INIT(&all_tags);
9592 TAILQ_INIT(&delete_args);
9593 TAILQ_INIT(&delete_branches);
9595 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9596 switch (ch) {
9597 case 'a':
9598 send_all_branches = 1;
9599 break;
9600 case 'b':
9601 error = got_pathlist_append(&branches, optarg, NULL);
9602 if (error)
9603 return error;
9604 nbranches++;
9605 break;
9606 case 'd':
9607 error = got_pathlist_append(&delete_args, optarg, NULL);
9608 if (error)
9609 return error;
9610 break;
9611 case 'f':
9612 overwrite_refs = 1;
9613 break;
9614 case 'q':
9615 verbosity = -1;
9616 break;
9617 case 'r':
9618 repo_path = realpath(optarg, NULL);
9619 if (repo_path == NULL)
9620 return got_error_from_errno2("realpath",
9621 optarg);
9622 got_path_strip_trailing_slashes(repo_path);
9623 break;
9624 case 'T':
9625 send_all_tags = 1;
9626 break;
9627 case 't':
9628 error = got_pathlist_append(&tags, optarg, NULL);
9629 if (error)
9630 return error;
9631 break;
9632 case 'v':
9633 if (verbosity < 0)
9634 verbosity = 0;
9635 else if (verbosity < 3)
9636 verbosity++;
9637 break;
9638 default:
9639 usage_send();
9640 /* NOTREACHED */
9643 argc -= optind;
9644 argv += optind;
9646 if (send_all_branches && !TAILQ_EMPTY(&branches))
9647 option_conflict('a', 'b');
9648 if (send_all_tags && !TAILQ_EMPTY(&tags))
9649 option_conflict('T', 't');
9652 if (argc == 0)
9653 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9654 else if (argc == 1)
9655 remote_name = argv[0];
9656 else
9657 usage_send();
9659 cwd = getcwd(NULL, 0);
9660 if (cwd == NULL) {
9661 error = got_error_from_errno("getcwd");
9662 goto done;
9665 error = got_repo_pack_fds_open(&pack_fds);
9666 if (error != NULL)
9667 goto done;
9669 if (repo_path == NULL) {
9670 error = got_worktree_open(&worktree, cwd);
9671 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9672 goto done;
9673 else
9674 error = NULL;
9675 if (worktree) {
9676 repo_path =
9677 strdup(got_worktree_get_repo_path(worktree));
9678 if (repo_path == NULL)
9679 error = got_error_from_errno("strdup");
9680 if (error)
9681 goto done;
9682 } else {
9683 repo_path = strdup(cwd);
9684 if (repo_path == NULL) {
9685 error = got_error_from_errno("strdup");
9686 goto done;
9691 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9692 if (error)
9693 goto done;
9695 if (worktree) {
9696 worktree_conf = got_worktree_get_gotconfig(worktree);
9697 if (worktree_conf) {
9698 got_gotconfig_get_remotes(&nremotes, &remotes,
9699 worktree_conf);
9700 for (i = 0; i < nremotes; i++) {
9701 if (strcmp(remotes[i].name, remote_name) == 0) {
9702 remote = &remotes[i];
9703 break;
9708 if (remote == NULL) {
9709 repo_conf = got_repo_get_gotconfig(repo);
9710 if (repo_conf) {
9711 got_gotconfig_get_remotes(&nremotes, &remotes,
9712 repo_conf);
9713 for (i = 0; i < nremotes; i++) {
9714 if (strcmp(remotes[i].name, remote_name) == 0) {
9715 remote = &remotes[i];
9716 break;
9721 if (remote == NULL) {
9722 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9723 for (i = 0; i < nremotes; i++) {
9724 if (strcmp(remotes[i].name, remote_name) == 0) {
9725 remote = &remotes[i];
9726 break;
9730 if (remote == NULL) {
9731 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9732 goto done;
9735 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9736 &repo_name, remote->send_url);
9737 if (error)
9738 goto done;
9740 if (strcmp(proto, "git") == 0) {
9741 #ifndef PROFILE
9742 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9743 "sendfd dns inet unveil", NULL) == -1)
9744 err(1, "pledge");
9745 #endif
9746 } else if (strcmp(proto, "git+ssh") == 0 ||
9747 strcmp(proto, "ssh") == 0) {
9748 #ifndef PROFILE
9749 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9750 "sendfd unveil", NULL) == -1)
9751 err(1, "pledge");
9752 #endif
9753 } else if (strcmp(proto, "http") == 0 ||
9754 strcmp(proto, "git+http") == 0) {
9755 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9756 goto done;
9757 } else {
9758 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9759 goto done;
9762 error = got_dial_apply_unveil(proto);
9763 if (error)
9764 goto done;
9766 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9767 if (error)
9768 goto done;
9770 if (send_all_branches) {
9771 error = got_ref_list(&all_branches, repo, "refs/heads",
9772 got_ref_cmp_by_name, NULL);
9773 if (error)
9774 goto done;
9775 TAILQ_FOREACH(re, &all_branches, entry) {
9776 const char *branchname = got_ref_get_name(re->ref);
9777 error = got_pathlist_append(&branches,
9778 branchname, NULL);
9779 if (error)
9780 goto done;
9781 nbranches++;
9783 } else if (nbranches == 0) {
9784 for (i = 0; i < remote->nsend_branches; i++) {
9785 error = got_pathlist_append(&branches,
9786 remote->send_branches[i], NULL);
9787 if (error)
9788 goto done;
9792 if (send_all_tags) {
9793 error = got_ref_list(&all_tags, repo, "refs/tags",
9794 got_ref_cmp_by_name, NULL);
9795 if (error)
9796 goto done;
9797 TAILQ_FOREACH(re, &all_tags, entry) {
9798 const char *tagname = got_ref_get_name(re->ref);
9799 error = got_pathlist_append(&tags,
9800 tagname, NULL);
9801 if (error)
9802 goto done;
9807 * To prevent accidents only branches in refs/heads/ can be deleted
9808 * with 'got send -d'.
9809 * Deleting anything else requires local repository access or Git.
9811 TAILQ_FOREACH(pe, &delete_args, entry) {
9812 const char *branchname = pe->path;
9813 char *s;
9814 struct got_pathlist_entry *new;
9815 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9816 s = strdup(branchname);
9817 if (s == NULL) {
9818 error = got_error_from_errno("strdup");
9819 goto done;
9821 } else {
9822 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9823 error = got_error_from_errno("asprintf");
9824 goto done;
9827 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9828 if (error || new == NULL /* duplicate */)
9829 free(s);
9830 if (error)
9831 goto done;
9832 ndelete_branches++;
9835 if (nbranches == 0 && ndelete_branches == 0) {
9836 struct got_reference *head_ref;
9837 if (worktree)
9838 error = got_ref_open(&head_ref, repo,
9839 got_worktree_get_head_ref_name(worktree), 0);
9840 else
9841 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9842 if (error)
9843 goto done;
9844 if (got_ref_is_symbolic(head_ref)) {
9845 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9846 got_ref_close(head_ref);
9847 if (error)
9848 goto done;
9849 } else
9850 ref = head_ref;
9851 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9852 NULL);
9853 if (error)
9854 goto done;
9855 nbranches++;
9858 if (verbosity >= 0) {
9859 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9860 remote->name, proto, host,
9861 port ? ":" : "", port ? port : "",
9862 *server_path == '/' ? "" : "/", server_path);
9865 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9866 server_path, verbosity);
9867 if (error)
9868 goto done;
9870 memset(&spa, 0, sizeof(spa));
9871 spa.last_scaled_packsize[0] = '\0';
9872 spa.last_p_deltify = -1;
9873 spa.last_p_written = -1;
9874 spa.verbosity = verbosity;
9875 spa.delete_branches = &delete_branches;
9876 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9877 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9878 check_cancelled, NULL);
9879 if (spa.printed_something)
9880 putchar('\n');
9881 if (error)
9882 goto done;
9883 if (!spa.sent_something && verbosity >= 0)
9884 printf("Already up-to-date\n");
9885 done:
9886 if (sendpid > 0) {
9887 if (kill(sendpid, SIGTERM) == -1)
9888 error = got_error_from_errno("kill");
9889 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9890 error = got_error_from_errno("waitpid");
9892 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9893 error = got_error_from_errno("close");
9894 if (repo) {
9895 const struct got_error *close_err = got_repo_close(repo);
9896 if (error == NULL)
9897 error = close_err;
9899 if (worktree)
9900 got_worktree_close(worktree);
9901 if (pack_fds) {
9902 const struct got_error *pack_err =
9903 got_repo_pack_fds_close(pack_fds);
9904 if (error == NULL)
9905 error = pack_err;
9907 if (ref)
9908 got_ref_close(ref);
9909 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9910 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9911 got_ref_list_free(&all_branches);
9912 got_ref_list_free(&all_tags);
9913 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9914 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9915 free(cwd);
9916 free(repo_path);
9917 free(proto);
9918 free(host);
9919 free(port);
9920 free(server_path);
9921 free(repo_name);
9922 return error;
9926 * Print and if delete is set delete all ref_prefix references.
9927 * If wanted_ref is not NULL, only print or delete this reference.
9929 static const struct got_error *
9930 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9931 const char *wanted_ref, int delete, struct got_worktree *worktree,
9932 struct got_repository *repo)
9934 const struct got_error *err;
9935 struct got_pathlist_head paths;
9936 struct got_reflist_head refs;
9937 struct got_reflist_entry *re;
9938 struct got_reflist_object_id_map *refs_idmap = NULL;
9939 struct got_commit_object *commit = NULL;
9940 struct got_object_id *id = NULL;
9941 const char *header_prefix;
9942 char *uuidstr = NULL;
9943 int found = 0;
9945 TAILQ_INIT(&refs);
9946 TAILQ_INIT(&paths);
9948 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9949 if (err)
9950 goto done;
9952 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9953 if (err)
9954 goto done;
9956 if (worktree != NULL) {
9957 err = got_worktree_get_uuid(&uuidstr, worktree);
9958 if (err)
9959 goto done;
9962 if (wanted_ref) {
9963 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9964 wanted_ref += 11;
9967 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9968 header_prefix = "backout";
9969 else
9970 header_prefix = "cherrypick";
9972 TAILQ_FOREACH(re, &refs, entry) {
9973 const char *refname, *wt;
9975 refname = got_ref_get_name(re->ref);
9977 err = check_cancelled(NULL);
9978 if (err)
9979 goto done;
9981 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9982 refname += prefix_len + 1; /* skip '-' delimiter */
9983 else
9984 continue;
9986 wt = refname;
9988 if (worktree == NULL || strncmp(refname, uuidstr,
9989 GOT_WORKTREE_UUID_STRLEN) == 0)
9990 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9991 else
9992 continue;
9994 err = got_repo_match_object_id(&id, NULL, refname,
9995 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9996 if (err)
9997 goto done;
9999 err = got_object_open_as_commit(&commit, repo, id);
10000 if (err)
10001 goto done;
10003 if (wanted_ref)
10004 found = strncmp(wanted_ref, refname,
10005 strlen(wanted_ref)) == 0;
10006 if (wanted_ref && !found) {
10007 struct got_reflist_head *ci_refs;
10009 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10010 id);
10012 if (ci_refs) {
10013 char *refs_str = NULL;
10014 char const *r = NULL;
10016 err = build_refs_str(&refs_str, ci_refs, id,
10017 repo, 1);
10018 if (err)
10019 goto done;
10021 r = refs_str;
10022 while (r) {
10023 if (strncmp(r, wanted_ref,
10024 strlen(wanted_ref)) == 0) {
10025 found = 1;
10026 break;
10028 r = strchr(r, ' ');
10029 if (r)
10030 ++r;
10032 free(refs_str);
10036 if (wanted_ref == NULL || found) {
10037 if (delete) {
10038 err = got_ref_delete(re->ref, repo);
10039 if (err)
10040 goto done;
10041 printf("Deleted: ");
10042 err = print_commit_oneline(commit, id, repo,
10043 refs_idmap);
10044 } else {
10046 * Print paths modified by commit to help
10047 * associate commits with worktree changes.
10049 err = get_changed_paths(&paths, commit,
10050 repo, NULL);
10051 if (err)
10052 goto done;
10054 err = print_commit(commit, id, repo, NULL,
10055 &paths, NULL, 0, 0, refs_idmap, NULL,
10056 header_prefix);
10057 got_pathlist_free(&paths,
10058 GOT_PATHLIST_FREE_ALL);
10060 if (worktree == NULL)
10061 printf("work tree: %.*s\n\n",
10062 GOT_WORKTREE_UUID_STRLEN, wt);
10064 if (err || found)
10065 goto done;
10068 got_object_commit_close(commit);
10069 commit = NULL;
10070 free(id);
10071 id = NULL;
10074 if (wanted_ref != NULL && !found)
10075 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10077 done:
10078 free(id);
10079 free(uuidstr);
10080 got_ref_list_free(&refs);
10081 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10082 if (refs_idmap)
10083 got_reflist_object_id_map_free(refs_idmap);
10084 if (commit)
10085 got_object_commit_close(commit);
10086 return err;
10090 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10091 * identified by id for log messages to prepopulate the editor on commit.
10093 static const struct got_error *
10094 logmsg_ref(struct got_object_id *id, const char *prefix,
10095 struct got_worktree *worktree, struct got_repository *repo)
10097 const struct got_error *err = NULL;
10098 char *idstr, *ref = NULL, *refname = NULL;
10099 int histedit_in_progress;
10100 int rebase_in_progress, merge_in_progress;
10103 * Silenty refuse to create merge reference if any histedit, merge,
10104 * or rebase operation is in progress.
10106 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10107 worktree);
10108 if (err)
10109 return err;
10110 if (histedit_in_progress)
10111 return NULL;
10113 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10114 if (err)
10115 return err;
10116 if (rebase_in_progress)
10117 return NULL;
10119 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10120 repo);
10121 if (err)
10122 return err;
10123 if (merge_in_progress)
10124 return NULL;
10126 err = got_object_id_str(&idstr, id);
10127 if (err)
10128 return err;
10130 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10131 if (err)
10132 goto done;
10134 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10135 err = got_error_from_errno("asprintf");
10136 goto done;
10139 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10140 -1, repo);
10141 done:
10142 free(ref);
10143 free(idstr);
10144 free(refname);
10145 return err;
10148 __dead static void
10149 usage_cherrypick(void)
10151 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10152 getprogname());
10153 exit(1);
10156 static const struct got_error *
10157 cmd_cherrypick(int argc, char *argv[])
10159 const struct got_error *error = NULL;
10160 struct got_worktree *worktree = NULL;
10161 struct got_repository *repo = NULL;
10162 char *cwd = NULL, *commit_id_str = NULL;
10163 struct got_object_id *commit_id = NULL;
10164 struct got_commit_object *commit = NULL;
10165 struct got_object_qid *pid;
10166 int ch, list_refs = 0, remove_refs = 0;
10167 struct got_update_progress_arg upa;
10168 int *pack_fds = NULL;
10170 #ifndef PROFILE
10171 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10172 "unveil", NULL) == -1)
10173 err(1, "pledge");
10174 #endif
10176 while ((ch = getopt(argc, argv, "lX")) != -1) {
10177 switch (ch) {
10178 case 'l':
10179 list_refs = 1;
10180 break;
10181 case 'X':
10182 remove_refs = 1;
10183 break;
10184 default:
10185 usage_cherrypick();
10186 /* NOTREACHED */
10190 argc -= optind;
10191 argv += optind;
10193 if (list_refs || remove_refs) {
10194 if (argc != 0 && argc != 1)
10195 usage_cherrypick();
10196 } else if (argc != 1)
10197 usage_cherrypick();
10198 if (list_refs && remove_refs)
10199 option_conflict('l', 'X');
10201 cwd = getcwd(NULL, 0);
10202 if (cwd == NULL) {
10203 error = got_error_from_errno("getcwd");
10204 goto done;
10207 error = got_repo_pack_fds_open(&pack_fds);
10208 if (error != NULL)
10209 goto done;
10211 error = got_worktree_open(&worktree, cwd);
10212 if (error) {
10213 if (list_refs || remove_refs) {
10214 if (error->code != GOT_ERR_NOT_WORKTREE)
10215 goto done;
10216 } else {
10217 if (error->code == GOT_ERR_NOT_WORKTREE)
10218 error = wrap_not_worktree_error(error,
10219 "cherrypick", cwd);
10220 goto done;
10224 error = got_repo_open(&repo,
10225 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10226 NULL, pack_fds);
10227 if (error != NULL)
10228 goto done;
10230 error = apply_unveil(got_repo_get_path(repo), 0,
10231 worktree ? got_worktree_get_root_path(worktree) : NULL);
10232 if (error)
10233 goto done;
10235 if (list_refs || remove_refs) {
10236 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10237 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10238 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10239 goto done;
10242 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10243 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10244 if (error)
10245 goto done;
10246 error = got_object_id_str(&commit_id_str, commit_id);
10247 if (error)
10248 goto done;
10250 error = got_object_open_as_commit(&commit, repo, commit_id);
10251 if (error)
10252 goto done;
10253 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10254 memset(&upa, 0, sizeof(upa));
10255 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10256 commit_id, repo, update_progress, &upa, check_cancelled,
10257 NULL);
10258 if (error != NULL)
10259 goto done;
10261 if (upa.did_something) {
10262 error = logmsg_ref(commit_id,
10263 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10264 if (error)
10265 goto done;
10266 printf("Merged commit %s\n", commit_id_str);
10268 print_merge_progress_stats(&upa);
10269 done:
10270 free(cwd);
10271 if (commit)
10272 got_object_commit_close(commit);
10273 free(commit_id_str);
10274 if (worktree)
10275 got_worktree_close(worktree);
10276 if (repo) {
10277 const struct got_error *close_err = got_repo_close(repo);
10278 if (error == NULL)
10279 error = close_err;
10281 if (pack_fds) {
10282 const struct got_error *pack_err =
10283 got_repo_pack_fds_close(pack_fds);
10284 if (error == NULL)
10285 error = pack_err;
10288 return error;
10291 __dead static void
10292 usage_backout(void)
10294 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10295 exit(1);
10298 static const struct got_error *
10299 cmd_backout(int argc, char *argv[])
10301 const struct got_error *error = NULL;
10302 struct got_worktree *worktree = NULL;
10303 struct got_repository *repo = NULL;
10304 char *cwd = NULL, *commit_id_str = NULL;
10305 struct got_object_id *commit_id = NULL;
10306 struct got_commit_object *commit = NULL;
10307 struct got_object_qid *pid;
10308 int ch, list_refs = 0, remove_refs = 0;
10309 struct got_update_progress_arg upa;
10310 int *pack_fds = NULL;
10312 #ifndef PROFILE
10313 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10314 "unveil", NULL) == -1)
10315 err(1, "pledge");
10316 #endif
10318 while ((ch = getopt(argc, argv, "lX")) != -1) {
10319 switch (ch) {
10320 case 'l':
10321 list_refs = 1;
10322 break;
10323 case 'X':
10324 remove_refs = 1;
10325 break;
10326 default:
10327 usage_backout();
10328 /* NOTREACHED */
10332 argc -= optind;
10333 argv += optind;
10335 if (list_refs || remove_refs) {
10336 if (argc != 0 && argc != 1)
10337 usage_backout();
10338 } else if (argc != 1)
10339 usage_backout();
10340 if (list_refs && remove_refs)
10341 option_conflict('l', 'X');
10343 cwd = getcwd(NULL, 0);
10344 if (cwd == NULL) {
10345 error = got_error_from_errno("getcwd");
10346 goto done;
10349 error = got_repo_pack_fds_open(&pack_fds);
10350 if (error != NULL)
10351 goto done;
10353 error = got_worktree_open(&worktree, cwd);
10354 if (error) {
10355 if (list_refs || remove_refs) {
10356 if (error->code != GOT_ERR_NOT_WORKTREE)
10357 goto done;
10358 } else {
10359 if (error->code == GOT_ERR_NOT_WORKTREE)
10360 error = wrap_not_worktree_error(error,
10361 "backout", cwd);
10362 goto done;
10366 error = got_repo_open(&repo,
10367 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10368 NULL, pack_fds);
10369 if (error != NULL)
10370 goto done;
10372 error = apply_unveil(got_repo_get_path(repo), 0,
10373 worktree ? got_worktree_get_root_path(worktree) : NULL);
10374 if (error)
10375 goto done;
10377 if (list_refs || remove_refs) {
10378 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10379 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10380 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10381 goto done;
10384 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10385 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10386 if (error)
10387 goto done;
10388 error = got_object_id_str(&commit_id_str, commit_id);
10389 if (error)
10390 goto done;
10392 error = got_object_open_as_commit(&commit, repo, commit_id);
10393 if (error)
10394 goto done;
10395 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10396 if (pid == NULL) {
10397 error = got_error(GOT_ERR_ROOT_COMMIT);
10398 goto done;
10401 memset(&upa, 0, sizeof(upa));
10402 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10403 repo, update_progress, &upa, check_cancelled, NULL);
10404 if (error != NULL)
10405 goto done;
10407 if (upa.did_something) {
10408 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10409 worktree, repo);
10410 if (error)
10411 goto done;
10412 printf("Backed out commit %s\n", commit_id_str);
10414 print_merge_progress_stats(&upa);
10415 done:
10416 free(cwd);
10417 if (commit)
10418 got_object_commit_close(commit);
10419 free(commit_id_str);
10420 if (worktree)
10421 got_worktree_close(worktree);
10422 if (repo) {
10423 const struct got_error *close_err = got_repo_close(repo);
10424 if (error == NULL)
10425 error = close_err;
10427 if (pack_fds) {
10428 const struct got_error *pack_err =
10429 got_repo_pack_fds_close(pack_fds);
10430 if (error == NULL)
10431 error = pack_err;
10433 return error;
10436 __dead static void
10437 usage_rebase(void)
10439 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10440 exit(1);
10443 static void
10444 trim_logmsg(char *logmsg, int limit)
10446 char *nl;
10447 size_t len;
10449 len = strlen(logmsg);
10450 if (len > limit)
10451 len = limit;
10452 logmsg[len] = '\0';
10453 nl = strchr(logmsg, '\n');
10454 if (nl)
10455 *nl = '\0';
10458 static const struct got_error *
10459 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10461 const struct got_error *err;
10462 char *logmsg0 = NULL;
10463 const char *s;
10465 err = got_object_commit_get_logmsg(&logmsg0, commit);
10466 if (err)
10467 return err;
10469 s = logmsg0;
10470 while (isspace((unsigned char)s[0]))
10471 s++;
10473 *logmsg = strdup(s);
10474 if (*logmsg == NULL) {
10475 err = got_error_from_errno("strdup");
10476 goto done;
10479 trim_logmsg(*logmsg, limit);
10480 done:
10481 free(logmsg0);
10482 return err;
10485 static const struct got_error *
10486 show_rebase_merge_conflict(struct got_object_id *id,
10487 struct got_repository *repo)
10489 const struct got_error *err;
10490 struct got_commit_object *commit = NULL;
10491 char *id_str = NULL, *logmsg = NULL;
10493 err = got_object_open_as_commit(&commit, repo, id);
10494 if (err)
10495 return err;
10497 err = got_object_id_str(&id_str, id);
10498 if (err)
10499 goto done;
10501 id_str[12] = '\0';
10503 err = get_short_logmsg(&logmsg, 42, commit);
10504 if (err)
10505 goto done;
10507 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10508 done:
10509 free(id_str);
10510 got_object_commit_close(commit);
10511 free(logmsg);
10512 return err;
10515 static const struct got_error *
10516 show_rebase_progress(struct got_commit_object *commit,
10517 struct got_object_id *old_id, struct got_object_id *new_id)
10519 const struct got_error *err;
10520 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10522 err = got_object_id_str(&old_id_str, old_id);
10523 if (err)
10524 goto done;
10526 if (new_id) {
10527 err = got_object_id_str(&new_id_str, new_id);
10528 if (err)
10529 goto done;
10532 old_id_str[12] = '\0';
10533 if (new_id_str)
10534 new_id_str[12] = '\0';
10536 err = get_short_logmsg(&logmsg, 42, commit);
10537 if (err)
10538 goto done;
10540 printf("%s -> %s: %s\n", old_id_str,
10541 new_id_str ? new_id_str : "no-op change", logmsg);
10542 done:
10543 free(old_id_str);
10544 free(new_id_str);
10545 free(logmsg);
10546 return err;
10549 static const struct got_error *
10550 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10551 struct got_reference *branch, struct got_reference *tmp_branch,
10552 struct got_repository *repo, int create_backup)
10554 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10555 return got_worktree_rebase_complete(worktree, fileindex,
10556 tmp_branch, branch, repo, create_backup);
10559 static const struct got_error *
10560 rebase_commit(struct got_pathlist_head *merged_paths,
10561 struct got_worktree *worktree, struct got_fileindex *fileindex,
10562 struct got_reference *tmp_branch, const char *committer,
10563 struct got_object_id *commit_id, int allow_conflict,
10564 struct got_repository *repo)
10566 const struct got_error *error;
10567 struct got_commit_object *commit;
10568 struct got_object_id *new_commit_id;
10570 error = got_object_open_as_commit(&commit, repo, commit_id);
10571 if (error)
10572 return error;
10574 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10575 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10576 allow_conflict, repo);
10577 if (error) {
10578 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10579 goto done;
10580 error = show_rebase_progress(commit, commit_id, NULL);
10581 } else {
10582 error = show_rebase_progress(commit, commit_id, new_commit_id);
10583 free(new_commit_id);
10585 done:
10586 got_object_commit_close(commit);
10587 return error;
10590 struct check_path_prefix_arg {
10591 const char *path_prefix;
10592 size_t len;
10593 int errcode;
10596 static const struct got_error *
10597 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10598 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10599 struct got_object_id *id1, struct got_object_id *id2,
10600 const char *path1, const char *path2,
10601 mode_t mode1, mode_t mode2, struct got_repository *repo)
10603 struct check_path_prefix_arg *a = arg;
10605 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10606 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10607 return got_error(a->errcode);
10609 return NULL;
10612 static const struct got_error *
10613 check_path_prefix(struct got_object_id *parent_id,
10614 struct got_object_id *commit_id, const char *path_prefix,
10615 int errcode, struct got_repository *repo)
10617 const struct got_error *err;
10618 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10619 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10620 struct check_path_prefix_arg cpp_arg;
10622 if (got_path_is_root_dir(path_prefix))
10623 return NULL;
10625 err = got_object_open_as_commit(&commit, repo, commit_id);
10626 if (err)
10627 goto done;
10629 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10630 if (err)
10631 goto done;
10633 err = got_object_open_as_tree(&tree1, repo,
10634 got_object_commit_get_tree_id(parent_commit));
10635 if (err)
10636 goto done;
10638 err = got_object_open_as_tree(&tree2, repo,
10639 got_object_commit_get_tree_id(commit));
10640 if (err)
10641 goto done;
10643 cpp_arg.path_prefix = path_prefix;
10644 while (cpp_arg.path_prefix[0] == '/')
10645 cpp_arg.path_prefix++;
10646 cpp_arg.len = strlen(cpp_arg.path_prefix);
10647 cpp_arg.errcode = errcode;
10648 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10649 check_path_prefix_in_diff, &cpp_arg, 0);
10650 done:
10651 if (tree1)
10652 got_object_tree_close(tree1);
10653 if (tree2)
10654 got_object_tree_close(tree2);
10655 if (commit)
10656 got_object_commit_close(commit);
10657 if (parent_commit)
10658 got_object_commit_close(parent_commit);
10659 return err;
10662 static const struct got_error *
10663 collect_commits(struct got_object_id_queue *commits,
10664 struct got_object_id *initial_commit_id,
10665 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10666 const char *path_prefix, int path_prefix_errcode,
10667 struct got_repository *repo)
10669 const struct got_error *err = NULL;
10670 struct got_commit_graph *graph = NULL;
10671 struct got_object_id parent_id, commit_id;
10672 struct got_object_qid *qid;
10674 err = got_commit_graph_open(&graph, "/", 1);
10675 if (err)
10676 return err;
10678 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10679 check_cancelled, NULL);
10680 if (err)
10681 goto done;
10683 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10684 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10685 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10686 check_cancelled, NULL);
10687 if (err) {
10688 if (err->code == GOT_ERR_ITER_COMPLETED) {
10689 err = got_error_msg(GOT_ERR_ANCESTRY,
10690 "ran out of commits to rebase before "
10691 "youngest common ancestor commit has "
10692 "been reached?!?");
10694 goto done;
10695 } else {
10696 err = check_path_prefix(&parent_id, &commit_id,
10697 path_prefix, path_prefix_errcode, repo);
10698 if (err)
10699 goto done;
10701 err = got_object_qid_alloc(&qid, &commit_id);
10702 if (err)
10703 goto done;
10704 STAILQ_INSERT_HEAD(commits, qid, entry);
10706 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10709 done:
10710 got_commit_graph_close(graph);
10711 return err;
10714 static const struct got_error *
10715 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10717 const struct got_error *err = NULL;
10718 time_t committer_time;
10719 struct tm tm;
10720 char datebuf[11]; /* YYYY-MM-DD + NUL */
10721 char *author0 = NULL, *author, *smallerthan;
10722 char *logmsg0 = NULL, *logmsg, *newline;
10724 committer_time = got_object_commit_get_committer_time(commit);
10725 if (gmtime_r(&committer_time, &tm) == NULL)
10726 return got_error_from_errno("gmtime_r");
10727 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10728 return got_error(GOT_ERR_NO_SPACE);
10730 author0 = strdup(got_object_commit_get_author(commit));
10731 if (author0 == NULL)
10732 return got_error_from_errno("strdup");
10733 author = author0;
10734 smallerthan = strchr(author, '<');
10735 if (smallerthan && smallerthan[1] != '\0')
10736 author = smallerthan + 1;
10737 author[strcspn(author, "@>")] = '\0';
10739 err = got_object_commit_get_logmsg(&logmsg0, commit);
10740 if (err)
10741 goto done;
10742 logmsg = logmsg0;
10743 while (*logmsg == '\n')
10744 logmsg++;
10745 newline = strchr(logmsg, '\n');
10746 if (newline)
10747 *newline = '\0';
10749 if (asprintf(brief_str, "%s %s %s",
10750 datebuf, author, logmsg) == -1)
10751 err = got_error_from_errno("asprintf");
10752 done:
10753 free(author0);
10754 free(logmsg0);
10755 return err;
10758 static const struct got_error *
10759 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10760 struct got_repository *repo)
10762 const struct got_error *err;
10763 char *id_str;
10765 err = got_object_id_str(&id_str, id);
10766 if (err)
10767 return err;
10769 err = got_ref_delete(ref, repo);
10770 if (err)
10771 goto done;
10773 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10774 done:
10775 free(id_str);
10776 return err;
10779 static const struct got_error *
10780 print_backup_ref(const char *branch_name, const char *new_id_str,
10781 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10782 struct got_reflist_object_id_map *refs_idmap,
10783 struct got_repository *repo)
10785 const struct got_error *err = NULL;
10786 struct got_reflist_head *refs;
10787 char *refs_str = NULL;
10788 struct got_object_id *new_commit_id = NULL;
10789 struct got_commit_object *new_commit = NULL;
10790 char *new_commit_brief_str = NULL;
10791 struct got_object_id *yca_id = NULL;
10792 struct got_commit_object *yca_commit = NULL;
10793 char *yca_id_str = NULL, *yca_brief_str = NULL;
10794 char *custom_refs_str;
10796 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10797 return got_error_from_errno("asprintf");
10799 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10800 0, 0, refs_idmap, custom_refs_str, NULL);
10801 if (err)
10802 goto done;
10804 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10805 if (err)
10806 goto done;
10808 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10809 if (refs) {
10810 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10811 if (err)
10812 goto done;
10815 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10816 if (err)
10817 goto done;
10819 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10820 if (err)
10821 goto done;
10823 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10824 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10825 if (err)
10826 goto done;
10828 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10829 refs_str ? " (" : "", refs_str ? refs_str : "",
10830 refs_str ? ")" : "", new_commit_brief_str);
10831 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10832 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10833 free(refs_str);
10834 refs_str = NULL;
10836 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10837 if (err)
10838 goto done;
10840 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10841 if (err)
10842 goto done;
10844 err = got_object_id_str(&yca_id_str, yca_id);
10845 if (err)
10846 goto done;
10848 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10849 if (refs) {
10850 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10851 if (err)
10852 goto done;
10854 printf("history forked at %s%s%s%s\n %s\n",
10855 yca_id_str,
10856 refs_str ? " (" : "", refs_str ? refs_str : "",
10857 refs_str ? ")" : "", yca_brief_str);
10859 done:
10860 free(custom_refs_str);
10861 free(new_commit_id);
10862 free(refs_str);
10863 free(yca_id);
10864 free(yca_id_str);
10865 free(yca_brief_str);
10866 if (new_commit)
10867 got_object_commit_close(new_commit);
10868 if (yca_commit)
10869 got_object_commit_close(yca_commit);
10871 return err;
10874 static const struct got_error *
10875 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10876 struct got_repository *repo)
10878 const struct got_error *err;
10879 struct got_reflist_head refs;
10880 struct got_reflist_entry *re;
10881 char *uuidstr = NULL;
10882 static char msg[160];
10884 TAILQ_INIT(&refs);
10886 err = got_worktree_get_uuid(&uuidstr, worktree);
10887 if (err)
10888 goto done;
10890 err = got_ref_list(&refs, repo, "refs/got/worktree",
10891 got_ref_cmp_by_name, repo);
10892 if (err)
10893 goto done;
10895 TAILQ_FOREACH(re, &refs, entry) {
10896 const char *cmd, *refname, *type;
10898 refname = got_ref_get_name(re->ref);
10900 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10901 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10902 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10903 cmd = "cherrypick";
10904 type = "cherrypicked";
10905 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10906 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10907 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10908 cmd = "backout";
10909 type = "backed-out";
10910 } else
10911 continue;
10913 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10914 continue;
10916 snprintf(msg, sizeof(msg),
10917 "work tree has references created by %s commits which "
10918 "must be removed with 'got %s -X' before running the %s "
10919 "command", type, cmd, caller);
10920 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10921 goto done;
10924 done:
10925 free(uuidstr);
10926 got_ref_list_free(&refs);
10927 return err;
10930 static const struct got_error *
10931 process_backup_refs(const char *backup_ref_prefix,
10932 const char *wanted_branch_name,
10933 int delete, struct got_repository *repo)
10935 const struct got_error *err;
10936 struct got_reflist_head refs, backup_refs;
10937 struct got_reflist_entry *re;
10938 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10939 struct got_object_id *old_commit_id = NULL;
10940 char *branch_name = NULL;
10941 struct got_commit_object *old_commit = NULL;
10942 struct got_reflist_object_id_map *refs_idmap = NULL;
10943 int wanted_branch_found = 0;
10945 TAILQ_INIT(&refs);
10946 TAILQ_INIT(&backup_refs);
10948 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10949 if (err)
10950 return err;
10952 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10953 if (err)
10954 goto done;
10956 if (wanted_branch_name) {
10957 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10958 wanted_branch_name += 11;
10961 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10962 got_ref_cmp_by_commit_timestamp_descending, repo);
10963 if (err)
10964 goto done;
10966 TAILQ_FOREACH(re, &backup_refs, entry) {
10967 const char *refname = got_ref_get_name(re->ref);
10968 char *slash;
10970 err = check_cancelled(NULL);
10971 if (err)
10972 break;
10974 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10975 if (err)
10976 break;
10978 err = got_object_open_as_commit(&old_commit, repo,
10979 old_commit_id);
10980 if (err)
10981 break;
10983 if (strncmp(backup_ref_prefix, refname,
10984 backup_ref_prefix_len) == 0)
10985 refname += backup_ref_prefix_len;
10987 while (refname[0] == '/')
10988 refname++;
10990 branch_name = strdup(refname);
10991 if (branch_name == NULL) {
10992 err = got_error_from_errno("strdup");
10993 break;
10995 slash = strrchr(branch_name, '/');
10996 if (slash) {
10997 *slash = '\0';
10998 refname += strlen(branch_name) + 1;
11001 if (wanted_branch_name == NULL ||
11002 strcmp(wanted_branch_name, branch_name) == 0) {
11003 wanted_branch_found = 1;
11004 if (delete) {
11005 err = delete_backup_ref(re->ref,
11006 old_commit_id, repo);
11007 } else {
11008 err = print_backup_ref(branch_name, refname,
11009 old_commit_id, old_commit, refs_idmap,
11010 repo);
11012 if (err)
11013 break;
11016 free(old_commit_id);
11017 old_commit_id = NULL;
11018 free(branch_name);
11019 branch_name = NULL;
11020 got_object_commit_close(old_commit);
11021 old_commit = NULL;
11024 if (wanted_branch_name && !wanted_branch_found) {
11025 err = got_error_fmt(GOT_ERR_NOT_REF,
11026 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11028 done:
11029 if (refs_idmap)
11030 got_reflist_object_id_map_free(refs_idmap);
11031 got_ref_list_free(&refs);
11032 got_ref_list_free(&backup_refs);
11033 free(old_commit_id);
11034 free(branch_name);
11035 if (old_commit)
11036 got_object_commit_close(old_commit);
11037 return err;
11040 static const struct got_error *
11041 abort_progress(void *arg, unsigned char status, const char *path)
11044 * Unversioned files should not clutter progress output when
11045 * an operation is aborted.
11047 if (status == GOT_STATUS_UNVERSIONED)
11048 return NULL;
11050 return update_progress(arg, status, path);
11053 static const struct got_error *
11054 cmd_rebase(int argc, char *argv[])
11056 const struct got_error *error = NULL;
11057 struct got_worktree *worktree = NULL;
11058 struct got_repository *repo = NULL;
11059 struct got_fileindex *fileindex = NULL;
11060 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11061 struct got_reference *branch = NULL;
11062 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11063 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11064 struct got_object_id *resume_commit_id = NULL;
11065 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11066 struct got_object_id *head_commit_id = NULL;
11067 struct got_reference *head_ref = NULL;
11068 struct got_commit_object *commit = NULL;
11069 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11070 int histedit_in_progress = 0, merge_in_progress = 0;
11071 int create_backup = 1, list_backups = 0, delete_backups = 0;
11072 int allow_conflict = 0;
11073 struct got_object_id_queue commits;
11074 struct got_pathlist_head merged_paths;
11075 const struct got_object_id_queue *parent_ids;
11076 struct got_object_qid *qid, *pid;
11077 struct got_update_progress_arg upa;
11078 int *pack_fds = NULL;
11080 STAILQ_INIT(&commits);
11081 TAILQ_INIT(&merged_paths);
11082 memset(&upa, 0, sizeof(upa));
11084 #ifndef PROFILE
11085 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11086 "unveil", NULL) == -1)
11087 err(1, "pledge");
11088 #endif
11090 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11091 switch (ch) {
11092 case 'a':
11093 abort_rebase = 1;
11094 break;
11095 case 'C':
11096 allow_conflict = 1;
11097 break;
11098 case 'c':
11099 continue_rebase = 1;
11100 break;
11101 case 'l':
11102 list_backups = 1;
11103 break;
11104 case 'X':
11105 delete_backups = 1;
11106 break;
11107 default:
11108 usage_rebase();
11109 /* NOTREACHED */
11113 argc -= optind;
11114 argv += optind;
11116 if (list_backups) {
11117 if (abort_rebase)
11118 option_conflict('l', 'a');
11119 if (allow_conflict)
11120 option_conflict('l', 'C');
11121 if (continue_rebase)
11122 option_conflict('l', 'c');
11123 if (delete_backups)
11124 option_conflict('l', 'X');
11125 if (argc != 0 && argc != 1)
11126 usage_rebase();
11127 } else if (delete_backups) {
11128 if (abort_rebase)
11129 option_conflict('X', 'a');
11130 if (allow_conflict)
11131 option_conflict('X', 'C');
11132 if (continue_rebase)
11133 option_conflict('X', 'c');
11134 if (list_backups)
11135 option_conflict('l', 'X');
11136 if (argc != 0 && argc != 1)
11137 usage_rebase();
11138 } else if (allow_conflict) {
11139 if (abort_rebase)
11140 option_conflict('C', 'a');
11141 if (!continue_rebase)
11142 errx(1, "-C option requires -c");
11143 } else {
11144 if (abort_rebase && continue_rebase)
11145 usage_rebase();
11146 else if (abort_rebase || continue_rebase) {
11147 if (argc != 0)
11148 usage_rebase();
11149 } else if (argc != 1)
11150 usage_rebase();
11153 cwd = getcwd(NULL, 0);
11154 if (cwd == NULL) {
11155 error = got_error_from_errno("getcwd");
11156 goto done;
11159 error = got_repo_pack_fds_open(&pack_fds);
11160 if (error != NULL)
11161 goto done;
11163 error = got_worktree_open(&worktree, cwd);
11164 if (error) {
11165 if (list_backups || delete_backups) {
11166 if (error->code != GOT_ERR_NOT_WORKTREE)
11167 goto done;
11168 } else {
11169 if (error->code == GOT_ERR_NOT_WORKTREE)
11170 error = wrap_not_worktree_error(error,
11171 "rebase", cwd);
11172 goto done;
11176 error = get_gitconfig_path(&gitconfig_path);
11177 if (error)
11178 goto done;
11179 error = got_repo_open(&repo,
11180 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11181 gitconfig_path, pack_fds);
11182 if (error != NULL)
11183 goto done;
11185 if (worktree != NULL && !list_backups && !delete_backups) {
11186 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11187 if (error)
11188 goto done;
11191 error = get_author(&committer, repo, worktree);
11192 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11193 goto done;
11195 error = apply_unveil(got_repo_get_path(repo), 0,
11196 worktree ? got_worktree_get_root_path(worktree) : NULL);
11197 if (error)
11198 goto done;
11200 if (list_backups || delete_backups) {
11201 error = process_backup_refs(
11202 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11203 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11204 goto done; /* nothing else to do */
11207 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11208 worktree);
11209 if (error)
11210 goto done;
11211 if (histedit_in_progress) {
11212 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11213 goto done;
11216 error = got_worktree_merge_in_progress(&merge_in_progress,
11217 worktree, repo);
11218 if (error)
11219 goto done;
11220 if (merge_in_progress) {
11221 error = got_error(GOT_ERR_MERGE_BUSY);
11222 goto done;
11225 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11226 if (error)
11227 goto done;
11229 if (abort_rebase) {
11230 if (!rebase_in_progress) {
11231 error = got_error(GOT_ERR_NOT_REBASING);
11232 goto done;
11234 error = got_worktree_rebase_continue(&resume_commit_id,
11235 &new_base_branch, &tmp_branch, &branch, &fileindex,
11236 worktree, repo);
11237 if (error)
11238 goto done;
11239 printf("Switching work tree to %s\n",
11240 got_ref_get_symref_target(new_base_branch));
11241 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11242 new_base_branch, abort_progress, &upa);
11243 if (error)
11244 goto done;
11245 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11246 print_merge_progress_stats(&upa);
11247 goto done; /* nothing else to do */
11250 if (continue_rebase) {
11251 if (!rebase_in_progress) {
11252 error = got_error(GOT_ERR_NOT_REBASING);
11253 goto done;
11255 error = got_worktree_rebase_continue(&resume_commit_id,
11256 &new_base_branch, &tmp_branch, &branch, &fileindex,
11257 worktree, repo);
11258 if (error)
11259 goto done;
11261 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11262 committer, resume_commit_id, allow_conflict, repo);
11263 if (error)
11264 goto done;
11266 yca_id = got_object_id_dup(resume_commit_id);
11267 if (yca_id == NULL) {
11268 error = got_error_from_errno("got_object_id_dup");
11269 goto done;
11271 } else {
11272 error = got_ref_open(&branch, repo, argv[0], 0);
11273 if (error != NULL)
11274 goto done;
11275 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11276 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11277 "will not rebase a branch which lives outside "
11278 "the \"refs/heads/\" reference namespace");
11279 goto done;
11283 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11284 if (error)
11285 goto done;
11287 if (!continue_rebase) {
11288 struct got_object_id *base_commit_id;
11290 error = got_ref_open(&head_ref, repo,
11291 got_worktree_get_head_ref_name(worktree), 0);
11292 if (error)
11293 goto done;
11294 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11295 if (error)
11296 goto done;
11297 base_commit_id = got_worktree_get_base_commit_id(worktree);
11298 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11299 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11300 goto done;
11303 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11304 base_commit_id, branch_head_commit_id, 1, repo,
11305 check_cancelled, NULL);
11306 if (error) {
11307 if (error->code == GOT_ERR_ANCESTRY) {
11308 error = got_error_msg(GOT_ERR_ANCESTRY,
11309 "specified branch shares no common "
11310 "ancestry with work tree's branch");
11312 goto done;
11315 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11316 struct got_pathlist_head paths;
11317 printf("%s is already based on %s\n",
11318 got_ref_get_name(branch),
11319 got_worktree_get_head_ref_name(worktree));
11320 error = switch_head_ref(branch, branch_head_commit_id,
11321 worktree, repo);
11322 if (error)
11323 goto done;
11324 error = got_worktree_set_base_commit_id(worktree, repo,
11325 branch_head_commit_id);
11326 if (error)
11327 goto done;
11328 TAILQ_INIT(&paths);
11329 error = got_pathlist_append(&paths, "", NULL);
11330 if (error)
11331 goto done;
11332 error = got_worktree_checkout_files(worktree,
11333 &paths, repo, update_progress, &upa,
11334 check_cancelled, NULL);
11335 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11336 if (error)
11337 goto done;
11338 if (upa.did_something) {
11339 char *id_str;
11340 error = got_object_id_str(&id_str,
11341 branch_head_commit_id);
11342 if (error)
11343 goto done;
11344 printf("Updated to %s: %s\n",
11345 got_worktree_get_head_ref_name(worktree),
11346 id_str);
11347 free(id_str);
11348 } else
11349 printf("Already up-to-date\n");
11350 print_update_progress_stats(&upa);
11351 goto done;
11355 commit_id = branch_head_commit_id;
11356 error = got_object_open_as_commit(&commit, repo, commit_id);
11357 if (error)
11358 goto done;
11360 parent_ids = got_object_commit_get_parent_ids(commit);
11361 pid = STAILQ_FIRST(parent_ids);
11362 if (pid) {
11363 error = collect_commits(&commits, commit_id, &pid->id,
11364 yca_id, got_worktree_get_path_prefix(worktree),
11365 GOT_ERR_REBASE_PATH, repo);
11366 if (error)
11367 goto done;
11370 got_object_commit_close(commit);
11371 commit = NULL;
11373 if (!continue_rebase) {
11374 error = got_worktree_rebase_prepare(&new_base_branch,
11375 &tmp_branch, &fileindex, worktree, branch, repo);
11376 if (error)
11377 goto done;
11380 if (STAILQ_EMPTY(&commits)) {
11381 if (continue_rebase) {
11382 error = rebase_complete(worktree, fileindex,
11383 branch, tmp_branch, repo, create_backup);
11384 goto done;
11385 } else {
11386 /* Fast-forward the reference of the branch. */
11387 struct got_object_id *new_head_commit_id;
11388 char *id_str;
11389 error = got_ref_resolve(&new_head_commit_id, repo,
11390 new_base_branch);
11391 if (error)
11392 goto done;
11393 error = got_object_id_str(&id_str, new_head_commit_id);
11394 if (error)
11395 goto done;
11396 printf("Forwarding %s to commit %s\n",
11397 got_ref_get_name(branch), id_str);
11398 free(id_str);
11399 error = got_ref_change_ref(branch,
11400 new_head_commit_id);
11401 if (error)
11402 goto done;
11403 /* No backup needed since objects did not change. */
11404 create_backup = 0;
11408 pid = NULL;
11409 STAILQ_FOREACH(qid, &commits, entry) {
11411 commit_id = &qid->id;
11412 parent_id = pid ? &pid->id : yca_id;
11413 pid = qid;
11415 memset(&upa, 0, sizeof(upa));
11416 error = got_worktree_rebase_merge_files(&merged_paths,
11417 worktree, fileindex, parent_id, commit_id, repo,
11418 update_progress, &upa, check_cancelled, NULL);
11419 if (error)
11420 goto done;
11422 print_merge_progress_stats(&upa);
11423 if (upa.conflicts > 0 || upa.missing > 0 ||
11424 upa.not_deleted > 0 || upa.unversioned > 0) {
11425 if (upa.conflicts > 0) {
11426 error = show_rebase_merge_conflict(&qid->id,
11427 repo);
11428 if (error)
11429 goto done;
11431 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11432 break;
11435 error = rebase_commit(&merged_paths, worktree, fileindex,
11436 tmp_branch, committer, commit_id, 0, repo);
11437 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11438 if (error)
11439 goto done;
11442 if (upa.conflicts > 0 || upa.missing > 0 ||
11443 upa.not_deleted > 0 || upa.unversioned > 0) {
11444 error = got_worktree_rebase_postpone(worktree, fileindex);
11445 if (error)
11446 goto done;
11447 if (upa.conflicts > 0 && upa.missing == 0 &&
11448 upa.not_deleted == 0 && upa.unversioned == 0) {
11449 error = got_error_msg(GOT_ERR_CONFLICTS,
11450 "conflicts must be resolved before rebasing "
11451 "can continue");
11452 } else if (upa.conflicts > 0) {
11453 error = got_error_msg(GOT_ERR_CONFLICTS,
11454 "conflicts must be resolved before rebasing "
11455 "can continue; changes destined for some "
11456 "files were not yet merged and should be "
11457 "merged manually if required before the "
11458 "rebase operation is continued");
11459 } else {
11460 error = got_error_msg(GOT_ERR_CONFLICTS,
11461 "changes destined for some files were not "
11462 "yet merged and should be merged manually "
11463 "if required before the rebase operation "
11464 "is continued");
11466 } else
11467 error = rebase_complete(worktree, fileindex, branch,
11468 tmp_branch, repo, create_backup);
11469 done:
11470 free(cwd);
11471 free(committer);
11472 free(gitconfig_path);
11473 got_object_id_queue_free(&commits);
11474 free(branch_head_commit_id);
11475 free(resume_commit_id);
11476 free(head_commit_id);
11477 free(yca_id);
11478 if (commit)
11479 got_object_commit_close(commit);
11480 if (branch)
11481 got_ref_close(branch);
11482 if (new_base_branch)
11483 got_ref_close(new_base_branch);
11484 if (tmp_branch)
11485 got_ref_close(tmp_branch);
11486 if (head_ref)
11487 got_ref_close(head_ref);
11488 if (worktree)
11489 got_worktree_close(worktree);
11490 if (repo) {
11491 const struct got_error *close_err = got_repo_close(repo);
11492 if (error == NULL)
11493 error = close_err;
11495 if (pack_fds) {
11496 const struct got_error *pack_err =
11497 got_repo_pack_fds_close(pack_fds);
11498 if (error == NULL)
11499 error = pack_err;
11501 return error;
11504 __dead static void
11505 usage_histedit(void)
11507 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11508 "[branch]\n", getprogname());
11509 exit(1);
11512 #define GOT_HISTEDIT_PICK 'p'
11513 #define GOT_HISTEDIT_EDIT 'e'
11514 #define GOT_HISTEDIT_FOLD 'f'
11515 #define GOT_HISTEDIT_DROP 'd'
11516 #define GOT_HISTEDIT_MESG 'm'
11518 static const struct got_histedit_cmd {
11519 unsigned char code;
11520 const char *name;
11521 const char *desc;
11522 } got_histedit_cmds[] = {
11523 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11524 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11525 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11526 "be used" },
11527 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11528 { GOT_HISTEDIT_MESG, "mesg",
11529 "single-line log message for commit above (open editor if empty)" },
11532 struct got_histedit_list_entry {
11533 TAILQ_ENTRY(got_histedit_list_entry) entry;
11534 struct got_object_id *commit_id;
11535 const struct got_histedit_cmd *cmd;
11536 char *logmsg;
11538 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11540 static const struct got_error *
11541 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11542 FILE *f, struct got_repository *repo)
11544 const struct got_error *err = NULL;
11545 char *logmsg = NULL, *id_str = NULL;
11546 struct got_commit_object *commit = NULL;
11547 int n;
11549 err = got_object_open_as_commit(&commit, repo, commit_id);
11550 if (err)
11551 goto done;
11553 err = get_short_logmsg(&logmsg, 34, commit);
11554 if (err)
11555 goto done;
11557 err = got_object_id_str(&id_str, commit_id);
11558 if (err)
11559 goto done;
11561 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11562 if (n < 0)
11563 err = got_ferror(f, GOT_ERR_IO);
11564 done:
11565 if (commit)
11566 got_object_commit_close(commit);
11567 free(id_str);
11568 free(logmsg);
11569 return err;
11572 static const struct got_error *
11573 histedit_write_commit_list(struct got_object_id_queue *commits,
11574 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11575 int edit_only, struct got_repository *repo)
11577 const struct got_error *err = NULL;
11578 struct got_object_qid *qid;
11579 const char *histedit_cmd = NULL;
11581 if (STAILQ_EMPTY(commits))
11582 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11584 STAILQ_FOREACH(qid, commits, entry) {
11585 histedit_cmd = got_histedit_cmds[0].name;
11586 if (drop_only)
11587 histedit_cmd = "drop";
11588 else if (edit_only)
11589 histedit_cmd = "edit";
11590 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11591 histedit_cmd = "fold";
11592 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11593 if (err)
11594 break;
11595 if (edit_logmsg_only) {
11596 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11597 if (n < 0) {
11598 err = got_ferror(f, GOT_ERR_IO);
11599 break;
11604 return err;
11607 static const struct got_error *
11608 write_cmd_list(FILE *f, const char *branch_name,
11609 struct got_object_id_queue *commits)
11611 const struct got_error *err = NULL;
11612 size_t i;
11613 int n;
11614 char *id_str;
11615 struct got_object_qid *qid;
11617 qid = STAILQ_FIRST(commits);
11618 err = got_object_id_str(&id_str, &qid->id);
11619 if (err)
11620 return err;
11622 n = fprintf(f,
11623 "# Editing the history of branch '%s' starting at\n"
11624 "# commit %s\n"
11625 "# Commits will be processed in order from top to "
11626 "bottom of this file.\n", branch_name, id_str);
11627 if (n < 0) {
11628 err = got_ferror(f, GOT_ERR_IO);
11629 goto done;
11632 n = fprintf(f, "# Available histedit commands:\n");
11633 if (n < 0) {
11634 err = got_ferror(f, GOT_ERR_IO);
11635 goto done;
11638 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11639 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11640 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11641 cmd->desc);
11642 if (n < 0) {
11643 err = got_ferror(f, GOT_ERR_IO);
11644 break;
11647 done:
11648 free(id_str);
11649 return err;
11652 static const struct got_error *
11653 histedit_syntax_error(int lineno)
11655 static char msg[42];
11656 int ret;
11658 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11659 lineno);
11660 if (ret < 0 || (size_t)ret >= sizeof(msg))
11661 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11663 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11666 static const struct got_error *
11667 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11668 char *logmsg, struct got_repository *repo)
11670 const struct got_error *err;
11671 struct got_commit_object *folded_commit = NULL;
11672 char *id_str, *folded_logmsg = NULL;
11674 err = got_object_id_str(&id_str, hle->commit_id);
11675 if (err)
11676 return err;
11678 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11679 if (err)
11680 goto done;
11682 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11683 if (err)
11684 goto done;
11685 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11686 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11687 folded_logmsg) == -1) {
11688 err = got_error_from_errno("asprintf");
11690 done:
11691 if (folded_commit)
11692 got_object_commit_close(folded_commit);
11693 free(id_str);
11694 free(folded_logmsg);
11695 return err;
11698 static struct got_histedit_list_entry *
11699 get_folded_commits(struct got_histedit_list_entry *hle)
11701 struct got_histedit_list_entry *prev, *folded = NULL;
11703 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11704 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11705 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11706 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11707 folded = prev;
11708 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11711 return folded;
11714 static const struct got_error *
11715 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11716 struct got_repository *repo)
11718 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11719 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11720 const struct got_error *err = NULL;
11721 struct got_commit_object *commit = NULL;
11722 int logmsg_len;
11723 int fd = -1;
11724 struct got_histedit_list_entry *folded = NULL;
11726 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11727 if (err)
11728 return err;
11730 folded = get_folded_commits(hle);
11731 if (folded) {
11732 while (folded != hle) {
11733 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11734 folded = TAILQ_NEXT(folded, entry);
11735 continue;
11737 err = append_folded_commit_msg(&new_msg, folded,
11738 logmsg, repo);
11739 if (err)
11740 goto done;
11741 free(logmsg);
11742 logmsg = new_msg;
11743 folded = TAILQ_NEXT(folded, entry);
11747 err = got_object_id_str(&id_str, hle->commit_id);
11748 if (err)
11749 goto done;
11750 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11751 if (err)
11752 goto done;
11753 logmsg_len = asprintf(&new_msg,
11754 "%s\n# original log message of commit %s: %s",
11755 logmsg ? logmsg : "", id_str, orig_logmsg);
11756 if (logmsg_len == -1) {
11757 err = got_error_from_errno("asprintf");
11758 goto done;
11760 free(logmsg);
11761 logmsg = new_msg;
11763 err = got_object_id_str(&id_str, hle->commit_id);
11764 if (err)
11765 goto done;
11767 err = got_opentemp_named_fd(&logmsg_path, &fd,
11768 GOT_TMPDIR_STR "/got-logmsg", "");
11769 if (err)
11770 goto done;
11772 if (write(fd, logmsg, logmsg_len) == -1) {
11773 err = got_error_from_errno2("write", logmsg_path);
11774 goto done;
11776 if (close(fd) == -1) {
11777 err = got_error_from_errno2("close", logmsg_path);
11778 goto done;
11780 fd = -1;
11782 err = get_editor(&editor);
11783 if (err)
11784 goto done;
11786 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11787 logmsg_len, 0);
11788 if (err) {
11789 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11790 goto done;
11791 err = NULL;
11792 hle->logmsg = strdup(new_msg);
11793 if (hle->logmsg == NULL)
11794 err = got_error_from_errno("strdup");
11796 done:
11797 if (fd != -1 && close(fd) == -1 && err == NULL)
11798 err = got_error_from_errno2("close", logmsg_path);
11799 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11800 err = got_error_from_errno2("unlink", logmsg_path);
11801 free(logmsg_path);
11802 free(logmsg);
11803 free(orig_logmsg);
11804 free(editor);
11805 if (commit)
11806 got_object_commit_close(commit);
11807 return err;
11810 static const struct got_error *
11811 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11812 FILE *f, struct got_repository *repo)
11814 const struct got_error *err = NULL;
11815 char *line = NULL, *p, *end;
11816 size_t i, linesize = 0;
11817 ssize_t linelen;
11818 int lineno = 0, lastcmd = -1;
11819 const struct got_histedit_cmd *cmd;
11820 struct got_object_id *commit_id = NULL;
11821 struct got_histedit_list_entry *hle = NULL;
11823 for (;;) {
11824 linelen = getline(&line, &linesize, f);
11825 if (linelen == -1) {
11826 const struct got_error *getline_err;
11827 if (feof(f))
11828 break;
11829 getline_err = got_error_from_errno("getline");
11830 err = got_ferror(f, getline_err->code);
11831 break;
11833 lineno++;
11834 p = line;
11835 while (isspace((unsigned char)p[0]))
11836 p++;
11837 if (p[0] == '#' || p[0] == '\0')
11838 continue;
11839 cmd = NULL;
11840 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11841 cmd = &got_histedit_cmds[i];
11842 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11843 isspace((unsigned char)p[strlen(cmd->name)])) {
11844 p += strlen(cmd->name);
11845 break;
11847 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11848 p++;
11849 break;
11852 if (i == nitems(got_histedit_cmds)) {
11853 err = histedit_syntax_error(lineno);
11854 break;
11856 while (isspace((unsigned char)p[0]))
11857 p++;
11858 if (cmd->code == GOT_HISTEDIT_MESG) {
11859 if (lastcmd != GOT_HISTEDIT_PICK &&
11860 lastcmd != GOT_HISTEDIT_EDIT) {
11861 err = got_error(GOT_ERR_HISTEDIT_CMD);
11862 break;
11864 if (p[0] == '\0') {
11865 err = histedit_edit_logmsg(hle, repo);
11866 if (err)
11867 break;
11868 } else {
11869 hle->logmsg = strdup(p);
11870 if (hle->logmsg == NULL) {
11871 err = got_error_from_errno("strdup");
11872 break;
11875 lastcmd = cmd->code;
11876 continue;
11877 } else {
11878 end = p;
11879 while (end[0] && !isspace((unsigned char)end[0]))
11880 end++;
11881 *end = '\0';
11883 err = got_object_resolve_id_str(&commit_id, repo, p);
11884 if (err) {
11885 /* override error code */
11886 err = histedit_syntax_error(lineno);
11887 break;
11890 hle = malloc(sizeof(*hle));
11891 if (hle == NULL) {
11892 err = got_error_from_errno("malloc");
11893 break;
11895 hle->cmd = cmd;
11896 hle->commit_id = commit_id;
11897 hle->logmsg = NULL;
11898 commit_id = NULL;
11899 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11900 lastcmd = cmd->code;
11903 free(line);
11904 free(commit_id);
11905 return err;
11908 static const struct got_error *
11909 histedit_check_script(struct got_histedit_list *histedit_cmds,
11910 struct got_object_id_queue *commits, struct got_repository *repo)
11912 const struct got_error *err = NULL;
11913 struct got_object_qid *qid;
11914 struct got_histedit_list_entry *hle;
11915 static char msg[92];
11916 char *id_str;
11918 if (TAILQ_EMPTY(histedit_cmds))
11919 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11920 "histedit script contains no commands");
11921 if (STAILQ_EMPTY(commits))
11922 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11924 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11925 struct got_histedit_list_entry *hle2;
11926 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11927 if (hle == hle2)
11928 continue;
11929 if (got_object_id_cmp(hle->commit_id,
11930 hle2->commit_id) != 0)
11931 continue;
11932 err = got_object_id_str(&id_str, hle->commit_id);
11933 if (err)
11934 return err;
11935 snprintf(msg, sizeof(msg), "commit %s is listed "
11936 "more than once in histedit script", id_str);
11937 free(id_str);
11938 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11942 STAILQ_FOREACH(qid, commits, entry) {
11943 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11944 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11945 break;
11947 if (hle == NULL) {
11948 err = got_object_id_str(&id_str, &qid->id);
11949 if (err)
11950 return err;
11951 snprintf(msg, sizeof(msg),
11952 "commit %s missing from histedit script", id_str);
11953 free(id_str);
11954 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11958 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11959 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11960 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11961 "last commit in histedit script cannot be folded");
11963 return NULL;
11966 static const struct got_error *
11967 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11968 const char *path, struct got_object_id_queue *commits,
11969 struct got_repository *repo)
11971 const struct got_error *err = NULL;
11972 char *editor;
11973 FILE *f = NULL;
11975 err = get_editor(&editor);
11976 if (err)
11977 return err;
11979 if (spawn_editor(editor, path) == -1) {
11980 err = got_error_from_errno("failed spawning editor");
11981 goto done;
11984 f = fopen(path, "re");
11985 if (f == NULL) {
11986 err = got_error_from_errno("fopen");
11987 goto done;
11989 err = histedit_parse_list(histedit_cmds, f, repo);
11990 if (err)
11991 goto done;
11993 err = histedit_check_script(histedit_cmds, commits, repo);
11994 done:
11995 if (f && fclose(f) == EOF && err == NULL)
11996 err = got_error_from_errno("fclose");
11997 free(editor);
11998 return err;
12001 static const struct got_error *
12002 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12003 struct got_object_id_queue *, const char *, const char *,
12004 struct got_repository *);
12006 static const struct got_error *
12007 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12008 struct got_object_id_queue *commits, const char *branch_name,
12009 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12010 struct got_repository *repo)
12012 const struct got_error *err;
12013 FILE *f = NULL;
12014 char *path = NULL;
12016 err = got_opentemp_named(&path, &f, "got-histedit", "");
12017 if (err)
12018 return err;
12020 err = write_cmd_list(f, branch_name, commits);
12021 if (err)
12022 goto done;
12024 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12025 fold_only, drop_only, edit_only, repo);
12026 if (err)
12027 goto done;
12029 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12030 rewind(f);
12031 err = histedit_parse_list(histedit_cmds, f, repo);
12032 } else {
12033 if (fclose(f) == EOF) {
12034 err = got_error_from_errno("fclose");
12035 goto done;
12037 f = NULL;
12038 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12039 if (err) {
12040 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12041 err->code != GOT_ERR_HISTEDIT_CMD)
12042 goto done;
12043 err = histedit_edit_list_retry(histedit_cmds, err,
12044 commits, path, branch_name, repo);
12047 done:
12048 if (f && fclose(f) == EOF && err == NULL)
12049 err = got_error_from_errno("fclose");
12050 if (path && unlink(path) != 0 && err == NULL)
12051 err = got_error_from_errno2("unlink", path);
12052 free(path);
12053 return err;
12056 static const struct got_error *
12057 histedit_save_list(struct got_histedit_list *histedit_cmds,
12058 struct got_worktree *worktree, struct got_repository *repo)
12060 const struct got_error *err = NULL;
12061 char *path = NULL;
12062 FILE *f = NULL;
12063 struct got_histedit_list_entry *hle;
12064 struct got_commit_object *commit = NULL;
12066 err = got_worktree_get_histedit_script_path(&path, worktree);
12067 if (err)
12068 return err;
12070 f = fopen(path, "we");
12071 if (f == NULL) {
12072 err = got_error_from_errno2("fopen", path);
12073 goto done;
12075 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12076 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12077 repo);
12078 if (err)
12079 break;
12081 if (hle->logmsg) {
12082 int n = fprintf(f, "%c %s\n",
12083 GOT_HISTEDIT_MESG, hle->logmsg);
12084 if (n < 0) {
12085 err = got_ferror(f, GOT_ERR_IO);
12086 break;
12090 done:
12091 if (f && fclose(f) == EOF && err == NULL)
12092 err = got_error_from_errno("fclose");
12093 free(path);
12094 if (commit)
12095 got_object_commit_close(commit);
12096 return err;
12099 static void
12100 histedit_free_list(struct got_histedit_list *histedit_cmds)
12102 struct got_histedit_list_entry *hle;
12104 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12105 TAILQ_REMOVE(histedit_cmds, hle, entry);
12106 free(hle);
12110 static const struct got_error *
12111 histedit_load_list(struct got_histedit_list *histedit_cmds,
12112 const char *path, struct got_repository *repo)
12114 const struct got_error *err = NULL;
12115 FILE *f = NULL;
12117 f = fopen(path, "re");
12118 if (f == NULL) {
12119 err = got_error_from_errno2("fopen", path);
12120 goto done;
12123 err = histedit_parse_list(histedit_cmds, f, repo);
12124 done:
12125 if (f && fclose(f) == EOF && err == NULL)
12126 err = got_error_from_errno("fclose");
12127 return err;
12130 static const struct got_error *
12131 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12132 const struct got_error *edit_err, struct got_object_id_queue *commits,
12133 const char *path, const char *branch_name, struct got_repository *repo)
12135 const struct got_error *err = NULL, *prev_err = edit_err;
12136 int resp = ' ';
12138 while (resp != 'c' && resp != 'r' && resp != 'a') {
12139 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12140 "or (a)bort: ", getprogname(), prev_err->msg);
12141 resp = getchar();
12142 if (resp == '\n')
12143 resp = getchar();
12144 if (resp == 'c') {
12145 histedit_free_list(histedit_cmds);
12146 err = histedit_run_editor(histedit_cmds, path, commits,
12147 repo);
12148 if (err) {
12149 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12150 err->code != GOT_ERR_HISTEDIT_CMD)
12151 break;
12152 prev_err = err;
12153 resp = ' ';
12154 continue;
12156 break;
12157 } else if (resp == 'r') {
12158 histedit_free_list(histedit_cmds);
12159 err = histedit_edit_script(histedit_cmds,
12160 commits, branch_name, 0, 0, 0, 0, repo);
12161 if (err) {
12162 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12163 err->code != GOT_ERR_HISTEDIT_CMD)
12164 break;
12165 prev_err = err;
12166 resp = ' ';
12167 continue;
12169 break;
12170 } else if (resp == 'a') {
12171 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12172 break;
12173 } else
12174 printf("invalid response '%c'\n", resp);
12177 return err;
12180 static const struct got_error *
12181 histedit_complete(struct got_worktree *worktree,
12182 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12183 struct got_reference *branch, struct got_repository *repo)
12185 printf("Switching work tree to %s\n",
12186 got_ref_get_symref_target(branch));
12187 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12188 branch, repo);
12191 static const struct got_error *
12192 show_histedit_progress(struct got_commit_object *commit,
12193 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12195 const struct got_error *err;
12196 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12198 err = got_object_id_str(&old_id_str, hle->commit_id);
12199 if (err)
12200 goto done;
12202 if (new_id) {
12203 err = got_object_id_str(&new_id_str, new_id);
12204 if (err)
12205 goto done;
12208 old_id_str[12] = '\0';
12209 if (new_id_str)
12210 new_id_str[12] = '\0';
12212 if (hle->logmsg) {
12213 logmsg = strdup(hle->logmsg);
12214 if (logmsg == NULL) {
12215 err = got_error_from_errno("strdup");
12216 goto done;
12218 trim_logmsg(logmsg, 42);
12219 } else {
12220 err = get_short_logmsg(&logmsg, 42, commit);
12221 if (err)
12222 goto done;
12225 switch (hle->cmd->code) {
12226 case GOT_HISTEDIT_PICK:
12227 case GOT_HISTEDIT_EDIT:
12228 printf("%s -> %s: %s\n", old_id_str,
12229 new_id_str ? new_id_str : "no-op change", logmsg);
12230 break;
12231 case GOT_HISTEDIT_DROP:
12232 case GOT_HISTEDIT_FOLD:
12233 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12234 logmsg);
12235 break;
12236 default:
12237 break;
12239 done:
12240 free(old_id_str);
12241 free(new_id_str);
12242 return err;
12245 static const struct got_error *
12246 histedit_commit(struct got_pathlist_head *merged_paths,
12247 struct got_worktree *worktree, struct got_fileindex *fileindex,
12248 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12249 const char *committer, int allow_conflict, struct got_repository *repo)
12251 const struct got_error *err;
12252 struct got_commit_object *commit;
12253 struct got_object_id *new_commit_id;
12255 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12256 && hle->logmsg == NULL) {
12257 err = histedit_edit_logmsg(hle, repo);
12258 if (err)
12259 return err;
12262 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12263 if (err)
12264 return err;
12266 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12267 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12268 hle->logmsg, allow_conflict, repo);
12269 if (err) {
12270 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12271 goto done;
12272 err = show_histedit_progress(commit, hle, NULL);
12273 } else {
12274 err = show_histedit_progress(commit, hle, new_commit_id);
12275 free(new_commit_id);
12277 done:
12278 got_object_commit_close(commit);
12279 return err;
12282 static const struct got_error *
12283 histedit_skip_commit(struct got_histedit_list_entry *hle,
12284 struct got_worktree *worktree, struct got_repository *repo)
12286 const struct got_error *error;
12287 struct got_commit_object *commit;
12289 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12290 repo);
12291 if (error)
12292 return error;
12294 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12295 if (error)
12296 return error;
12298 error = show_histedit_progress(commit, hle, NULL);
12299 got_object_commit_close(commit);
12300 return error;
12303 static const struct got_error *
12304 check_local_changes(void *arg, unsigned char status,
12305 unsigned char staged_status, const char *path,
12306 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12307 struct got_object_id *commit_id, int dirfd, const char *de_name)
12309 int *have_local_changes = arg;
12311 switch (status) {
12312 case GOT_STATUS_ADD:
12313 case GOT_STATUS_DELETE:
12314 case GOT_STATUS_MODIFY:
12315 case GOT_STATUS_CONFLICT:
12316 *have_local_changes = 1;
12317 return got_error(GOT_ERR_CANCELLED);
12318 default:
12319 break;
12322 switch (staged_status) {
12323 case GOT_STATUS_ADD:
12324 case GOT_STATUS_DELETE:
12325 case GOT_STATUS_MODIFY:
12326 *have_local_changes = 1;
12327 return got_error(GOT_ERR_CANCELLED);
12328 default:
12329 break;
12332 return NULL;
12335 static const struct got_error *
12336 cmd_histedit(int argc, char *argv[])
12338 const struct got_error *error = NULL;
12339 struct got_worktree *worktree = NULL;
12340 struct got_fileindex *fileindex = NULL;
12341 struct got_repository *repo = NULL;
12342 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12343 struct got_reference *branch = NULL;
12344 struct got_reference *tmp_branch = NULL;
12345 struct got_object_id *resume_commit_id = NULL;
12346 struct got_object_id *base_commit_id = NULL;
12347 struct got_object_id *head_commit_id = NULL;
12348 struct got_commit_object *commit = NULL;
12349 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12350 struct got_update_progress_arg upa;
12351 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12352 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12353 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12354 const char *edit_script_path = NULL;
12355 struct got_object_id_queue commits;
12356 struct got_pathlist_head merged_paths;
12357 const struct got_object_id_queue *parent_ids;
12358 struct got_object_qid *pid;
12359 struct got_histedit_list histedit_cmds;
12360 struct got_histedit_list_entry *hle;
12361 int *pack_fds = NULL;
12363 STAILQ_INIT(&commits);
12364 TAILQ_INIT(&histedit_cmds);
12365 TAILQ_INIT(&merged_paths);
12366 memset(&upa, 0, sizeof(upa));
12368 #ifndef PROFILE
12369 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12370 "unveil", NULL) == -1)
12371 err(1, "pledge");
12372 #endif
12374 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12375 switch (ch) {
12376 case 'a':
12377 abort_edit = 1;
12378 break;
12379 case 'C':
12380 allow_conflict = 1;
12381 break;
12382 case 'c':
12383 continue_edit = 1;
12384 break;
12385 case 'd':
12386 drop_only = 1;
12387 break;
12388 case 'e':
12389 edit_only = 1;
12390 break;
12391 case 'F':
12392 edit_script_path = optarg;
12393 break;
12394 case 'f':
12395 fold_only = 1;
12396 break;
12397 case 'l':
12398 list_backups = 1;
12399 break;
12400 case 'm':
12401 edit_logmsg_only = 1;
12402 break;
12403 case 'X':
12404 delete_backups = 1;
12405 break;
12406 default:
12407 usage_histedit();
12408 /* NOTREACHED */
12412 argc -= optind;
12413 argv += optind;
12415 if (abort_edit && allow_conflict)
12416 option_conflict('a', 'C');
12417 if (abort_edit && continue_edit)
12418 option_conflict('a', 'c');
12419 if (edit_script_path && allow_conflict)
12420 option_conflict('F', 'C');
12421 if (edit_script_path && edit_logmsg_only)
12422 option_conflict('F', 'm');
12423 if (abort_edit && edit_logmsg_only)
12424 option_conflict('a', 'm');
12425 if (edit_logmsg_only && allow_conflict)
12426 option_conflict('m', 'C');
12427 if (continue_edit && edit_logmsg_only)
12428 option_conflict('c', 'm');
12429 if (abort_edit && fold_only)
12430 option_conflict('a', 'f');
12431 if (fold_only && allow_conflict)
12432 option_conflict('f', 'C');
12433 if (continue_edit && fold_only)
12434 option_conflict('c', 'f');
12435 if (fold_only && edit_logmsg_only)
12436 option_conflict('f', 'm');
12437 if (edit_script_path && fold_only)
12438 option_conflict('F', 'f');
12439 if (abort_edit && edit_only)
12440 option_conflict('a', 'e');
12441 if (continue_edit && edit_only)
12442 option_conflict('c', 'e');
12443 if (edit_only && edit_logmsg_only)
12444 option_conflict('e', 'm');
12445 if (edit_script_path && edit_only)
12446 option_conflict('F', 'e');
12447 if (fold_only && edit_only)
12448 option_conflict('f', 'e');
12449 if (drop_only && abort_edit)
12450 option_conflict('d', 'a');
12451 if (drop_only && allow_conflict)
12452 option_conflict('d', 'C');
12453 if (drop_only && continue_edit)
12454 option_conflict('d', 'c');
12455 if (drop_only && edit_logmsg_only)
12456 option_conflict('d', 'm');
12457 if (drop_only && edit_only)
12458 option_conflict('d', 'e');
12459 if (drop_only && edit_script_path)
12460 option_conflict('d', 'F');
12461 if (drop_only && fold_only)
12462 option_conflict('d', 'f');
12463 if (list_backups) {
12464 if (abort_edit)
12465 option_conflict('l', 'a');
12466 if (allow_conflict)
12467 option_conflict('l', 'C');
12468 if (continue_edit)
12469 option_conflict('l', 'c');
12470 if (edit_script_path)
12471 option_conflict('l', 'F');
12472 if (edit_logmsg_only)
12473 option_conflict('l', 'm');
12474 if (drop_only)
12475 option_conflict('l', 'd');
12476 if (fold_only)
12477 option_conflict('l', 'f');
12478 if (edit_only)
12479 option_conflict('l', 'e');
12480 if (delete_backups)
12481 option_conflict('l', 'X');
12482 if (argc != 0 && argc != 1)
12483 usage_histedit();
12484 } else if (delete_backups) {
12485 if (abort_edit)
12486 option_conflict('X', 'a');
12487 if (allow_conflict)
12488 option_conflict('X', 'C');
12489 if (continue_edit)
12490 option_conflict('X', 'c');
12491 if (drop_only)
12492 option_conflict('X', 'd');
12493 if (edit_script_path)
12494 option_conflict('X', 'F');
12495 if (edit_logmsg_only)
12496 option_conflict('X', 'm');
12497 if (fold_only)
12498 option_conflict('X', 'f');
12499 if (edit_only)
12500 option_conflict('X', 'e');
12501 if (list_backups)
12502 option_conflict('X', 'l');
12503 if (argc != 0 && argc != 1)
12504 usage_histedit();
12505 } else if (allow_conflict && !continue_edit)
12506 errx(1, "-C option requires -c");
12507 else if (argc != 0)
12508 usage_histedit();
12511 * This command cannot apply unveil(2) in all cases because the
12512 * user may choose to run an editor to edit the histedit script
12513 * and to edit individual commit log messages.
12514 * unveil(2) traverses exec(2); if an editor is used we have to
12515 * apply unveil after edit script and log messages have been written.
12516 * XXX TODO: Make use of unveil(2) where possible.
12519 cwd = getcwd(NULL, 0);
12520 if (cwd == NULL) {
12521 error = got_error_from_errno("getcwd");
12522 goto done;
12525 error = got_repo_pack_fds_open(&pack_fds);
12526 if (error != NULL)
12527 goto done;
12529 error = got_worktree_open(&worktree, cwd);
12530 if (error) {
12531 if (list_backups || delete_backups) {
12532 if (error->code != GOT_ERR_NOT_WORKTREE)
12533 goto done;
12534 } else {
12535 if (error->code == GOT_ERR_NOT_WORKTREE)
12536 error = wrap_not_worktree_error(error,
12537 "histedit", cwd);
12538 goto done;
12542 if (list_backups || delete_backups) {
12543 error = got_repo_open(&repo,
12544 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12545 NULL, pack_fds);
12546 if (error != NULL)
12547 goto done;
12548 error = apply_unveil(got_repo_get_path(repo), 0,
12549 worktree ? got_worktree_get_root_path(worktree) : NULL);
12550 if (error)
12551 goto done;
12552 error = process_backup_refs(
12553 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12554 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12555 goto done; /* nothing else to do */
12558 error = get_gitconfig_path(&gitconfig_path);
12559 if (error)
12560 goto done;
12561 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12562 gitconfig_path, pack_fds);
12563 if (error != NULL)
12564 goto done;
12566 if (worktree != NULL && !list_backups && !delete_backups) {
12567 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12568 if (error)
12569 goto done;
12572 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12573 if (error)
12574 goto done;
12575 if (rebase_in_progress) {
12576 error = got_error(GOT_ERR_REBASING);
12577 goto done;
12580 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12581 repo);
12582 if (error)
12583 goto done;
12584 if (merge_in_progress) {
12585 error = got_error(GOT_ERR_MERGE_BUSY);
12586 goto done;
12589 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12590 if (error)
12591 goto done;
12593 if (edit_in_progress && edit_logmsg_only) {
12594 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12595 "histedit operation is in progress in this "
12596 "work tree and must be continued or aborted "
12597 "before the -m option can be used");
12598 goto done;
12600 if (edit_in_progress && drop_only) {
12601 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12602 "histedit operation is in progress in this "
12603 "work tree and must be continued or aborted "
12604 "before the -d option can be used");
12605 goto done;
12607 if (edit_in_progress && fold_only) {
12608 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12609 "histedit operation is in progress in this "
12610 "work tree and must be continued or aborted "
12611 "before the -f option can be used");
12612 goto done;
12614 if (edit_in_progress && edit_only) {
12615 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12616 "histedit operation is in progress in this "
12617 "work tree and must be continued or aborted "
12618 "before the -e option can be used");
12619 goto done;
12622 if (edit_in_progress && abort_edit) {
12623 error = got_worktree_histedit_continue(&resume_commit_id,
12624 &tmp_branch, &branch, &base_commit_id, &fileindex,
12625 worktree, repo);
12626 if (error)
12627 goto done;
12628 printf("Switching work tree to %s\n",
12629 got_ref_get_symref_target(branch));
12630 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12631 branch, base_commit_id, abort_progress, &upa);
12632 if (error)
12633 goto done;
12634 printf("Histedit of %s aborted\n",
12635 got_ref_get_symref_target(branch));
12636 print_merge_progress_stats(&upa);
12637 goto done; /* nothing else to do */
12638 } else if (abort_edit) {
12639 error = got_error(GOT_ERR_NOT_HISTEDIT);
12640 goto done;
12643 error = get_author(&committer, repo, worktree);
12644 if (error)
12645 goto done;
12647 if (continue_edit) {
12648 char *path;
12650 if (!edit_in_progress) {
12651 error = got_error(GOT_ERR_NOT_HISTEDIT);
12652 goto done;
12655 error = got_worktree_get_histedit_script_path(&path, worktree);
12656 if (error)
12657 goto done;
12659 error = histedit_load_list(&histedit_cmds, path, repo);
12660 free(path);
12661 if (error)
12662 goto done;
12664 error = got_worktree_histedit_continue(&resume_commit_id,
12665 &tmp_branch, &branch, &base_commit_id, &fileindex,
12666 worktree, repo);
12667 if (error)
12668 goto done;
12670 error = got_ref_resolve(&head_commit_id, repo, branch);
12671 if (error)
12672 goto done;
12674 error = got_object_open_as_commit(&commit, repo,
12675 head_commit_id);
12676 if (error)
12677 goto done;
12678 parent_ids = got_object_commit_get_parent_ids(commit);
12679 pid = STAILQ_FIRST(parent_ids);
12680 if (pid == NULL) {
12681 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12682 goto done;
12684 error = collect_commits(&commits, head_commit_id, &pid->id,
12685 base_commit_id, got_worktree_get_path_prefix(worktree),
12686 GOT_ERR_HISTEDIT_PATH, repo);
12687 got_object_commit_close(commit);
12688 commit = NULL;
12689 if (error)
12690 goto done;
12691 } else {
12692 if (edit_in_progress) {
12693 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12694 goto done;
12697 error = got_ref_open(&branch, repo,
12698 got_worktree_get_head_ref_name(worktree), 0);
12699 if (error != NULL)
12700 goto done;
12702 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12703 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12704 "will not edit commit history of a branch outside "
12705 "the \"refs/heads/\" reference namespace");
12706 goto done;
12709 error = got_ref_resolve(&head_commit_id, repo, branch);
12710 got_ref_close(branch);
12711 branch = NULL;
12712 if (error)
12713 goto done;
12715 error = got_object_open_as_commit(&commit, repo,
12716 head_commit_id);
12717 if (error)
12718 goto done;
12719 parent_ids = got_object_commit_get_parent_ids(commit);
12720 pid = STAILQ_FIRST(parent_ids);
12721 if (pid == NULL) {
12722 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12723 goto done;
12725 error = collect_commits(&commits, head_commit_id, &pid->id,
12726 got_worktree_get_base_commit_id(worktree),
12727 got_worktree_get_path_prefix(worktree),
12728 GOT_ERR_HISTEDIT_PATH, repo);
12729 got_object_commit_close(commit);
12730 commit = NULL;
12731 if (error)
12732 goto done;
12734 if (STAILQ_EMPTY(&commits)) {
12735 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12736 goto done;
12739 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12740 &base_commit_id, &fileindex, worktree, repo);
12741 if (error)
12742 goto done;
12744 if (edit_script_path) {
12745 error = histedit_load_list(&histedit_cmds,
12746 edit_script_path, repo);
12747 if (error) {
12748 got_worktree_histedit_abort(worktree, fileindex,
12749 repo, branch, base_commit_id,
12750 abort_progress, &upa);
12751 print_merge_progress_stats(&upa);
12752 goto done;
12754 } else {
12755 const char *branch_name;
12756 branch_name = got_ref_get_symref_target(branch);
12757 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12758 branch_name += 11;
12759 error = histedit_edit_script(&histedit_cmds, &commits,
12760 branch_name, edit_logmsg_only, fold_only,
12761 drop_only, edit_only, repo);
12762 if (error) {
12763 got_worktree_histedit_abort(worktree, fileindex,
12764 repo, branch, base_commit_id,
12765 abort_progress, &upa);
12766 print_merge_progress_stats(&upa);
12767 goto done;
12772 error = histedit_save_list(&histedit_cmds, worktree,
12773 repo);
12774 if (error) {
12775 got_worktree_histedit_abort(worktree, fileindex,
12776 repo, branch, base_commit_id,
12777 abort_progress, &upa);
12778 print_merge_progress_stats(&upa);
12779 goto done;
12784 error = histedit_check_script(&histedit_cmds, &commits, repo);
12785 if (error)
12786 goto done;
12788 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12789 if (resume_commit_id) {
12790 if (got_object_id_cmp(hle->commit_id,
12791 resume_commit_id) != 0)
12792 continue;
12794 resume_commit_id = NULL;
12795 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12796 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12797 error = histedit_skip_commit(hle, worktree,
12798 repo);
12799 if (error)
12800 goto done;
12801 } else {
12802 struct got_pathlist_head paths;
12803 int have_changes = 0;
12805 TAILQ_INIT(&paths);
12806 error = got_pathlist_append(&paths, "", NULL);
12807 if (error)
12808 goto done;
12809 error = got_worktree_status(worktree, &paths,
12810 repo, 0, check_local_changes, &have_changes,
12811 check_cancelled, NULL);
12812 got_pathlist_free(&paths,
12813 GOT_PATHLIST_FREE_NONE);
12814 if (error) {
12815 if (error->code != GOT_ERR_CANCELLED)
12816 goto done;
12817 if (sigint_received || sigpipe_received)
12818 goto done;
12820 if (have_changes) {
12821 error = histedit_commit(NULL, worktree,
12822 fileindex, tmp_branch, hle,
12823 committer, allow_conflict, repo);
12824 if (error)
12825 goto done;
12826 } else {
12827 error = got_object_open_as_commit(
12828 &commit, repo, hle->commit_id);
12829 if (error)
12830 goto done;
12831 error = show_histedit_progress(commit,
12832 hle, NULL);
12833 got_object_commit_close(commit);
12834 commit = NULL;
12835 if (error)
12836 goto done;
12839 continue;
12842 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12843 error = histedit_skip_commit(hle, worktree, repo);
12844 if (error)
12845 goto done;
12846 continue;
12849 error = got_object_open_as_commit(&commit, repo,
12850 hle->commit_id);
12851 if (error)
12852 goto done;
12853 parent_ids = got_object_commit_get_parent_ids(commit);
12854 pid = STAILQ_FIRST(parent_ids);
12856 error = got_worktree_histedit_merge_files(&merged_paths,
12857 worktree, fileindex, &pid->id, hle->commit_id, repo,
12858 update_progress, &upa, check_cancelled, NULL);
12859 if (error)
12860 goto done;
12861 got_object_commit_close(commit);
12862 commit = NULL;
12864 print_merge_progress_stats(&upa);
12865 if (upa.conflicts > 0 || upa.missing > 0 ||
12866 upa.not_deleted > 0 || upa.unversioned > 0) {
12867 if (upa.conflicts > 0) {
12868 error = show_rebase_merge_conflict(
12869 hle->commit_id, repo);
12870 if (error)
12871 goto done;
12873 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12874 break;
12877 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12878 char *id_str;
12879 error = got_object_id_str(&id_str, hle->commit_id);
12880 if (error)
12881 goto done;
12882 printf("Stopping histedit for amending commit %s\n",
12883 id_str);
12884 free(id_str);
12885 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12886 error = got_worktree_histedit_postpone(worktree,
12887 fileindex);
12888 goto done;
12891 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12892 error = histedit_skip_commit(hle, worktree, repo);
12893 if (error)
12894 goto done;
12895 continue;
12898 error = histedit_commit(&merged_paths, worktree, fileindex,
12899 tmp_branch, hle, committer, allow_conflict, repo);
12900 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12901 if (error)
12902 goto done;
12905 if (upa.conflicts > 0 || upa.missing > 0 ||
12906 upa.not_deleted > 0 || upa.unversioned > 0) {
12907 error = got_worktree_histedit_postpone(worktree, fileindex);
12908 if (error)
12909 goto done;
12910 if (upa.conflicts > 0 && upa.missing == 0 &&
12911 upa.not_deleted == 0 && upa.unversioned == 0) {
12912 error = got_error_msg(GOT_ERR_CONFLICTS,
12913 "conflicts must be resolved before histedit "
12914 "can continue");
12915 } else if (upa.conflicts > 0) {
12916 error = got_error_msg(GOT_ERR_CONFLICTS,
12917 "conflicts must be resolved before histedit "
12918 "can continue; changes destined for some "
12919 "files were not yet merged and should be "
12920 "merged manually if required before the "
12921 "histedit operation is continued");
12922 } else {
12923 error = got_error_msg(GOT_ERR_CONFLICTS,
12924 "changes destined for some files were not "
12925 "yet merged and should be merged manually "
12926 "if required before the histedit operation "
12927 "is continued");
12929 } else
12930 error = histedit_complete(worktree, fileindex, tmp_branch,
12931 branch, repo);
12932 done:
12933 free(cwd);
12934 free(committer);
12935 free(gitconfig_path);
12936 got_object_id_queue_free(&commits);
12937 histedit_free_list(&histedit_cmds);
12938 free(head_commit_id);
12939 free(base_commit_id);
12940 free(resume_commit_id);
12941 if (commit)
12942 got_object_commit_close(commit);
12943 if (branch)
12944 got_ref_close(branch);
12945 if (tmp_branch)
12946 got_ref_close(tmp_branch);
12947 if (worktree)
12948 got_worktree_close(worktree);
12949 if (repo) {
12950 const struct got_error *close_err = got_repo_close(repo);
12951 if (error == NULL)
12952 error = close_err;
12954 if (pack_fds) {
12955 const struct got_error *pack_err =
12956 got_repo_pack_fds_close(pack_fds);
12957 if (error == NULL)
12958 error = pack_err;
12960 return error;
12963 __dead static void
12964 usage_integrate(void)
12966 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12967 exit(1);
12970 static const struct got_error *
12971 cmd_integrate(int argc, char *argv[])
12973 const struct got_error *error = NULL;
12974 struct got_repository *repo = NULL;
12975 struct got_worktree *worktree = NULL;
12976 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12977 const char *branch_arg = NULL;
12978 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12979 struct got_fileindex *fileindex = NULL;
12980 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12981 int ch;
12982 struct got_update_progress_arg upa;
12983 int *pack_fds = NULL;
12985 #ifndef PROFILE
12986 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12987 "unveil", NULL) == -1)
12988 err(1, "pledge");
12989 #endif
12991 while ((ch = getopt(argc, argv, "")) != -1) {
12992 switch (ch) {
12993 default:
12994 usage_integrate();
12995 /* NOTREACHED */
12999 argc -= optind;
13000 argv += optind;
13002 if (argc != 1)
13003 usage_integrate();
13004 branch_arg = argv[0];
13006 cwd = getcwd(NULL, 0);
13007 if (cwd == NULL) {
13008 error = got_error_from_errno("getcwd");
13009 goto done;
13012 error = got_repo_pack_fds_open(&pack_fds);
13013 if (error != NULL)
13014 goto done;
13016 error = got_worktree_open(&worktree, cwd);
13017 if (error) {
13018 if (error->code == GOT_ERR_NOT_WORKTREE)
13019 error = wrap_not_worktree_error(error, "integrate",
13020 cwd);
13021 goto done;
13024 error = check_rebase_or_histedit_in_progress(worktree);
13025 if (error)
13026 goto done;
13028 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13029 NULL, pack_fds);
13030 if (error != NULL)
13031 goto done;
13033 error = apply_unveil(got_repo_get_path(repo), 0,
13034 got_worktree_get_root_path(worktree));
13035 if (error)
13036 goto done;
13038 error = check_merge_in_progress(worktree, repo);
13039 if (error)
13040 goto done;
13042 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13043 error = got_error_from_errno("asprintf");
13044 goto done;
13047 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13048 &base_branch_ref, worktree, refname, repo);
13049 if (error)
13050 goto done;
13052 refname = strdup(got_ref_get_name(branch_ref));
13053 if (refname == NULL) {
13054 error = got_error_from_errno("strdup");
13055 got_worktree_integrate_abort(worktree, fileindex, repo,
13056 branch_ref, base_branch_ref);
13057 goto done;
13059 base_refname = strdup(got_ref_get_name(base_branch_ref));
13060 if (base_refname == NULL) {
13061 error = got_error_from_errno("strdup");
13062 got_worktree_integrate_abort(worktree, fileindex, repo,
13063 branch_ref, base_branch_ref);
13064 goto done;
13066 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13067 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13068 got_worktree_integrate_abort(worktree, fileindex, repo,
13069 branch_ref, base_branch_ref);
13070 goto done;
13073 error = got_ref_resolve(&commit_id, repo, branch_ref);
13074 if (error)
13075 goto done;
13077 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13078 if (error)
13079 goto done;
13081 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13082 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13083 "specified branch has already been integrated");
13084 got_worktree_integrate_abort(worktree, fileindex, repo,
13085 branch_ref, base_branch_ref);
13086 goto done;
13089 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13090 if (error) {
13091 if (error->code == GOT_ERR_ANCESTRY)
13092 error = got_error(GOT_ERR_REBASE_REQUIRED);
13093 got_worktree_integrate_abort(worktree, fileindex, repo,
13094 branch_ref, base_branch_ref);
13095 goto done;
13098 memset(&upa, 0, sizeof(upa));
13099 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13100 branch_ref, base_branch_ref, update_progress, &upa,
13101 check_cancelled, NULL);
13102 if (error)
13103 goto done;
13105 printf("Integrated %s into %s\n", refname, base_refname);
13106 print_update_progress_stats(&upa);
13107 done:
13108 if (repo) {
13109 const struct got_error *close_err = got_repo_close(repo);
13110 if (error == NULL)
13111 error = close_err;
13113 if (worktree)
13114 got_worktree_close(worktree);
13115 if (pack_fds) {
13116 const struct got_error *pack_err =
13117 got_repo_pack_fds_close(pack_fds);
13118 if (error == NULL)
13119 error = pack_err;
13121 free(cwd);
13122 free(base_commit_id);
13123 free(commit_id);
13124 free(refname);
13125 free(base_refname);
13126 return error;
13129 __dead static void
13130 usage_merge(void)
13132 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13133 exit(1);
13136 static const struct got_error *
13137 cmd_merge(int argc, char *argv[])
13139 const struct got_error *error = NULL;
13140 struct got_worktree *worktree = NULL;
13141 struct got_repository *repo = NULL;
13142 struct got_fileindex *fileindex = NULL;
13143 char *cwd = NULL, *id_str = NULL, *author = NULL;
13144 char *gitconfig_path = NULL;
13145 struct got_reference *branch = NULL, *wt_branch = NULL;
13146 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13147 struct got_object_id *wt_branch_tip = NULL;
13148 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13149 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13150 struct got_update_progress_arg upa;
13151 struct got_object_id *merge_commit_id = NULL;
13152 char *branch_name = NULL;
13153 int *pack_fds = NULL;
13155 memset(&upa, 0, sizeof(upa));
13157 #ifndef PROFILE
13158 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13159 "unveil", NULL) == -1)
13160 err(1, "pledge");
13161 #endif
13163 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13164 switch (ch) {
13165 case 'a':
13166 abort_merge = 1;
13167 break;
13168 case 'C':
13169 allow_conflict = 1;
13170 break;
13171 case 'c':
13172 continue_merge = 1;
13173 break;
13174 case 'M':
13175 prefer_fast_forward = 0;
13176 break;
13177 case 'n':
13178 interrupt_merge = 1;
13179 break;
13180 default:
13181 usage_merge();
13182 /* NOTREACHED */
13186 argc -= optind;
13187 argv += optind;
13189 if (abort_merge) {
13190 if (continue_merge)
13191 option_conflict('a', 'c');
13192 if (!prefer_fast_forward)
13193 option_conflict('a', 'M');
13194 if (interrupt_merge)
13195 option_conflict('a', 'n');
13196 } else if (continue_merge) {
13197 if (!prefer_fast_forward)
13198 option_conflict('c', 'M');
13199 if (interrupt_merge)
13200 option_conflict('c', 'n');
13202 if (allow_conflict) {
13203 if (!continue_merge)
13204 errx(1, "-C option requires -c");
13206 if (abort_merge || continue_merge) {
13207 if (argc != 0)
13208 usage_merge();
13209 } else if (argc != 1)
13210 usage_merge();
13212 cwd = getcwd(NULL, 0);
13213 if (cwd == NULL) {
13214 error = got_error_from_errno("getcwd");
13215 goto done;
13218 error = got_repo_pack_fds_open(&pack_fds);
13219 if (error != NULL)
13220 goto done;
13222 error = got_worktree_open(&worktree, cwd);
13223 if (error) {
13224 if (error->code == GOT_ERR_NOT_WORKTREE)
13225 error = wrap_not_worktree_error(error,
13226 "merge", cwd);
13227 goto done;
13230 error = get_gitconfig_path(&gitconfig_path);
13231 if (error)
13232 goto done;
13233 error = got_repo_open(&repo,
13234 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13235 gitconfig_path, pack_fds);
13236 if (error != NULL)
13237 goto done;
13239 if (worktree != NULL) {
13240 error = worktree_has_logmsg_ref("merge", worktree, repo);
13241 if (error)
13242 goto done;
13245 error = apply_unveil(got_repo_get_path(repo), 0,
13246 worktree ? got_worktree_get_root_path(worktree) : NULL);
13247 if (error)
13248 goto done;
13250 error = check_rebase_or_histedit_in_progress(worktree);
13251 if (error)
13252 goto done;
13254 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13255 repo);
13256 if (error)
13257 goto done;
13259 if (merge_in_progress && !(abort_merge || continue_merge)) {
13260 error = got_error(GOT_ERR_MERGE_BUSY);
13261 goto done;
13264 if (!merge_in_progress && (abort_merge || continue_merge)) {
13265 error = got_error(GOT_ERR_NOT_MERGING);
13266 goto done;
13269 if (abort_merge) {
13270 error = got_worktree_merge_continue(&branch_name,
13271 &branch_tip, &fileindex, worktree, repo);
13272 if (error)
13273 goto done;
13274 error = got_worktree_merge_abort(worktree, fileindex, repo,
13275 abort_progress, &upa);
13276 if (error)
13277 goto done;
13278 printf("Merge of %s aborted\n", branch_name);
13279 goto done; /* nothing else to do */
13282 if (strncmp(got_worktree_get_head_ref_name(worktree),
13283 "refs/heads/", 11) != 0) {
13284 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13285 "work tree's current branch %s is outside the "
13286 "\"refs/heads/\" reference namespace; "
13287 "update -b required",
13288 got_worktree_get_head_ref_name(worktree));
13289 goto done;
13292 error = get_author(&author, repo, worktree);
13293 if (error)
13294 goto done;
13296 error = got_ref_open(&wt_branch, repo,
13297 got_worktree_get_head_ref_name(worktree), 0);
13298 if (error)
13299 goto done;
13300 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13301 if (error)
13302 goto done;
13304 if (continue_merge) {
13305 struct got_object_id *base_commit_id;
13306 base_commit_id = got_worktree_get_base_commit_id(worktree);
13307 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13308 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13309 goto done;
13311 error = got_worktree_merge_continue(&branch_name,
13312 &branch_tip, &fileindex, worktree, repo);
13313 if (error)
13314 goto done;
13315 } else {
13316 error = got_ref_open(&branch, repo, argv[0], 0);
13317 if (error != NULL)
13318 goto done;
13319 branch_name = strdup(got_ref_get_name(branch));
13320 if (branch_name == NULL) {
13321 error = got_error_from_errno("strdup");
13322 goto done;
13324 error = got_ref_resolve(&branch_tip, repo, branch);
13325 if (error)
13326 goto done;
13329 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13330 wt_branch_tip, branch_tip, 0, repo,
13331 check_cancelled, NULL);
13332 if (error && error->code != GOT_ERR_ANCESTRY)
13333 goto done;
13335 if (!continue_merge) {
13336 error = check_path_prefix(wt_branch_tip, branch_tip,
13337 got_worktree_get_path_prefix(worktree),
13338 GOT_ERR_MERGE_PATH, repo);
13339 if (error)
13340 goto done;
13341 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13342 if (error)
13343 goto done;
13344 if (prefer_fast_forward && yca_id &&
13345 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13346 struct got_pathlist_head paths;
13347 if (interrupt_merge) {
13348 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13349 "there are no changes to merge since %s "
13350 "is already based on %s; merge cannot be "
13351 "interrupted for amending; -n",
13352 branch_name, got_ref_get_name(wt_branch));
13353 goto done;
13355 printf("Forwarding %s to %s\n",
13356 got_ref_get_name(wt_branch), branch_name);
13357 error = got_ref_change_ref(wt_branch, branch_tip);
13358 if (error)
13359 goto done;
13360 error = got_ref_write(wt_branch, repo);
13361 if (error)
13362 goto done;
13363 error = got_worktree_set_base_commit_id(worktree, repo,
13364 branch_tip);
13365 if (error)
13366 goto done;
13367 TAILQ_INIT(&paths);
13368 error = got_pathlist_append(&paths, "", NULL);
13369 if (error)
13370 goto done;
13371 error = got_worktree_checkout_files(worktree,
13372 &paths, repo, update_progress, &upa,
13373 check_cancelled, NULL);
13374 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13375 if (error)
13376 goto done;
13377 if (upa.did_something) {
13378 char *id_str;
13379 error = got_object_id_str(&id_str, branch_tip);
13380 if (error)
13381 goto done;
13382 printf("Updated to commit %s\n", id_str);
13383 free(id_str);
13384 } else
13385 printf("Already up-to-date\n");
13386 print_update_progress_stats(&upa);
13387 goto done;
13389 error = got_worktree_merge_write_refs(worktree, branch, repo);
13390 if (error)
13391 goto done;
13393 error = got_worktree_merge_branch(worktree, fileindex,
13394 yca_id, branch_tip, repo, update_progress, &upa,
13395 check_cancelled, NULL);
13396 if (error)
13397 goto done;
13398 print_merge_progress_stats(&upa);
13399 if (!upa.did_something) {
13400 error = got_worktree_merge_abort(worktree, fileindex,
13401 repo, abort_progress, &upa);
13402 if (error)
13403 goto done;
13404 printf("Already up-to-date\n");
13405 goto done;
13409 if (interrupt_merge) {
13410 error = got_worktree_merge_postpone(worktree, fileindex);
13411 if (error)
13412 goto done;
13413 printf("Merge of %s interrupted on request\n", branch_name);
13414 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13415 upa.not_deleted > 0 || upa.unversioned > 0) {
13416 error = got_worktree_merge_postpone(worktree, fileindex);
13417 if (error)
13418 goto done;
13419 if (upa.conflicts > 0 && upa.missing == 0 &&
13420 upa.not_deleted == 0 && upa.unversioned == 0) {
13421 error = got_error_msg(GOT_ERR_CONFLICTS,
13422 "conflicts must be resolved before merging "
13423 "can continue");
13424 } else if (upa.conflicts > 0) {
13425 error = got_error_msg(GOT_ERR_CONFLICTS,
13426 "conflicts must be resolved before merging "
13427 "can continue; changes destined for some "
13428 "files were not yet merged and "
13429 "should be merged manually if required before the "
13430 "merge operation is continued");
13431 } else {
13432 error = got_error_msg(GOT_ERR_CONFLICTS,
13433 "changes destined for some "
13434 "files were not yet merged and should be "
13435 "merged manually if required before the "
13436 "merge operation is continued");
13438 goto done;
13439 } else {
13440 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13441 fileindex, author, NULL, 1, branch_tip, branch_name,
13442 allow_conflict, repo, continue_merge ? print_status : NULL,
13443 NULL);
13444 if (error)
13445 goto done;
13446 error = got_worktree_merge_complete(worktree, fileindex, repo);
13447 if (error)
13448 goto done;
13449 error = got_object_id_str(&id_str, merge_commit_id);
13450 if (error)
13451 goto done;
13452 printf("Merged %s into %s: %s\n", branch_name,
13453 got_worktree_get_head_ref_name(worktree),
13454 id_str);
13457 done:
13458 free(gitconfig_path);
13459 free(id_str);
13460 free(merge_commit_id);
13461 free(author);
13462 free(branch_tip);
13463 free(branch_name);
13464 free(yca_id);
13465 if (branch)
13466 got_ref_close(branch);
13467 if (wt_branch)
13468 got_ref_close(wt_branch);
13469 if (worktree)
13470 got_worktree_close(worktree);
13471 if (repo) {
13472 const struct got_error *close_err = got_repo_close(repo);
13473 if (error == NULL)
13474 error = close_err;
13476 if (pack_fds) {
13477 const struct got_error *pack_err =
13478 got_repo_pack_fds_close(pack_fds);
13479 if (error == NULL)
13480 error = pack_err;
13482 return error;
13485 __dead static void
13486 usage_stage(void)
13488 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13489 "[path ...]\n", getprogname());
13490 exit(1);
13493 static const struct got_error *
13494 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13495 const char *path, struct got_object_id *blob_id,
13496 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13497 int dirfd, const char *de_name)
13499 const struct got_error *err = NULL;
13500 char *id_str = NULL;
13502 if (staged_status != GOT_STATUS_ADD &&
13503 staged_status != GOT_STATUS_MODIFY &&
13504 staged_status != GOT_STATUS_DELETE)
13505 return NULL;
13507 if (staged_status == GOT_STATUS_ADD ||
13508 staged_status == GOT_STATUS_MODIFY)
13509 err = got_object_id_str(&id_str, staged_blob_id);
13510 else
13511 err = got_object_id_str(&id_str, blob_id);
13512 if (err)
13513 return err;
13515 printf("%s %c %s\n", id_str, staged_status, path);
13516 free(id_str);
13517 return NULL;
13520 static const struct got_error *
13521 cmd_stage(int argc, char *argv[])
13523 const struct got_error *error = NULL;
13524 struct got_repository *repo = NULL;
13525 struct got_worktree *worktree = NULL;
13526 char *cwd = NULL;
13527 struct got_pathlist_head paths;
13528 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13529 FILE *patch_script_file = NULL;
13530 const char *patch_script_path = NULL;
13531 struct choose_patch_arg cpa;
13532 int *pack_fds = NULL;
13534 TAILQ_INIT(&paths);
13536 #ifndef PROFILE
13537 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13538 "unveil", NULL) == -1)
13539 err(1, "pledge");
13540 #endif
13542 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13543 switch (ch) {
13544 case 'F':
13545 patch_script_path = optarg;
13546 break;
13547 case 'l':
13548 list_stage = 1;
13549 break;
13550 case 'p':
13551 pflag = 1;
13552 break;
13553 case 'S':
13554 allow_bad_symlinks = 1;
13555 break;
13556 default:
13557 usage_stage();
13558 /* NOTREACHED */
13562 argc -= optind;
13563 argv += optind;
13565 if (list_stage && (pflag || patch_script_path))
13566 errx(1, "-l option cannot be used with other options");
13567 if (patch_script_path && !pflag)
13568 errx(1, "-F option can only be used together with -p option");
13570 cwd = getcwd(NULL, 0);
13571 if (cwd == NULL) {
13572 error = got_error_from_errno("getcwd");
13573 goto done;
13576 error = got_repo_pack_fds_open(&pack_fds);
13577 if (error != NULL)
13578 goto done;
13580 error = got_worktree_open(&worktree, cwd);
13581 if (error) {
13582 if (error->code == GOT_ERR_NOT_WORKTREE)
13583 error = wrap_not_worktree_error(error, "stage", cwd);
13584 goto done;
13587 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13588 NULL, pack_fds);
13589 if (error != NULL)
13590 goto done;
13592 if (patch_script_path) {
13593 patch_script_file = fopen(patch_script_path, "re");
13594 if (patch_script_file == NULL) {
13595 error = got_error_from_errno2("fopen",
13596 patch_script_path);
13597 goto done;
13600 error = apply_unveil(got_repo_get_path(repo), 0,
13601 got_worktree_get_root_path(worktree));
13602 if (error)
13603 goto done;
13605 error = check_merge_in_progress(worktree, repo);
13606 if (error)
13607 goto done;
13609 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13610 if (error)
13611 goto done;
13613 if (list_stage)
13614 error = got_worktree_status(worktree, &paths, repo, 0,
13615 print_stage, NULL, check_cancelled, NULL);
13616 else {
13617 cpa.patch_script_file = patch_script_file;
13618 cpa.action = "stage";
13619 error = got_worktree_stage(worktree, &paths,
13620 pflag ? NULL : print_status, NULL,
13621 pflag ? choose_patch : NULL, &cpa,
13622 allow_bad_symlinks, repo);
13624 done:
13625 if (patch_script_file && fclose(patch_script_file) == EOF &&
13626 error == NULL)
13627 error = got_error_from_errno2("fclose", patch_script_path);
13628 if (repo) {
13629 const struct got_error *close_err = got_repo_close(repo);
13630 if (error == NULL)
13631 error = close_err;
13633 if (worktree)
13634 got_worktree_close(worktree);
13635 if (pack_fds) {
13636 const struct got_error *pack_err =
13637 got_repo_pack_fds_close(pack_fds);
13638 if (error == NULL)
13639 error = pack_err;
13641 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13642 free(cwd);
13643 return error;
13646 __dead static void
13647 usage_unstage(void)
13649 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13650 "[path ...]\n", getprogname());
13651 exit(1);
13655 static const struct got_error *
13656 cmd_unstage(int argc, char *argv[])
13658 const struct got_error *error = NULL;
13659 struct got_repository *repo = NULL;
13660 struct got_worktree *worktree = NULL;
13661 char *cwd = NULL;
13662 struct got_pathlist_head paths;
13663 int ch, pflag = 0;
13664 struct got_update_progress_arg upa;
13665 FILE *patch_script_file = NULL;
13666 const char *patch_script_path = NULL;
13667 struct choose_patch_arg cpa;
13668 int *pack_fds = NULL;
13670 TAILQ_INIT(&paths);
13672 #ifndef PROFILE
13673 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13674 "unveil", NULL) == -1)
13675 err(1, "pledge");
13676 #endif
13678 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13679 switch (ch) {
13680 case 'F':
13681 patch_script_path = optarg;
13682 break;
13683 case 'p':
13684 pflag = 1;
13685 break;
13686 default:
13687 usage_unstage();
13688 /* NOTREACHED */
13692 argc -= optind;
13693 argv += optind;
13695 if (patch_script_path && !pflag)
13696 errx(1, "-F option can only be used together with -p option");
13698 cwd = getcwd(NULL, 0);
13699 if (cwd == NULL) {
13700 error = got_error_from_errno("getcwd");
13701 goto done;
13704 error = got_repo_pack_fds_open(&pack_fds);
13705 if (error != NULL)
13706 goto done;
13708 error = got_worktree_open(&worktree, cwd);
13709 if (error) {
13710 if (error->code == GOT_ERR_NOT_WORKTREE)
13711 error = wrap_not_worktree_error(error, "unstage", cwd);
13712 goto done;
13715 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13716 NULL, pack_fds);
13717 if (error != NULL)
13718 goto done;
13720 if (patch_script_path) {
13721 patch_script_file = fopen(patch_script_path, "re");
13722 if (patch_script_file == NULL) {
13723 error = got_error_from_errno2("fopen",
13724 patch_script_path);
13725 goto done;
13729 error = apply_unveil(got_repo_get_path(repo), 0,
13730 got_worktree_get_root_path(worktree));
13731 if (error)
13732 goto done;
13734 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13735 if (error)
13736 goto done;
13738 cpa.patch_script_file = patch_script_file;
13739 cpa.action = "unstage";
13740 memset(&upa, 0, sizeof(upa));
13741 error = got_worktree_unstage(worktree, &paths, update_progress,
13742 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13743 if (!error)
13744 print_merge_progress_stats(&upa);
13745 done:
13746 if (patch_script_file && fclose(patch_script_file) == EOF &&
13747 error == NULL)
13748 error = got_error_from_errno2("fclose", patch_script_path);
13749 if (repo) {
13750 const struct got_error *close_err = got_repo_close(repo);
13751 if (error == NULL)
13752 error = close_err;
13754 if (worktree)
13755 got_worktree_close(worktree);
13756 if (pack_fds) {
13757 const struct got_error *pack_err =
13758 got_repo_pack_fds_close(pack_fds);
13759 if (error == NULL)
13760 error = pack_err;
13762 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13763 free(cwd);
13764 return error;
13767 __dead static void
13768 usage_cat(void)
13770 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13771 "arg ...\n", getprogname());
13772 exit(1);
13775 static const struct got_error *
13776 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13778 const struct got_error *err;
13779 struct got_blob_object *blob;
13780 int fd = -1;
13782 fd = got_opentempfd();
13783 if (fd == -1)
13784 return got_error_from_errno("got_opentempfd");
13786 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13787 if (err)
13788 goto done;
13790 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13791 done:
13792 if (fd != -1 && close(fd) == -1 && err == NULL)
13793 err = got_error_from_errno("close");
13794 if (blob)
13795 got_object_blob_close(blob);
13796 return err;
13799 static const struct got_error *
13800 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13802 const struct got_error *err;
13803 struct got_tree_object *tree;
13804 int nentries, i;
13806 err = got_object_open_as_tree(&tree, repo, id);
13807 if (err)
13808 return err;
13810 nentries = got_object_tree_get_nentries(tree);
13811 for (i = 0; i < nentries; i++) {
13812 struct got_tree_entry *te;
13813 char *id_str;
13814 if (sigint_received || sigpipe_received)
13815 break;
13816 te = got_object_tree_get_entry(tree, i);
13817 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13818 if (err)
13819 break;
13820 fprintf(outfile, "%s %.7o %s\n", id_str,
13821 got_tree_entry_get_mode(te),
13822 got_tree_entry_get_name(te));
13823 free(id_str);
13826 got_object_tree_close(tree);
13827 return err;
13830 static const struct got_error *
13831 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13833 const struct got_error *err;
13834 struct got_commit_object *commit;
13835 const struct got_object_id_queue *parent_ids;
13836 struct got_object_qid *pid;
13837 char *id_str = NULL;
13838 const char *logmsg = NULL;
13839 char gmtoff[6];
13841 err = got_object_open_as_commit(&commit, repo, id);
13842 if (err)
13843 return err;
13845 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13846 if (err)
13847 goto done;
13849 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13850 parent_ids = got_object_commit_get_parent_ids(commit);
13851 fprintf(outfile, "numparents %d\n",
13852 got_object_commit_get_nparents(commit));
13853 STAILQ_FOREACH(pid, parent_ids, entry) {
13854 char *pid_str;
13855 err = got_object_id_str(&pid_str, &pid->id);
13856 if (err)
13857 goto done;
13858 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13859 free(pid_str);
13861 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13862 got_object_commit_get_author_gmtoff(commit));
13863 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13864 got_object_commit_get_author(commit),
13865 (long long)got_object_commit_get_author_time(commit),
13866 gmtoff);
13868 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13869 got_object_commit_get_committer_gmtoff(commit));
13870 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13871 got_object_commit_get_committer(commit),
13872 (long long)got_object_commit_get_committer_time(commit),
13873 gmtoff);
13875 logmsg = got_object_commit_get_logmsg_raw(commit);
13876 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13877 fprintf(outfile, "%s", logmsg);
13878 done:
13879 free(id_str);
13880 got_object_commit_close(commit);
13881 return err;
13884 static const struct got_error *
13885 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13887 const struct got_error *err;
13888 struct got_tag_object *tag;
13889 char *id_str = NULL;
13890 const char *tagmsg = NULL;
13891 char gmtoff[6];
13893 err = got_object_open_as_tag(&tag, repo, id);
13894 if (err)
13895 return err;
13897 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13898 if (err)
13899 goto done;
13901 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13903 switch (got_object_tag_get_object_type(tag)) {
13904 case GOT_OBJ_TYPE_BLOB:
13905 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13906 GOT_OBJ_LABEL_BLOB);
13907 break;
13908 case GOT_OBJ_TYPE_TREE:
13909 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13910 GOT_OBJ_LABEL_TREE);
13911 break;
13912 case GOT_OBJ_TYPE_COMMIT:
13913 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13914 GOT_OBJ_LABEL_COMMIT);
13915 break;
13916 case GOT_OBJ_TYPE_TAG:
13917 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13918 GOT_OBJ_LABEL_TAG);
13919 break;
13920 default:
13921 break;
13924 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13925 got_object_tag_get_name(tag));
13927 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13928 got_object_tag_get_tagger_gmtoff(tag));
13929 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13930 got_object_tag_get_tagger(tag),
13931 (long long)got_object_tag_get_tagger_time(tag),
13932 gmtoff);
13934 tagmsg = got_object_tag_get_message(tag);
13935 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13936 fprintf(outfile, "%s", tagmsg);
13937 done:
13938 free(id_str);
13939 got_object_tag_close(tag);
13940 return err;
13943 static const struct got_error *
13944 cmd_cat(int argc, char *argv[])
13946 const struct got_error *error;
13947 struct got_repository *repo = NULL;
13948 struct got_worktree *worktree = NULL;
13949 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13950 const char *commit_id_str = NULL;
13951 struct got_object_id *id = NULL, *commit_id = NULL;
13952 struct got_commit_object *commit = NULL;
13953 int ch, obj_type, i, force_path = 0;
13954 struct got_reflist_head refs;
13955 int *pack_fds = NULL;
13957 TAILQ_INIT(&refs);
13959 #ifndef PROFILE
13960 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13961 NULL) == -1)
13962 err(1, "pledge");
13963 #endif
13965 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13966 switch (ch) {
13967 case 'c':
13968 commit_id_str = optarg;
13969 break;
13970 case 'P':
13971 force_path = 1;
13972 break;
13973 case 'r':
13974 repo_path = realpath(optarg, NULL);
13975 if (repo_path == NULL)
13976 return got_error_from_errno2("realpath",
13977 optarg);
13978 got_path_strip_trailing_slashes(repo_path);
13979 break;
13980 default:
13981 usage_cat();
13982 /* NOTREACHED */
13986 argc -= optind;
13987 argv += optind;
13989 cwd = getcwd(NULL, 0);
13990 if (cwd == NULL) {
13991 error = got_error_from_errno("getcwd");
13992 goto done;
13995 error = got_repo_pack_fds_open(&pack_fds);
13996 if (error != NULL)
13997 goto done;
13999 if (repo_path == NULL) {
14000 error = got_worktree_open(&worktree, cwd);
14001 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14002 goto done;
14003 if (worktree) {
14004 repo_path = strdup(
14005 got_worktree_get_repo_path(worktree));
14006 if (repo_path == NULL) {
14007 error = got_error_from_errno("strdup");
14008 goto done;
14011 /* Release work tree lock. */
14012 got_worktree_close(worktree);
14013 worktree = NULL;
14017 if (repo_path == NULL) {
14018 repo_path = strdup(cwd);
14019 if (repo_path == NULL)
14020 return got_error_from_errno("strdup");
14023 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14024 free(repo_path);
14025 if (error != NULL)
14026 goto done;
14028 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14029 if (error)
14030 goto done;
14032 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14033 if (error)
14034 goto done;
14036 if (commit_id_str == NULL)
14037 commit_id_str = GOT_REF_HEAD;
14038 error = got_repo_match_object_id(&commit_id, NULL,
14039 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14040 if (error)
14041 goto done;
14043 error = got_object_open_as_commit(&commit, repo, commit_id);
14044 if (error)
14045 goto done;
14047 for (i = 0; i < argc; i++) {
14048 if (force_path) {
14049 error = got_object_id_by_path(&id, repo, commit,
14050 argv[i]);
14051 if (error)
14052 break;
14053 } else {
14054 error = got_repo_match_object_id(&id, &label, argv[i],
14055 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14056 repo);
14057 if (error) {
14058 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14059 error->code != GOT_ERR_NOT_REF)
14060 break;
14061 error = got_object_id_by_path(&id, repo,
14062 commit, argv[i]);
14063 if (error)
14064 break;
14068 error = got_object_get_type(&obj_type, repo, id);
14069 if (error)
14070 break;
14072 switch (obj_type) {
14073 case GOT_OBJ_TYPE_BLOB:
14074 error = cat_blob(id, repo, stdout);
14075 break;
14076 case GOT_OBJ_TYPE_TREE:
14077 error = cat_tree(id, repo, stdout);
14078 break;
14079 case GOT_OBJ_TYPE_COMMIT:
14080 error = cat_commit(id, repo, stdout);
14081 break;
14082 case GOT_OBJ_TYPE_TAG:
14083 error = cat_tag(id, repo, stdout);
14084 break;
14085 default:
14086 error = got_error(GOT_ERR_OBJ_TYPE);
14087 break;
14089 if (error)
14090 break;
14091 free(label);
14092 label = NULL;
14093 free(id);
14094 id = NULL;
14096 done:
14097 free(label);
14098 free(id);
14099 free(commit_id);
14100 if (commit)
14101 got_object_commit_close(commit);
14102 if (worktree)
14103 got_worktree_close(worktree);
14104 if (repo) {
14105 const struct got_error *close_err = got_repo_close(repo);
14106 if (error == NULL)
14107 error = close_err;
14109 if (pack_fds) {
14110 const struct got_error *pack_err =
14111 got_repo_pack_fds_close(pack_fds);
14112 if (error == NULL)
14113 error = pack_err;
14116 got_ref_list_free(&refs);
14117 return error;
14120 __dead static void
14121 usage_info(void)
14123 fprintf(stderr, "usage: %s info [path ...]\n",
14124 getprogname());
14125 exit(1);
14128 static const struct got_error *
14129 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14130 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14131 struct got_object_id *commit_id)
14133 const struct got_error *err = NULL;
14134 char *id_str = NULL;
14135 char datebuf[128];
14136 struct tm mytm, *tm;
14137 struct got_pathlist_head *paths = arg;
14138 struct got_pathlist_entry *pe;
14141 * Clear error indication from any of the path arguments which
14142 * would cause this file index entry to be displayed.
14144 TAILQ_FOREACH(pe, paths, entry) {
14145 if (got_path_cmp(path, pe->path, strlen(path),
14146 pe->path_len) == 0 ||
14147 got_path_is_child(path, pe->path, pe->path_len))
14148 pe->data = NULL; /* no error */
14151 printf(GOT_COMMIT_SEP_STR);
14152 if (S_ISLNK(mode))
14153 printf("symlink: %s\n", path);
14154 else if (S_ISREG(mode)) {
14155 printf("file: %s\n", path);
14156 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14157 } else if (S_ISDIR(mode))
14158 printf("directory: %s\n", path);
14159 else
14160 printf("something: %s\n", path);
14162 tm = localtime_r(&mtime, &mytm);
14163 if (tm == NULL)
14164 return NULL;
14165 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14166 return got_error(GOT_ERR_NO_SPACE);
14167 printf("timestamp: %s\n", datebuf);
14169 if (blob_id) {
14170 err = got_object_id_str(&id_str, blob_id);
14171 if (err)
14172 return err;
14173 printf("based on blob: %s\n", id_str);
14174 free(id_str);
14177 if (staged_blob_id) {
14178 err = got_object_id_str(&id_str, staged_blob_id);
14179 if (err)
14180 return err;
14181 printf("based on staged blob: %s\n", id_str);
14182 free(id_str);
14185 if (commit_id) {
14186 err = got_object_id_str(&id_str, commit_id);
14187 if (err)
14188 return err;
14189 printf("based on commit: %s\n", id_str);
14190 free(id_str);
14193 return NULL;
14196 static const struct got_error *
14197 cmd_info(int argc, char *argv[])
14199 const struct got_error *error = NULL;
14200 struct got_worktree *worktree = NULL;
14201 char *cwd = NULL, *id_str = NULL;
14202 struct got_pathlist_head paths;
14203 char *uuidstr = NULL;
14204 int ch, show_files = 0;
14206 TAILQ_INIT(&paths);
14208 #ifndef PROFILE
14209 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14210 NULL) == -1)
14211 err(1, "pledge");
14212 #endif
14214 while ((ch = getopt(argc, argv, "")) != -1) {
14215 switch (ch) {
14216 default:
14217 usage_info();
14218 /* NOTREACHED */
14222 argc -= optind;
14223 argv += optind;
14225 cwd = getcwd(NULL, 0);
14226 if (cwd == NULL) {
14227 error = got_error_from_errno("getcwd");
14228 goto done;
14231 error = got_worktree_open(&worktree, cwd);
14232 if (error) {
14233 if (error->code == GOT_ERR_NOT_WORKTREE)
14234 error = wrap_not_worktree_error(error, "info", cwd);
14235 goto done;
14238 #ifndef PROFILE
14239 /* Remove "wpath cpath proc exec sendfd" promises. */
14240 if (pledge("stdio rpath flock unveil", NULL) == -1)
14241 err(1, "pledge");
14242 #endif
14243 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14244 if (error)
14245 goto done;
14247 if (argc >= 1) {
14248 error = get_worktree_paths_from_argv(&paths, argc, argv,
14249 worktree);
14250 if (error)
14251 goto done;
14252 show_files = 1;
14255 error = got_object_id_str(&id_str,
14256 got_worktree_get_base_commit_id(worktree));
14257 if (error)
14258 goto done;
14260 error = got_worktree_get_uuid(&uuidstr, worktree);
14261 if (error)
14262 goto done;
14264 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14265 printf("work tree base commit: %s\n", id_str);
14266 printf("work tree path prefix: %s\n",
14267 got_worktree_get_path_prefix(worktree));
14268 printf("work tree branch reference: %s\n",
14269 got_worktree_get_head_ref_name(worktree));
14270 printf("work tree UUID: %s\n", uuidstr);
14271 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14273 if (show_files) {
14274 struct got_pathlist_entry *pe;
14275 TAILQ_FOREACH(pe, &paths, entry) {
14276 if (pe->path_len == 0)
14277 continue;
14279 * Assume this path will fail. This will be corrected
14280 * in print_path_info() in case the path does suceeed.
14282 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14284 error = got_worktree_path_info(worktree, &paths,
14285 print_path_info, &paths, check_cancelled, NULL);
14286 if (error)
14287 goto done;
14288 TAILQ_FOREACH(pe, &paths, entry) {
14289 if (pe->data != NULL) {
14290 const struct got_error *perr;
14292 perr = pe->data;
14293 error = got_error_fmt(perr->code, "%s",
14294 pe->path);
14295 break;
14299 done:
14300 if (worktree)
14301 got_worktree_close(worktree);
14302 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14303 free(cwd);
14304 free(id_str);
14305 free(uuidstr);
14306 return error;