Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
80 {
81 sigint_received = 1;
82 }
84 static void
85 catch_sigpipe(int signo)
86 {
87 sigpipe_received = 1;
88 }
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
96 };
98 __dead static void usage(int, int);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_fetch(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_ref(void);
110 __dead static void usage_branch(void);
111 __dead static void usage_tag(void);
112 __dead static void usage_add(void);
113 __dead static void usage_remove(void);
114 __dead static void usage_patch(void);
115 __dead static void usage_revert(void);
116 __dead static void usage_commit(void);
117 __dead static void usage_send(void);
118 __dead static void usage_cherrypick(void);
119 __dead static void usage_backout(void);
120 __dead static void usage_rebase(void);
121 __dead static void usage_histedit(void);
122 __dead static void usage_integrate(void);
123 __dead static void usage_merge(void);
124 __dead static void usage_stage(void);
125 __dead static void usage_unstage(void);
126 __dead static void usage_cat(void);
127 __dead static void usage_info(void);
129 static const struct got_error* cmd_import(int, char *[]);
130 static const struct got_error* cmd_clone(int, char *[]);
131 static const struct got_error* cmd_fetch(int, char *[]);
132 static const struct got_error* cmd_checkout(int, char *[]);
133 static const struct got_error* cmd_update(int, char *[]);
134 static const struct got_error* cmd_log(int, char *[]);
135 static const struct got_error* cmd_diff(int, char *[]);
136 static const struct got_error* cmd_blame(int, char *[]);
137 static const struct got_error* cmd_tree(int, char *[]);
138 static const struct got_error* cmd_status(int, char *[]);
139 static const struct got_error* cmd_ref(int, char *[]);
140 static const struct got_error* cmd_branch(int, char *[]);
141 static const struct got_error* cmd_tag(int, char *[]);
142 static const struct got_error* cmd_add(int, char *[]);
143 static const struct got_error* cmd_remove(int, char *[]);
144 static const struct got_error* cmd_patch(int, char *[]);
145 static const struct got_error* cmd_revert(int, char *[]);
146 static const struct got_error* cmd_commit(int, char *[]);
147 static const struct got_error* cmd_send(int, char *[]);
148 static const struct got_error* cmd_cherrypick(int, char *[]);
149 static const struct got_error* cmd_backout(int, char *[]);
150 static const struct got_error* cmd_rebase(int, char *[]);
151 static const struct got_error* cmd_histedit(int, char *[]);
152 static const struct got_error* cmd_integrate(int, char *[]);
153 static const struct got_error* cmd_merge(int, char *[]);
154 static const struct got_error* cmd_stage(int, char *[]);
155 static const struct got_error* cmd_unstage(int, char *[]);
156 static const struct got_error* cmd_cat(int, char *[]);
157 static const struct got_error* cmd_info(int, char *[]);
159 static const struct got_cmd got_commands[] = {
160 { "import", cmd_import, usage_import, "im" },
161 { "clone", cmd_clone, usage_clone, "cl" },
162 { "fetch", cmd_fetch, usage_fetch, "fe" },
163 { "checkout", cmd_checkout, usage_checkout, "co" },
164 { "update", cmd_update, usage_update, "up" },
165 { "log", cmd_log, usage_log, "" },
166 { "diff", cmd_diff, usage_diff, "di" },
167 { "blame", cmd_blame, usage_blame, "bl" },
168 { "tree", cmd_tree, usage_tree, "tr" },
169 { "status", cmd_status, usage_status, "st" },
170 { "ref", cmd_ref, usage_ref, "" },
171 { "branch", cmd_branch, usage_branch, "br" },
172 { "tag", cmd_tag, usage_tag, "" },
173 { "add", cmd_add, usage_add, "" },
174 { "remove", cmd_remove, usage_remove, "rm" },
175 { "patch", cmd_patch, usage_patch, "pa" },
176 { "revert", cmd_revert, usage_revert, "rv" },
177 { "commit", cmd_commit, usage_commit, "ci" },
178 { "send", cmd_send, usage_send, "se" },
179 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
180 { "backout", cmd_backout, usage_backout, "bo" },
181 { "rebase", cmd_rebase, usage_rebase, "rb" },
182 { "histedit", cmd_histedit, usage_histedit, "he" },
183 { "integrate", cmd_integrate, usage_integrate,"ig" },
184 { "merge", cmd_merge, usage_merge, "mg" },
185 { "stage", cmd_stage, usage_stage, "sg" },
186 { "unstage", cmd_unstage, usage_unstage, "ug" },
187 { "cat", cmd_cat, usage_cat, "" },
188 { "info", cmd_info, usage_info, "" },
189 };
191 static void
192 list_commands(FILE *fp)
194 size_t i;
196 fprintf(fp, "commands:");
197 for (i = 0; i < nitems(got_commands); i++) {
198 const struct got_cmd *cmd = &got_commands[i];
199 fprintf(fp, " %s", cmd->cmd_name);
201 fputc('\n', fp);
204 __dead static void
205 option_conflict(char a, char b)
207 errx(1, "-%c and -%c options are mutually exclusive", a, b);
210 int
211 main(int argc, char *argv[])
213 const struct got_cmd *cmd;
214 size_t i;
215 int ch;
216 int hflag = 0, Vflag = 0;
217 static const struct option longopts[] = {
218 { "version", no_argument, NULL, 'V' },
219 { NULL, 0, NULL, 0 }
220 };
222 setlocale(LC_CTYPE, "");
224 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
225 switch (ch) {
226 case 'h':
227 hflag = 1;
228 break;
229 case 'V':
230 Vflag = 1;
231 break;
232 default:
233 usage(hflag, 1);
234 /* NOTREACHED */
238 argc -= optind;
239 argv += optind;
240 optind = 1;
241 optreset = 1;
243 if (Vflag) {
244 got_version_print_str();
245 return 0;
248 if (argc <= 0)
249 usage(hflag, hflag ? 0 : 1);
251 signal(SIGINT, catch_sigint);
252 signal(SIGPIPE, catch_sigpipe);
254 for (i = 0; i < nitems(got_commands); i++) {
255 const struct got_error *error;
257 cmd = &got_commands[i];
259 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
260 strcmp(cmd->cmd_alias, argv[0]) != 0)
261 continue;
263 if (hflag)
264 cmd->cmd_usage();
266 error = cmd->cmd_main(argc, argv);
267 if (error && error->code != GOT_ERR_CANCELLED &&
268 error->code != GOT_ERR_PRIVSEP_EXIT &&
269 !(sigpipe_received &&
270 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
271 !(sigint_received &&
272 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
273 fflush(stdout);
274 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
275 return 1;
278 return 0;
281 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
282 list_commands(stderr);
283 return 1;
286 __dead static void
287 usage(int hflag, int status)
289 FILE *fp = (status == 0) ? stdout : stderr;
291 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
292 getprogname());
293 if (hflag)
294 list_commands(fp);
295 exit(status);
298 static const struct got_error *
299 get_editor(char **abspath)
301 const struct got_error *err = NULL;
302 const char *editor;
304 *abspath = NULL;
306 editor = getenv("VISUAL");
307 if (editor == NULL)
308 editor = getenv("EDITOR");
310 if (editor) {
311 err = got_path_find_prog(abspath, editor);
312 if (err)
313 return err;
316 if (*abspath == NULL) {
317 *abspath = strdup(GOT_DEFAULT_EDITOR);
318 if (*abspath == NULL)
319 return got_error_from_errno("strdup");
322 return NULL;
325 static const struct got_error *
326 apply_unveil(const char *repo_path, int repo_read_only,
327 const char *worktree_path)
329 const struct got_error *err;
331 #ifdef PROFILE
332 if (unveil("gmon.out", "rwc") != 0)
333 return got_error_from_errno2("unveil", "gmon.out");
334 #endif
335 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
336 return got_error_from_errno2("unveil", repo_path);
338 if (worktree_path && unveil(worktree_path, "rwc") != 0)
339 return got_error_from_errno2("unveil", worktree_path);
341 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
342 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
344 err = got_privsep_unveil_exec_helpers();
345 if (err != NULL)
346 return err;
348 if (unveil(NULL, NULL) != 0)
349 return got_error_from_errno("unveil");
351 return NULL;
354 __dead static void
355 usage_import(void)
357 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
358 "[-r repository-path] directory\n", getprogname());
359 exit(1);
362 static int
363 spawn_editor(const char *editor, const char *file)
365 pid_t pid;
366 sig_t sighup, sigint, sigquit;
367 int st = -1;
369 sighup = signal(SIGHUP, SIG_IGN);
370 sigint = signal(SIGINT, SIG_IGN);
371 sigquit = signal(SIGQUIT, SIG_IGN);
373 switch (pid = fork()) {
374 case -1:
375 goto doneediting;
376 case 0:
377 execl(editor, editor, file, (char *)NULL);
378 _exit(127);
381 while (waitpid(pid, &st, 0) == -1)
382 if (errno != EINTR)
383 break;
385 doneediting:
386 (void)signal(SIGHUP, sighup);
387 (void)signal(SIGINT, sigint);
388 (void)signal(SIGQUIT, sigquit);
390 if (!WIFEXITED(st)) {
391 errno = EINTR;
392 return -1;
395 return WEXITSTATUS(st);
398 static const struct got_error *
399 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
401 const struct got_error *err = NULL;
402 char *line = NULL;
403 size_t linesize = 0;
405 *logmsg = NULL;
406 *len = 0;
408 if (fseeko(fp, 0L, SEEK_SET) == -1)
409 return got_error_from_errno("fseeko");
411 *logmsg = malloc(filesize + 1);
412 if (*logmsg == NULL)
413 return got_error_from_errno("malloc");
414 (*logmsg)[0] = '\0';
416 while (getline(&line, &linesize, fp) != -1) {
417 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
418 continue; /* remove comments and leading empty lines */
419 *len = strlcat(*logmsg, line, filesize + 1);
420 if (*len >= filesize + 1) {
421 err = got_error(GOT_ERR_NO_SPACE);
422 goto done;
425 if (ferror(fp)) {
426 err = got_ferror(fp, GOT_ERR_IO);
427 goto done;
430 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
431 (*logmsg)[*len - 1] = '\0';
432 (*len)--;
434 done:
435 free(line);
436 if (err) {
437 free(*logmsg);
438 *logmsg = NULL;
439 *len = 0;
441 return err;
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 struct stat st, st2;
451 FILE *fp = NULL;
452 size_t logmsg_len;
454 *logmsg = NULL;
456 if (stat(logmsg_path, &st) == -1)
457 return got_error_from_errno2("stat", logmsg_path);
459 if (spawn_editor(editor, logmsg_path) == -1)
460 return got_error_from_errno("failed spawning editor");
462 if (require_modification) {
463 struct timespec timeout;
465 timeout.tv_sec = 0;
466 timeout.tv_nsec = 1;
467 nanosleep(&timeout, NULL);
470 if (stat(logmsg_path, &st2) == -1)
471 return got_error_from_errno2("stat", logmsg_path);
473 if (require_modification && st.st_size == st2.st_size &&
474 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
475 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "no changes made to commit message, aborting");
478 fp = fopen(logmsg_path, "re");
479 if (fp == NULL) {
480 err = got_error_from_errno("fopen");
481 goto done;
484 /* strip comments and leading/trailing newlines */
485 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
486 if (err)
487 goto done;
488 if (logmsg_len == 0) {
489 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
490 "commit message cannot be empty, aborting");
491 goto done;
493 done:
494 if (fp && fclose(fp) == EOF && err == NULL)
495 err = got_error_from_errno("fclose");
496 if (err) {
497 free(*logmsg);
498 *logmsg = NULL;
500 return err;
503 static const struct got_error *
504 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
505 const char *path_dir, const char *branch_name)
507 char *initial_content = NULL;
508 const struct got_error *err = NULL;
509 int initial_content_len;
510 int fd = -1;
512 initial_content_len = asprintf(&initial_content,
513 "\n# %s to be imported to branch %s\n", path_dir,
514 branch_name);
515 if (initial_content_len == -1)
516 return got_error_from_errno("asprintf");
518 err = got_opentemp_named_fd(logmsg_path, &fd,
519 GOT_TMPDIR_STR "/got-importmsg", "");
520 if (err)
521 goto done;
523 if (write(fd, initial_content, initial_content_len) == -1) {
524 err = got_error_from_errno2("write", *logmsg_path);
525 goto done;
527 if (close(fd) == -1) {
528 err = got_error_from_errno2("close", *logmsg_path);
529 goto done;
531 fd = -1;
533 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
534 initial_content_len, 1);
535 done:
536 if (fd != -1 && close(fd) == -1 && err == NULL)
537 err = got_error_from_errno2("close", *logmsg_path);
538 free(initial_content);
539 if (err) {
540 free(*logmsg_path);
541 *logmsg_path = NULL;
543 return err;
546 static const struct got_error *
547 import_progress(void *arg, const char *path)
549 printf("A %s\n", path);
550 return NULL;
553 static const struct got_error *
554 valid_author(const char *author)
556 const char *email = author;
558 /*
559 * Git' expects the author (or committer) to be in the form
560 * "name <email>", which are mostly free form (see the
561 * "committer" description in git-fast-import(1)). We're only
562 * doing this to avoid git's object parser breaking on commits
563 * we create.
564 */
566 while (*author && *author != '\n' && *author != '<' && *author != '>')
567 author++;
568 if (author != email && *author == '<' && *(author - 1) != ' ')
569 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
570 "between author name and email required", email);
571 if (*author++ != '<')
572 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
573 while (*author && *author != '\n' && *author != '<' && *author != '>')
574 author++;
575 if (strcmp(author, ">") != 0)
576 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
577 return NULL;
580 static const struct got_error *
581 get_author(char **author, struct got_repository *repo,
582 struct got_worktree *worktree)
584 const struct got_error *err = NULL;
585 const char *got_author = NULL, *name, *email;
586 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
588 *author = NULL;
590 if (worktree)
591 worktree_conf = got_worktree_get_gotconfig(worktree);
592 repo_conf = got_repo_get_gotconfig(repo);
594 /*
595 * Priority of potential author information sources, from most
596 * significant to least significant:
597 * 1) work tree's .got/got.conf file
598 * 2) repository's got.conf file
599 * 3) repository's git config file
600 * 4) environment variables
601 * 5) global git config files (in user's home directory or /etc)
602 */
604 if (worktree_conf)
605 got_author = got_gotconfig_get_author(worktree_conf);
606 if (got_author == NULL)
607 got_author = got_gotconfig_get_author(repo_conf);
608 if (got_author == NULL) {
609 name = got_repo_get_gitconfig_author_name(repo);
610 email = got_repo_get_gitconfig_author_email(repo);
611 if (name && email) {
612 if (asprintf(author, "%s <%s>", name, email) == -1)
613 return got_error_from_errno("asprintf");
614 return NULL;
617 got_author = getenv("GOT_AUTHOR");
618 if (got_author == NULL) {
619 name = got_repo_get_global_gitconfig_author_name(repo);
620 email = got_repo_get_global_gitconfig_author_email(
621 repo);
622 if (name && email) {
623 if (asprintf(author, "%s <%s>", name, email)
624 == -1)
625 return got_error_from_errno("asprintf");
626 return NULL;
628 /* TODO: Look up user in password database? */
629 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
633 *author = strdup(got_author);
634 if (*author == NULL)
635 return got_error_from_errno("strdup");
637 err = valid_author(*author);
638 if (err) {
639 free(*author);
640 *author = NULL;
642 return err;
645 static const struct got_error *
646 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
647 struct got_worktree *worktree)
649 const char *got_allowed_signers = NULL;
650 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
652 *allowed_signers = NULL;
654 if (worktree)
655 worktree_conf = got_worktree_get_gotconfig(worktree);
656 repo_conf = got_repo_get_gotconfig(repo);
658 /*
659 * Priority of potential author information sources, from most
660 * significant to least significant:
661 * 1) work tree's .got/got.conf file
662 * 2) repository's got.conf file
663 */
665 if (worktree_conf)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 worktree_conf);
668 if (got_allowed_signers == NULL)
669 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
670 repo_conf);
672 if (got_allowed_signers) {
673 *allowed_signers = strdup(got_allowed_signers);
674 if (*allowed_signers == NULL)
675 return got_error_from_errno("strdup");
677 return NULL;
680 static const struct got_error *
681 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
682 struct got_worktree *worktree)
684 const char *got_revoked_signers = NULL;
685 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
687 *revoked_signers = NULL;
689 if (worktree)
690 worktree_conf = got_worktree_get_gotconfig(worktree);
691 repo_conf = got_repo_get_gotconfig(repo);
693 /*
694 * Priority of potential author information sources, from most
695 * significant to least significant:
696 * 1) work tree's .got/got.conf file
697 * 2) repository's got.conf file
698 */
700 if (worktree_conf)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 worktree_conf);
703 if (got_revoked_signers == NULL)
704 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
705 repo_conf);
707 if (got_revoked_signers) {
708 *revoked_signers = strdup(got_revoked_signers);
709 if (*revoked_signers == NULL)
710 return got_error_from_errno("strdup");
712 return NULL;
715 static const char *
716 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
718 const char *got_signer_id = NULL;
719 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 return got_signer_id;
740 static const struct got_error *
741 get_gitconfig_path(char **gitconfig_path)
743 const char *homedir = getenv("HOME");
745 *gitconfig_path = NULL;
746 if (homedir) {
747 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
748 return got_error_from_errno("asprintf");
751 return NULL;
754 static const struct got_error *
755 cmd_import(int argc, char *argv[])
757 const struct got_error *error = NULL;
758 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
759 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
760 const char *branch_name = NULL;
761 char *id_str = NULL, *logmsg_path = NULL;
762 char refname[PATH_MAX] = "refs/heads/";
763 struct got_repository *repo = NULL;
764 struct got_reference *branch_ref = NULL, *head_ref = NULL;
765 struct got_object_id *new_commit_id = NULL;
766 int ch, n = 0;
767 struct got_pathlist_head ignores;
768 struct got_pathlist_entry *pe;
769 int preserve_logmsg = 0;
770 int *pack_fds = NULL;
772 TAILQ_INIT(&ignores);
774 #ifndef PROFILE
775 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
776 "unveil",
777 NULL) == -1)
778 err(1, "pledge");
779 #endif
781 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
782 switch (ch) {
783 case 'b':
784 branch_name = optarg;
785 break;
786 case 'I':
787 if (optarg[0] == '\0')
788 break;
789 error = got_pathlist_insert(&pe, &ignores, optarg,
790 NULL);
791 if (error)
792 goto done;
793 break;
794 case 'm':
795 logmsg = strdup(optarg);
796 if (logmsg == NULL) {
797 error = got_error_from_errno("strdup");
798 goto done;
800 break;
801 case 'r':
802 repo_path = realpath(optarg, NULL);
803 if (repo_path == NULL) {
804 error = got_error_from_errno2("realpath",
805 optarg);
806 goto done;
808 break;
809 default:
810 usage_import();
811 /* NOTREACHED */
815 argc -= optind;
816 argv += optind;
818 if (argc != 1)
819 usage_import();
821 if (repo_path == NULL) {
822 repo_path = getcwd(NULL, 0);
823 if (repo_path == NULL)
824 return got_error_from_errno("getcwd");
826 got_path_strip_trailing_slashes(repo_path);
827 error = get_gitconfig_path(&gitconfig_path);
828 if (error)
829 goto done;
830 error = got_repo_pack_fds_open(&pack_fds);
831 if (error != NULL)
832 goto done;
833 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
834 if (error)
835 goto done;
837 error = get_author(&author, repo, NULL);
838 if (error)
839 return error;
841 /*
842 * Don't let the user create a branch name with a leading '-'.
843 * While technically a valid reference name, this case is usually
844 * an unintended typo.
845 */
846 if (branch_name && branch_name[0] == '-')
847 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
849 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
850 if (error && error->code != GOT_ERR_NOT_REF)
851 goto done;
853 if (branch_name)
854 n = strlcat(refname, branch_name, sizeof(refname));
855 else if (head_ref && got_ref_is_symbolic(head_ref))
856 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
857 sizeof(refname));
858 else
859 n = strlcat(refname, "main", sizeof(refname));
860 if (n >= sizeof(refname)) {
861 error = got_error(GOT_ERR_NO_SPACE);
862 goto done;
865 error = got_ref_open(&branch_ref, repo, refname, 0);
866 if (error) {
867 if (error->code != GOT_ERR_NOT_REF)
868 goto done;
869 } else {
870 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
871 "import target branch already exists");
872 goto done;
875 path_dir = realpath(argv[0], NULL);
876 if (path_dir == NULL) {
877 error = got_error_from_errno2("realpath", argv[0]);
878 goto done;
880 got_path_strip_trailing_slashes(path_dir);
882 /*
883 * unveil(2) traverses exec(2); if an editor is used we have
884 * to apply unveil after the log message has been written.
885 */
886 if (logmsg == NULL || *logmsg == '\0') {
887 error = get_editor(&editor);
888 if (error)
889 goto done;
890 free(logmsg);
891 error = collect_import_msg(&logmsg, &logmsg_path, editor,
892 path_dir, refname);
893 if (error) {
894 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
895 logmsg_path != NULL)
896 preserve_logmsg = 1;
897 goto done;
901 if (unveil(path_dir, "r") != 0) {
902 error = got_error_from_errno2("unveil", path_dir);
903 if (logmsg_path)
904 preserve_logmsg = 1;
905 goto done;
908 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
909 if (error) {
910 if (logmsg_path)
911 preserve_logmsg = 1;
912 goto done;
915 error = got_repo_import(&new_commit_id, path_dir, logmsg,
916 author, &ignores, repo, import_progress, NULL);
917 if (error) {
918 if (logmsg_path)
919 preserve_logmsg = 1;
920 goto done;
923 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
924 if (error) {
925 if (logmsg_path)
926 preserve_logmsg = 1;
927 goto done;
930 error = got_ref_write(branch_ref, repo);
931 if (error) {
932 if (logmsg_path)
933 preserve_logmsg = 1;
934 goto done;
937 error = got_object_id_str(&id_str, new_commit_id);
938 if (error) {
939 if (logmsg_path)
940 preserve_logmsg = 1;
941 goto done;
944 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
945 if (error) {
946 if (error->code != GOT_ERR_NOT_REF) {
947 if (logmsg_path)
948 preserve_logmsg = 1;
949 goto done;
952 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
953 branch_ref);
954 if (error) {
955 if (logmsg_path)
956 preserve_logmsg = 1;
957 goto done;
960 error = got_ref_write(head_ref, repo);
961 if (error) {
962 if (logmsg_path)
963 preserve_logmsg = 1;
964 goto done;
968 printf("Created branch %s with commit %s\n",
969 got_ref_get_name(branch_ref), id_str);
970 done:
971 if (pack_fds) {
972 const struct got_error *pack_err =
973 got_repo_pack_fds_close(pack_fds);
974 if (error == NULL)
975 error = pack_err;
977 if (repo) {
978 const struct got_error *close_err = got_repo_close(repo);
979 if (error == NULL)
980 error = close_err;
982 if (preserve_logmsg) {
983 fprintf(stderr, "%s: log message preserved in %s\n",
984 getprogname(), logmsg_path);
985 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
986 error = got_error_from_errno2("unlink", logmsg_path);
987 free(logmsg);
988 free(logmsg_path);
989 free(repo_path);
990 free(editor);
991 free(new_commit_id);
992 free(id_str);
993 free(author);
994 free(gitconfig_path);
995 if (branch_ref)
996 got_ref_close(branch_ref);
997 if (head_ref)
998 got_ref_close(head_ref);
999 return error;
1002 __dead static void
1003 usage_clone(void)
1005 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1006 "repository-URL [directory]\n", getprogname());
1007 exit(1);
1010 struct got_fetch_progress_arg {
1011 char last_scaled_size[FMT_SCALED_STRSIZE];
1012 int last_p_indexed;
1013 int last_p_resolved;
1014 int verbosity;
1016 struct got_repository *repo;
1018 int create_configs;
1019 int configs_created;
1020 struct {
1021 struct got_pathlist_head *symrefs;
1022 struct got_pathlist_head *wanted_branches;
1023 struct got_pathlist_head *wanted_refs;
1024 const char *proto;
1025 const char *host;
1026 const char *port;
1027 const char *remote_repo_path;
1028 const char *git_url;
1029 int fetch_all_branches;
1030 int mirror_references;
1031 } config_info;
1034 /* XXX forward declaration */
1035 static const struct got_error *
1036 create_config_files(const char *proto, const char *host, const char *port,
1037 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1038 int mirror_references, struct got_pathlist_head *symrefs,
1039 struct got_pathlist_head *wanted_branches,
1040 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1042 static const struct got_error *
1043 fetch_progress(void *arg, const char *message, off_t packfile_size,
1044 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1046 const struct got_error *err = NULL;
1047 struct got_fetch_progress_arg *a = arg;
1048 char scaled_size[FMT_SCALED_STRSIZE];
1049 int p_indexed, p_resolved;
1050 int print_size = 0, print_indexed = 0, print_resolved = 0;
1053 * In order to allow a failed clone to be resumed with 'got fetch'
1054 * we try to create configuration files as soon as possible.
1055 * Once the server has sent information about its default branch
1056 * we have all required information.
1058 if (a->create_configs && !a->configs_created &&
1059 !TAILQ_EMPTY(a->config_info.symrefs)) {
1060 err = create_config_files(a->config_info.proto,
1061 a->config_info.host, a->config_info.port,
1062 a->config_info.remote_repo_path,
1063 a->config_info.git_url,
1064 a->config_info.fetch_all_branches,
1065 a->config_info.mirror_references,
1066 a->config_info.symrefs,
1067 a->config_info.wanted_branches,
1068 a->config_info.wanted_refs, a->repo);
1069 if (err)
1070 return err;
1071 a->configs_created = 1;
1074 if (a->verbosity < 0)
1075 return NULL;
1077 if (message && message[0] != '\0') {
1078 printf("\rserver: %s", message);
1079 fflush(stdout);
1080 return NULL;
1083 if (packfile_size > 0 || nobj_indexed > 0) {
1084 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1085 (a->last_scaled_size[0] == '\0' ||
1086 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1087 print_size = 1;
1088 if (strlcpy(a->last_scaled_size, scaled_size,
1089 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1090 return got_error(GOT_ERR_NO_SPACE);
1092 if (nobj_indexed > 0) {
1093 p_indexed = (nobj_indexed * 100) / nobj_total;
1094 if (p_indexed != a->last_p_indexed) {
1095 a->last_p_indexed = p_indexed;
1096 print_indexed = 1;
1097 print_size = 1;
1100 if (nobj_resolved > 0) {
1101 p_resolved = (nobj_resolved * 100) /
1102 (nobj_total - nobj_loose);
1103 if (p_resolved != a->last_p_resolved) {
1104 a->last_p_resolved = p_resolved;
1105 print_resolved = 1;
1106 print_indexed = 1;
1107 print_size = 1;
1112 if (print_size || print_indexed || print_resolved)
1113 printf("\r");
1114 if (print_size)
1115 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1116 if (print_indexed)
1117 printf("; indexing %d%%", p_indexed);
1118 if (print_resolved)
1119 printf("; resolving deltas %d%%", p_resolved);
1120 if (print_size || print_indexed || print_resolved)
1121 fflush(stdout);
1123 return NULL;
1126 static const struct got_error *
1127 create_symref(const char *refname, struct got_reference *target_ref,
1128 int verbosity, struct got_repository *repo)
1130 const struct got_error *err;
1131 struct got_reference *head_symref;
1133 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1134 if (err)
1135 return err;
1137 err = got_ref_write(head_symref, repo);
1138 if (err == NULL && verbosity > 0) {
1139 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1140 got_ref_get_name(target_ref));
1142 got_ref_close(head_symref);
1143 return err;
1146 static const struct got_error *
1147 list_remote_refs(struct got_pathlist_head *symrefs,
1148 struct got_pathlist_head *refs)
1150 const struct got_error *err;
1151 struct got_pathlist_entry *pe;
1153 TAILQ_FOREACH(pe, symrefs, entry) {
1154 const char *refname = pe->path;
1155 const char *targetref = pe->data;
1157 printf("%s: %s\n", refname, targetref);
1160 TAILQ_FOREACH(pe, refs, entry) {
1161 const char *refname = pe->path;
1162 struct got_object_id *id = pe->data;
1163 char *id_str;
1165 err = got_object_id_str(&id_str, id);
1166 if (err)
1167 return err;
1168 printf("%s: %s\n", refname, id_str);
1169 free(id_str);
1172 return NULL;
1175 static const struct got_error *
1176 create_ref(const char *refname, struct got_object_id *id,
1177 int verbosity, struct got_repository *repo)
1179 const struct got_error *err = NULL;
1180 struct got_reference *ref;
1181 char *id_str;
1183 err = got_object_id_str(&id_str, id);
1184 if (err)
1185 return err;
1187 err = got_ref_alloc(&ref, refname, id);
1188 if (err)
1189 goto done;
1191 err = got_ref_write(ref, repo);
1192 got_ref_close(ref);
1194 if (err == NULL && verbosity >= 0)
1195 printf("Created reference %s: %s\n", refname, id_str);
1196 done:
1197 free(id_str);
1198 return err;
1201 static int
1202 match_wanted_ref(const char *refname, const char *wanted_ref)
1204 if (strncmp(refname, "refs/", 5) != 0)
1205 return 0;
1206 refname += 5;
1209 * Prevent fetching of references that won't make any
1210 * sense outside of the remote repository's context.
1212 if (strncmp(refname, "got/", 4) == 0)
1213 return 0;
1214 if (strncmp(refname, "remotes/", 8) == 0)
1215 return 0;
1217 if (strncmp(wanted_ref, "refs/", 5) == 0)
1218 wanted_ref += 5;
1220 /* Allow prefix match. */
1221 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1222 return 1;
1224 /* Allow exact match. */
1225 return (strcmp(refname, wanted_ref) == 0);
1228 static int
1229 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1231 struct got_pathlist_entry *pe;
1233 TAILQ_FOREACH(pe, wanted_refs, entry) {
1234 if (match_wanted_ref(refname, pe->path))
1235 return 1;
1238 return 0;
1241 static const struct got_error *
1242 create_wanted_ref(const char *refname, struct got_object_id *id,
1243 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1245 const struct got_error *err;
1246 char *remote_refname;
1248 if (strncmp("refs/", refname, 5) == 0)
1249 refname += 5;
1251 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1252 remote_repo_name, refname) == -1)
1253 return got_error_from_errno("asprintf");
1255 err = create_ref(remote_refname, id, verbosity, repo);
1256 free(remote_refname);
1257 return err;
1260 static const struct got_error *
1261 create_gotconfig(const char *proto, const char *host, const char *port,
1262 const char *remote_repo_path, const char *default_branch,
1263 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1264 struct got_pathlist_head *wanted_refs, int mirror_references,
1265 struct got_repository *repo)
1267 const struct got_error *err = NULL;
1268 char *gotconfig_path = NULL;
1269 char *gotconfig = NULL;
1270 FILE *gotconfig_file = NULL;
1271 const char *branchname = NULL;
1272 char *branches = NULL, *refs = NULL;
1273 ssize_t n;
1275 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1276 struct got_pathlist_entry *pe;
1277 TAILQ_FOREACH(pe, wanted_branches, entry) {
1278 char *s;
1279 branchname = pe->path;
1280 if (strncmp(branchname, "refs/heads/", 11) == 0)
1281 branchname += 11;
1282 if (asprintf(&s, "%s\"%s\" ",
1283 branches ? branches : "", branchname) == -1) {
1284 err = got_error_from_errno("asprintf");
1285 goto done;
1287 free(branches);
1288 branches = s;
1290 } else if (!fetch_all_branches && default_branch) {
1291 branchname = default_branch;
1292 if (strncmp(branchname, "refs/heads/", 11) == 0)
1293 branchname += 11;
1294 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1295 err = got_error_from_errno("asprintf");
1296 goto done;
1299 if (!TAILQ_EMPTY(wanted_refs)) {
1300 struct got_pathlist_entry *pe;
1301 TAILQ_FOREACH(pe, wanted_refs, entry) {
1302 char *s;
1303 const char *refname = pe->path;
1304 if (strncmp(refname, "refs/", 5) == 0)
1305 branchname += 5;
1306 if (asprintf(&s, "%s\"%s\" ",
1307 refs ? refs : "", refname) == -1) {
1308 err = got_error_from_errno("asprintf");
1309 goto done;
1311 free(refs);
1312 refs = s;
1316 /* Create got.conf(5). */
1317 gotconfig_path = got_repo_get_path_gotconfig(repo);
1318 if (gotconfig_path == NULL) {
1319 err = got_error_from_errno("got_repo_get_path_gotconfig");
1320 goto done;
1322 gotconfig_file = fopen(gotconfig_path, "ae");
1323 if (gotconfig_file == NULL) {
1324 err = got_error_from_errno2("fopen", gotconfig_path);
1325 goto done;
1327 if (asprintf(&gotconfig,
1328 "remote \"%s\" {\n"
1329 "\tserver %s\n"
1330 "\tprotocol %s\n"
1331 "%s%s%s"
1332 "\trepository \"%s\"\n"
1333 "%s%s%s"
1334 "%s%s%s"
1335 "%s"
1336 "%s"
1337 "}\n",
1338 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1339 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1340 remote_repo_path, branches ? "\tbranch { " : "",
1341 branches ? branches : "", branches ? "}\n" : "",
1342 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1343 mirror_references ? "\tmirror_references yes\n" : "",
1344 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1345 err = got_error_from_errno("asprintf");
1346 goto done;
1348 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1349 if (n != strlen(gotconfig)) {
1350 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1351 goto done;
1354 done:
1355 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1356 err = got_error_from_errno2("fclose", gotconfig_path);
1357 free(gotconfig_path);
1358 free(branches);
1359 return err;
1362 static const struct got_error *
1363 create_gitconfig(const char *git_url, const char *default_branch,
1364 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1365 struct got_pathlist_head *wanted_refs, int mirror_references,
1366 struct got_repository *repo)
1368 const struct got_error *err = NULL;
1369 char *gitconfig_path = NULL;
1370 char *gitconfig = NULL;
1371 FILE *gitconfig_file = NULL;
1372 char *branches = NULL, *refs = NULL;
1373 const char *branchname;
1374 ssize_t n;
1376 /* Create a config file Git can understand. */
1377 gitconfig_path = got_repo_get_path_gitconfig(repo);
1378 if (gitconfig_path == NULL) {
1379 err = got_error_from_errno("got_repo_get_path_gitconfig");
1380 goto done;
1382 gitconfig_file = fopen(gitconfig_path, "ae");
1383 if (gitconfig_file == NULL) {
1384 err = got_error_from_errno2("fopen", gitconfig_path);
1385 goto done;
1387 if (fetch_all_branches) {
1388 if (mirror_references) {
1389 if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 } else if (asprintf(&branches,
1395 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1396 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 } else if (!TAILQ_EMPTY(wanted_branches)) {
1401 struct got_pathlist_entry *pe;
1402 TAILQ_FOREACH(pe, wanted_branches, entry) {
1403 char *s;
1404 branchname = pe->path;
1405 if (strncmp(branchname, "refs/heads/", 11) == 0)
1406 branchname += 11;
1407 if (mirror_references) {
1408 if (asprintf(&s,
1409 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1410 branches ? branches : "",
1411 branchname, branchname) == -1) {
1412 err = got_error_from_errno("asprintf");
1413 goto done;
1415 } else if (asprintf(&s,
1416 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1417 branches ? branches : "",
1418 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1419 branchname) == -1) {
1420 err = got_error_from_errno("asprintf");
1421 goto done;
1423 free(branches);
1424 branches = s;
1426 } else {
1428 * If the server specified a default branch, use just that one.
1429 * Otherwise fall back to fetching all branches on next fetch.
1431 if (default_branch) {
1432 branchname = default_branch;
1433 if (strncmp(branchname, "refs/heads/", 11) == 0)
1434 branchname += 11;
1435 } else
1436 branchname = "*"; /* fall back to all branches */
1437 if (mirror_references) {
1438 if (asprintf(&branches,
1439 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1440 branchname, branchname) == -1) {
1441 err = got_error_from_errno("asprintf");
1442 goto done;
1444 } else if (asprintf(&branches,
1445 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1446 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1447 branchname) == -1) {
1448 err = got_error_from_errno("asprintf");
1449 goto done;
1452 if (!TAILQ_EMPTY(wanted_refs)) {
1453 struct got_pathlist_entry *pe;
1454 TAILQ_FOREACH(pe, wanted_refs, entry) {
1455 char *s;
1456 const char *refname = pe->path;
1457 if (strncmp(refname, "refs/", 5) == 0)
1458 refname += 5;
1459 if (mirror_references) {
1460 if (asprintf(&s,
1461 "%s\tfetch = refs/%s:refs/%s\n",
1462 refs ? refs : "", refname, refname) == -1) {
1463 err = got_error_from_errno("asprintf");
1464 goto done;
1466 } else if (asprintf(&s,
1467 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1468 refs ? refs : "",
1469 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1470 refname) == -1) {
1471 err = got_error_from_errno("asprintf");
1472 goto done;
1474 free(refs);
1475 refs = s;
1479 if (asprintf(&gitconfig,
1480 "[remote \"%s\"]\n"
1481 "\turl = %s\n"
1482 "%s"
1483 "%s"
1484 "\tfetch = refs/tags/*:refs/tags/*\n",
1485 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1486 refs ? refs : "") == -1) {
1487 err = got_error_from_errno("asprintf");
1488 goto done;
1490 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1491 if (n != strlen(gitconfig)) {
1492 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1493 goto done;
1495 done:
1496 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1497 err = got_error_from_errno2("fclose", gitconfig_path);
1498 free(gitconfig_path);
1499 free(branches);
1500 return err;
1503 static const struct got_error *
1504 create_config_files(const char *proto, const char *host, const char *port,
1505 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1506 int mirror_references, struct got_pathlist_head *symrefs,
1507 struct got_pathlist_head *wanted_branches,
1508 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1510 const struct got_error *err = NULL;
1511 const char *default_branch = NULL;
1512 struct got_pathlist_entry *pe;
1515 * If we asked for a set of wanted branches then use the first
1516 * one of those.
1518 if (!TAILQ_EMPTY(wanted_branches)) {
1519 pe = TAILQ_FIRST(wanted_branches);
1520 default_branch = pe->path;
1521 } else {
1522 /* First HEAD ref listed by server is the default branch. */
1523 TAILQ_FOREACH(pe, symrefs, entry) {
1524 const char *refname = pe->path;
1525 const char *target = pe->data;
1527 if (strcmp(refname, GOT_REF_HEAD) != 0)
1528 continue;
1530 default_branch = target;
1531 break;
1535 /* Create got.conf(5). */
1536 err = create_gotconfig(proto, host, port, remote_repo_path,
1537 default_branch, fetch_all_branches, wanted_branches,
1538 wanted_refs, mirror_references, repo);
1539 if (err)
1540 return err;
1542 /* Create a config file Git can understand. */
1543 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1544 wanted_branches, wanted_refs, mirror_references, repo);
1547 static const struct got_error *
1548 cmd_clone(int argc, char *argv[])
1550 const struct got_error *error = NULL;
1551 const char *uri, *dirname;
1552 char *proto, *host, *port, *repo_name, *server_path;
1553 char *default_destdir = NULL, *id_str = NULL;
1554 const char *repo_path;
1555 struct got_repository *repo = NULL;
1556 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1557 struct got_pathlist_entry *pe;
1558 struct got_object_id *pack_hash = NULL;
1559 int ch, fetchfd = -1, fetchstatus;
1560 pid_t fetchpid = -1;
1561 struct got_fetch_progress_arg fpa;
1562 char *git_url = NULL;
1563 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1564 int bflag = 0, list_refs_only = 0;
1565 int *pack_fds = NULL;
1567 TAILQ_INIT(&refs);
1568 TAILQ_INIT(&symrefs);
1569 TAILQ_INIT(&wanted_branches);
1570 TAILQ_INIT(&wanted_refs);
1572 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1573 switch (ch) {
1574 case 'a':
1575 fetch_all_branches = 1;
1576 break;
1577 case 'b':
1578 error = got_pathlist_append(&wanted_branches,
1579 optarg, NULL);
1580 if (error)
1581 return error;
1582 bflag = 1;
1583 break;
1584 case 'l':
1585 list_refs_only = 1;
1586 break;
1587 case 'm':
1588 mirror_references = 1;
1589 break;
1590 case 'q':
1591 verbosity = -1;
1592 break;
1593 case 'R':
1594 error = got_pathlist_append(&wanted_refs,
1595 optarg, NULL);
1596 if (error)
1597 return error;
1598 break;
1599 case 'v':
1600 if (verbosity < 0)
1601 verbosity = 0;
1602 else if (verbosity < 3)
1603 verbosity++;
1604 break;
1605 default:
1606 usage_clone();
1607 break;
1610 argc -= optind;
1611 argv += optind;
1613 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1614 option_conflict('a', 'b');
1615 if (list_refs_only) {
1616 if (!TAILQ_EMPTY(&wanted_branches))
1617 option_conflict('l', 'b');
1618 if (fetch_all_branches)
1619 option_conflict('l', 'a');
1620 if (mirror_references)
1621 option_conflict('l', 'm');
1622 if (!TAILQ_EMPTY(&wanted_refs))
1623 option_conflict('l', 'R');
1626 uri = argv[0];
1628 if (argc == 1)
1629 dirname = NULL;
1630 else if (argc == 2)
1631 dirname = argv[1];
1632 else
1633 usage_clone();
1635 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1636 &repo_name, uri);
1637 if (error)
1638 goto done;
1640 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1641 host, port ? ":" : "", port ? port : "",
1642 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1643 error = got_error_from_errno("asprintf");
1644 goto done;
1647 if (strcmp(proto, "git") == 0) {
1648 #ifndef PROFILE
1649 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1650 "sendfd dns inet unveil", NULL) == -1)
1651 err(1, "pledge");
1652 #endif
1653 } else if (strcmp(proto, "git+ssh") == 0 ||
1654 strcmp(proto, "ssh") == 0) {
1655 #ifndef PROFILE
1656 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1657 "sendfd unveil", NULL) == -1)
1658 err(1, "pledge");
1659 #endif
1660 } else if (strcmp(proto, "http") == 0 ||
1661 strcmp(proto, "git+http") == 0) {
1662 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1663 goto done;
1664 } else {
1665 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1666 goto done;
1668 if (dirname == NULL) {
1669 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1670 error = got_error_from_errno("asprintf");
1671 goto done;
1673 repo_path = default_destdir;
1674 } else
1675 repo_path = dirname;
1677 if (!list_refs_only) {
1678 error = got_path_mkdir(repo_path);
1679 if (error &&
1680 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1681 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1682 goto done;
1683 if (!got_path_dir_is_empty(repo_path)) {
1684 error = got_error_path(repo_path,
1685 GOT_ERR_DIR_NOT_EMPTY);
1686 goto done;
1690 error = got_dial_apply_unveil(proto);
1691 if (error)
1692 goto done;
1694 error = apply_unveil(repo_path, 0, NULL);
1695 if (error)
1696 goto done;
1698 if (verbosity >= 0)
1699 printf("Connecting to %s\n", git_url);
1701 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1702 server_path, verbosity);
1703 if (error)
1704 goto done;
1706 if (!list_refs_only) {
1707 error = got_repo_init(repo_path, NULL);
1708 if (error)
1709 goto done;
1710 error = got_repo_pack_fds_open(&pack_fds);
1711 if (error != NULL)
1712 goto done;
1713 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1714 if (error)
1715 goto done;
1718 fpa.last_scaled_size[0] = '\0';
1719 fpa.last_p_indexed = -1;
1720 fpa.last_p_resolved = -1;
1721 fpa.verbosity = verbosity;
1722 fpa.create_configs = 1;
1723 fpa.configs_created = 0;
1724 fpa.repo = repo;
1725 fpa.config_info.symrefs = &symrefs;
1726 fpa.config_info.wanted_branches = &wanted_branches;
1727 fpa.config_info.wanted_refs = &wanted_refs;
1728 fpa.config_info.proto = proto;
1729 fpa.config_info.host = host;
1730 fpa.config_info.port = port;
1731 fpa.config_info.remote_repo_path = server_path;
1732 fpa.config_info.git_url = git_url;
1733 fpa.config_info.fetch_all_branches = fetch_all_branches;
1734 fpa.config_info.mirror_references = mirror_references;
1735 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1736 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1737 fetch_all_branches, &wanted_branches, &wanted_refs,
1738 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1739 fetch_progress, &fpa);
1740 if (error)
1741 goto done;
1743 if (list_refs_only) {
1744 error = list_remote_refs(&symrefs, &refs);
1745 goto done;
1748 if (pack_hash == NULL) {
1749 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1750 "server sent an empty pack file");
1751 goto done;
1753 error = got_object_id_str(&id_str, pack_hash);
1754 if (error)
1755 goto done;
1756 if (verbosity >= 0)
1757 printf("\nFetched %s.pack\n", id_str);
1758 free(id_str);
1760 /* Set up references provided with the pack file. */
1761 TAILQ_FOREACH(pe, &refs, entry) {
1762 const char *refname = pe->path;
1763 struct got_object_id *id = pe->data;
1764 char *remote_refname;
1766 if (is_wanted_ref(&wanted_refs, refname) &&
1767 !mirror_references) {
1768 error = create_wanted_ref(refname, id,
1769 GOT_FETCH_DEFAULT_REMOTE_NAME,
1770 verbosity - 1, repo);
1771 if (error)
1772 goto done;
1773 continue;
1776 error = create_ref(refname, id, verbosity - 1, repo);
1777 if (error)
1778 goto done;
1780 if (mirror_references)
1781 continue;
1783 if (strncmp("refs/heads/", refname, 11) != 0)
1784 continue;
1786 if (asprintf(&remote_refname,
1787 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1788 refname + 11) == -1) {
1789 error = got_error_from_errno("asprintf");
1790 goto done;
1792 error = create_ref(remote_refname, id, verbosity - 1, repo);
1793 free(remote_refname);
1794 if (error)
1795 goto done;
1798 /* Set the HEAD reference if the server provided one. */
1799 TAILQ_FOREACH(pe, &symrefs, entry) {
1800 struct got_reference *target_ref;
1801 const char *refname = pe->path;
1802 const char *target = pe->data;
1803 char *remote_refname = NULL, *remote_target = NULL;
1805 if (strcmp(refname, GOT_REF_HEAD) != 0)
1806 continue;
1808 error = got_ref_open(&target_ref, repo, target, 0);
1809 if (error) {
1810 if (error->code == GOT_ERR_NOT_REF) {
1811 error = NULL;
1812 continue;
1814 goto done;
1817 error = create_symref(refname, target_ref, verbosity, repo);
1818 got_ref_close(target_ref);
1819 if (error)
1820 goto done;
1822 if (mirror_references)
1823 continue;
1825 if (strncmp("refs/heads/", target, 11) != 0)
1826 continue;
1828 if (asprintf(&remote_refname,
1829 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1830 refname) == -1) {
1831 error = got_error_from_errno("asprintf");
1832 goto done;
1834 if (asprintf(&remote_target,
1835 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1836 target + 11) == -1) {
1837 error = got_error_from_errno("asprintf");
1838 free(remote_refname);
1839 goto done;
1841 error = got_ref_open(&target_ref, repo, remote_target, 0);
1842 if (error) {
1843 free(remote_refname);
1844 free(remote_target);
1845 if (error->code == GOT_ERR_NOT_REF) {
1846 error = NULL;
1847 continue;
1849 goto done;
1851 error = create_symref(remote_refname, target_ref,
1852 verbosity - 1, repo);
1853 free(remote_refname);
1854 free(remote_target);
1855 got_ref_close(target_ref);
1856 if (error)
1857 goto done;
1859 if (pe == NULL) {
1861 * We failed to set the HEAD reference. If we asked for
1862 * a set of wanted branches use the first of one of those
1863 * which could be fetched instead.
1865 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1866 const char *target = pe->path;
1867 struct got_reference *target_ref;
1869 error = got_ref_open(&target_ref, repo, target, 0);
1870 if (error) {
1871 if (error->code == GOT_ERR_NOT_REF) {
1872 error = NULL;
1873 continue;
1875 goto done;
1878 error = create_symref(GOT_REF_HEAD, target_ref,
1879 verbosity, repo);
1880 got_ref_close(target_ref);
1881 if (error)
1882 goto done;
1883 break;
1886 if (!fpa.configs_created && pe != NULL) {
1887 error = create_config_files(fpa.config_info.proto,
1888 fpa.config_info.host, fpa.config_info.port,
1889 fpa.config_info.remote_repo_path,
1890 fpa.config_info.git_url,
1891 fpa.config_info.fetch_all_branches,
1892 fpa.config_info.mirror_references,
1893 fpa.config_info.symrefs,
1894 fpa.config_info.wanted_branches,
1895 fpa.config_info.wanted_refs, fpa.repo);
1896 if (error)
1897 goto done;
1901 if (verbosity >= 0)
1902 printf("Created %s repository '%s'\n",
1903 mirror_references ? "mirrored" : "cloned", repo_path);
1904 done:
1905 if (pack_fds) {
1906 const struct got_error *pack_err =
1907 got_repo_pack_fds_close(pack_fds);
1908 if (error == NULL)
1909 error = pack_err;
1911 if (fetchpid > 0) {
1912 if (kill(fetchpid, SIGTERM) == -1)
1913 error = got_error_from_errno("kill");
1914 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1915 error = got_error_from_errno("waitpid");
1917 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1918 error = got_error_from_errno("close");
1919 if (repo) {
1920 const struct got_error *close_err = got_repo_close(repo);
1921 if (error == NULL)
1922 error = close_err;
1924 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1925 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1926 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1927 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1928 free(pack_hash);
1929 free(proto);
1930 free(host);
1931 free(port);
1932 free(server_path);
1933 free(repo_name);
1934 free(default_destdir);
1935 free(git_url);
1936 return error;
1939 static const struct got_error *
1940 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1941 int replace_tags, int verbosity, struct got_repository *repo)
1943 const struct got_error *err = NULL;
1944 char *new_id_str = NULL;
1945 struct got_object_id *old_id = NULL;
1947 err = got_object_id_str(&new_id_str, new_id);
1948 if (err)
1949 goto done;
1951 if (!replace_tags &&
1952 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1953 err = got_ref_resolve(&old_id, repo, ref);
1954 if (err)
1955 goto done;
1956 if (got_object_id_cmp(old_id, new_id) == 0)
1957 goto done;
1958 if (verbosity >= 0) {
1959 printf("Rejecting update of existing tag %s: %s\n",
1960 got_ref_get_name(ref), new_id_str);
1962 goto done;
1965 if (got_ref_is_symbolic(ref)) {
1966 if (verbosity >= 0) {
1967 printf("Replacing reference %s: %s\n",
1968 got_ref_get_name(ref),
1969 got_ref_get_symref_target(ref));
1971 err = got_ref_change_symref_to_ref(ref, new_id);
1972 if (err)
1973 goto done;
1974 err = got_ref_write(ref, repo);
1975 if (err)
1976 goto done;
1977 } else {
1978 err = got_ref_resolve(&old_id, repo, ref);
1979 if (err)
1980 goto done;
1981 if (got_object_id_cmp(old_id, new_id) == 0)
1982 goto done;
1984 err = got_ref_change_ref(ref, new_id);
1985 if (err)
1986 goto done;
1987 err = got_ref_write(ref, repo);
1988 if (err)
1989 goto done;
1992 if (verbosity >= 0)
1993 printf("Updated %s: %s\n", got_ref_get_name(ref),
1994 new_id_str);
1995 done:
1996 free(old_id);
1997 free(new_id_str);
1998 return err;
2001 static const struct got_error *
2002 update_symref(const char *refname, struct got_reference *target_ref,
2003 int verbosity, struct got_repository *repo)
2005 const struct got_error *err = NULL, *unlock_err;
2006 struct got_reference *symref;
2007 int symref_is_locked = 0;
2009 err = got_ref_open(&symref, repo, refname, 1);
2010 if (err) {
2011 if (err->code != GOT_ERR_NOT_REF)
2012 return err;
2013 err = got_ref_alloc_symref(&symref, refname, target_ref);
2014 if (err)
2015 goto done;
2017 err = got_ref_write(symref, repo);
2018 if (err)
2019 goto done;
2021 if (verbosity >= 0)
2022 printf("Created reference %s: %s\n",
2023 got_ref_get_name(symref),
2024 got_ref_get_symref_target(symref));
2025 } else {
2026 symref_is_locked = 1;
2028 if (strcmp(got_ref_get_symref_target(symref),
2029 got_ref_get_name(target_ref)) == 0)
2030 goto done;
2032 err = got_ref_change_symref(symref,
2033 got_ref_get_name(target_ref));
2034 if (err)
2035 goto done;
2037 err = got_ref_write(symref, repo);
2038 if (err)
2039 goto done;
2041 if (verbosity >= 0)
2042 printf("Updated %s: %s\n", got_ref_get_name(symref),
2043 got_ref_get_symref_target(symref));
2046 done:
2047 if (symref_is_locked) {
2048 unlock_err = got_ref_unlock(symref);
2049 if (unlock_err && err == NULL)
2050 err = unlock_err;
2052 got_ref_close(symref);
2053 return err;
2056 __dead static void
2057 usage_fetch(void)
2059 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2060 "[-R reference] [-r repository-path] [remote-repository]\n",
2061 getprogname());
2062 exit(1);
2065 static const struct got_error *
2066 delete_missing_ref(struct got_reference *ref,
2067 int verbosity, struct got_repository *repo)
2069 const struct got_error *err = NULL;
2070 struct got_object_id *id = NULL;
2071 char *id_str = NULL;
2073 if (got_ref_is_symbolic(ref)) {
2074 err = got_ref_delete(ref, repo);
2075 if (err)
2076 return err;
2077 if (verbosity >= 0) {
2078 printf("Deleted %s: %s\n",
2079 got_ref_get_name(ref),
2080 got_ref_get_symref_target(ref));
2082 } else {
2083 err = got_ref_resolve(&id, repo, ref);
2084 if (err)
2085 return err;
2086 err = got_object_id_str(&id_str, id);
2087 if (err)
2088 goto done;
2090 err = got_ref_delete(ref, repo);
2091 if (err)
2092 goto done;
2093 if (verbosity >= 0) {
2094 printf("Deleted %s: %s\n",
2095 got_ref_get_name(ref), id_str);
2098 done:
2099 free(id);
2100 free(id_str);
2101 return err;
2104 static const struct got_error *
2105 delete_missing_refs(struct got_pathlist_head *their_refs,
2106 struct got_pathlist_head *their_symrefs,
2107 const struct got_remote_repo *remote,
2108 int verbosity, struct got_repository *repo)
2110 const struct got_error *err = NULL, *unlock_err;
2111 struct got_reflist_head my_refs;
2112 struct got_reflist_entry *re;
2113 struct got_pathlist_entry *pe;
2114 char *remote_namespace = NULL;
2115 char *local_refname = NULL;
2117 TAILQ_INIT(&my_refs);
2119 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2120 == -1)
2121 return got_error_from_errno("asprintf");
2123 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2124 if (err)
2125 goto done;
2127 TAILQ_FOREACH(re, &my_refs, entry) {
2128 const char *refname = got_ref_get_name(re->ref);
2129 const char *their_refname;
2131 if (remote->mirror_references) {
2132 their_refname = refname;
2133 } else {
2134 if (strncmp(refname, remote_namespace,
2135 strlen(remote_namespace)) == 0) {
2136 if (strcmp(refname + strlen(remote_namespace),
2137 GOT_REF_HEAD) == 0)
2138 continue;
2139 if (asprintf(&local_refname, "refs/heads/%s",
2140 refname + strlen(remote_namespace)) == -1) {
2141 err = got_error_from_errno("asprintf");
2142 goto done;
2144 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2145 continue;
2147 their_refname = local_refname;
2150 TAILQ_FOREACH(pe, their_refs, entry) {
2151 if (strcmp(their_refname, pe->path) == 0)
2152 break;
2154 if (pe != NULL)
2155 continue;
2157 TAILQ_FOREACH(pe, their_symrefs, entry) {
2158 if (strcmp(their_refname, pe->path) == 0)
2159 break;
2161 if (pe != NULL)
2162 continue;
2164 err = delete_missing_ref(re->ref, verbosity, repo);
2165 if (err)
2166 break;
2168 if (local_refname) {
2169 struct got_reference *ref;
2170 err = got_ref_open(&ref, repo, local_refname, 1);
2171 if (err) {
2172 if (err->code != GOT_ERR_NOT_REF)
2173 break;
2174 free(local_refname);
2175 local_refname = NULL;
2176 continue;
2178 err = delete_missing_ref(ref, verbosity, repo);
2179 if (err)
2180 break;
2181 unlock_err = got_ref_unlock(ref);
2182 got_ref_close(ref);
2183 if (unlock_err && err == NULL) {
2184 err = unlock_err;
2185 break;
2188 free(local_refname);
2189 local_refname = NULL;
2192 done:
2193 got_ref_list_free(&my_refs);
2194 free(remote_namespace);
2195 free(local_refname);
2196 return err;
2199 static const struct got_error *
2200 update_wanted_ref(const char *refname, struct got_object_id *id,
2201 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2203 const struct got_error *err, *unlock_err;
2204 char *remote_refname;
2205 struct got_reference *ref;
2207 if (strncmp("refs/", refname, 5) == 0)
2208 refname += 5;
2210 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2211 remote_repo_name, refname) == -1)
2212 return got_error_from_errno("asprintf");
2214 err = got_ref_open(&ref, repo, remote_refname, 1);
2215 if (err) {
2216 if (err->code != GOT_ERR_NOT_REF)
2217 goto done;
2218 err = create_ref(remote_refname, id, verbosity, repo);
2219 } else {
2220 err = update_ref(ref, id, 0, verbosity, repo);
2221 unlock_err = got_ref_unlock(ref);
2222 if (unlock_err && err == NULL)
2223 err = unlock_err;
2224 got_ref_close(ref);
2226 done:
2227 free(remote_refname);
2228 return err;
2231 static const struct got_error *
2232 delete_ref(struct got_repository *repo, struct got_reference *ref)
2234 const struct got_error *err = NULL;
2235 struct got_object_id *id = NULL;
2236 char *id_str = NULL;
2237 const char *target;
2239 if (got_ref_is_symbolic(ref)) {
2240 target = got_ref_get_symref_target(ref);
2241 } else {
2242 err = got_ref_resolve(&id, repo, ref);
2243 if (err)
2244 goto done;
2245 err = got_object_id_str(&id_str, id);
2246 if (err)
2247 goto done;
2248 target = id_str;
2251 err = got_ref_delete(ref, repo);
2252 if (err)
2253 goto done;
2255 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2256 done:
2257 free(id);
2258 free(id_str);
2259 return err;
2262 static const struct got_error *
2263 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2265 const struct got_error *err = NULL;
2266 struct got_reflist_head refs;
2267 struct got_reflist_entry *re;
2268 char *prefix;
2270 TAILQ_INIT(&refs);
2272 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2273 err = got_error_from_errno("asprintf");
2274 goto done;
2276 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2277 if (err)
2278 goto done;
2280 TAILQ_FOREACH(re, &refs, entry)
2281 delete_ref(repo, re->ref);
2282 done:
2283 got_ref_list_free(&refs);
2284 return err;
2287 static const struct got_error *
2288 cmd_fetch(int argc, char *argv[])
2290 const struct got_error *error = NULL, *unlock_err;
2291 char *cwd = NULL, *repo_path = NULL;
2292 const char *remote_name;
2293 char *proto = NULL, *host = NULL, *port = NULL;
2294 char *repo_name = NULL, *server_path = NULL;
2295 const struct got_remote_repo *remotes;
2296 struct got_remote_repo *remote = NULL;
2297 int nremotes;
2298 char *id_str = NULL;
2299 struct got_repository *repo = NULL;
2300 struct got_worktree *worktree = NULL;
2301 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2302 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2303 char *head_refname = NULL;
2304 struct got_pathlist_entry *pe;
2305 struct got_reflist_head remote_refs;
2306 struct got_reflist_entry *re;
2307 struct got_object_id *pack_hash = NULL;
2308 int i, ch, fetchfd = -1, fetchstatus;
2309 pid_t fetchpid = -1;
2310 struct got_fetch_progress_arg fpa;
2311 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2312 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2313 int *pack_fds = NULL, have_bflag = 0;
2314 const char *remote_head = NULL, *worktree_branch = NULL;
2316 TAILQ_INIT(&refs);
2317 TAILQ_INIT(&symrefs);
2318 TAILQ_INIT(&remote_refs);
2319 TAILQ_INIT(&wanted_branches);
2320 TAILQ_INIT(&wanted_refs);
2322 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2323 switch (ch) {
2324 case 'a':
2325 fetch_all_branches = 1;
2326 break;
2327 case 'b':
2328 error = got_pathlist_append(&wanted_branches,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 have_bflag = 1;
2333 break;
2334 case 'd':
2335 delete_refs = 1;
2336 break;
2337 case 'l':
2338 list_refs_only = 1;
2339 break;
2340 case 'q':
2341 verbosity = -1;
2342 break;
2343 case 'R':
2344 error = got_pathlist_append(&wanted_refs,
2345 optarg, NULL);
2346 if (error)
2347 return error;
2348 break;
2349 case 'r':
2350 repo_path = realpath(optarg, NULL);
2351 if (repo_path == NULL)
2352 return got_error_from_errno2("realpath",
2353 optarg);
2354 got_path_strip_trailing_slashes(repo_path);
2355 break;
2356 case 't':
2357 replace_tags = 1;
2358 break;
2359 case 'v':
2360 if (verbosity < 0)
2361 verbosity = 0;
2362 else if (verbosity < 3)
2363 verbosity++;
2364 break;
2365 case 'X':
2366 delete_remote = 1;
2367 break;
2368 default:
2369 usage_fetch();
2370 break;
2373 argc -= optind;
2374 argv += optind;
2376 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2377 option_conflict('a', 'b');
2378 if (list_refs_only) {
2379 if (!TAILQ_EMPTY(&wanted_branches))
2380 option_conflict('l', 'b');
2381 if (fetch_all_branches)
2382 option_conflict('l', 'a');
2383 if (delete_refs)
2384 option_conflict('l', 'd');
2385 if (delete_remote)
2386 option_conflict('l', 'X');
2388 if (delete_remote) {
2389 if (fetch_all_branches)
2390 option_conflict('X', 'a');
2391 if (!TAILQ_EMPTY(&wanted_branches))
2392 option_conflict('X', 'b');
2393 if (delete_refs)
2394 option_conflict('X', 'd');
2395 if (replace_tags)
2396 option_conflict('X', 't');
2397 if (!TAILQ_EMPTY(&wanted_refs))
2398 option_conflict('X', 'R');
2401 if (argc == 0) {
2402 if (delete_remote)
2403 errx(1, "-X option requires a remote name");
2404 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2405 } else if (argc == 1)
2406 remote_name = argv[0];
2407 else
2408 usage_fetch();
2410 cwd = getcwd(NULL, 0);
2411 if (cwd == NULL) {
2412 error = got_error_from_errno("getcwd");
2413 goto done;
2416 error = got_repo_pack_fds_open(&pack_fds);
2417 if (error != NULL)
2418 goto done;
2420 if (repo_path == NULL) {
2421 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2422 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2423 goto done;
2424 else
2425 error = NULL;
2426 if (worktree) {
2427 repo_path =
2428 strdup(got_worktree_get_repo_path(worktree));
2429 if (repo_path == NULL)
2430 error = got_error_from_errno("strdup");
2431 if (error)
2432 goto done;
2433 } else {
2434 repo_path = strdup(cwd);
2435 if (repo_path == NULL) {
2436 error = got_error_from_errno("strdup");
2437 goto done;
2442 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2443 if (error)
2444 goto done;
2446 if (delete_remote) {
2447 error = delete_refs_for_remote(repo, remote_name);
2448 goto done; /* nothing else to do */
2451 if (worktree) {
2452 worktree_conf = got_worktree_get_gotconfig(worktree);
2453 if (worktree_conf) {
2454 got_gotconfig_get_remotes(&nremotes, &remotes,
2455 worktree_conf);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 error = got_repo_remote_repo_dup(&remote,
2459 &remotes[i]);
2460 if (error)
2461 goto done;
2462 break;
2467 if (remote == NULL) {
2468 repo_conf = got_repo_get_gotconfig(repo);
2469 if (repo_conf) {
2470 got_gotconfig_get_remotes(&nremotes, &remotes,
2471 repo_conf);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 error = got_repo_remote_repo_dup(&remote,
2475 &remotes[i]);
2476 if (error)
2477 goto done;
2478 break;
2483 if (remote == NULL) {
2484 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2485 for (i = 0; i < nremotes; i++) {
2486 if (strcmp(remotes[i].name, remote_name) == 0) {
2487 error = got_repo_remote_repo_dup(&remote,
2488 &remotes[i]);
2489 if (error)
2490 goto done;
2491 break;
2495 if (remote == NULL) {
2496 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2497 goto done;
2500 if (TAILQ_EMPTY(&wanted_branches)) {
2501 if (!fetch_all_branches)
2502 fetch_all_branches = remote->fetch_all_branches;
2503 for (i = 0; i < remote->nfetch_branches; i++) {
2504 error = got_pathlist_append(&wanted_branches,
2505 remote->fetch_branches[i], NULL);
2506 if (error)
2507 goto done;
2510 if (TAILQ_EMPTY(&wanted_refs)) {
2511 for (i = 0; i < remote->nfetch_refs; i++) {
2512 error = got_pathlist_append(&wanted_refs,
2513 remote->fetch_refs[i], NULL);
2514 if (error)
2515 goto done;
2519 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2520 &repo_name, remote->fetch_url);
2521 if (error)
2522 goto done;
2524 if (strcmp(proto, "git") == 0) {
2525 #ifndef PROFILE
2526 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2527 "sendfd dns inet unveil", NULL) == -1)
2528 err(1, "pledge");
2529 #endif
2530 } else if (strcmp(proto, "git+ssh") == 0 ||
2531 strcmp(proto, "ssh") == 0) {
2532 #ifndef PROFILE
2533 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2534 "sendfd unveil", NULL) == -1)
2535 err(1, "pledge");
2536 #endif
2537 } else if (strcmp(proto, "http") == 0 ||
2538 strcmp(proto, "git+http") == 0) {
2539 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2540 goto done;
2541 } else {
2542 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2543 goto done;
2546 error = got_dial_apply_unveil(proto);
2547 if (error)
2548 goto done;
2550 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2551 if (error)
2552 goto done;
2554 if (worktree) {
2555 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2556 if (head_refname == NULL) {
2557 error = got_error_from_errno("strdup");
2558 goto done;
2561 /* Release work tree lock. */
2562 got_worktree_close(worktree);
2563 worktree = NULL;
2566 if (verbosity >= 0) {
2567 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2568 remote->name, proto, host,
2569 port ? ":" : "", port ? port : "",
2570 *server_path == '/' ? "" : "/", server_path);
2573 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2574 server_path, verbosity);
2575 if (error)
2576 goto done;
2578 if (!have_bflag) {
2580 * If set, get this remote's HEAD ref target so
2581 * if it has changed on the server we can fetch it.
2583 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2584 got_ref_cmp_by_name, repo);
2585 if (error)
2586 goto done;
2588 TAILQ_FOREACH(re, &remote_refs, entry) {
2589 const char *remote_refname, *remote_target;
2590 size_t remote_name_len;
2592 if (!got_ref_is_symbolic(re->ref))
2593 continue;
2595 remote_name_len = strlen(remote->name);
2596 remote_refname = got_ref_get_name(re->ref);
2598 /* we only want refs/remotes/$remote->name/HEAD */
2599 if (strncmp(remote_refname + 13, remote->name,
2600 remote_name_len) != 0)
2601 continue;
2603 if (strcmp(remote_refname + remote_name_len + 14,
2604 GOT_REF_HEAD) != 0)
2605 continue;
2608 * Take the name itself because we already
2609 * only match with refs/heads/ in fetch_pack().
2611 remote_target = got_ref_get_symref_target(re->ref);
2612 remote_head = remote_target + remote_name_len + 14;
2613 break;
2616 if (head_refname &&
2617 strncmp(head_refname, "refs/heads/", 11) == 0)
2618 worktree_branch = head_refname;
2621 fpa.last_scaled_size[0] = '\0';
2622 fpa.last_p_indexed = -1;
2623 fpa.last_p_resolved = -1;
2624 fpa.verbosity = verbosity;
2625 fpa.repo = repo;
2626 fpa.create_configs = 0;
2627 fpa.configs_created = 0;
2628 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2630 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2631 remote->mirror_references, fetch_all_branches, &wanted_branches,
2632 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2633 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2634 if (error)
2635 goto done;
2637 if (list_refs_only) {
2638 error = list_remote_refs(&symrefs, &refs);
2639 goto done;
2642 if (pack_hash == NULL) {
2643 if (verbosity >= 0)
2644 printf("Already up-to-date\n");
2645 } else if (verbosity >= 0) {
2646 error = got_object_id_str(&id_str, pack_hash);
2647 if (error)
2648 goto done;
2649 printf("\nFetched %s.pack\n", id_str);
2650 free(id_str);
2651 id_str = NULL;
2654 /* Update references provided with the pack file. */
2655 TAILQ_FOREACH(pe, &refs, entry) {
2656 const char *refname = pe->path;
2657 struct got_object_id *id = pe->data;
2658 struct got_reference *ref;
2659 char *remote_refname;
2661 if (is_wanted_ref(&wanted_refs, refname) &&
2662 !remote->mirror_references) {
2663 error = update_wanted_ref(refname, id,
2664 remote->name, verbosity, repo);
2665 if (error)
2666 goto done;
2667 continue;
2670 if (remote->mirror_references ||
2671 strncmp("refs/tags/", refname, 10) == 0) {
2672 error = got_ref_open(&ref, repo, refname, 1);
2673 if (error) {
2674 if (error->code != GOT_ERR_NOT_REF)
2675 goto done;
2676 error = create_ref(refname, id, verbosity,
2677 repo);
2678 if (error)
2679 goto done;
2680 } else {
2681 error = update_ref(ref, id, replace_tags,
2682 verbosity, repo);
2683 unlock_err = got_ref_unlock(ref);
2684 if (unlock_err && error == NULL)
2685 error = unlock_err;
2686 got_ref_close(ref);
2687 if (error)
2688 goto done;
2690 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2691 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2692 remote_name, refname + 11) == -1) {
2693 error = got_error_from_errno("asprintf");
2694 goto done;
2697 error = got_ref_open(&ref, repo, remote_refname, 1);
2698 if (error) {
2699 if (error->code != GOT_ERR_NOT_REF)
2700 goto done;
2701 error = create_ref(remote_refname, id,
2702 verbosity, repo);
2703 if (error)
2704 goto done;
2705 } else {
2706 error = update_ref(ref, id, replace_tags,
2707 verbosity, repo);
2708 unlock_err = got_ref_unlock(ref);
2709 if (unlock_err && error == NULL)
2710 error = unlock_err;
2711 got_ref_close(ref);
2712 if (error)
2713 goto done;
2716 /* Also create a local branch if none exists yet. */
2717 error = got_ref_open(&ref, repo, refname, 1);
2718 if (error) {
2719 if (error->code != GOT_ERR_NOT_REF)
2720 goto done;
2721 error = create_ref(refname, id, verbosity,
2722 repo);
2723 if (error)
2724 goto done;
2725 } else {
2726 unlock_err = got_ref_unlock(ref);
2727 if (unlock_err && error == NULL)
2728 error = unlock_err;
2729 got_ref_close(ref);
2733 if (delete_refs) {
2734 error = delete_missing_refs(&refs, &symrefs, remote,
2735 verbosity, repo);
2736 if (error)
2737 goto done;
2740 if (!remote->mirror_references) {
2741 /* Update remote HEAD reference if the server provided one. */
2742 TAILQ_FOREACH(pe, &symrefs, entry) {
2743 struct got_reference *target_ref;
2744 const char *refname = pe->path;
2745 const char *target = pe->data;
2746 char *remote_refname = NULL, *remote_target = NULL;
2748 if (strcmp(refname, GOT_REF_HEAD) != 0)
2749 continue;
2751 if (strncmp("refs/heads/", target, 11) != 0)
2752 continue;
2754 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2755 remote->name, refname) == -1) {
2756 error = got_error_from_errno("asprintf");
2757 goto done;
2759 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2760 remote->name, target + 11) == -1) {
2761 error = got_error_from_errno("asprintf");
2762 free(remote_refname);
2763 goto done;
2766 error = got_ref_open(&target_ref, repo, remote_target,
2767 0);
2768 if (error) {
2769 free(remote_refname);
2770 free(remote_target);
2771 if (error->code == GOT_ERR_NOT_REF) {
2772 error = NULL;
2773 continue;
2775 goto done;
2777 error = update_symref(remote_refname, target_ref,
2778 verbosity, repo);
2779 free(remote_refname);
2780 free(remote_target);
2781 got_ref_close(target_ref);
2782 if (error)
2783 goto done;
2786 done:
2787 if (fetchpid > 0) {
2788 if (kill(fetchpid, SIGTERM) == -1)
2789 error = got_error_from_errno("kill");
2790 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2791 error = got_error_from_errno("waitpid");
2793 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2794 error = got_error_from_errno("close");
2795 if (repo) {
2796 const struct got_error *close_err = got_repo_close(repo);
2797 if (error == NULL)
2798 error = close_err;
2800 if (worktree)
2801 got_worktree_close(worktree);
2802 if (pack_fds) {
2803 const struct got_error *pack_err =
2804 got_repo_pack_fds_close(pack_fds);
2805 if (error == NULL)
2806 error = pack_err;
2808 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2809 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2810 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2811 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2812 got_ref_list_free(&remote_refs);
2813 got_repo_free_remote_repo_data(remote);
2814 free(remote);
2815 free(head_refname);
2816 free(id_str);
2817 free(cwd);
2818 free(repo_path);
2819 free(pack_hash);
2820 free(proto);
2821 free(host);
2822 free(port);
2823 free(server_path);
2824 free(repo_name);
2825 return error;
2829 __dead static void
2830 usage_checkout(void)
2832 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2833 "[-p path-prefix] repository-path [work-tree-path]\n",
2834 getprogname());
2835 exit(1);
2838 static void
2839 show_worktree_base_ref_warning(void)
2841 fprintf(stderr, "%s: warning: could not create a reference "
2842 "to the work tree's base commit; the commit could be "
2843 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2844 "repository writable and running 'got update' will prevent this\n",
2845 getprogname());
2848 struct got_checkout_progress_arg {
2849 const char *worktree_path;
2850 int had_base_commit_ref_error;
2851 int verbosity;
2854 static const struct got_error *
2855 checkout_progress(void *arg, unsigned char status, const char *path)
2857 struct got_checkout_progress_arg *a = arg;
2859 /* Base commit bump happens silently. */
2860 if (status == GOT_STATUS_BUMP_BASE)
2861 return NULL;
2863 if (status == GOT_STATUS_BASE_REF_ERR) {
2864 a->had_base_commit_ref_error = 1;
2865 return NULL;
2868 while (path[0] == '/')
2869 path++;
2871 if (a->verbosity >= 0)
2872 printf("%c %s/%s\n", status, a->worktree_path, path);
2874 return NULL;
2877 static const struct got_error *
2878 check_cancelled(void *arg)
2880 if (sigint_received || sigpipe_received)
2881 return got_error(GOT_ERR_CANCELLED);
2882 return NULL;
2885 static const struct got_error *
2886 check_linear_ancestry(struct got_object_id *commit_id,
2887 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2888 struct got_repository *repo)
2890 const struct got_error *err = NULL;
2891 struct got_object_id *yca_id;
2893 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2894 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2895 if (err)
2896 return err;
2898 if (yca_id == NULL)
2899 return got_error(GOT_ERR_ANCESTRY);
2902 * Require a straight line of history between the target commit
2903 * and the work tree's base commit.
2905 * Non-linear situations such as this require a rebase:
2907 * (commit) D F (base_commit)
2908 * \ /
2909 * C E
2910 * \ /
2911 * B (yca)
2912 * |
2913 * A
2915 * 'got update' only handles linear cases:
2916 * Update forwards in time: A (base/yca) - B - C - D (commit)
2917 * Update backwards in time: D (base) - C - B - A (commit/yca)
2919 if (allow_forwards_in_time_only) {
2920 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2921 return got_error(GOT_ERR_ANCESTRY);
2922 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2923 got_object_id_cmp(base_commit_id, yca_id) != 0)
2924 return got_error(GOT_ERR_ANCESTRY);
2926 free(yca_id);
2927 return NULL;
2930 static const struct got_error *
2931 check_same_branch(struct got_object_id *commit_id,
2932 struct got_reference *head_ref, struct got_repository *repo)
2934 const struct got_error *err = NULL;
2935 struct got_commit_graph *graph = NULL;
2936 struct got_object_id *head_commit_id = NULL;
2938 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2939 if (err)
2940 goto done;
2942 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2943 goto done;
2945 err = got_commit_graph_open(&graph, "/", 1);
2946 if (err)
2947 goto done;
2949 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2950 check_cancelled, NULL);
2951 if (err)
2952 goto done;
2954 for (;;) {
2955 struct got_object_id id;
2957 err = got_commit_graph_iter_next(&id, graph, repo,
2958 check_cancelled, NULL);
2959 if (err) {
2960 if (err->code == GOT_ERR_ITER_COMPLETED)
2961 err = got_error(GOT_ERR_ANCESTRY);
2962 break;
2965 if (got_object_id_cmp(&id, commit_id) == 0)
2966 break;
2968 done:
2969 if (graph)
2970 got_commit_graph_close(graph);
2971 free(head_commit_id);
2972 return err;
2975 static const struct got_error *
2976 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2978 static char msg[512];
2979 const char *branch_name;
2981 if (got_ref_is_symbolic(ref))
2982 branch_name = got_ref_get_symref_target(ref);
2983 else
2984 branch_name = got_ref_get_name(ref);
2986 if (strncmp("refs/heads/", branch_name, 11) == 0)
2987 branch_name += 11;
2989 snprintf(msg, sizeof(msg),
2990 "target commit is not contained in branch '%s'; "
2991 "the branch to use must be specified with -b; "
2992 "if necessary a new branch can be created for "
2993 "this commit with 'got branch -c %s BRANCH_NAME'",
2994 branch_name, commit_id_str);
2996 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2999 static const struct got_error *
3000 cmd_checkout(int argc, char *argv[])
3002 const struct got_error *close_err, *error = NULL;
3003 struct got_repository *repo = NULL;
3004 struct got_reference *head_ref = NULL, *ref = NULL;
3005 struct got_worktree *worktree = NULL;
3006 char *repo_path = NULL;
3007 char *worktree_path = NULL;
3008 const char *path_prefix = "";
3009 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3010 char *commit_id_str = NULL, *keyword_idstr = NULL;
3011 struct got_object_id *commit_id = NULL;
3012 char *cwd = NULL;
3013 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3014 struct got_pathlist_head paths;
3015 struct got_checkout_progress_arg cpa;
3016 int *pack_fds = NULL;
3018 TAILQ_INIT(&paths);
3020 #ifndef PROFILE
3021 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3022 "unveil", NULL) == -1)
3023 err(1, "pledge");
3024 #endif
3026 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3027 switch (ch) {
3028 case 'b':
3029 branch_name = optarg;
3030 break;
3031 case 'c':
3032 commit_id_str = strdup(optarg);
3033 if (commit_id_str == NULL)
3034 return got_error_from_errno("strdup");
3035 break;
3036 case 'E':
3037 allow_nonempty = 1;
3038 break;
3039 case 'p':
3040 path_prefix = optarg;
3041 break;
3042 case 'q':
3043 verbosity = -1;
3044 break;
3045 default:
3046 usage_checkout();
3047 /* NOTREACHED */
3051 argc -= optind;
3052 argv += optind;
3054 if (argc == 1) {
3055 char *base, *dotgit;
3056 const char *path;
3057 repo_path = realpath(argv[0], NULL);
3058 if (repo_path == NULL)
3059 return got_error_from_errno2("realpath", argv[0]);
3060 cwd = getcwd(NULL, 0);
3061 if (cwd == NULL) {
3062 error = got_error_from_errno("getcwd");
3063 goto done;
3065 if (path_prefix[0])
3066 path = path_prefix;
3067 else
3068 path = repo_path;
3069 error = got_path_basename(&base, path);
3070 if (error)
3071 goto done;
3072 dotgit = strstr(base, ".git");
3073 if (dotgit)
3074 *dotgit = '\0';
3075 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3076 error = got_error_from_errno("asprintf");
3077 free(base);
3078 goto done;
3080 free(base);
3081 } else if (argc == 2) {
3082 repo_path = realpath(argv[0], NULL);
3083 if (repo_path == NULL) {
3084 error = got_error_from_errno2("realpath", argv[0]);
3085 goto done;
3087 worktree_path = realpath(argv[1], NULL);
3088 if (worktree_path == NULL) {
3089 if (errno != ENOENT) {
3090 error = got_error_from_errno2("realpath",
3091 argv[1]);
3092 goto done;
3094 worktree_path = strdup(argv[1]);
3095 if (worktree_path == NULL) {
3096 error = got_error_from_errno("strdup");
3097 goto done;
3100 } else
3101 usage_checkout();
3103 got_path_strip_trailing_slashes(repo_path);
3104 got_path_strip_trailing_slashes(worktree_path);
3106 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3107 got_path_is_child(repo_path, worktree_path,
3108 strlen(worktree_path))) {
3109 error = got_error_fmt(GOT_ERR_BAD_PATH,
3110 "work tree and repository paths may not overlap: %s",
3111 worktree_path);
3112 goto done;
3115 error = got_repo_pack_fds_open(&pack_fds);
3116 if (error != NULL)
3117 goto done;
3119 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3120 if (error != NULL)
3121 goto done;
3123 /* Pre-create work tree path for unveil(2) */
3124 error = got_path_mkdir(worktree_path);
3125 if (error) {
3126 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3127 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3128 goto done;
3129 if (!allow_nonempty &&
3130 !got_path_dir_is_empty(worktree_path)) {
3131 error = got_error_path(worktree_path,
3132 GOT_ERR_DIR_NOT_EMPTY);
3133 goto done;
3137 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3138 if (error)
3139 goto done;
3141 error = got_ref_open(&head_ref, repo, branch_name, 0);
3142 if (error != NULL)
3143 goto done;
3145 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3146 GOT_WORKTREE_GOT_DIR, repo);
3147 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3148 goto done;
3150 error = got_worktree_open(&worktree, worktree_path,
3151 GOT_WORKTREE_GOT_DIR);
3152 if (error != NULL)
3153 goto done;
3155 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3156 path_prefix);
3157 if (error != NULL)
3158 goto done;
3159 if (!same_path_prefix) {
3160 error = got_error(GOT_ERR_PATH_PREFIX);
3161 goto done;
3164 if (commit_id_str) {
3165 struct got_reflist_head refs;
3166 TAILQ_INIT(&refs);
3167 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3168 NULL);
3169 if (error)
3170 goto done;
3172 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3173 repo, worktree);
3174 if (error != NULL)
3175 goto done;
3176 if (keyword_idstr != NULL) {
3177 free(commit_id_str);
3178 commit_id_str = keyword_idstr;
3181 error = got_repo_match_object_id(&commit_id, NULL,
3182 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3183 got_ref_list_free(&refs);
3184 if (error)
3185 goto done;
3186 error = check_linear_ancestry(commit_id,
3187 got_worktree_get_base_commit_id(worktree), 0, repo);
3188 if (error != NULL) {
3189 if (error->code == GOT_ERR_ANCESTRY) {
3190 error = checkout_ancestry_error(
3191 head_ref, commit_id_str);
3193 goto done;
3195 error = check_same_branch(commit_id, head_ref, repo);
3196 if (error) {
3197 if (error->code == GOT_ERR_ANCESTRY) {
3198 error = checkout_ancestry_error(
3199 head_ref, commit_id_str);
3201 goto done;
3203 error = got_worktree_set_base_commit_id(worktree, repo,
3204 commit_id);
3205 if (error)
3206 goto done;
3207 /* Expand potentially abbreviated commit ID string. */
3208 free(commit_id_str);
3209 error = got_object_id_str(&commit_id_str, commit_id);
3210 if (error)
3211 goto done;
3212 } else {
3213 commit_id = got_object_id_dup(
3214 got_worktree_get_base_commit_id(worktree));
3215 if (commit_id == NULL) {
3216 error = got_error_from_errno("got_object_id_dup");
3217 goto done;
3219 error = got_object_id_str(&commit_id_str, commit_id);
3220 if (error)
3221 goto done;
3224 error = got_pathlist_append(&paths, "", NULL);
3225 if (error)
3226 goto done;
3227 cpa.worktree_path = worktree_path;
3228 cpa.had_base_commit_ref_error = 0;
3229 cpa.verbosity = verbosity;
3230 error = got_worktree_checkout_files(worktree, &paths, repo,
3231 checkout_progress, &cpa, check_cancelled, NULL);
3232 if (error != NULL)
3233 goto done;
3235 if (got_ref_is_symbolic(head_ref)) {
3236 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3237 if (error)
3238 goto done;
3239 refname = got_ref_get_name(ref);
3240 } else
3241 refname = got_ref_get_name(head_ref);
3242 printf("Checked out %s: %s\n", refname, commit_id_str);
3243 printf("Now shut up and hack\n");
3244 if (cpa.had_base_commit_ref_error)
3245 show_worktree_base_ref_warning();
3246 done:
3247 if (pack_fds) {
3248 const struct got_error *pack_err =
3249 got_repo_pack_fds_close(pack_fds);
3250 if (error == NULL)
3251 error = pack_err;
3253 if (head_ref)
3254 got_ref_close(head_ref);
3255 if (ref)
3256 got_ref_close(ref);
3257 if (repo) {
3258 close_err = got_repo_close(repo);
3259 if (error == NULL)
3260 error = close_err;
3262 if (worktree != NULL) {
3263 close_err = got_worktree_close(worktree);
3264 if (error == NULL)
3265 error = close_err;
3267 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3268 free(commit_id_str);
3269 free(commit_id);
3270 free(repo_path);
3271 free(worktree_path);
3272 free(cwd);
3273 return error;
3276 struct got_update_progress_arg {
3277 int did_something;
3278 int conflicts;
3279 int obstructed;
3280 int not_updated;
3281 int missing;
3282 int not_deleted;
3283 int unversioned;
3284 int verbosity;
3287 static void
3288 print_update_progress_stats(struct got_update_progress_arg *upa)
3290 if (!upa->did_something)
3291 return;
3293 if (upa->conflicts > 0)
3294 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3295 if (upa->obstructed > 0)
3296 printf("File paths obstructed by a non-regular file: %d\n",
3297 upa->obstructed);
3298 if (upa->not_updated > 0)
3299 printf("Files not updated because of existing merge "
3300 "conflicts: %d\n", upa->not_updated);
3304 * The meaning of some status codes differs between merge-style operations and
3305 * update operations. For example, the ! status code means "file was missing"
3306 * if changes were merged into the work tree, and "missing file was restored"
3307 * if the work tree was updated. This function should be used by any operation
3308 * which merges changes into the work tree without updating the work tree.
3310 static void
3311 print_merge_progress_stats(struct got_update_progress_arg *upa)
3313 if (!upa->did_something)
3314 return;
3316 if (upa->conflicts > 0)
3317 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3318 if (upa->obstructed > 0)
3319 printf("File paths obstructed by a non-regular file: %d\n",
3320 upa->obstructed);
3321 if (upa->missing > 0)
3322 printf("Files which had incoming changes but could not be "
3323 "found in the work tree: %d\n", upa->missing);
3324 if (upa->not_deleted > 0)
3325 printf("Files not deleted due to differences in deleted "
3326 "content: %d\n", upa->not_deleted);
3327 if (upa->unversioned > 0)
3328 printf("Files not merged because an unversioned file was "
3329 "found in the work tree: %d\n", upa->unversioned);
3332 __dead static void
3333 usage_update(void)
3335 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3336 "[path ...]\n", getprogname());
3337 exit(1);
3340 static const struct got_error *
3341 update_progress(void *arg, unsigned char status, const char *path)
3343 struct got_update_progress_arg *upa = arg;
3345 if (status == GOT_STATUS_EXISTS ||
3346 status == GOT_STATUS_BASE_REF_ERR)
3347 return NULL;
3349 upa->did_something = 1;
3351 /* Base commit bump happens silently. */
3352 if (status == GOT_STATUS_BUMP_BASE)
3353 return NULL;
3355 if (status == GOT_STATUS_CONFLICT)
3356 upa->conflicts++;
3357 if (status == GOT_STATUS_OBSTRUCTED)
3358 upa->obstructed++;
3359 if (status == GOT_STATUS_CANNOT_UPDATE)
3360 upa->not_updated++;
3361 if (status == GOT_STATUS_MISSING)
3362 upa->missing++;
3363 if (status == GOT_STATUS_CANNOT_DELETE)
3364 upa->not_deleted++;
3365 if (status == GOT_STATUS_UNVERSIONED)
3366 upa->unversioned++;
3368 while (path[0] == '/')
3369 path++;
3370 if (upa->verbosity >= 0)
3371 printf("%c %s\n", status, path);
3373 return NULL;
3376 static const struct got_error *
3377 switch_head_ref(struct got_reference *head_ref,
3378 struct got_object_id *commit_id, struct got_worktree *worktree,
3379 struct got_repository *repo)
3381 const struct got_error *err = NULL;
3382 char *base_id_str;
3383 int ref_has_moved = 0;
3385 /* Trivial case: switching between two different references. */
3386 if (strcmp(got_ref_get_name(head_ref),
3387 got_worktree_get_head_ref_name(worktree)) != 0) {
3388 printf("Switching work tree from %s to %s\n",
3389 got_worktree_get_head_ref_name(worktree),
3390 got_ref_get_name(head_ref));
3391 return got_worktree_set_head_ref(worktree, head_ref);
3394 err = check_linear_ancestry(commit_id,
3395 got_worktree_get_base_commit_id(worktree), 0, repo);
3396 if (err) {
3397 if (err->code != GOT_ERR_ANCESTRY)
3398 return err;
3399 ref_has_moved = 1;
3401 if (!ref_has_moved)
3402 return NULL;
3404 /* Switching to a rebased branch with the same reference name. */
3405 err = got_object_id_str(&base_id_str,
3406 got_worktree_get_base_commit_id(worktree));
3407 if (err)
3408 return err;
3409 printf("Reference %s now points at a different branch\n",
3410 got_worktree_get_head_ref_name(worktree));
3411 printf("Switching work tree from %s to %s\n", base_id_str,
3412 got_worktree_get_head_ref_name(worktree));
3413 return NULL;
3416 static const struct got_error *
3417 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3419 const struct got_error *err;
3420 int in_progress;
3422 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3423 if (err)
3424 return err;
3425 if (in_progress)
3426 return got_error(GOT_ERR_REBASING);
3428 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3429 if (err)
3430 return err;
3431 if (in_progress)
3432 return got_error(GOT_ERR_HISTEDIT_BUSY);
3434 return NULL;
3437 static const struct got_error *
3438 check_merge_in_progress(struct got_worktree *worktree,
3439 struct got_repository *repo)
3441 const struct got_error *err;
3442 int in_progress;
3444 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3445 if (err)
3446 return err;
3447 if (in_progress)
3448 return got_error(GOT_ERR_MERGE_BUSY);
3450 return NULL;
3453 static const struct got_error *
3454 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3455 char *argv[], struct got_worktree *worktree)
3457 const struct got_error *err = NULL;
3458 char *path;
3459 struct got_pathlist_entry *new;
3460 int i;
3462 if (argc == 0) {
3463 path = strdup("");
3464 if (path == NULL)
3465 return got_error_from_errno("strdup");
3466 return got_pathlist_append(paths, path, NULL);
3469 for (i = 0; i < argc; i++) {
3470 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3471 if (err)
3472 break;
3473 err = got_pathlist_insert(&new, paths, path, NULL);
3474 if (err || new == NULL /* duplicate */) {
3475 free(path);
3476 if (err)
3477 break;
3481 return err;
3484 static const struct got_error *
3485 wrap_not_worktree_error(const struct got_error *orig_err,
3486 const char *cmdname, const char *path)
3488 const struct got_error *err;
3489 struct got_repository *repo;
3490 static char msg[512];
3491 int *pack_fds = NULL;
3493 err = got_repo_pack_fds_open(&pack_fds);
3494 if (err)
3495 return err;
3497 err = got_repo_open(&repo, path, NULL, pack_fds);
3498 if (err)
3499 return orig_err;
3501 snprintf(msg, sizeof(msg),
3502 "'got %s' needs a work tree in addition to a git repository\n"
3503 "Work trees can be checked out from this Git repository with "
3504 "'got checkout'.\n"
3505 "The got(1) manual page contains more information.", cmdname);
3506 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3507 if (repo) {
3508 const struct got_error *close_err = got_repo_close(repo);
3509 if (err == NULL)
3510 err = close_err;
3512 if (pack_fds) {
3513 const struct got_error *pack_err =
3514 got_repo_pack_fds_close(pack_fds);
3515 if (err == NULL)
3516 err = pack_err;
3518 return err;
3521 static const struct got_error *
3522 cmd_update(int argc, char *argv[])
3524 const struct got_error *close_err, *error = NULL;
3525 struct got_repository *repo = NULL;
3526 struct got_worktree *worktree = NULL;
3527 char *worktree_path = NULL;
3528 struct got_object_id *commit_id = NULL;
3529 char *commit_id_str = NULL;
3530 const char *branch_name = NULL;
3531 struct got_reference *head_ref = NULL;
3532 struct got_pathlist_head paths;
3533 struct got_pathlist_entry *pe;
3534 int ch, verbosity = 0;
3535 struct got_update_progress_arg upa;
3536 int *pack_fds = NULL;
3538 TAILQ_INIT(&paths);
3540 #ifndef PROFILE
3541 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3542 "unveil", NULL) == -1)
3543 err(1, "pledge");
3544 #endif
3546 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3547 switch (ch) {
3548 case 'b':
3549 branch_name = optarg;
3550 break;
3551 case 'c':
3552 commit_id_str = strdup(optarg);
3553 if (commit_id_str == NULL)
3554 return got_error_from_errno("strdup");
3555 break;
3556 case 'q':
3557 verbosity = -1;
3558 break;
3559 default:
3560 usage_update();
3561 /* NOTREACHED */
3565 argc -= optind;
3566 argv += optind;
3568 worktree_path = getcwd(NULL, 0);
3569 if (worktree_path == NULL) {
3570 error = got_error_from_errno("getcwd");
3571 goto done;
3574 error = got_repo_pack_fds_open(&pack_fds);
3575 if (error != NULL)
3576 goto done;
3578 error = got_worktree_open(&worktree, worktree_path,
3579 GOT_WORKTREE_GOT_DIR);
3580 if (error) {
3581 if (error->code == GOT_ERR_NOT_WORKTREE)
3582 error = wrap_not_worktree_error(error, "update",
3583 worktree_path);
3584 goto done;
3587 error = check_rebase_or_histedit_in_progress(worktree);
3588 if (error)
3589 goto done;
3591 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3592 NULL, pack_fds);
3593 if (error != NULL)
3594 goto done;
3596 error = apply_unveil(got_repo_get_path(repo), 0,
3597 got_worktree_get_root_path(worktree));
3598 if (error)
3599 goto done;
3601 error = check_merge_in_progress(worktree, repo);
3602 if (error)
3603 goto done;
3605 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3606 if (error)
3607 goto done;
3609 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3610 got_worktree_get_head_ref_name(worktree), 0);
3611 if (error != NULL)
3612 goto done;
3613 if (commit_id_str == NULL) {
3614 error = got_ref_resolve(&commit_id, repo, head_ref);
3615 if (error != NULL)
3616 goto done;
3617 error = got_object_id_str(&commit_id_str, commit_id);
3618 if (error != NULL)
3619 goto done;
3620 } else {
3621 struct got_reflist_head refs;
3622 char *keyword_idstr = NULL;
3624 TAILQ_INIT(&refs);
3626 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3627 NULL);
3628 if (error)
3629 goto done;
3631 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3632 repo, worktree);
3633 if (error != NULL)
3634 goto done;
3635 if (keyword_idstr != NULL) {
3636 free(commit_id_str);
3637 commit_id_str = keyword_idstr;
3640 error = got_repo_match_object_id(&commit_id, NULL,
3641 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3642 got_ref_list_free(&refs);
3643 free(commit_id_str);
3644 commit_id_str = NULL;
3645 if (error)
3646 goto done;
3647 error = got_object_id_str(&commit_id_str, commit_id);
3648 if (error)
3649 goto done;
3652 if (branch_name) {
3653 struct got_object_id *head_commit_id;
3654 TAILQ_FOREACH(pe, &paths, entry) {
3655 if (pe->path_len == 0)
3656 continue;
3657 error = got_error_msg(GOT_ERR_BAD_PATH,
3658 "switching between branches requires that "
3659 "the entire work tree gets updated");
3660 goto done;
3662 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3663 if (error)
3664 goto done;
3665 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3666 repo);
3667 free(head_commit_id);
3668 if (error != NULL)
3669 goto done;
3670 error = check_same_branch(commit_id, head_ref, repo);
3671 if (error)
3672 goto done;
3673 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3674 if (error)
3675 goto done;
3676 } else {
3677 error = check_linear_ancestry(commit_id,
3678 got_worktree_get_base_commit_id(worktree), 0, repo);
3679 if (error != NULL) {
3680 if (error->code == GOT_ERR_ANCESTRY)
3681 error = got_error(GOT_ERR_BRANCH_MOVED);
3682 goto done;
3684 error = check_same_branch(commit_id, head_ref, repo);
3685 if (error)
3686 goto done;
3689 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3690 commit_id) != 0) {
3691 error = got_worktree_set_base_commit_id(worktree, repo,
3692 commit_id);
3693 if (error)
3694 goto done;
3697 memset(&upa, 0, sizeof(upa));
3698 upa.verbosity = verbosity;
3699 error = got_worktree_checkout_files(worktree, &paths, repo,
3700 update_progress, &upa, check_cancelled, NULL);
3701 if (error != NULL)
3702 goto done;
3704 if (upa.did_something) {
3705 printf("Updated to %s: %s\n",
3706 got_worktree_get_head_ref_name(worktree), commit_id_str);
3707 } else
3708 printf("Already up-to-date\n");
3710 print_update_progress_stats(&upa);
3711 done:
3712 if (pack_fds) {
3713 const struct got_error *pack_err =
3714 got_repo_pack_fds_close(pack_fds);
3715 if (error == NULL)
3716 error = pack_err;
3718 if (repo) {
3719 close_err = got_repo_close(repo);
3720 if (error == NULL)
3721 error = close_err;
3723 if (worktree != NULL) {
3724 close_err = got_worktree_close(worktree);
3725 if (error == NULL)
3726 error = close_err;
3728 if (head_ref != NULL)
3729 got_ref_close(head_ref);
3730 free(worktree_path);
3731 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3732 free(commit_id);
3733 free(commit_id_str);
3734 return error;
3737 static const struct got_error *
3738 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3739 const char *path, int diff_context, int ignore_whitespace,
3740 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3741 struct got_repository *repo, FILE *outfile)
3743 const struct got_error *err = NULL;
3744 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3745 FILE *f1 = NULL, *f2 = NULL;
3746 int fd1 = -1, fd2 = -1;
3748 fd1 = got_opentempfd();
3749 if (fd1 == -1)
3750 return got_error_from_errno("got_opentempfd");
3751 fd2 = got_opentempfd();
3752 if (fd2 == -1) {
3753 err = got_error_from_errno("got_opentempfd");
3754 goto done;
3757 if (blob_id1) {
3758 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3759 fd1);
3760 if (err)
3761 goto done;
3764 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3765 if (err)
3766 goto done;
3768 f1 = got_opentemp();
3769 if (f1 == NULL) {
3770 err = got_error_from_errno("got_opentemp");
3771 goto done;
3773 f2 = got_opentemp();
3774 if (f2 == NULL) {
3775 err = got_error_from_errno("got_opentemp");
3776 goto done;
3779 while (path[0] == '/')
3780 path++;
3781 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3782 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3783 force_text_diff, dsa, outfile);
3784 done:
3785 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3786 err = got_error_from_errno("close");
3787 if (blob1)
3788 got_object_blob_close(blob1);
3789 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3790 err = got_error_from_errno("close");
3791 if (blob2)
3792 got_object_blob_close(blob2);
3793 if (f1 && fclose(f1) == EOF && err == NULL)
3794 err = got_error_from_errno("fclose");
3795 if (f2 && fclose(f2) == EOF && err == NULL)
3796 err = got_error_from_errno("fclose");
3797 return err;
3800 static const struct got_error *
3801 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3802 const char *path, int diff_context, int ignore_whitespace,
3803 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3804 struct got_repository *repo, FILE *outfile)
3806 const struct got_error *err = NULL;
3807 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3808 struct got_diff_blob_output_unidiff_arg arg;
3809 FILE *f1 = NULL, *f2 = NULL;
3810 int fd1 = -1, fd2 = -1;
3812 if (tree_id1) {
3813 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3814 if (err)
3815 goto done;
3816 fd1 = got_opentempfd();
3817 if (fd1 == -1) {
3818 err = got_error_from_errno("got_opentempfd");
3819 goto done;
3823 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3824 if (err)
3825 goto done;
3827 f1 = got_opentemp();
3828 if (f1 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3833 f2 = got_opentemp();
3834 if (f2 == NULL) {
3835 err = got_error_from_errno("got_opentemp");
3836 goto done;
3838 fd2 = got_opentempfd();
3839 if (fd2 == -1) {
3840 err = got_error_from_errno("got_opentempfd");
3841 goto done;
3843 arg.diff_context = diff_context;
3844 arg.ignore_whitespace = ignore_whitespace;
3845 arg.force_text_diff = force_text_diff;
3846 arg.diffstat = dsa;
3847 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3848 arg.outfile = outfile;
3849 arg.lines = NULL;
3850 arg.nlines = 0;
3851 while (path[0] == '/')
3852 path++;
3853 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3854 got_diff_blob_output_unidiff, &arg, 1);
3855 done:
3856 if (tree1)
3857 got_object_tree_close(tree1);
3858 if (tree2)
3859 got_object_tree_close(tree2);
3860 if (f1 && fclose(f1) == EOF && err == NULL)
3861 err = got_error_from_errno("fclose");
3862 if (f2 && fclose(f2) == EOF && err == NULL)
3863 err = got_error_from_errno("fclose");
3864 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3865 err = got_error_from_errno("close");
3866 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3867 err = got_error_from_errno("close");
3868 return err;
3871 static const struct got_error *
3872 get_changed_paths(struct got_pathlist_head *paths,
3873 struct got_commit_object *commit, struct got_repository *repo,
3874 struct got_diffstat_cb_arg *dsa)
3876 const struct got_error *err = NULL;
3877 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3878 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3879 struct got_object_qid *qid;
3880 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3881 FILE *f1 = NULL, *f2 = NULL;
3882 int fd1 = -1, fd2 = -1;
3884 if (dsa) {
3885 cb = got_diff_tree_compute_diffstat;
3887 f1 = got_opentemp();
3888 if (f1 == NULL) {
3889 err = got_error_from_errno("got_opentemp");
3890 goto done;
3892 f2 = got_opentemp();
3893 if (f2 == NULL) {
3894 err = got_error_from_errno("got_opentemp");
3895 goto done;
3897 fd1 = got_opentempfd();
3898 if (fd1 == -1) {
3899 err = got_error_from_errno("got_opentempfd");
3900 goto done;
3902 fd2 = got_opentempfd();
3903 if (fd2 == -1) {
3904 err = got_error_from_errno("got_opentempfd");
3905 goto done;
3909 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3910 if (qid != NULL) {
3911 struct got_commit_object *pcommit;
3912 err = got_object_open_as_commit(&pcommit, repo,
3913 &qid->id);
3914 if (err)
3915 return err;
3917 tree_id1 = got_object_id_dup(
3918 got_object_commit_get_tree_id(pcommit));
3919 if (tree_id1 == NULL) {
3920 got_object_commit_close(pcommit);
3921 return got_error_from_errno("got_object_id_dup");
3923 got_object_commit_close(pcommit);
3927 if (tree_id1) {
3928 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3929 if (err)
3930 goto done;
3933 tree_id2 = got_object_commit_get_tree_id(commit);
3934 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3935 if (err)
3936 goto done;
3938 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3939 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3940 done:
3941 if (tree1)
3942 got_object_tree_close(tree1);
3943 if (tree2)
3944 got_object_tree_close(tree2);
3945 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3946 err = got_error_from_errno("close");
3947 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3948 err = got_error_from_errno("close");
3949 if (f1 && fclose(f1) == EOF && err == NULL)
3950 err = got_error_from_errno("fclose");
3951 if (f2 && fclose(f2) == EOF && err == NULL)
3952 err = got_error_from_errno("fclose");
3953 free(tree_id1);
3954 return err;
3957 static const struct got_error *
3958 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3959 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3960 struct got_repository *repo, FILE *outfile)
3962 const struct got_error *err = NULL;
3963 struct got_commit_object *pcommit = NULL;
3964 char *id_str1 = NULL, *id_str2 = NULL;
3965 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3966 struct got_object_qid *qid;
3968 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3969 if (qid != NULL) {
3970 err = got_object_open_as_commit(&pcommit, repo,
3971 &qid->id);
3972 if (err)
3973 return err;
3974 err = got_object_id_str(&id_str1, &qid->id);
3975 if (err)
3976 goto done;
3979 err = got_object_id_str(&id_str2, id);
3980 if (err)
3981 goto done;
3983 if (path && path[0] != '\0') {
3984 int obj_type;
3985 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3986 if (err)
3987 goto done;
3988 if (pcommit) {
3989 err = got_object_id_by_path(&obj_id1, repo,
3990 pcommit, path);
3991 if (err) {
3992 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3993 free(obj_id2);
3994 goto done;
3998 err = got_object_get_type(&obj_type, repo, obj_id2);
3999 if (err) {
4000 free(obj_id2);
4001 goto done;
4003 fprintf(outfile,
4004 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4005 fprintf(outfile, "commit - %s\n",
4006 id_str1 ? id_str1 : "/dev/null");
4007 fprintf(outfile, "commit + %s\n", id_str2);
4008 switch (obj_type) {
4009 case GOT_OBJ_TYPE_BLOB:
4010 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4011 0, 0, dsa, repo, outfile);
4012 break;
4013 case GOT_OBJ_TYPE_TREE:
4014 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4015 0, 0, dsa, repo, outfile);
4016 break;
4017 default:
4018 err = got_error(GOT_ERR_OBJ_TYPE);
4019 break;
4021 free(obj_id1);
4022 free(obj_id2);
4023 } else {
4024 obj_id2 = got_object_commit_get_tree_id(commit);
4025 if (pcommit)
4026 obj_id1 = got_object_commit_get_tree_id(pcommit);
4027 fprintf(outfile,
4028 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4029 fprintf(outfile, "commit - %s\n",
4030 id_str1 ? id_str1 : "/dev/null");
4031 fprintf(outfile, "commit + %s\n", id_str2);
4032 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4033 dsa, repo, outfile);
4035 done:
4036 free(id_str1);
4037 free(id_str2);
4038 if (pcommit)
4039 got_object_commit_close(pcommit);
4040 return err;
4043 static char *
4044 get_datestr(time_t *time, char *datebuf)
4046 struct tm mytm, *tm;
4047 char *p, *s;
4049 tm = gmtime_r(time, &mytm);
4050 if (tm == NULL)
4051 return NULL;
4052 s = asctime_r(tm, datebuf);
4053 if (s == NULL)
4054 return NULL;
4055 p = strchr(s, '\n');
4056 if (p)
4057 *p = '\0';
4058 return s;
4061 static const struct got_error *
4062 match_commit(int *have_match, struct got_object_id *id,
4063 struct got_commit_object *commit, regex_t *regex)
4065 const struct got_error *err = NULL;
4066 regmatch_t regmatch;
4067 char *id_str = NULL, *logmsg = NULL;
4069 *have_match = 0;
4071 err = got_object_id_str(&id_str, id);
4072 if (err)
4073 return err;
4075 err = got_object_commit_get_logmsg(&logmsg, commit);
4076 if (err)
4077 goto done;
4079 if (regexec(regex, got_object_commit_get_author(commit), 1,
4080 &regmatch, 0) == 0 ||
4081 regexec(regex, got_object_commit_get_committer(commit), 1,
4082 &regmatch, 0) == 0 ||
4083 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4084 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4085 *have_match = 1;
4086 done:
4087 free(id_str);
4088 free(logmsg);
4089 return err;
4092 static void
4093 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4094 regex_t *regex)
4096 regmatch_t regmatch;
4097 struct got_pathlist_entry *pe;
4099 *have_match = 0;
4101 TAILQ_FOREACH(pe, changed_paths, entry) {
4102 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4103 *have_match = 1;
4104 break;
4109 static const struct got_error *
4110 match_patch(int *have_match, struct got_commit_object *commit,
4111 struct got_object_id *id, const char *path, int diff_context,
4112 struct got_repository *repo, regex_t *regex, FILE *f)
4114 const struct got_error *err = NULL;
4115 char *line = NULL;
4116 size_t linesize = 0;
4117 regmatch_t regmatch;
4119 *have_match = 0;
4121 err = got_opentemp_truncate(f);
4122 if (err)
4123 return err;
4125 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4126 if (err)
4127 goto done;
4129 if (fseeko(f, 0L, SEEK_SET) == -1) {
4130 err = got_error_from_errno("fseeko");
4131 goto done;
4134 while (getline(&line, &linesize, f) != -1) {
4135 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4136 *have_match = 1;
4137 break;
4140 done:
4141 free(line);
4142 return err;
4145 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4147 static const struct got_error*
4148 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4149 struct got_object_id *id, struct got_repository *repo,
4150 int local_only)
4152 static const struct got_error *err = NULL;
4153 struct got_reflist_entry *re;
4154 char *s;
4155 const char *name;
4157 *refs_str = NULL;
4159 TAILQ_FOREACH(re, refs, entry) {
4160 struct got_tag_object *tag = NULL;
4161 struct got_object_id *ref_id;
4162 int cmp;
4164 name = got_ref_get_name(re->ref);
4165 if (strcmp(name, GOT_REF_HEAD) == 0)
4166 continue;
4167 if (strncmp(name, "refs/", 5) == 0)
4168 name += 5;
4169 if (strncmp(name, "got/", 4) == 0)
4170 continue;
4171 if (strncmp(name, "heads/", 6) == 0)
4172 name += 6;
4173 if (strncmp(name, "remotes/", 8) == 0) {
4174 if (local_only)
4175 continue;
4176 name += 8;
4177 s = strstr(name, "/" GOT_REF_HEAD);
4178 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4179 continue;
4181 err = got_ref_resolve(&ref_id, repo, re->ref);
4182 if (err)
4183 break;
4184 if (strncmp(name, "tags/", 5) == 0) {
4185 err = got_object_open_as_tag(&tag, repo, ref_id);
4186 if (err) {
4187 if (err->code != GOT_ERR_OBJ_TYPE) {
4188 free(ref_id);
4189 break;
4191 /* Ref points at something other than a tag. */
4192 err = NULL;
4193 tag = NULL;
4196 cmp = got_object_id_cmp(tag ?
4197 got_object_tag_get_object_id(tag) : ref_id, id);
4198 free(ref_id);
4199 if (tag)
4200 got_object_tag_close(tag);
4201 if (cmp != 0)
4202 continue;
4203 s = *refs_str;
4204 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4205 s ? ", " : "", name) == -1) {
4206 err = got_error_from_errno("asprintf");
4207 free(s);
4208 *refs_str = NULL;
4209 break;
4211 free(s);
4214 return err;
4217 static const struct got_error *
4218 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4219 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4221 const struct got_error *err = NULL;
4222 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4223 char *comma, *s, *nl;
4224 struct got_reflist_head *refs;
4225 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4226 struct tm tm;
4227 time_t committer_time;
4229 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4230 if (refs) {
4231 err = build_refs_str(&ref_str, refs, id, repo, 1);
4232 if (err)
4233 return err;
4235 /* Display the first matching ref only. */
4236 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4237 *comma = '\0';
4240 if (ref_str == NULL) {
4241 err = got_object_id_str(&id_str, id);
4242 if (err)
4243 return err;
4246 committer_time = got_object_commit_get_committer_time(commit);
4247 if (gmtime_r(&committer_time, &tm) == NULL) {
4248 err = got_error_from_errno("gmtime_r");
4249 goto done;
4251 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4252 err = got_error(GOT_ERR_NO_SPACE);
4253 goto done;
4256 err = got_object_commit_get_logmsg(&logmsg0, commit);
4257 if (err)
4258 goto done;
4260 s = logmsg0;
4261 while (isspace((unsigned char)s[0]))
4262 s++;
4264 nl = strchr(s, '\n');
4265 if (nl) {
4266 *nl = '\0';
4269 if (ref_str)
4270 printf("%s%-7s %s\n", datebuf, ref_str, s);
4271 else
4272 printf("%s%.7s %s\n", datebuf, id_str, s);
4274 if (fflush(stdout) != 0 && err == NULL)
4275 err = got_error_from_errno("fflush");
4276 done:
4277 free(id_str);
4278 free(ref_str);
4279 free(logmsg0);
4280 return err;
4283 static const struct got_error *
4284 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4286 struct got_pathlist_entry *pe;
4288 if (header != NULL)
4289 printf("%s\n", header);
4291 TAILQ_FOREACH(pe, dsa->paths, entry) {
4292 struct got_diff_changed_path *cp = pe->data;
4293 int pad = dsa->max_path_len - pe->path_len + 1;
4295 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4296 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4298 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4299 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4300 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4302 if (fflush(stdout) != 0)
4303 return got_error_from_errno("fflush");
4305 return NULL;
4308 static const struct got_error *
4309 printfile(FILE *f)
4311 char buf[8192];
4312 size_t r;
4314 if (fseeko(f, 0L, SEEK_SET) == -1)
4315 return got_error_from_errno("fseek");
4317 for (;;) {
4318 r = fread(buf, 1, sizeof(buf), f);
4319 if (r == 0) {
4320 if (ferror(f))
4321 return got_error_from_errno("fread");
4322 if (feof(f))
4323 break;
4325 if (fwrite(buf, 1, r, stdout) != r)
4326 return got_ferror(stdout, GOT_ERR_IO);
4329 return NULL;
4332 static const struct got_error *
4333 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4334 struct got_repository *repo, const char *path,
4335 struct got_pathlist_head *changed_paths,
4336 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4337 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4338 const char *prefix)
4340 const struct got_error *err = NULL;
4341 FILE *f = NULL;
4342 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4343 char datebuf[26];
4344 time_t committer_time;
4345 const char *author, *committer;
4346 char *refs_str = NULL;
4348 err = got_object_id_str(&id_str, id);
4349 if (err)
4350 return err;
4352 if (custom_refs_str == NULL) {
4353 struct got_reflist_head *refs;
4354 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4355 if (refs) {
4356 err = build_refs_str(&refs_str, refs, id, repo, 0);
4357 if (err)
4358 goto done;
4362 printf(GOT_COMMIT_SEP_STR);
4363 if (custom_refs_str)
4364 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4365 custom_refs_str);
4366 else
4367 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4368 refs_str ? " (" : "", refs_str ? refs_str : "",
4369 refs_str ? ")" : "");
4370 free(id_str);
4371 id_str = NULL;
4372 free(refs_str);
4373 refs_str = NULL;
4374 printf("from: %s\n", got_object_commit_get_author(commit));
4375 author = got_object_commit_get_author(commit);
4376 committer = got_object_commit_get_committer(commit);
4377 if (strcmp(author, committer) != 0)
4378 printf("via: %s\n", committer);
4379 committer_time = got_object_commit_get_committer_time(commit);
4380 datestr = get_datestr(&committer_time, datebuf);
4381 if (datestr)
4382 printf("date: %s UTC\n", datestr);
4383 if (got_object_commit_get_nparents(commit) > 1) {
4384 const struct got_object_id_queue *parent_ids;
4385 struct got_object_qid *qid;
4386 int n = 1;
4387 parent_ids = got_object_commit_get_parent_ids(commit);
4388 STAILQ_FOREACH(qid, parent_ids, entry) {
4389 err = got_object_id_str(&id_str, &qid->id);
4390 if (err)
4391 goto done;
4392 printf("parent %d: %s\n", n++, id_str);
4393 free(id_str);
4394 id_str = NULL;
4398 err = got_object_commit_get_logmsg(&logmsg0, commit);
4399 if (err)
4400 goto done;
4402 logmsg = logmsg0;
4403 do {
4404 line = strsep(&logmsg, "\n");
4405 if (line)
4406 printf(" %s\n", line);
4407 } while (line);
4408 free(logmsg0);
4410 if (changed_paths && diffstat == NULL) {
4411 struct got_pathlist_entry *pe;
4413 TAILQ_FOREACH(pe, changed_paths, entry) {
4414 struct got_diff_changed_path *cp = pe->data;
4416 printf(" %c %s\n", cp->status, pe->path);
4418 printf("\n");
4420 if (show_patch) {
4421 if (diffstat) {
4422 f = got_opentemp();
4423 if (f == NULL) {
4424 err = got_error_from_errno("got_opentemp");
4425 goto done;
4429 err = print_patch(commit, id, path, diff_context, diffstat,
4430 repo, diffstat == NULL ? stdout : f);
4431 if (err)
4432 goto done;
4434 if (diffstat) {
4435 err = print_diffstat(diffstat, NULL);
4436 if (err)
4437 goto done;
4438 if (show_patch) {
4439 err = printfile(f);
4440 if (err)
4441 goto done;
4444 if (show_patch)
4445 printf("\n");
4447 if (fflush(stdout) != 0 && err == NULL)
4448 err = got_error_from_errno("fflush");
4449 done:
4450 if (f && fclose(f) == EOF && err == NULL)
4451 err = got_error_from_errno("fclose");
4452 free(id_str);
4453 free(refs_str);
4454 return err;
4457 static const struct got_error *
4458 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4459 struct got_repository *repo, const char *path, int show_changed_paths,
4460 int show_diffstat, int show_patch, const char *search_pattern,
4461 int diff_context, int limit, int log_branches, int reverse_display_order,
4462 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4463 FILE *tmpfile)
4465 const struct got_error *err;
4466 struct got_commit_graph *graph;
4467 regex_t regex;
4468 int have_match;
4469 struct got_object_id_queue reversed_commits;
4470 struct got_object_qid *qid;
4471 struct got_commit_object *commit;
4472 struct got_pathlist_head changed_paths;
4474 STAILQ_INIT(&reversed_commits);
4475 TAILQ_INIT(&changed_paths);
4477 if (search_pattern && regcomp(&regex, search_pattern,
4478 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4479 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4481 err = got_commit_graph_open(&graph, path, !log_branches);
4482 if (err)
4483 return err;
4484 if (log_branches && toposort) {
4485 err = got_commit_graph_toposort(graph, root_id, repo,
4486 check_cancelled, NULL);
4487 } else {
4488 err = got_commit_graph_bfsort(graph, root_id, repo,
4489 check_cancelled, NULL);
4491 if (err)
4492 goto done;
4493 for (;;) {
4494 struct got_object_id id;
4495 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4496 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4498 if (sigint_received || sigpipe_received)
4499 break;
4501 err = got_commit_graph_iter_next(&id, graph, repo,
4502 check_cancelled, NULL);
4503 if (err) {
4504 if (err->code == GOT_ERR_ITER_COMPLETED)
4505 err = NULL;
4506 break;
4509 err = got_object_open_as_commit(&commit, repo, &id);
4510 if (err)
4511 break;
4513 if (((show_changed_paths && !show_diffstat) ||
4514 (show_diffstat && !show_patch))
4515 && !reverse_display_order) {
4516 err = get_changed_paths(&changed_paths, commit, repo,
4517 show_diffstat ? &dsa : NULL);
4518 if (err)
4519 break;
4522 if (search_pattern) {
4523 err = match_commit(&have_match, &id, commit, &regex);
4524 if (err) {
4525 got_object_commit_close(commit);
4526 break;
4528 if (have_match == 0 && show_changed_paths)
4529 match_changed_paths(&have_match,
4530 &changed_paths, &regex);
4531 if (have_match == 0 && show_patch) {
4532 err = match_patch(&have_match, commit, &id,
4533 path, diff_context, repo, &regex, tmpfile);
4534 if (err)
4535 break;
4537 if (have_match == 0) {
4538 got_object_commit_close(commit);
4539 got_pathlist_free(&changed_paths,
4540 GOT_PATHLIST_FREE_ALL);
4541 continue;
4545 if (reverse_display_order) {
4546 err = got_object_qid_alloc(&qid, &id);
4547 if (err)
4548 break;
4549 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4550 got_object_commit_close(commit);
4551 } else {
4552 if (one_line)
4553 err = print_commit_oneline(commit, &id,
4554 repo, refs_idmap);
4555 else
4556 err = print_commit(commit, &id, repo, path,
4557 (show_changed_paths || show_diffstat) ?
4558 &changed_paths : NULL,
4559 show_diffstat ? &dsa : NULL, show_patch,
4560 diff_context, refs_idmap, NULL, NULL);
4561 got_object_commit_close(commit);
4562 if (err)
4563 break;
4565 if ((limit && --limit == 0) ||
4566 (end_id && got_object_id_cmp(&id, end_id) == 0))
4567 break;
4569 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4571 if (reverse_display_order) {
4572 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4573 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4574 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4576 err = got_object_open_as_commit(&commit, repo,
4577 &qid->id);
4578 if (err)
4579 break;
4580 if ((show_changed_paths && !show_diffstat) ||
4581 (show_diffstat && !show_patch)) {
4582 err = get_changed_paths(&changed_paths, commit,
4583 repo, show_diffstat ? &dsa : NULL);
4584 if (err)
4585 break;
4587 if (one_line)
4588 err = print_commit_oneline(commit, &qid->id,
4589 repo, refs_idmap);
4590 else
4591 err = print_commit(commit, &qid->id, repo, path,
4592 (show_changed_paths || show_diffstat) ?
4593 &changed_paths : NULL,
4594 show_diffstat ? &dsa : NULL, show_patch,
4595 diff_context, refs_idmap, NULL, NULL);
4596 got_object_commit_close(commit);
4597 if (err)
4598 break;
4599 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4602 done:
4603 while (!STAILQ_EMPTY(&reversed_commits)) {
4604 qid = STAILQ_FIRST(&reversed_commits);
4605 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4606 got_object_qid_free(qid);
4608 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4609 if (search_pattern)
4610 regfree(&regex);
4611 got_commit_graph_close(graph);
4612 return err;
4615 __dead static void
4616 usage_log(void)
4618 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4619 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4620 "[path]\n", getprogname());
4621 exit(1);
4624 static int
4625 get_default_log_limit(void)
4627 const char *got_default_log_limit;
4628 long long n;
4629 const char *errstr;
4631 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4632 if (got_default_log_limit == NULL)
4633 return 0;
4634 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4635 if (errstr != NULL)
4636 return 0;
4637 return n;
4640 static const struct got_error *
4641 cmd_log(int argc, char *argv[])
4643 const struct got_error *error;
4644 struct got_repository *repo = NULL;
4645 struct got_worktree *worktree = NULL;
4646 struct got_object_id *start_id = NULL, *end_id = NULL;
4647 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4648 char *keyword_idstr = NULL;
4649 const char *start_commit = NULL, *end_commit = NULL;
4650 const char *search_pattern = NULL;
4651 int diff_context = -1, ch;
4652 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4653 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4654 int toposort = 0;
4655 const char *errstr;
4656 struct got_reflist_head refs;
4657 struct got_reflist_object_id_map *refs_idmap = NULL;
4658 FILE *tmpfile = NULL;
4659 int *pack_fds = NULL;
4661 TAILQ_INIT(&refs);
4663 #ifndef PROFILE
4664 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4665 NULL)
4666 == -1)
4667 err(1, "pledge");
4668 #endif
4670 limit = get_default_log_limit();
4672 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4673 switch (ch) {
4674 case 'b':
4675 log_branches = 1;
4676 break;
4677 case 'C':
4678 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4679 &errstr);
4680 if (errstr != NULL)
4681 errx(1, "number of context lines is %s: %s",
4682 errstr, optarg);
4683 break;
4684 case 'c':
4685 start_commit = optarg;
4686 break;
4687 case 'd':
4688 show_diffstat = 1;
4689 break;
4690 case 'l':
4691 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4692 if (errstr != NULL)
4693 errx(1, "number of commits is %s: %s",
4694 errstr, optarg);
4695 break;
4696 case 'P':
4697 show_changed_paths = 1;
4698 break;
4699 case 'p':
4700 show_patch = 1;
4701 break;
4702 case 'R':
4703 reverse_display_order = 1;
4704 break;
4705 case 'r':
4706 repo_path = realpath(optarg, NULL);
4707 if (repo_path == NULL)
4708 return got_error_from_errno2("realpath",
4709 optarg);
4710 got_path_strip_trailing_slashes(repo_path);
4711 break;
4712 case 'S':
4713 search_pattern = optarg;
4714 break;
4715 case 's':
4716 one_line = 1;
4717 break;
4718 case 't':
4719 toposort = 1;
4720 break;
4721 case 'x':
4722 end_commit = optarg;
4723 break;
4724 default:
4725 usage_log();
4726 /* NOTREACHED */
4730 argc -= optind;
4731 argv += optind;
4733 if (diff_context == -1)
4734 diff_context = 3;
4735 else if (!show_patch)
4736 errx(1, "-C requires -p");
4738 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4739 errx(1, "cannot use -s with -d, -p or -P");
4741 cwd = getcwd(NULL, 0);
4742 if (cwd == NULL) {
4743 error = got_error_from_errno("getcwd");
4744 goto done;
4747 error = got_repo_pack_fds_open(&pack_fds);
4748 if (error != NULL)
4749 goto done;
4751 if (repo_path == NULL) {
4752 error = got_worktree_open(&worktree, cwd,
4753 GOT_WORKTREE_GOT_DIR);
4754 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4755 goto done;
4756 error = NULL;
4759 if (argc == 1) {
4760 if (worktree) {
4761 error = got_worktree_resolve_path(&path, worktree,
4762 argv[0]);
4763 if (error)
4764 goto done;
4765 } else {
4766 path = strdup(argv[0]);
4767 if (path == NULL) {
4768 error = got_error_from_errno("strdup");
4769 goto done;
4772 } else if (argc != 0)
4773 usage_log();
4775 if (repo_path == NULL) {
4776 repo_path = worktree ?
4777 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4779 if (repo_path == NULL) {
4780 error = got_error_from_errno("strdup");
4781 goto done;
4784 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4785 if (error != NULL)
4786 goto done;
4788 error = apply_unveil(got_repo_get_path(repo), 1,
4789 worktree ? got_worktree_get_root_path(worktree) : NULL);
4790 if (error)
4791 goto done;
4793 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4794 if (error)
4795 goto done;
4797 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4798 if (error)
4799 goto done;
4801 if (start_commit == NULL) {
4802 struct got_reference *head_ref;
4803 struct got_commit_object *commit = NULL;
4804 error = got_ref_open(&head_ref, repo,
4805 worktree ? got_worktree_get_head_ref_name(worktree)
4806 : GOT_REF_HEAD, 0);
4807 if (error != NULL)
4808 goto done;
4809 error = got_ref_resolve(&start_id, repo, head_ref);
4810 got_ref_close(head_ref);
4811 if (error != NULL)
4812 goto done;
4813 error = got_object_open_as_commit(&commit, repo,
4814 start_id);
4815 if (error != NULL)
4816 goto done;
4817 got_object_commit_close(commit);
4818 } else {
4819 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4820 repo, worktree);
4821 if (error != NULL)
4822 goto done;
4823 if (keyword_idstr != NULL)
4824 start_commit = keyword_idstr;
4826 error = got_repo_match_object_id(&start_id, NULL,
4827 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4828 if (error != NULL)
4829 goto done;
4831 if (end_commit != NULL) {
4832 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4833 repo, worktree);
4834 if (error != NULL)
4835 goto done;
4836 if (keyword_idstr != NULL)
4837 end_commit = keyword_idstr;
4839 error = got_repo_match_object_id(&end_id, NULL,
4840 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4841 if (error != NULL)
4842 goto done;
4845 if (worktree) {
4847 * If a path was specified on the command line it was resolved
4848 * to a path in the work tree above. Prepend the work tree's
4849 * path prefix to obtain the corresponding in-repository path.
4851 if (path) {
4852 const char *prefix;
4853 prefix = got_worktree_get_path_prefix(worktree);
4854 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4855 (path[0] != '\0') ? "/" : "", path) == -1) {
4856 error = got_error_from_errno("asprintf");
4857 goto done;
4860 } else
4861 error = got_repo_map_path(&in_repo_path, repo,
4862 path ? path : "");
4863 if (error != NULL)
4864 goto done;
4865 if (in_repo_path) {
4866 free(path);
4867 path = in_repo_path;
4870 if (worktree) {
4871 /* Release work tree lock. */
4872 got_worktree_close(worktree);
4873 worktree = NULL;
4876 if (search_pattern && show_patch) {
4877 tmpfile = got_opentemp();
4878 if (tmpfile == NULL) {
4879 error = got_error_from_errno("got_opentemp");
4880 goto done;
4884 error = print_commits(start_id, end_id, repo, path ? path : "",
4885 show_changed_paths, show_diffstat, show_patch, search_pattern,
4886 diff_context, limit, log_branches, reverse_display_order,
4887 refs_idmap, one_line, toposort, tmpfile);
4888 done:
4889 free(path);
4890 free(repo_path);
4891 free(cwd);
4892 free(start_id);
4893 free(end_id);
4894 free(keyword_idstr);
4895 if (worktree)
4896 got_worktree_close(worktree);
4897 if (repo) {
4898 const struct got_error *close_err = got_repo_close(repo);
4899 if (error == NULL)
4900 error = close_err;
4902 if (pack_fds) {
4903 const struct got_error *pack_err =
4904 got_repo_pack_fds_close(pack_fds);
4905 if (error == NULL)
4906 error = pack_err;
4908 if (refs_idmap)
4909 got_reflist_object_id_map_free(refs_idmap);
4910 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4911 error = got_error_from_errno("fclose");
4912 got_ref_list_free(&refs);
4913 return error;
4916 __dead static void
4917 usage_diff(void)
4919 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4920 "[-r repository-path] [object1 object2 | path ...]\n",
4921 getprogname());
4922 exit(1);
4925 struct print_diff_arg {
4926 struct got_repository *repo;
4927 struct got_worktree *worktree;
4928 struct got_diffstat_cb_arg *diffstat;
4929 int diff_context;
4930 const char *id_str;
4931 int header_shown;
4932 int diff_staged;
4933 enum got_diff_algorithm diff_algo;
4934 int ignore_whitespace;
4935 int force_text_diff;
4936 FILE *f1;
4937 FILE *f2;
4938 FILE *outfile;
4942 * Create a file which contains the target path of a symlink so we can feed
4943 * it as content to the diff engine.
4945 static const struct got_error *
4946 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4947 const char *abspath)
4949 const struct got_error *err = NULL;
4950 char target_path[PATH_MAX];
4951 ssize_t target_len, outlen;
4953 *fd = -1;
4955 if (dirfd != -1) {
4956 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4957 if (target_len == -1)
4958 return got_error_from_errno2("readlinkat", abspath);
4959 } else {
4960 target_len = readlink(abspath, target_path, PATH_MAX);
4961 if (target_len == -1)
4962 return got_error_from_errno2("readlink", abspath);
4965 *fd = got_opentempfd();
4966 if (*fd == -1)
4967 return got_error_from_errno("got_opentempfd");
4969 outlen = write(*fd, target_path, target_len);
4970 if (outlen == -1) {
4971 err = got_error_from_errno("got_opentempfd");
4972 goto done;
4975 if (lseek(*fd, 0, SEEK_SET) == -1) {
4976 err = got_error_from_errno2("lseek", abspath);
4977 goto done;
4979 done:
4980 if (err) {
4981 close(*fd);
4982 *fd = -1;
4984 return err;
4987 static const struct got_error *
4988 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4989 const char *path, struct got_object_id *blob_id,
4990 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4991 int dirfd, const char *de_name)
4993 struct print_diff_arg *a = arg;
4994 const struct got_error *err = NULL;
4995 struct got_blob_object *blob1 = NULL;
4996 int fd = -1, fd1 = -1, fd2 = -1;
4997 FILE *f2 = NULL;
4998 char *abspath = NULL, *label1 = NULL;
4999 struct stat sb;
5000 off_t size1 = 0;
5001 int f2_exists = 0;
5003 memset(&sb, 0, sizeof(sb));
5005 if (a->diff_staged) {
5006 if (staged_status != GOT_STATUS_MODIFY &&
5007 staged_status != GOT_STATUS_ADD &&
5008 staged_status != GOT_STATUS_DELETE)
5009 return NULL;
5010 } else {
5011 if (staged_status == GOT_STATUS_DELETE)
5012 return NULL;
5013 if (status == GOT_STATUS_NONEXISTENT)
5014 return got_error_set_errno(ENOENT, path);
5015 if (status != GOT_STATUS_MODIFY &&
5016 status != GOT_STATUS_ADD &&
5017 status != GOT_STATUS_DELETE &&
5018 status != GOT_STATUS_CONFLICT)
5019 return NULL;
5022 err = got_opentemp_truncate(a->f1);
5023 if (err)
5024 return got_error_from_errno("got_opentemp_truncate");
5025 err = got_opentemp_truncate(a->f2);
5026 if (err)
5027 return got_error_from_errno("got_opentemp_truncate");
5029 if (!a->header_shown) {
5030 if (fprintf(a->outfile, "diff %s%s\n",
5031 a->diff_staged ? "-s " : "",
5032 got_worktree_get_root_path(a->worktree)) < 0) {
5033 err = got_error_from_errno("fprintf");
5034 goto done;
5036 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5037 err = got_error_from_errno("fprintf");
5038 goto done;
5040 if (fprintf(a->outfile, "path + %s%s\n",
5041 got_worktree_get_root_path(a->worktree),
5042 a->diff_staged ? " (staged changes)" : "") < 0) {
5043 err = got_error_from_errno("fprintf");
5044 goto done;
5046 a->header_shown = 1;
5049 if (a->diff_staged) {
5050 const char *label1 = NULL, *label2 = NULL;
5051 switch (staged_status) {
5052 case GOT_STATUS_MODIFY:
5053 label1 = path;
5054 label2 = path;
5055 break;
5056 case GOT_STATUS_ADD:
5057 label2 = path;
5058 break;
5059 case GOT_STATUS_DELETE:
5060 label1 = path;
5061 break;
5062 default:
5063 return got_error(GOT_ERR_FILE_STATUS);
5065 fd1 = got_opentempfd();
5066 if (fd1 == -1) {
5067 err = got_error_from_errno("got_opentempfd");
5068 goto done;
5070 fd2 = got_opentempfd();
5071 if (fd2 == -1) {
5072 err = got_error_from_errno("got_opentempfd");
5073 goto done;
5075 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5076 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5077 a->diff_algo, a->diff_context, a->ignore_whitespace,
5078 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5079 goto done;
5082 fd1 = got_opentempfd();
5083 if (fd1 == -1) {
5084 err = got_error_from_errno("got_opentempfd");
5085 goto done;
5088 if (staged_status == GOT_STATUS_ADD ||
5089 staged_status == GOT_STATUS_MODIFY) {
5090 char *id_str;
5091 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5092 8192, fd1);
5093 if (err)
5094 goto done;
5095 err = got_object_id_str(&id_str, staged_blob_id);
5096 if (err)
5097 goto done;
5098 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5099 err = got_error_from_errno("asprintf");
5100 free(id_str);
5101 goto done;
5103 free(id_str);
5104 } else if (status != GOT_STATUS_ADD) {
5105 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5106 fd1);
5107 if (err)
5108 goto done;
5111 if (status != GOT_STATUS_DELETE) {
5112 if (asprintf(&abspath, "%s/%s",
5113 got_worktree_get_root_path(a->worktree), path) == -1) {
5114 err = got_error_from_errno("asprintf");
5115 goto done;
5118 if (dirfd != -1) {
5119 fd = openat(dirfd, de_name,
5120 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5121 if (fd == -1) {
5122 if (!got_err_open_nofollow_on_symlink()) {
5123 err = got_error_from_errno2("openat",
5124 abspath);
5125 goto done;
5127 err = get_symlink_target_file(&fd, dirfd,
5128 de_name, abspath);
5129 if (err)
5130 goto done;
5132 } else {
5133 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5134 if (fd == -1) {
5135 if (!got_err_open_nofollow_on_symlink()) {
5136 err = got_error_from_errno2("open",
5137 abspath);
5138 goto done;
5140 err = get_symlink_target_file(&fd, dirfd,
5141 de_name, abspath);
5142 if (err)
5143 goto done;
5146 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5147 err = got_error_from_errno2("fstatat", abspath);
5148 goto done;
5150 f2 = fdopen(fd, "r");
5151 if (f2 == NULL) {
5152 err = got_error_from_errno2("fdopen", abspath);
5153 goto done;
5155 fd = -1;
5156 f2_exists = 1;
5159 if (blob1) {
5160 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5161 a->f1, blob1);
5162 if (err)
5163 goto done;
5166 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5167 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5168 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5169 done:
5170 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5171 err = got_error_from_errno("close");
5172 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5173 err = got_error_from_errno("close");
5174 if (blob1)
5175 got_object_blob_close(blob1);
5176 if (fd != -1 && close(fd) == -1 && err == NULL)
5177 err = got_error_from_errno("close");
5178 if (f2 && fclose(f2) == EOF && err == NULL)
5179 err = got_error_from_errno("fclose");
5180 free(abspath);
5181 return err;
5184 static const struct got_error *
5185 cmd_diff(int argc, char *argv[])
5187 const struct got_error *error;
5188 struct got_repository *repo = NULL;
5189 struct got_worktree *worktree = NULL;
5190 char *cwd = NULL, *repo_path = NULL;
5191 const char *commit_args[2] = { NULL, NULL };
5192 int ncommit_args = 0;
5193 struct got_object_id *ids[2] = { NULL, NULL };
5194 char *labels[2] = { NULL, NULL };
5195 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5196 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5197 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5198 const char *errstr;
5199 struct got_reflist_head refs;
5200 struct got_pathlist_head diffstat_paths, paths;
5201 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5202 int fd1 = -1, fd2 = -1;
5203 int *pack_fds = NULL;
5204 struct got_diffstat_cb_arg dsa;
5206 memset(&dsa, 0, sizeof(dsa));
5208 TAILQ_INIT(&refs);
5209 TAILQ_INIT(&paths);
5210 TAILQ_INIT(&diffstat_paths);
5212 #ifndef PROFILE
5213 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5214 NULL) == -1)
5215 err(1, "pledge");
5216 #endif
5218 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5219 switch (ch) {
5220 case 'a':
5221 force_text_diff = 1;
5222 break;
5223 case 'C':
5224 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5225 &errstr);
5226 if (errstr != NULL)
5227 errx(1, "number of context lines is %s: %s",
5228 errstr, optarg);
5229 break;
5230 case 'c':
5231 if (ncommit_args >= 2)
5232 errx(1, "too many -c options used");
5233 commit_args[ncommit_args++] = optarg;
5234 break;
5235 case 'd':
5236 show_diffstat = 1;
5237 break;
5238 case 'P':
5239 force_path = 1;
5240 break;
5241 case 'r':
5242 repo_path = realpath(optarg, NULL);
5243 if (repo_path == NULL)
5244 return got_error_from_errno2("realpath",
5245 optarg);
5246 got_path_strip_trailing_slashes(repo_path);
5247 rflag = 1;
5248 break;
5249 case 's':
5250 diff_staged = 1;
5251 break;
5252 case 'w':
5253 ignore_whitespace = 1;
5254 break;
5255 default:
5256 usage_diff();
5257 /* NOTREACHED */
5261 argc -= optind;
5262 argv += optind;
5264 cwd = getcwd(NULL, 0);
5265 if (cwd == NULL) {
5266 error = got_error_from_errno("getcwd");
5267 goto done;
5270 error = got_repo_pack_fds_open(&pack_fds);
5271 if (error != NULL)
5272 goto done;
5274 if (repo_path == NULL) {
5275 error = got_worktree_open(&worktree, cwd,
5276 GOT_WORKTREE_GOT_DIR);
5277 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5278 goto done;
5279 else
5280 error = NULL;
5281 if (worktree) {
5282 repo_path =
5283 strdup(got_worktree_get_repo_path(worktree));
5284 if (repo_path == NULL) {
5285 error = got_error_from_errno("strdup");
5286 goto done;
5288 } else {
5289 repo_path = strdup(cwd);
5290 if (repo_path == NULL) {
5291 error = got_error_from_errno("strdup");
5292 goto done;
5297 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5298 free(repo_path);
5299 if (error != NULL)
5300 goto done;
5302 if (show_diffstat) {
5303 dsa.paths = &diffstat_paths;
5304 dsa.force_text = force_text_diff;
5305 dsa.ignore_ws = ignore_whitespace;
5306 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5309 if (rflag || worktree == NULL || ncommit_args > 0) {
5310 if (force_path) {
5311 error = got_error_msg(GOT_ERR_NOT_IMPL,
5312 "-P option can only be used when diffing "
5313 "a work tree");
5314 goto done;
5316 if (diff_staged) {
5317 error = got_error_msg(GOT_ERR_NOT_IMPL,
5318 "-s option can only be used when diffing "
5319 "a work tree");
5320 goto done;
5324 error = apply_unveil(got_repo_get_path(repo), 1,
5325 worktree ? got_worktree_get_root_path(worktree) : NULL);
5326 if (error)
5327 goto done;
5329 if ((!force_path && argc == 2) || ncommit_args > 0) {
5330 int obj_type = (ncommit_args > 0 ?
5331 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5332 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5333 NULL);
5334 if (error)
5335 goto done;
5336 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5337 const char *arg;
5338 char *keyword_idstr = NULL;
5340 if (ncommit_args > 0)
5341 arg = commit_args[i];
5342 else
5343 arg = argv[i];
5345 error = got_keyword_to_idstr(&keyword_idstr, arg,
5346 repo, worktree);
5347 if (error != NULL)
5348 goto done;
5349 if (keyword_idstr != NULL)
5350 arg = keyword_idstr;
5352 error = got_repo_match_object_id(&ids[i], &labels[i],
5353 arg, obj_type, &refs, repo);
5354 free(keyword_idstr);
5355 if (error) {
5356 if (error->code != GOT_ERR_NOT_REF &&
5357 error->code != GOT_ERR_NO_OBJ)
5358 goto done;
5359 if (ncommit_args > 0)
5360 goto done;
5361 error = NULL;
5362 break;
5367 f1 = got_opentemp();
5368 if (f1 == NULL) {
5369 error = got_error_from_errno("got_opentemp");
5370 goto done;
5373 f2 = got_opentemp();
5374 if (f2 == NULL) {
5375 error = got_error_from_errno("got_opentemp");
5376 goto done;
5379 outfile = got_opentemp();
5380 if (outfile == NULL) {
5381 error = got_error_from_errno("got_opentemp");
5382 goto done;
5385 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5386 struct print_diff_arg arg;
5387 char *id_str;
5389 if (worktree == NULL) {
5390 if (argc == 2 && ids[0] == NULL) {
5391 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5392 goto done;
5393 } else if (argc == 2 && ids[1] == NULL) {
5394 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5395 goto done;
5396 } else if (argc > 0) {
5397 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5398 "%s", "specified paths cannot be resolved");
5399 goto done;
5400 } else {
5401 error = got_error(GOT_ERR_NOT_WORKTREE);
5402 goto done;
5406 error = get_worktree_paths_from_argv(&paths, argc, argv,
5407 worktree);
5408 if (error)
5409 goto done;
5411 error = got_object_id_str(&id_str,
5412 got_worktree_get_base_commit_id(worktree));
5413 if (error)
5414 goto done;
5415 arg.repo = repo;
5416 arg.worktree = worktree;
5417 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5418 arg.diff_context = diff_context;
5419 arg.id_str = id_str;
5420 arg.header_shown = 0;
5421 arg.diff_staged = diff_staged;
5422 arg.ignore_whitespace = ignore_whitespace;
5423 arg.force_text_diff = force_text_diff;
5424 arg.diffstat = show_diffstat ? &dsa : NULL;
5425 arg.f1 = f1;
5426 arg.f2 = f2;
5427 arg.outfile = outfile;
5429 error = got_worktree_status(worktree, &paths, repo, 0,
5430 print_diff, &arg, check_cancelled, NULL);
5431 free(id_str);
5432 if (error)
5433 goto done;
5435 if (show_diffstat && dsa.nfiles > 0) {
5436 char *header;
5438 if (asprintf(&header, "diffstat %s%s",
5439 diff_staged ? "-s " : "",
5440 got_worktree_get_root_path(worktree)) == -1) {
5441 error = got_error_from_errno("asprintf");
5442 goto done;
5445 error = print_diffstat(&dsa, header);
5446 free(header);
5447 if (error)
5448 goto done;
5451 error = printfile(outfile);
5452 goto done;
5455 if (ncommit_args == 1) {
5456 struct got_commit_object *commit;
5457 error = got_object_open_as_commit(&commit, repo, ids[0]);
5458 if (error)
5459 goto done;
5461 labels[1] = labels[0];
5462 ids[1] = ids[0];
5463 if (got_object_commit_get_nparents(commit) > 0) {
5464 const struct got_object_id_queue *pids;
5465 struct got_object_qid *pid;
5466 pids = got_object_commit_get_parent_ids(commit);
5467 pid = STAILQ_FIRST(pids);
5468 ids[0] = got_object_id_dup(&pid->id);
5469 if (ids[0] == NULL) {
5470 error = got_error_from_errno(
5471 "got_object_id_dup");
5472 got_object_commit_close(commit);
5473 goto done;
5475 error = got_object_id_str(&labels[0], ids[0]);
5476 if (error) {
5477 got_object_commit_close(commit);
5478 goto done;
5480 } else {
5481 ids[0] = NULL;
5482 labels[0] = strdup("/dev/null");
5483 if (labels[0] == NULL) {
5484 error = got_error_from_errno("strdup");
5485 got_object_commit_close(commit);
5486 goto done;
5490 got_object_commit_close(commit);
5493 if (ncommit_args == 0 && argc > 2) {
5494 error = got_error_msg(GOT_ERR_BAD_PATH,
5495 "path arguments cannot be used when diffing two objects");
5496 goto done;
5499 if (ids[0]) {
5500 error = got_object_get_type(&type1, repo, ids[0]);
5501 if (error)
5502 goto done;
5505 error = got_object_get_type(&type2, repo, ids[1]);
5506 if (error)
5507 goto done;
5508 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5509 error = got_error(GOT_ERR_OBJ_TYPE);
5510 goto done;
5512 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5513 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5514 "path arguments cannot be used when diffing blobs");
5515 goto done;
5518 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5519 char *in_repo_path;
5520 struct got_pathlist_entry *new;
5521 if (worktree) {
5522 const char *prefix;
5523 char *p;
5524 error = got_worktree_resolve_path(&p, worktree,
5525 argv[i]);
5526 if (error)
5527 goto done;
5528 prefix = got_worktree_get_path_prefix(worktree);
5529 while (prefix[0] == '/')
5530 prefix++;
5531 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5532 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5533 p) == -1) {
5534 error = got_error_from_errno("asprintf");
5535 free(p);
5536 goto done;
5538 free(p);
5539 } else {
5540 char *mapped_path, *s;
5541 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5542 if (error)
5543 goto done;
5544 s = mapped_path;
5545 while (s[0] == '/')
5546 s++;
5547 in_repo_path = strdup(s);
5548 if (in_repo_path == NULL) {
5549 error = got_error_from_errno("asprintf");
5550 free(mapped_path);
5551 goto done;
5553 free(mapped_path);
5556 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5557 if (error || new == NULL /* duplicate */)
5558 free(in_repo_path);
5559 if (error)
5560 goto done;
5563 if (worktree) {
5564 /* Release work tree lock. */
5565 got_worktree_close(worktree);
5566 worktree = NULL;
5569 fd1 = got_opentempfd();
5570 if (fd1 == -1) {
5571 error = got_error_from_errno("got_opentempfd");
5572 goto done;
5575 fd2 = got_opentempfd();
5576 if (fd2 == -1) {
5577 error = got_error_from_errno("got_opentempfd");
5578 goto done;
5581 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5582 case GOT_OBJ_TYPE_BLOB:
5583 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5584 fd1, fd2, ids[0], ids[1], NULL, NULL,
5585 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5586 ignore_whitespace, force_text_diff,
5587 show_diffstat ? &dsa : NULL, repo, outfile);
5588 break;
5589 case GOT_OBJ_TYPE_TREE:
5590 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5591 ids[0], ids[1], &paths, "", "",
5592 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5593 ignore_whitespace, force_text_diff,
5594 show_diffstat ? &dsa : NULL, repo, outfile);
5595 break;
5596 case GOT_OBJ_TYPE_COMMIT:
5597 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5598 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5599 fd1, fd2, ids[0], ids[1], &paths,
5600 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5601 ignore_whitespace, force_text_diff,
5602 show_diffstat ? &dsa : NULL, repo, outfile);
5603 break;
5604 default:
5605 error = got_error(GOT_ERR_OBJ_TYPE);
5607 if (error)
5608 goto done;
5610 if (show_diffstat && dsa.nfiles > 0) {
5611 char *header = NULL;
5613 if (asprintf(&header, "diffstat %s %s",
5614 labels[0], labels[1]) == -1) {
5615 error = got_error_from_errno("asprintf");
5616 goto done;
5619 error = print_diffstat(&dsa, header);
5620 free(header);
5621 if (error)
5622 goto done;
5625 error = printfile(outfile);
5627 done:
5628 free(labels[0]);
5629 free(labels[1]);
5630 free(ids[0]);
5631 free(ids[1]);
5632 if (worktree)
5633 got_worktree_close(worktree);
5634 if (repo) {
5635 const struct got_error *close_err = got_repo_close(repo);
5636 if (error == NULL)
5637 error = close_err;
5639 if (pack_fds) {
5640 const struct got_error *pack_err =
5641 got_repo_pack_fds_close(pack_fds);
5642 if (error == NULL)
5643 error = pack_err;
5645 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5646 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5647 got_ref_list_free(&refs);
5648 if (outfile && fclose(outfile) == EOF && error == NULL)
5649 error = got_error_from_errno("fclose");
5650 if (f1 && fclose(f1) == EOF && error == NULL)
5651 error = got_error_from_errno("fclose");
5652 if (f2 && fclose(f2) == EOF && error == NULL)
5653 error = got_error_from_errno("fclose");
5654 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5655 error = got_error_from_errno("close");
5656 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5657 error = got_error_from_errno("close");
5658 return error;
5661 __dead static void
5662 usage_blame(void)
5664 fprintf(stderr,
5665 "usage: %s blame [-c commit] [-r repository-path] path\n",
5666 getprogname());
5667 exit(1);
5670 struct blame_line {
5671 int annotated;
5672 char *id_str;
5673 char *committer;
5674 char datebuf[11]; /* YYYY-MM-DD + NUL */
5677 struct blame_cb_args {
5678 struct blame_line *lines;
5679 int nlines;
5680 int nlines_prec;
5681 int lineno_cur;
5682 off_t *line_offsets;
5683 FILE *f;
5684 struct got_repository *repo;
5687 static const struct got_error *
5688 blame_cb(void *arg, int nlines, int lineno,
5689 struct got_commit_object *commit, struct got_object_id *id)
5691 const struct got_error *err = NULL;
5692 struct blame_cb_args *a = arg;
5693 struct blame_line *bline;
5694 char *line = NULL;
5695 size_t linesize = 0;
5696 off_t offset;
5697 struct tm tm;
5698 time_t committer_time;
5700 if (nlines != a->nlines ||
5701 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5702 return got_error(GOT_ERR_RANGE);
5704 if (sigint_received)
5705 return got_error(GOT_ERR_ITER_COMPLETED);
5707 if (lineno == -1)
5708 return NULL; /* no change in this commit */
5710 /* Annotate this line. */
5711 bline = &a->lines[lineno - 1];
5712 if (bline->annotated)
5713 return NULL;
5714 err = got_object_id_str(&bline->id_str, id);
5715 if (err)
5716 return err;
5718 bline->committer = strdup(got_object_commit_get_committer(commit));
5719 if (bline->committer == NULL) {
5720 err = got_error_from_errno("strdup");
5721 goto done;
5724 committer_time = got_object_commit_get_committer_time(commit);
5725 if (gmtime_r(&committer_time, &tm) == NULL)
5726 return got_error_from_errno("gmtime_r");
5727 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5728 &tm) == 0) {
5729 err = got_error(GOT_ERR_NO_SPACE);
5730 goto done;
5732 bline->annotated = 1;
5734 /* Print lines annotated so far. */
5735 bline = &a->lines[a->lineno_cur - 1];
5736 if (!bline->annotated)
5737 goto done;
5739 offset = a->line_offsets[a->lineno_cur - 1];
5740 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5741 err = got_error_from_errno("fseeko");
5742 goto done;
5745 while (a->lineno_cur <= a->nlines && bline->annotated) {
5746 char *smallerthan, *at, *nl, *committer;
5747 size_t len;
5749 if (getline(&line, &linesize, a->f) == -1) {
5750 if (ferror(a->f))
5751 err = got_error_from_errno("getline");
5752 break;
5755 committer = bline->committer;
5756 smallerthan = strchr(committer, '<');
5757 if (smallerthan && smallerthan[1] != '\0')
5758 committer = smallerthan + 1;
5759 at = strchr(committer, '@');
5760 if (at)
5761 *at = '\0';
5762 len = strlen(committer);
5763 if (len >= 9)
5764 committer[8] = '\0';
5766 nl = strchr(line, '\n');
5767 if (nl)
5768 *nl = '\0';
5769 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5770 bline->id_str, bline->datebuf, committer, line);
5772 a->lineno_cur++;
5773 bline = &a->lines[a->lineno_cur - 1];
5775 done:
5776 free(line);
5777 return err;
5780 static const struct got_error *
5781 cmd_blame(int argc, char *argv[])
5783 const struct got_error *error;
5784 struct got_repository *repo = NULL;
5785 struct got_worktree *worktree = NULL;
5786 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5787 char *link_target = NULL;
5788 struct got_object_id *obj_id = NULL;
5789 struct got_object_id *commit_id = NULL;
5790 struct got_commit_object *commit = NULL;
5791 struct got_blob_object *blob = NULL;
5792 char *commit_id_str = NULL, *keyword_idstr = NULL;
5793 struct blame_cb_args bca;
5794 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5795 off_t filesize;
5796 int *pack_fds = NULL;
5797 FILE *f1 = NULL, *f2 = NULL;
5799 fd1 = got_opentempfd();
5800 if (fd1 == -1)
5801 return got_error_from_errno("got_opentempfd");
5803 memset(&bca, 0, sizeof(bca));
5805 #ifndef PROFILE
5806 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5807 NULL) == -1)
5808 err(1, "pledge");
5809 #endif
5811 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5812 switch (ch) {
5813 case 'c':
5814 commit_id_str = optarg;
5815 break;
5816 case 'r':
5817 repo_path = realpath(optarg, NULL);
5818 if (repo_path == NULL)
5819 return got_error_from_errno2("realpath",
5820 optarg);
5821 got_path_strip_trailing_slashes(repo_path);
5822 break;
5823 default:
5824 usage_blame();
5825 /* NOTREACHED */
5829 argc -= optind;
5830 argv += optind;
5832 if (argc == 1)
5833 path = argv[0];
5834 else
5835 usage_blame();
5837 cwd = getcwd(NULL, 0);
5838 if (cwd == NULL) {
5839 error = got_error_from_errno("getcwd");
5840 goto done;
5843 error = got_repo_pack_fds_open(&pack_fds);
5844 if (error != NULL)
5845 goto done;
5847 if (repo_path == NULL) {
5848 error = got_worktree_open(&worktree, cwd,
5849 GOT_WORKTREE_GOT_DIR);
5850 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5851 goto done;
5852 else
5853 error = NULL;
5854 if (worktree) {
5855 repo_path =
5856 strdup(got_worktree_get_repo_path(worktree));
5857 if (repo_path == NULL) {
5858 error = got_error_from_errno("strdup");
5859 if (error)
5860 goto done;
5862 } else {
5863 repo_path = strdup(cwd);
5864 if (repo_path == NULL) {
5865 error = got_error_from_errno("strdup");
5866 goto done;
5871 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5872 if (error != NULL)
5873 goto done;
5875 if (worktree) {
5876 const char *prefix = got_worktree_get_path_prefix(worktree);
5877 char *p;
5879 error = got_worktree_resolve_path(&p, worktree, path);
5880 if (error)
5881 goto done;
5882 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5883 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5884 p) == -1) {
5885 error = got_error_from_errno("asprintf");
5886 free(p);
5887 goto done;
5889 free(p);
5890 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5891 } else {
5892 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5893 if (error)
5894 goto done;
5895 error = got_repo_map_path(&in_repo_path, repo, path);
5897 if (error)
5898 goto done;
5900 if (commit_id_str == NULL) {
5901 struct got_reference *head_ref;
5902 error = got_ref_open(&head_ref, repo, worktree ?
5903 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5904 if (error != NULL)
5905 goto done;
5906 error = got_ref_resolve(&commit_id, repo, head_ref);
5907 got_ref_close(head_ref);
5908 if (error != NULL)
5909 goto done;
5910 } else {
5911 struct got_reflist_head refs;
5913 TAILQ_INIT(&refs);
5914 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5915 NULL);
5916 if (error)
5917 goto done;
5919 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5920 repo, worktree);
5921 if (error != NULL)
5922 goto done;
5923 if (keyword_idstr != NULL)
5924 commit_id_str = keyword_idstr;
5926 error = got_repo_match_object_id(&commit_id, NULL,
5927 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5928 got_ref_list_free(&refs);
5929 if (error)
5930 goto done;
5933 if (worktree) {
5934 /* Release work tree lock. */
5935 got_worktree_close(worktree);
5936 worktree = NULL;
5939 error = got_object_open_as_commit(&commit, repo, commit_id);
5940 if (error)
5941 goto done;
5943 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5944 commit, repo);
5945 if (error)
5946 goto done;
5948 error = got_object_id_by_path(&obj_id, repo, commit,
5949 link_target ? link_target : in_repo_path);
5950 if (error)
5951 goto done;
5953 error = got_object_get_type(&obj_type, repo, obj_id);
5954 if (error)
5955 goto done;
5957 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5958 error = got_error_path(link_target ? link_target : in_repo_path,
5959 GOT_ERR_OBJ_TYPE);
5960 goto done;
5963 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5964 if (error)
5965 goto done;
5966 bca.f = got_opentemp();
5967 if (bca.f == NULL) {
5968 error = got_error_from_errno("got_opentemp");
5969 goto done;
5971 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5972 &bca.line_offsets, bca.f, blob);
5973 if (error || bca.nlines == 0)
5974 goto done;
5976 /* Don't include \n at EOF in the blame line count. */
5977 if (bca.line_offsets[bca.nlines - 1] == filesize)
5978 bca.nlines--;
5980 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5981 if (bca.lines == NULL) {
5982 error = got_error_from_errno("calloc");
5983 goto done;
5985 bca.lineno_cur = 1;
5986 bca.nlines_prec = 0;
5987 i = bca.nlines;
5988 while (i > 0) {
5989 i /= 10;
5990 bca.nlines_prec++;
5992 bca.repo = repo;
5994 fd2 = got_opentempfd();
5995 if (fd2 == -1) {
5996 error = got_error_from_errno("got_opentempfd");
5997 goto done;
5999 fd3 = got_opentempfd();
6000 if (fd3 == -1) {
6001 error = got_error_from_errno("got_opentempfd");
6002 goto done;
6004 f1 = got_opentemp();
6005 if (f1 == NULL) {
6006 error = got_error_from_errno("got_opentemp");
6007 goto done;
6009 f2 = got_opentemp();
6010 if (f2 == NULL) {
6011 error = got_error_from_errno("got_opentemp");
6012 goto done;
6014 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6015 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6016 check_cancelled, NULL, fd2, fd3, f1, f2);
6017 done:
6018 free(keyword_idstr);
6019 free(in_repo_path);
6020 free(link_target);
6021 free(repo_path);
6022 free(cwd);
6023 free(commit_id);
6024 free(obj_id);
6025 if (commit)
6026 got_object_commit_close(commit);
6028 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6029 error = got_error_from_errno("close");
6030 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6031 error = got_error_from_errno("close");
6032 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6033 error = got_error_from_errno("close");
6034 if (f1 && fclose(f1) == EOF && error == NULL)
6035 error = got_error_from_errno("fclose");
6036 if (f2 && fclose(f2) == EOF && error == NULL)
6037 error = got_error_from_errno("fclose");
6039 if (blob)
6040 got_object_blob_close(blob);
6041 if (worktree)
6042 got_worktree_close(worktree);
6043 if (repo) {
6044 const struct got_error *close_err = got_repo_close(repo);
6045 if (error == NULL)
6046 error = close_err;
6048 if (pack_fds) {
6049 const struct got_error *pack_err =
6050 got_repo_pack_fds_close(pack_fds);
6051 if (error == NULL)
6052 error = pack_err;
6054 if (bca.lines) {
6055 for (i = 0; i < bca.nlines; i++) {
6056 struct blame_line *bline = &bca.lines[i];
6057 free(bline->id_str);
6058 free(bline->committer);
6060 free(bca.lines);
6062 free(bca.line_offsets);
6063 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6064 error = got_error_from_errno("fclose");
6065 return error;
6068 __dead static void
6069 usage_tree(void)
6071 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6072 "[path]\n", getprogname());
6073 exit(1);
6076 static const struct got_error *
6077 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6078 const char *root_path, struct got_repository *repo)
6080 const struct got_error *err = NULL;
6081 int is_root_path = (strcmp(path, root_path) == 0);
6082 const char *modestr = "";
6083 mode_t mode = got_tree_entry_get_mode(te);
6084 char *link_target = NULL;
6086 path += strlen(root_path);
6087 while (path[0] == '/')
6088 path++;
6090 if (got_object_tree_entry_is_submodule(te))
6091 modestr = "$";
6092 else if (S_ISLNK(mode)) {
6093 int i;
6095 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6096 if (err)
6097 return err;
6098 for (i = 0; link_target[i] != '\0'; i++) {
6099 if (!isprint((unsigned char)link_target[i]))
6100 link_target[i] = '?';
6103 modestr = "@";
6105 else if (S_ISDIR(mode))
6106 modestr = "/";
6107 else if (mode & S_IXUSR)
6108 modestr = "*";
6110 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6111 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6112 link_target ? " -> ": "", link_target ? link_target : "");
6114 free(link_target);
6115 return NULL;
6118 static const struct got_error *
6119 print_tree(const char *path, struct got_commit_object *commit,
6120 int show_ids, int recurse, const char *root_path,
6121 struct got_repository *repo)
6123 const struct got_error *err = NULL;
6124 struct got_object_id *tree_id = NULL;
6125 struct got_tree_object *tree = NULL;
6126 int nentries, i;
6128 err = got_object_id_by_path(&tree_id, repo, commit, path);
6129 if (err)
6130 goto done;
6132 err = got_object_open_as_tree(&tree, repo, tree_id);
6133 if (err)
6134 goto done;
6135 nentries = got_object_tree_get_nentries(tree);
6136 for (i = 0; i < nentries; i++) {
6137 struct got_tree_entry *te;
6138 char *id = NULL;
6140 if (sigint_received || sigpipe_received)
6141 break;
6143 te = got_object_tree_get_entry(tree, i);
6144 if (show_ids) {
6145 char *id_str;
6146 err = got_object_id_str(&id_str,
6147 got_tree_entry_get_id(te));
6148 if (err)
6149 goto done;
6150 if (asprintf(&id, "%s ", id_str) == -1) {
6151 err = got_error_from_errno("asprintf");
6152 free(id_str);
6153 goto done;
6155 free(id_str);
6157 err = print_entry(te, id, path, root_path, repo);
6158 free(id);
6159 if (err)
6160 goto done;
6162 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6163 char *child_path;
6164 if (asprintf(&child_path, "%s%s%s", path,
6165 path[0] == '/' && path[1] == '\0' ? "" : "/",
6166 got_tree_entry_get_name(te)) == -1) {
6167 err = got_error_from_errno("asprintf");
6168 goto done;
6170 err = print_tree(child_path, commit, show_ids, 1,
6171 root_path, repo);
6172 free(child_path);
6173 if (err)
6174 goto done;
6177 done:
6178 if (tree)
6179 got_object_tree_close(tree);
6180 free(tree_id);
6181 return err;
6184 static const struct got_error *
6185 cmd_tree(int argc, char *argv[])
6187 const struct got_error *error;
6188 struct got_repository *repo = NULL;
6189 struct got_worktree *worktree = NULL;
6190 const char *path, *refname = NULL;
6191 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6192 struct got_object_id *commit_id = NULL;
6193 struct got_commit_object *commit = NULL;
6194 char *commit_id_str = NULL, *keyword_idstr = NULL;
6195 int show_ids = 0, recurse = 0;
6196 int ch;
6197 int *pack_fds = NULL;
6199 #ifndef PROFILE
6200 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6201 NULL) == -1)
6202 err(1, "pledge");
6203 #endif
6205 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6206 switch (ch) {
6207 case 'c':
6208 commit_id_str = optarg;
6209 break;
6210 case 'i':
6211 show_ids = 1;
6212 break;
6213 case 'R':
6214 recurse = 1;
6215 break;
6216 case 'r':
6217 repo_path = realpath(optarg, NULL);
6218 if (repo_path == NULL)
6219 return got_error_from_errno2("realpath",
6220 optarg);
6221 got_path_strip_trailing_slashes(repo_path);
6222 break;
6223 default:
6224 usage_tree();
6225 /* NOTREACHED */
6229 argc -= optind;
6230 argv += optind;
6232 if (argc == 1)
6233 path = argv[0];
6234 else if (argc > 1)
6235 usage_tree();
6236 else
6237 path = NULL;
6239 cwd = getcwd(NULL, 0);
6240 if (cwd == NULL) {
6241 error = got_error_from_errno("getcwd");
6242 goto done;
6245 error = got_repo_pack_fds_open(&pack_fds);
6246 if (error != NULL)
6247 goto done;
6249 if (repo_path == NULL) {
6250 error = got_worktree_open(&worktree, cwd,
6251 GOT_WORKTREE_GOT_DIR);
6252 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6253 goto done;
6254 else
6255 error = NULL;
6256 if (worktree) {
6257 repo_path =
6258 strdup(got_worktree_get_repo_path(worktree));
6259 if (repo_path == NULL)
6260 error = got_error_from_errno("strdup");
6261 if (error)
6262 goto done;
6263 } else {
6264 repo_path = strdup(cwd);
6265 if (repo_path == NULL) {
6266 error = got_error_from_errno("strdup");
6267 goto done;
6272 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6273 if (error != NULL)
6274 goto done;
6276 if (worktree) {
6277 const char *prefix = got_worktree_get_path_prefix(worktree);
6278 char *p;
6280 if (path == NULL || got_path_is_root_dir(path))
6281 path = "";
6282 error = got_worktree_resolve_path(&p, worktree, path);
6283 if (error)
6284 goto done;
6285 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6286 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6287 p) == -1) {
6288 error = got_error_from_errno("asprintf");
6289 free(p);
6290 goto done;
6292 free(p);
6293 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6294 if (error)
6295 goto done;
6296 } else {
6297 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6298 if (error)
6299 goto done;
6300 if (path == NULL)
6301 path = "/";
6302 error = got_repo_map_path(&in_repo_path, repo, path);
6303 if (error != NULL)
6304 goto done;
6307 if (commit_id_str == NULL) {
6308 struct got_reference *head_ref;
6309 if (worktree)
6310 refname = got_worktree_get_head_ref_name(worktree);
6311 else
6312 refname = GOT_REF_HEAD;
6313 error = got_ref_open(&head_ref, repo, refname, 0);
6314 if (error != NULL)
6315 goto done;
6316 error = got_ref_resolve(&commit_id, repo, head_ref);
6317 got_ref_close(head_ref);
6318 if (error != NULL)
6319 goto done;
6320 } else {
6321 struct got_reflist_head refs;
6323 TAILQ_INIT(&refs);
6324 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6325 NULL);
6326 if (error)
6327 goto done;
6329 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6330 repo, worktree);
6331 if (error != NULL)
6332 goto done;
6333 if (keyword_idstr != NULL)
6334 commit_id_str = keyword_idstr;
6336 error = got_repo_match_object_id(&commit_id, NULL,
6337 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6338 got_ref_list_free(&refs);
6339 if (error)
6340 goto done;
6343 if (worktree) {
6344 /* Release work tree lock. */
6345 got_worktree_close(worktree);
6346 worktree = NULL;
6349 error = got_object_open_as_commit(&commit, repo, commit_id);
6350 if (error)
6351 goto done;
6353 error = print_tree(in_repo_path, commit, show_ids, recurse,
6354 in_repo_path, repo);
6355 done:
6356 free(keyword_idstr);
6357 free(in_repo_path);
6358 free(repo_path);
6359 free(cwd);
6360 free(commit_id);
6361 if (commit)
6362 got_object_commit_close(commit);
6363 if (worktree)
6364 got_worktree_close(worktree);
6365 if (repo) {
6366 const struct got_error *close_err = got_repo_close(repo);
6367 if (error == NULL)
6368 error = close_err;
6370 if (pack_fds) {
6371 const struct got_error *pack_err =
6372 got_repo_pack_fds_close(pack_fds);
6373 if (error == NULL)
6374 error = pack_err;
6376 return error;
6379 __dead static void
6380 usage_status(void)
6382 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6383 "[-s status-codes] [path ...]\n", getprogname());
6384 exit(1);
6387 struct got_status_arg {
6388 char *status_codes;
6389 int suppress;
6392 static const struct got_error *
6393 print_status(void *arg, unsigned char status, unsigned char staged_status,
6394 const char *path, struct got_object_id *blob_id,
6395 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6396 int dirfd, const char *de_name)
6398 struct got_status_arg *st = arg;
6400 if (status == staged_status && (status == GOT_STATUS_DELETE))
6401 status = GOT_STATUS_NO_CHANGE;
6402 if (st != NULL && st->status_codes) {
6403 size_t ncodes = strlen(st->status_codes);
6404 int i, j = 0;
6406 for (i = 0; i < ncodes ; i++) {
6407 if (st->suppress) {
6408 if (status == st->status_codes[i] ||
6409 staged_status == st->status_codes[i]) {
6410 j++;
6411 continue;
6413 } else {
6414 if (status == st->status_codes[i] ||
6415 staged_status == st->status_codes[i])
6416 break;
6420 if (st->suppress && j == 0)
6421 goto print;
6423 if (i == ncodes)
6424 return NULL;
6426 print:
6427 printf("%c%c %s\n", status, staged_status, path);
6428 return NULL;
6431 static const struct got_error *
6432 cmd_status(int argc, char *argv[])
6434 const struct got_error *close_err, *error = NULL;
6435 struct got_repository *repo = NULL;
6436 struct got_worktree *worktree = NULL;
6437 struct got_status_arg st;
6438 char *cwd = NULL;
6439 struct got_pathlist_head paths;
6440 int ch, i, no_ignores = 0;
6441 int *pack_fds = NULL;
6443 TAILQ_INIT(&paths);
6445 memset(&st, 0, sizeof(st));
6446 st.status_codes = NULL;
6447 st.suppress = 0;
6449 #ifndef PROFILE
6450 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6451 NULL) == -1)
6452 err(1, "pledge");
6453 #endif
6455 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6456 switch (ch) {
6457 case 'I':
6458 no_ignores = 1;
6459 break;
6460 case 'S':
6461 if (st.status_codes != NULL && st.suppress == 0)
6462 option_conflict('S', 's');
6463 st.suppress = 1;
6464 /* fallthrough */
6465 case 's':
6466 for (i = 0; optarg[i] != '\0'; i++) {
6467 switch (optarg[i]) {
6468 case GOT_STATUS_MODIFY:
6469 case GOT_STATUS_ADD:
6470 case GOT_STATUS_DELETE:
6471 case GOT_STATUS_CONFLICT:
6472 case GOT_STATUS_MISSING:
6473 case GOT_STATUS_OBSTRUCTED:
6474 case GOT_STATUS_UNVERSIONED:
6475 case GOT_STATUS_MODE_CHANGE:
6476 case GOT_STATUS_NONEXISTENT:
6477 break;
6478 default:
6479 errx(1, "invalid status code '%c'",
6480 optarg[i]);
6483 if (ch == 's' && st.suppress)
6484 option_conflict('s', 'S');
6485 st.status_codes = optarg;
6486 break;
6487 default:
6488 usage_status();
6489 /* NOTREACHED */
6493 argc -= optind;
6494 argv += optind;
6496 cwd = getcwd(NULL, 0);
6497 if (cwd == NULL) {
6498 error = got_error_from_errno("getcwd");
6499 goto done;
6502 error = got_repo_pack_fds_open(&pack_fds);
6503 if (error != NULL)
6504 goto done;
6506 error = got_worktree_open(&worktree, cwd,
6507 GOT_WORKTREE_GOT_DIR);
6508 if (error) {
6509 if (error->code == GOT_ERR_NOT_WORKTREE)
6510 error = wrap_not_worktree_error(error, "status", cwd);
6511 goto done;
6514 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6515 NULL, pack_fds);
6516 if (error != NULL)
6517 goto done;
6519 error = apply_unveil(got_repo_get_path(repo), 1,
6520 got_worktree_get_root_path(worktree));
6521 if (error)
6522 goto done;
6524 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6525 if (error)
6526 goto done;
6528 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6529 print_status, &st, check_cancelled, NULL);
6530 done:
6531 if (pack_fds) {
6532 const struct got_error *pack_err =
6533 got_repo_pack_fds_close(pack_fds);
6534 if (error == NULL)
6535 error = pack_err;
6537 if (repo) {
6538 close_err = got_repo_close(repo);
6539 if (error == NULL)
6540 error = close_err;
6542 if (worktree != NULL) {
6543 close_err = got_worktree_close(worktree);
6544 if (error == NULL)
6545 error = close_err;
6548 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6549 free(cwd);
6550 return error;
6553 __dead static void
6554 usage_ref(void)
6556 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6557 "[-s reference] [name]\n", getprogname());
6558 exit(1);
6561 static const struct got_error *
6562 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6564 static const struct got_error *err = NULL;
6565 struct got_reflist_head refs;
6566 struct got_reflist_entry *re;
6568 TAILQ_INIT(&refs);
6569 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6570 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6571 repo);
6572 if (err)
6573 return err;
6575 TAILQ_FOREACH(re, &refs, entry) {
6576 char *refstr;
6577 refstr = got_ref_to_str(re->ref);
6578 if (refstr == NULL) {
6579 err = got_error_from_errno("got_ref_to_str");
6580 break;
6582 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6583 free(refstr);
6586 got_ref_list_free(&refs);
6587 return err;
6590 static const struct got_error *
6591 delete_ref_by_name(struct got_repository *repo, const char *refname)
6593 const struct got_error *err;
6594 struct got_reference *ref;
6596 err = got_ref_open(&ref, repo, refname, 0);
6597 if (err)
6598 return err;
6600 err = delete_ref(repo, ref);
6601 got_ref_close(ref);
6602 return err;
6605 static const struct got_error *
6606 add_ref(struct got_repository *repo, const char *refname, const char *target)
6608 const struct got_error *err = NULL;
6609 struct got_object_id *id = NULL;
6610 struct got_reference *ref = NULL;
6611 struct got_reflist_head refs;
6614 * Don't let the user create a reference name with a leading '-'.
6615 * While technically a valid reference name, this case is usually
6616 * an unintended typo.
6618 if (refname[0] == '-')
6619 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6621 TAILQ_INIT(&refs);
6622 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6623 if (err)
6624 goto done;
6625 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6626 &refs, repo);
6627 got_ref_list_free(&refs);
6628 if (err)
6629 goto done;
6631 err = got_ref_alloc(&ref, refname, id);
6632 if (err)
6633 goto done;
6635 err = got_ref_write(ref, repo);
6636 done:
6637 if (ref)
6638 got_ref_close(ref);
6639 free(id);
6640 return err;
6643 static const struct got_error *
6644 add_symref(struct got_repository *repo, const char *refname, const char *target)
6646 const struct got_error *err = NULL;
6647 struct got_reference *ref = NULL;
6648 struct got_reference *target_ref = NULL;
6651 * Don't let the user create a reference name with a leading '-'.
6652 * While technically a valid reference name, this case is usually
6653 * an unintended typo.
6655 if (refname[0] == '-')
6656 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6658 err = got_ref_open(&target_ref, repo, target, 0);
6659 if (err)
6660 return err;
6662 err = got_ref_alloc_symref(&ref, refname, target_ref);
6663 if (err)
6664 goto done;
6666 err = got_ref_write(ref, repo);
6667 done:
6668 if (target_ref)
6669 got_ref_close(target_ref);
6670 if (ref)
6671 got_ref_close(ref);
6672 return err;
6675 static const struct got_error *
6676 cmd_ref(int argc, char *argv[])
6678 const struct got_error *error = NULL;
6679 struct got_repository *repo = NULL;
6680 struct got_worktree *worktree = NULL;
6681 char *cwd = NULL, *repo_path = NULL;
6682 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6683 const char *obj_arg = NULL, *symref_target= NULL;
6684 char *refname = NULL, *keyword_idstr = NULL;
6685 int *pack_fds = NULL;
6687 #ifndef PROFILE
6688 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6689 "sendfd unveil", NULL) == -1)
6690 err(1, "pledge");
6691 #endif
6693 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6694 switch (ch) {
6695 case 'c':
6696 obj_arg = optarg;
6697 break;
6698 case 'd':
6699 do_delete = 1;
6700 break;
6701 case 'l':
6702 do_list = 1;
6703 break;
6704 case 'r':
6705 repo_path = realpath(optarg, NULL);
6706 if (repo_path == NULL)
6707 return got_error_from_errno2("realpath",
6708 optarg);
6709 got_path_strip_trailing_slashes(repo_path);
6710 break;
6711 case 's':
6712 symref_target = optarg;
6713 break;
6714 case 't':
6715 sort_by_time = 1;
6716 break;
6717 default:
6718 usage_ref();
6719 /* NOTREACHED */
6723 if (obj_arg && do_list)
6724 option_conflict('c', 'l');
6725 if (obj_arg && do_delete)
6726 option_conflict('c', 'd');
6727 if (obj_arg && symref_target)
6728 option_conflict('c', 's');
6729 if (symref_target && do_delete)
6730 option_conflict('s', 'd');
6731 if (symref_target && do_list)
6732 option_conflict('s', 'l');
6733 if (do_delete && do_list)
6734 option_conflict('d', 'l');
6735 if (sort_by_time && !do_list)
6736 errx(1, "-t option requires -l option");
6738 argc -= optind;
6739 argv += optind;
6741 if (do_list) {
6742 if (argc != 0 && argc != 1)
6743 usage_ref();
6744 if (argc == 1) {
6745 refname = strdup(argv[0]);
6746 if (refname == NULL) {
6747 error = got_error_from_errno("strdup");
6748 goto done;
6751 } else {
6752 if (argc != 1)
6753 usage_ref();
6754 refname = strdup(argv[0]);
6755 if (refname == NULL) {
6756 error = got_error_from_errno("strdup");
6757 goto done;
6761 if (refname)
6762 got_path_strip_trailing_slashes(refname);
6764 cwd = getcwd(NULL, 0);
6765 if (cwd == NULL) {
6766 error = got_error_from_errno("getcwd");
6767 goto done;
6770 error = got_repo_pack_fds_open(&pack_fds);
6771 if (error != NULL)
6772 goto done;
6774 if (repo_path == NULL) {
6775 error = got_worktree_open(&worktree, cwd,
6776 GOT_WORKTREE_GOT_DIR);
6777 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6778 goto done;
6779 else
6780 error = NULL;
6781 if (worktree) {
6782 repo_path =
6783 strdup(got_worktree_get_repo_path(worktree));
6784 if (repo_path == NULL)
6785 error = got_error_from_errno("strdup");
6786 if (error)
6787 goto done;
6788 } else {
6789 repo_path = strdup(cwd);
6790 if (repo_path == NULL) {
6791 error = got_error_from_errno("strdup");
6792 goto done;
6797 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6798 if (error != NULL)
6799 goto done;
6801 #ifndef PROFILE
6802 if (do_list) {
6803 /* Remove "cpath" promise. */
6804 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6805 NULL) == -1)
6806 err(1, "pledge");
6808 #endif
6810 error = apply_unveil(got_repo_get_path(repo), do_list,
6811 worktree ? got_worktree_get_root_path(worktree) : NULL);
6812 if (error)
6813 goto done;
6815 if (do_list)
6816 error = list_refs(repo, refname, sort_by_time);
6817 else if (do_delete)
6818 error = delete_ref_by_name(repo, refname);
6819 else if (symref_target)
6820 error = add_symref(repo, refname, symref_target);
6821 else {
6822 if (obj_arg == NULL)
6823 usage_ref();
6825 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6826 repo, worktree);
6827 if (error != NULL)
6828 goto done;
6829 if (keyword_idstr != NULL)
6830 obj_arg = keyword_idstr;
6832 error = add_ref(repo, refname, obj_arg);
6834 done:
6835 free(refname);
6836 if (repo) {
6837 const struct got_error *close_err = got_repo_close(repo);
6838 if (error == NULL)
6839 error = close_err;
6841 if (worktree)
6842 got_worktree_close(worktree);
6843 if (pack_fds) {
6844 const struct got_error *pack_err =
6845 got_repo_pack_fds_close(pack_fds);
6846 if (error == NULL)
6847 error = pack_err;
6849 free(cwd);
6850 free(repo_path);
6851 free(keyword_idstr);
6852 return error;
6855 __dead static void
6856 usage_branch(void)
6858 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6859 "[-r repository-path] [name]\n", getprogname());
6860 exit(1);
6863 static const struct got_error *
6864 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6865 struct got_reference *ref)
6867 const struct got_error *err = NULL;
6868 const char *refname;
6869 char *refstr;
6870 char marker = ' ';
6872 refname = got_ref_get_name(ref);
6873 if (worktree && strcmp(refname,
6874 got_worktree_get_head_ref_name(worktree)) == 0) {
6875 err = got_worktree_get_state(&marker, repo, worktree,
6876 check_cancelled, NULL);
6877 if (err != NULL)
6878 return err;
6881 if (strncmp(refname, "refs/heads/", 11) == 0)
6882 refname += 11;
6883 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6884 refname += 18;
6885 if (strncmp(refname, "refs/remotes/", 13) == 0)
6886 refname += 13;
6888 refstr = got_ref_to_str(ref);
6889 if (refstr == NULL)
6890 return got_error_from_errno("got_ref_to_str");
6892 printf("%c %s: %s\n", marker, refname, refstr);
6893 free(refstr);
6894 return NULL;
6897 static const struct got_error *
6898 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6900 const char *refname;
6902 if (worktree == NULL)
6903 return got_error(GOT_ERR_NOT_WORKTREE);
6905 refname = got_worktree_get_head_ref_name(worktree);
6907 if (strncmp(refname, "refs/heads/", 11) == 0)
6908 refname += 11;
6909 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6910 refname += 18;
6912 printf("%s\n", refname);
6914 return NULL;
6917 static const struct got_error *
6918 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6919 int sort_by_time)
6921 static const struct got_error *err = NULL;
6922 struct got_reflist_head refs;
6923 struct got_reflist_entry *re;
6924 struct got_reference *temp_ref = NULL;
6925 int rebase_in_progress, histedit_in_progress;
6927 TAILQ_INIT(&refs);
6929 if (worktree) {
6930 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6931 worktree);
6932 if (err)
6933 return err;
6935 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6936 worktree);
6937 if (err)
6938 return err;
6940 if (rebase_in_progress || histedit_in_progress) {
6941 err = got_ref_open(&temp_ref, repo,
6942 got_worktree_get_head_ref_name(worktree), 0);
6943 if (err)
6944 return err;
6945 list_branch(repo, worktree, temp_ref);
6946 got_ref_close(temp_ref);
6950 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6951 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6952 repo);
6953 if (err)
6954 return err;
6956 TAILQ_FOREACH(re, &refs, entry)
6957 list_branch(repo, worktree, re->ref);
6959 got_ref_list_free(&refs);
6961 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6962 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6963 repo);
6964 if (err)
6965 return err;
6967 TAILQ_FOREACH(re, &refs, entry)
6968 list_branch(repo, worktree, re->ref);
6970 got_ref_list_free(&refs);
6972 return NULL;
6975 static const struct got_error *
6976 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6977 const char *branch_name)
6979 const struct got_error *err = NULL;
6980 struct got_reference *ref = NULL;
6981 char *refname, *remote_refname = NULL;
6983 if (strncmp(branch_name, "refs/", 5) == 0)
6984 branch_name += 5;
6985 if (strncmp(branch_name, "heads/", 6) == 0)
6986 branch_name += 6;
6987 else if (strncmp(branch_name, "remotes/", 8) == 0)
6988 branch_name += 8;
6990 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6991 return got_error_from_errno("asprintf");
6993 if (asprintf(&remote_refname, "refs/remotes/%s",
6994 branch_name) == -1) {
6995 err = got_error_from_errno("asprintf");
6996 goto done;
6999 err = got_ref_open(&ref, repo, refname, 0);
7000 if (err) {
7001 const struct got_error *err2;
7002 if (err->code != GOT_ERR_NOT_REF)
7003 goto done;
7005 * Keep 'err' intact such that if neither branch exists
7006 * we report "refs/heads" rather than "refs/remotes" in
7007 * our error message.
7009 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7010 if (err2)
7011 goto done;
7012 err = NULL;
7015 if (worktree &&
7016 strcmp(got_worktree_get_head_ref_name(worktree),
7017 got_ref_get_name(ref)) == 0) {
7018 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7019 "will not delete this work tree's current branch");
7020 goto done;
7023 err = delete_ref(repo, ref);
7024 done:
7025 if (ref)
7026 got_ref_close(ref);
7027 free(refname);
7028 free(remote_refname);
7029 return err;
7032 static const struct got_error *
7033 add_branch(struct got_repository *repo, const char *branch_name,
7034 struct got_object_id *base_commit_id)
7036 const struct got_error *err = NULL;
7037 struct got_reference *ref = NULL;
7038 char *refname = NULL;
7041 * Don't let the user create a branch name with a leading '-'.
7042 * While technically a valid reference name, this case is usually
7043 * an unintended typo.
7045 if (branch_name[0] == '-')
7046 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7048 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7049 branch_name += 11;
7051 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7052 err = got_error_from_errno("asprintf");
7053 goto done;
7056 err = got_ref_open(&ref, repo, refname, 0);
7057 if (err == NULL) {
7058 err = got_error(GOT_ERR_BRANCH_EXISTS);
7059 goto done;
7060 } else if (err->code != GOT_ERR_NOT_REF)
7061 goto done;
7063 err = got_ref_alloc(&ref, refname, base_commit_id);
7064 if (err)
7065 goto done;
7067 err = got_ref_write(ref, repo);
7068 done:
7069 if (ref)
7070 got_ref_close(ref);
7071 free(refname);
7072 return err;
7075 static const struct got_error *
7076 cmd_branch(int argc, char *argv[])
7078 const struct got_error *error = NULL;
7079 struct got_repository *repo = NULL;
7080 struct got_worktree *worktree = NULL;
7081 char *cwd = NULL, *repo_path = NULL;
7082 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7083 const char *delref = NULL, *commit_id_arg = NULL;
7084 struct got_reference *ref = NULL;
7085 struct got_pathlist_head paths;
7086 struct got_object_id *commit_id = NULL;
7087 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7088 int *pack_fds = NULL;
7090 TAILQ_INIT(&paths);
7092 #ifndef PROFILE
7093 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7094 "sendfd unveil", NULL) == -1)
7095 err(1, "pledge");
7096 #endif
7098 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7099 switch (ch) {
7100 case 'c':
7101 commit_id_arg = optarg;
7102 break;
7103 case 'd':
7104 delref = optarg;
7105 break;
7106 case 'l':
7107 do_list = 1;
7108 break;
7109 case 'n':
7110 do_update = 0;
7111 break;
7112 case 'r':
7113 repo_path = realpath(optarg, NULL);
7114 if (repo_path == NULL)
7115 return got_error_from_errno2("realpath",
7116 optarg);
7117 got_path_strip_trailing_slashes(repo_path);
7118 break;
7119 case 't':
7120 sort_by_time = 1;
7121 break;
7122 default:
7123 usage_branch();
7124 /* NOTREACHED */
7128 if (do_list && delref)
7129 option_conflict('l', 'd');
7130 if (sort_by_time && !do_list)
7131 errx(1, "-t option requires -l option");
7133 argc -= optind;
7134 argv += optind;
7136 if (!do_list && !delref && argc == 0)
7137 do_show = 1;
7139 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7140 errx(1, "-c option can only be used when creating a branch");
7142 if (do_list || delref) {
7143 if (argc > 0)
7144 usage_branch();
7145 } else if (!do_show && argc != 1)
7146 usage_branch();
7148 cwd = getcwd(NULL, 0);
7149 if (cwd == NULL) {
7150 error = got_error_from_errno("getcwd");
7151 goto done;
7154 error = got_repo_pack_fds_open(&pack_fds);
7155 if (error != NULL)
7156 goto done;
7158 if (repo_path == NULL) {
7159 error = got_worktree_open(&worktree, cwd,
7160 GOT_WORKTREE_GOT_DIR);
7161 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7162 goto done;
7163 else
7164 error = NULL;
7165 if (worktree) {
7166 repo_path =
7167 strdup(got_worktree_get_repo_path(worktree));
7168 if (repo_path == NULL)
7169 error = got_error_from_errno("strdup");
7170 if (error)
7171 goto done;
7172 } else {
7173 repo_path = strdup(cwd);
7174 if (repo_path == NULL) {
7175 error = got_error_from_errno("strdup");
7176 goto done;
7181 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7182 if (error != NULL)
7183 goto done;
7185 #ifndef PROFILE
7186 if (do_list || do_show) {
7187 /* Remove "cpath" promise. */
7188 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7189 NULL) == -1)
7190 err(1, "pledge");
7192 #endif
7194 error = apply_unveil(got_repo_get_path(repo), do_list,
7195 worktree ? got_worktree_get_root_path(worktree) : NULL);
7196 if (error)
7197 goto done;
7199 if (do_show)
7200 error = show_current_branch(repo, worktree);
7201 else if (do_list)
7202 error = list_branches(repo, worktree, sort_by_time);
7203 else if (delref)
7204 error = delete_branch(repo, worktree, delref);
7205 else {
7206 struct got_reflist_head refs;
7207 TAILQ_INIT(&refs);
7208 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7209 NULL);
7210 if (error)
7211 goto done;
7212 if (commit_id_arg == NULL)
7213 commit_id_arg = worktree ?
7214 got_worktree_get_head_ref_name(worktree) :
7215 GOT_REF_HEAD;
7216 else {
7217 error = got_keyword_to_idstr(&keyword_idstr,
7218 commit_id_arg, repo, worktree);
7219 if (error != NULL)
7220 goto done;
7221 if (keyword_idstr != NULL)
7222 commit_id_arg = keyword_idstr;
7224 error = got_repo_match_object_id(&commit_id, NULL,
7225 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7226 got_ref_list_free(&refs);
7227 if (error)
7228 goto done;
7229 error = add_branch(repo, argv[0], commit_id);
7230 if (error)
7231 goto done;
7232 if (worktree && do_update) {
7233 struct got_update_progress_arg upa;
7234 char *branch_refname = NULL;
7236 error = got_object_id_str(&commit_id_str, commit_id);
7237 if (error)
7238 goto done;
7239 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7240 worktree);
7241 if (error)
7242 goto done;
7243 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7244 == -1) {
7245 error = got_error_from_errno("asprintf");
7246 goto done;
7248 error = got_ref_open(&ref, repo, branch_refname, 0);
7249 free(branch_refname);
7250 if (error)
7251 goto done;
7252 error = switch_head_ref(ref, commit_id, worktree,
7253 repo);
7254 if (error)
7255 goto done;
7256 error = got_worktree_set_base_commit_id(worktree, repo,
7257 commit_id);
7258 if (error)
7259 goto done;
7260 memset(&upa, 0, sizeof(upa));
7261 error = got_worktree_checkout_files(worktree, &paths,
7262 repo, update_progress, &upa, check_cancelled,
7263 NULL);
7264 if (error)
7265 goto done;
7266 if (upa.did_something) {
7267 printf("Updated to %s: %s\n",
7268 got_worktree_get_head_ref_name(worktree),
7269 commit_id_str);
7271 print_update_progress_stats(&upa);
7274 done:
7275 free(keyword_idstr);
7276 if (ref)
7277 got_ref_close(ref);
7278 if (repo) {
7279 const struct got_error *close_err = got_repo_close(repo);
7280 if (error == NULL)
7281 error = close_err;
7283 if (worktree)
7284 got_worktree_close(worktree);
7285 if (pack_fds) {
7286 const struct got_error *pack_err =
7287 got_repo_pack_fds_close(pack_fds);
7288 if (error == NULL)
7289 error = pack_err;
7291 free(cwd);
7292 free(repo_path);
7293 free(commit_id);
7294 free(commit_id_str);
7295 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7296 return error;
7300 __dead static void
7301 usage_tag(void)
7303 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7304 "[-r repository-path] [-s signer-id] name\n", getprogname());
7305 exit(1);
7308 #if 0
7309 static const struct got_error *
7310 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7312 const struct got_error *err = NULL;
7313 struct got_reflist_entry *re, *se, *new;
7314 struct got_object_id *re_id, *se_id;
7315 struct got_tag_object *re_tag, *se_tag;
7316 time_t re_time, se_time;
7318 STAILQ_FOREACH(re, tags, entry) {
7319 se = STAILQ_FIRST(sorted);
7320 if (se == NULL) {
7321 err = got_reflist_entry_dup(&new, re);
7322 if (err)
7323 return err;
7324 STAILQ_INSERT_HEAD(sorted, new, entry);
7325 continue;
7326 } else {
7327 err = got_ref_resolve(&re_id, repo, re->ref);
7328 if (err)
7329 break;
7330 err = got_object_open_as_tag(&re_tag, repo, re_id);
7331 free(re_id);
7332 if (err)
7333 break;
7334 re_time = got_object_tag_get_tagger_time(re_tag);
7335 got_object_tag_close(re_tag);
7338 while (se) {
7339 err = got_ref_resolve(&se_id, repo, re->ref);
7340 if (err)
7341 break;
7342 err = got_object_open_as_tag(&se_tag, repo, se_id);
7343 free(se_id);
7344 if (err)
7345 break;
7346 se_time = got_object_tag_get_tagger_time(se_tag);
7347 got_object_tag_close(se_tag);
7349 if (se_time > re_time) {
7350 err = got_reflist_entry_dup(&new, re);
7351 if (err)
7352 return err;
7353 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7354 break;
7356 se = STAILQ_NEXT(se, entry);
7357 continue;
7360 done:
7361 return err;
7363 #endif
7365 static const struct got_error *
7366 get_tag_refname(char **refname, const char *tag_name)
7368 const struct got_error *err;
7370 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7371 *refname = strdup(tag_name);
7372 if (*refname == NULL)
7373 return got_error_from_errno("strdup");
7374 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7375 err = got_error_from_errno("asprintf");
7376 *refname = NULL;
7377 return err;
7380 return NULL;
7383 static const struct got_error *
7384 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7385 const char *allowed_signers, const char *revoked_signers, int verbosity)
7387 static const struct got_error *err = NULL;
7388 struct got_reflist_head refs;
7389 struct got_reflist_entry *re;
7390 char *wanted_refname = NULL;
7391 int bad_sigs = 0;
7393 TAILQ_INIT(&refs);
7395 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7396 if (err)
7397 return err;
7399 if (tag_name) {
7400 struct got_reference *ref;
7401 err = get_tag_refname(&wanted_refname, tag_name);
7402 if (err)
7403 goto done;
7404 /* Wanted tag reference should exist. */
7405 err = got_ref_open(&ref, repo, wanted_refname, 0);
7406 if (err)
7407 goto done;
7408 got_ref_close(ref);
7411 TAILQ_FOREACH(re, &refs, entry) {
7412 const char *refname;
7413 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7414 char datebuf[26];
7415 const char *tagger, *ssh_sig = NULL;
7416 char *sig_msg = NULL;
7417 time_t tagger_time;
7418 struct got_object_id *id;
7419 struct got_tag_object *tag;
7420 struct got_commit_object *commit = NULL;
7422 refname = got_ref_get_name(re->ref);
7423 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7424 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7425 continue;
7426 refname += 10;
7427 refstr = got_ref_to_str(re->ref);
7428 if (refstr == NULL) {
7429 err = got_error_from_errno("got_ref_to_str");
7430 break;
7433 err = got_ref_resolve(&id, repo, re->ref);
7434 if (err)
7435 break;
7436 err = got_object_open_as_tag(&tag, repo, id);
7437 if (err) {
7438 if (err->code != GOT_ERR_OBJ_TYPE) {
7439 free(id);
7440 break;
7442 /* "lightweight" tag */
7443 err = got_object_open_as_commit(&commit, repo, id);
7444 if (err) {
7445 free(id);
7446 break;
7448 tagger = got_object_commit_get_committer(commit);
7449 tagger_time =
7450 got_object_commit_get_committer_time(commit);
7451 err = got_object_id_str(&id_str, id);
7452 free(id);
7453 if (err)
7454 break;
7455 } else {
7456 free(id);
7457 tagger = got_object_tag_get_tagger(tag);
7458 tagger_time = got_object_tag_get_tagger_time(tag);
7459 err = got_object_id_str(&id_str,
7460 got_object_tag_get_object_id(tag));
7461 if (err)
7462 break;
7465 if (tag && verify_tags) {
7466 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7467 got_object_tag_get_message(tag));
7468 if (ssh_sig && allowed_signers == NULL) {
7469 err = got_error_msg(
7470 GOT_ERR_VERIFY_TAG_SIGNATURE,
7471 "SSH signature verification requires "
7472 "setting allowed_signers in "
7473 "got.conf(5)");
7474 break;
7478 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7479 free(refstr);
7480 printf("from: %s\n", tagger);
7481 datestr = get_datestr(&tagger_time, datebuf);
7482 if (datestr)
7483 printf("date: %s UTC\n", datestr);
7484 if (commit)
7485 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7486 else {
7487 switch (got_object_tag_get_object_type(tag)) {
7488 case GOT_OBJ_TYPE_BLOB:
7489 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7490 id_str);
7491 break;
7492 case GOT_OBJ_TYPE_TREE:
7493 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7494 id_str);
7495 break;
7496 case GOT_OBJ_TYPE_COMMIT:
7497 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7498 id_str);
7499 break;
7500 case GOT_OBJ_TYPE_TAG:
7501 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7502 id_str);
7503 break;
7504 default:
7505 break;
7508 free(id_str);
7510 if (ssh_sig) {
7511 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7512 allowed_signers, revoked_signers, verbosity);
7513 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7514 bad_sigs = 1;
7515 else if (err)
7516 break;
7517 printf("signature: %s", sig_msg);
7518 free(sig_msg);
7519 sig_msg = NULL;
7522 if (commit) {
7523 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7524 if (err)
7525 break;
7526 got_object_commit_close(commit);
7527 } else {
7528 tagmsg0 = strdup(got_object_tag_get_message(tag));
7529 got_object_tag_close(tag);
7530 if (tagmsg0 == NULL) {
7531 err = got_error_from_errno("strdup");
7532 break;
7536 tagmsg = tagmsg0;
7537 do {
7538 line = strsep(&tagmsg, "\n");
7539 if (line)
7540 printf(" %s\n", line);
7541 } while (line);
7542 free(tagmsg0);
7544 done:
7545 got_ref_list_free(&refs);
7546 free(wanted_refname);
7548 if (err == NULL && bad_sigs)
7549 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7550 return err;
7553 static const struct got_error *
7554 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7555 const char *tag_name, const char *repo_path)
7557 const struct got_error *err = NULL;
7558 char *template = NULL, *initial_content = NULL;
7559 char *editor = NULL;
7560 int initial_content_len;
7561 int fd = -1;
7563 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7564 err = got_error_from_errno("asprintf");
7565 goto done;
7568 initial_content_len = asprintf(&initial_content,
7569 "\n# tagging commit %s as %s\n",
7570 commit_id_str, tag_name);
7571 if (initial_content_len == -1) {
7572 err = got_error_from_errno("asprintf");
7573 goto done;
7576 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7577 if (err)
7578 goto done;
7580 if (write(fd, initial_content, initial_content_len) == -1) {
7581 err = got_error_from_errno2("write", *tagmsg_path);
7582 goto done;
7584 if (close(fd) == -1) {
7585 err = got_error_from_errno2("close", *tagmsg_path);
7586 goto done;
7588 fd = -1;
7590 err = get_editor(&editor);
7591 if (err)
7592 goto done;
7593 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7594 initial_content_len, 1);
7595 done:
7596 free(initial_content);
7597 free(template);
7598 free(editor);
7600 if (fd != -1 && close(fd) == -1 && err == NULL)
7601 err = got_error_from_errno2("close", *tagmsg_path);
7603 if (err) {
7604 free(*tagmsg);
7605 *tagmsg = NULL;
7607 return err;
7610 static const struct got_error *
7611 add_tag(struct got_repository *repo, const char *tagger,
7612 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7613 const char *signer_id, int verbosity)
7615 const struct got_error *err = NULL;
7616 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7617 char *label = NULL, *commit_id_str = NULL;
7618 struct got_reference *ref = NULL;
7619 char *refname = NULL, *tagmsg = NULL;
7620 char *tagmsg_path = NULL, *tag_id_str = NULL;
7621 int preserve_tagmsg = 0;
7622 struct got_reflist_head refs;
7624 TAILQ_INIT(&refs);
7627 * Don't let the user create a tag name with a leading '-'.
7628 * While technically a valid reference name, this case is usually
7629 * an unintended typo.
7631 if (tag_name[0] == '-')
7632 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7634 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7635 if (err)
7636 goto done;
7638 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7639 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7640 if (err)
7641 goto done;
7643 err = got_object_id_str(&commit_id_str, commit_id);
7644 if (err)
7645 goto done;
7647 err = get_tag_refname(&refname, tag_name);
7648 if (err)
7649 goto done;
7650 if (strncmp("refs/tags/", tag_name, 10) == 0)
7651 tag_name += 10;
7653 err = got_ref_open(&ref, repo, refname, 0);
7654 if (err == NULL) {
7655 err = got_error(GOT_ERR_TAG_EXISTS);
7656 goto done;
7657 } else if (err->code != GOT_ERR_NOT_REF)
7658 goto done;
7660 if (tagmsg_arg == NULL) {
7661 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7662 tag_name, got_repo_get_path(repo));
7663 if (err) {
7664 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7665 tagmsg_path != NULL)
7666 preserve_tagmsg = 1;
7667 goto done;
7669 /* Editor is done; we can now apply unveil(2) */
7670 err = got_sigs_apply_unveil();
7671 if (err)
7672 goto done;
7673 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7674 if (err)
7675 goto done;
7678 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7679 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7680 verbosity);
7681 if (err) {
7682 if (tagmsg_path)
7683 preserve_tagmsg = 1;
7684 goto done;
7687 err = got_ref_alloc(&ref, refname, tag_id);
7688 if (err) {
7689 if (tagmsg_path)
7690 preserve_tagmsg = 1;
7691 goto done;
7694 err = got_ref_write(ref, repo);
7695 if (err) {
7696 if (tagmsg_path)
7697 preserve_tagmsg = 1;
7698 goto done;
7701 err = got_object_id_str(&tag_id_str, tag_id);
7702 if (err) {
7703 if (tagmsg_path)
7704 preserve_tagmsg = 1;
7705 goto done;
7707 printf("Created tag %s\n", tag_id_str);
7708 done:
7709 if (preserve_tagmsg) {
7710 fprintf(stderr, "%s: tag message preserved in %s\n",
7711 getprogname(), tagmsg_path);
7712 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7713 err = got_error_from_errno2("unlink", tagmsg_path);
7714 free(tag_id_str);
7715 if (ref)
7716 got_ref_close(ref);
7717 free(commit_id);
7718 free(commit_id_str);
7719 free(refname);
7720 free(tagmsg);
7721 free(tagmsg_path);
7722 got_ref_list_free(&refs);
7723 return err;
7726 static const struct got_error *
7727 cmd_tag(int argc, char *argv[])
7729 const struct got_error *error = NULL;
7730 struct got_repository *repo = NULL;
7731 struct got_worktree *worktree = NULL;
7732 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7733 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7734 char *allowed_signers = NULL, *revoked_signers = NULL;
7735 const char *signer_id = NULL;
7736 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7737 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7738 int *pack_fds = NULL;
7740 #ifndef PROFILE
7741 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7742 "sendfd unveil", NULL) == -1)
7743 err(1, "pledge");
7744 #endif
7746 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7747 switch (ch) {
7748 case 'c':
7749 commit_id_arg = optarg;
7750 break;
7751 case 'l':
7752 do_list = 1;
7753 break;
7754 case 'm':
7755 tagmsg = optarg;
7756 break;
7757 case 'r':
7758 repo_path = realpath(optarg, NULL);
7759 if (repo_path == NULL) {
7760 error = got_error_from_errno2("realpath",
7761 optarg);
7762 goto done;
7764 got_path_strip_trailing_slashes(repo_path);
7765 break;
7766 case 's':
7767 signer_id = optarg;
7768 break;
7769 case 'V':
7770 verify_tags = 1;
7771 break;
7772 case 'v':
7773 if (verbosity < 0)
7774 verbosity = 0;
7775 else if (verbosity < 3)
7776 verbosity++;
7777 break;
7778 default:
7779 usage_tag();
7780 /* NOTREACHED */
7784 argc -= optind;
7785 argv += optind;
7787 if (do_list || verify_tags) {
7788 if (commit_id_arg != NULL)
7789 errx(1,
7790 "-c option can only be used when creating a tag");
7791 if (tagmsg) {
7792 if (do_list)
7793 option_conflict('l', 'm');
7794 else
7795 option_conflict('V', 'm');
7797 if (signer_id) {
7798 if (do_list)
7799 option_conflict('l', 's');
7800 else
7801 option_conflict('V', 's');
7803 if (argc > 1)
7804 usage_tag();
7805 } else if (argc != 1)
7806 usage_tag();
7808 if (argc == 1)
7809 tag_name = argv[0];
7811 cwd = getcwd(NULL, 0);
7812 if (cwd == NULL) {
7813 error = got_error_from_errno("getcwd");
7814 goto done;
7817 error = got_repo_pack_fds_open(&pack_fds);
7818 if (error != NULL)
7819 goto done;
7821 if (repo_path == NULL) {
7822 error = got_worktree_open(&worktree, cwd,
7823 GOT_WORKTREE_GOT_DIR);
7824 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7825 goto done;
7826 else
7827 error = NULL;
7828 if (worktree) {
7829 repo_path =
7830 strdup(got_worktree_get_repo_path(worktree));
7831 if (repo_path == NULL)
7832 error = got_error_from_errno("strdup");
7833 if (error)
7834 goto done;
7835 } else {
7836 repo_path = strdup(cwd);
7837 if (repo_path == NULL) {
7838 error = got_error_from_errno("strdup");
7839 goto done;
7844 if (do_list || verify_tags) {
7845 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7846 if (error != NULL)
7847 goto done;
7848 error = get_allowed_signers(&allowed_signers, repo, worktree);
7849 if (error)
7850 goto done;
7851 error = get_revoked_signers(&revoked_signers, repo, worktree);
7852 if (error)
7853 goto done;
7854 if (worktree) {
7855 /* Release work tree lock. */
7856 got_worktree_close(worktree);
7857 worktree = NULL;
7861 * Remove "cpath" promise unless needed for signature tmpfile
7862 * creation.
7864 if (verify_tags)
7865 got_sigs_apply_unveil();
7866 else {
7867 #ifndef PROFILE
7868 if (pledge("stdio rpath wpath flock proc exec sendfd "
7869 "unveil", NULL) == -1)
7870 err(1, "pledge");
7871 #endif
7873 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7874 if (error)
7875 goto done;
7876 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7877 revoked_signers, verbosity);
7878 } else {
7879 error = get_gitconfig_path(&gitconfig_path);
7880 if (error)
7881 goto done;
7882 error = got_repo_open(&repo, repo_path, gitconfig_path,
7883 pack_fds);
7884 if (error != NULL)
7885 goto done;
7887 error = get_author(&tagger, repo, worktree);
7888 if (error)
7889 goto done;
7890 if (signer_id == NULL)
7891 signer_id = get_signer_id(repo, worktree);
7893 if (tagmsg) {
7894 if (signer_id) {
7895 error = got_sigs_apply_unveil();
7896 if (error)
7897 goto done;
7899 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7900 if (error)
7901 goto done;
7904 if (commit_id_arg == NULL) {
7905 struct got_reference *head_ref;
7906 struct got_object_id *commit_id;
7907 error = got_ref_open(&head_ref, repo,
7908 worktree ? got_worktree_get_head_ref_name(worktree)
7909 : GOT_REF_HEAD, 0);
7910 if (error)
7911 goto done;
7912 error = got_ref_resolve(&commit_id, repo, head_ref);
7913 got_ref_close(head_ref);
7914 if (error)
7915 goto done;
7916 error = got_object_id_str(&commit_id_str, commit_id);
7917 free(commit_id);
7918 if (error)
7919 goto done;
7920 } else {
7921 error = got_keyword_to_idstr(&keyword_idstr,
7922 commit_id_arg, repo, worktree);
7923 if (error != NULL)
7924 goto done;
7925 commit_id_str = keyword_idstr;
7928 if (worktree) {
7929 /* Release work tree lock. */
7930 got_worktree_close(worktree);
7931 worktree = NULL;
7934 error = add_tag(repo, tagger, tag_name,
7935 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7936 signer_id, verbosity);
7938 done:
7939 if (repo) {
7940 const struct got_error *close_err = got_repo_close(repo);
7941 if (error == NULL)
7942 error = close_err;
7944 if (worktree)
7945 got_worktree_close(worktree);
7946 if (pack_fds) {
7947 const struct got_error *pack_err =
7948 got_repo_pack_fds_close(pack_fds);
7949 if (error == NULL)
7950 error = pack_err;
7952 free(cwd);
7953 free(repo_path);
7954 free(gitconfig_path);
7955 free(commit_id_str);
7956 free(tagger);
7957 free(allowed_signers);
7958 free(revoked_signers);
7959 return error;
7962 __dead static void
7963 usage_add(void)
7965 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7966 exit(1);
7969 static const struct got_error *
7970 add_progress(void *arg, unsigned char status, const char *path)
7972 while (path[0] == '/')
7973 path++;
7974 printf("%c %s\n", status, path);
7975 return NULL;
7978 static const struct got_error *
7979 cmd_add(int argc, char *argv[])
7981 const struct got_error *error = NULL;
7982 struct got_repository *repo = NULL;
7983 struct got_worktree *worktree = NULL;
7984 char *cwd = NULL;
7985 struct got_pathlist_head paths;
7986 struct got_pathlist_entry *pe;
7987 int ch, can_recurse = 0, no_ignores = 0;
7988 int *pack_fds = NULL;
7990 TAILQ_INIT(&paths);
7992 #ifndef PROFILE
7993 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7994 NULL) == -1)
7995 err(1, "pledge");
7996 #endif
7998 while ((ch = getopt(argc, argv, "IR")) != -1) {
7999 switch (ch) {
8000 case 'I':
8001 no_ignores = 1;
8002 break;
8003 case 'R':
8004 can_recurse = 1;
8005 break;
8006 default:
8007 usage_add();
8008 /* NOTREACHED */
8012 argc -= optind;
8013 argv += optind;
8015 if (argc < 1)
8016 usage_add();
8018 cwd = getcwd(NULL, 0);
8019 if (cwd == NULL) {
8020 error = got_error_from_errno("getcwd");
8021 goto done;
8024 error = got_repo_pack_fds_open(&pack_fds);
8025 if (error != NULL)
8026 goto done;
8028 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8029 if (error) {
8030 if (error->code == GOT_ERR_NOT_WORKTREE)
8031 error = wrap_not_worktree_error(error, "add", cwd);
8032 goto done;
8035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8036 NULL, pack_fds);
8037 if (error != NULL)
8038 goto done;
8040 error = apply_unveil(got_repo_get_path(repo), 1,
8041 got_worktree_get_root_path(worktree));
8042 if (error)
8043 goto done;
8045 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8046 if (error)
8047 goto done;
8049 if (!can_recurse) {
8050 char *ondisk_path;
8051 struct stat sb;
8052 TAILQ_FOREACH(pe, &paths, entry) {
8053 if (asprintf(&ondisk_path, "%s/%s",
8054 got_worktree_get_root_path(worktree),
8055 pe->path) == -1) {
8056 error = got_error_from_errno("asprintf");
8057 goto done;
8059 if (lstat(ondisk_path, &sb) == -1) {
8060 if (errno == ENOENT) {
8061 free(ondisk_path);
8062 continue;
8064 error = got_error_from_errno2("lstat",
8065 ondisk_path);
8066 free(ondisk_path);
8067 goto done;
8069 free(ondisk_path);
8070 if (S_ISDIR(sb.st_mode)) {
8071 error = got_error_msg(GOT_ERR_BAD_PATH,
8072 "adding directories requires -R option");
8073 goto done;
8078 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8079 NULL, repo, no_ignores);
8080 done:
8081 if (repo) {
8082 const struct got_error *close_err = got_repo_close(repo);
8083 if (error == NULL)
8084 error = close_err;
8086 if (worktree)
8087 got_worktree_close(worktree);
8088 if (pack_fds) {
8089 const struct got_error *pack_err =
8090 got_repo_pack_fds_close(pack_fds);
8091 if (error == NULL)
8092 error = pack_err;
8094 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8095 free(cwd);
8096 return error;
8099 __dead static void
8100 usage_remove(void)
8102 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8103 getprogname());
8104 exit(1);
8107 static const struct got_error *
8108 print_remove_status(void *arg, unsigned char status,
8109 unsigned char staged_status, const char *path)
8111 while (path[0] == '/')
8112 path++;
8113 if (status == GOT_STATUS_NONEXISTENT)
8114 return NULL;
8115 if (status == staged_status && (status == GOT_STATUS_DELETE))
8116 status = GOT_STATUS_NO_CHANGE;
8117 printf("%c%c %s\n", status, staged_status, path);
8118 return NULL;
8121 static const struct got_error *
8122 cmd_remove(int argc, char *argv[])
8124 const struct got_error *error = NULL;
8125 struct got_worktree *worktree = NULL;
8126 struct got_repository *repo = NULL;
8127 const char *status_codes = NULL;
8128 char *cwd = NULL;
8129 struct got_pathlist_head paths;
8130 struct got_pathlist_entry *pe;
8131 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8132 int ignore_missing_paths = 0;
8133 int *pack_fds = NULL;
8135 TAILQ_INIT(&paths);
8137 #ifndef PROFILE
8138 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8139 NULL) == -1)
8140 err(1, "pledge");
8141 #endif
8143 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8144 switch (ch) {
8145 case 'f':
8146 delete_local_mods = 1;
8147 ignore_missing_paths = 1;
8148 break;
8149 case 'k':
8150 keep_on_disk = 1;
8151 break;
8152 case 'R':
8153 can_recurse = 1;
8154 break;
8155 case 's':
8156 for (i = 0; optarg[i] != '\0'; i++) {
8157 switch (optarg[i]) {
8158 case GOT_STATUS_MODIFY:
8159 delete_local_mods = 1;
8160 break;
8161 case GOT_STATUS_MISSING:
8162 ignore_missing_paths = 1;
8163 break;
8164 default:
8165 errx(1, "invalid status code '%c'",
8166 optarg[i]);
8169 status_codes = optarg;
8170 break;
8171 default:
8172 usage_remove();
8173 /* NOTREACHED */
8177 argc -= optind;
8178 argv += optind;
8180 if (argc < 1)
8181 usage_remove();
8183 cwd = getcwd(NULL, 0);
8184 if (cwd == NULL) {
8185 error = got_error_from_errno("getcwd");
8186 goto done;
8189 error = got_repo_pack_fds_open(&pack_fds);
8190 if (error != NULL)
8191 goto done;
8193 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8194 if (error) {
8195 if (error->code == GOT_ERR_NOT_WORKTREE)
8196 error = wrap_not_worktree_error(error, "remove", cwd);
8197 goto done;
8200 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8201 NULL, pack_fds);
8202 if (error)
8203 goto done;
8205 error = apply_unveil(got_repo_get_path(repo), 1,
8206 got_worktree_get_root_path(worktree));
8207 if (error)
8208 goto done;
8210 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8211 if (error)
8212 goto done;
8214 if (!can_recurse) {
8215 char *ondisk_path;
8216 struct stat sb;
8217 TAILQ_FOREACH(pe, &paths, entry) {
8218 if (asprintf(&ondisk_path, "%s/%s",
8219 got_worktree_get_root_path(worktree),
8220 pe->path) == -1) {
8221 error = got_error_from_errno("asprintf");
8222 goto done;
8224 if (lstat(ondisk_path, &sb) == -1) {
8225 if (errno == ENOENT) {
8226 free(ondisk_path);
8227 continue;
8229 error = got_error_from_errno2("lstat",
8230 ondisk_path);
8231 free(ondisk_path);
8232 goto done;
8234 free(ondisk_path);
8235 if (S_ISDIR(sb.st_mode)) {
8236 error = got_error_msg(GOT_ERR_BAD_PATH,
8237 "removing directories requires -R option");
8238 goto done;
8243 error = got_worktree_schedule_delete(worktree, &paths,
8244 delete_local_mods, status_codes, print_remove_status, NULL,
8245 repo, keep_on_disk, ignore_missing_paths);
8246 done:
8247 if (repo) {
8248 const struct got_error *close_err = got_repo_close(repo);
8249 if (error == NULL)
8250 error = close_err;
8252 if (worktree)
8253 got_worktree_close(worktree);
8254 if (pack_fds) {
8255 const struct got_error *pack_err =
8256 got_repo_pack_fds_close(pack_fds);
8257 if (error == NULL)
8258 error = pack_err;
8260 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8261 free(cwd);
8262 return error;
8265 __dead static void
8266 usage_patch(void)
8268 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8269 "[patchfile]\n", getprogname());
8270 exit(1);
8273 static const struct got_error *
8274 patch_from_stdin(int *patchfd)
8276 const struct got_error *err = NULL;
8277 ssize_t r;
8278 char buf[BUFSIZ];
8279 sig_t sighup, sigint, sigquit;
8281 *patchfd = got_opentempfd();
8282 if (*patchfd == -1)
8283 return got_error_from_errno("got_opentempfd");
8285 sighup = signal(SIGHUP, SIG_DFL);
8286 sigint = signal(SIGINT, SIG_DFL);
8287 sigquit = signal(SIGQUIT, SIG_DFL);
8289 for (;;) {
8290 r = read(0, buf, sizeof(buf));
8291 if (r == -1) {
8292 err = got_error_from_errno("read");
8293 break;
8295 if (r == 0)
8296 break;
8297 if (write(*patchfd, buf, r) == -1) {
8298 err = got_error_from_errno("write");
8299 break;
8303 signal(SIGHUP, sighup);
8304 signal(SIGINT, sigint);
8305 signal(SIGQUIT, sigquit);
8307 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8308 err = got_error_from_errno("lseek");
8310 if (err != NULL) {
8311 close(*patchfd);
8312 *patchfd = -1;
8315 return err;
8318 struct got_patch_progress_arg {
8319 int did_something;
8320 int conflicts;
8321 int rejects;
8324 static const struct got_error *
8325 patch_progress(void *arg, const char *old, const char *new,
8326 unsigned char status, const struct got_error *error, int old_from,
8327 int old_lines, int new_from, int new_lines, int offset,
8328 int ws_mangled, const struct got_error *hunk_err)
8330 const char *path = new == NULL ? old : new;
8331 struct got_patch_progress_arg *a = arg;
8333 while (*path == '/')
8334 path++;
8336 if (status != GOT_STATUS_NO_CHANGE &&
8337 status != 0 /* per-hunk progress */) {
8338 printf("%c %s\n", status, path);
8339 a->did_something = 1;
8342 if (hunk_err == NULL) {
8343 if (status == GOT_STATUS_CANNOT_UPDATE)
8344 a->rejects++;
8345 else if (status == GOT_STATUS_CONFLICT)
8346 a->conflicts++;
8349 if (error != NULL)
8350 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8352 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8353 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8354 old_lines, new_from, new_lines);
8355 if (hunk_err != NULL)
8356 printf("%s\n", hunk_err->msg);
8357 else if (offset != 0)
8358 printf("applied with offset %d\n", offset);
8359 else
8360 printf("hunk contains mangled whitespace\n");
8363 return NULL;
8366 static void
8367 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8369 if (!ppa->did_something)
8370 return;
8372 if (ppa->conflicts > 0)
8373 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8375 if (ppa->rejects > 0) {
8376 printf("Files where patch failed to apply: %d\n",
8377 ppa->rejects);
8381 static const struct got_error *
8382 cmd_patch(int argc, char *argv[])
8384 const struct got_error *error = NULL, *close_error = NULL;
8385 struct got_worktree *worktree = NULL;
8386 struct got_repository *repo = NULL;
8387 struct got_reflist_head refs;
8388 struct got_object_id *commit_id = NULL;
8389 const char *commit_id_str = NULL;
8390 struct stat sb;
8391 const char *errstr;
8392 char *cwd = NULL, *keyword_idstr = NULL;
8393 int ch, nop = 0, strip = -1, reverse = 0;
8394 int patchfd;
8395 int *pack_fds = NULL;
8396 struct got_patch_progress_arg ppa;
8398 TAILQ_INIT(&refs);
8400 #ifndef PROFILE
8401 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8402 "unveil", NULL) == -1)
8403 err(1, "pledge");
8404 #endif
8406 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8407 switch (ch) {
8408 case 'c':
8409 commit_id_str = optarg;
8410 break;
8411 case 'n':
8412 nop = 1;
8413 break;
8414 case 'p':
8415 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8416 if (errstr != NULL)
8417 errx(1, "pathname strip count is %s: %s",
8418 errstr, optarg);
8419 break;
8420 case 'R':
8421 reverse = 1;
8422 break;
8423 default:
8424 usage_patch();
8425 /* NOTREACHED */
8429 argc -= optind;
8430 argv += optind;
8432 if (argc == 0) {
8433 error = patch_from_stdin(&patchfd);
8434 if (error)
8435 return error;
8436 } else if (argc == 1) {
8437 patchfd = open(argv[0], O_RDONLY);
8438 if (patchfd == -1) {
8439 error = got_error_from_errno2("open", argv[0]);
8440 return error;
8442 if (fstat(patchfd, &sb) == -1) {
8443 error = got_error_from_errno2("fstat", argv[0]);
8444 goto done;
8446 if (!S_ISREG(sb.st_mode)) {
8447 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8448 goto done;
8450 } else
8451 usage_patch();
8453 if ((cwd = getcwd(NULL, 0)) == NULL) {
8454 error = got_error_from_errno("getcwd");
8455 goto done;
8458 error = got_repo_pack_fds_open(&pack_fds);
8459 if (error != NULL)
8460 goto done;
8462 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8463 if (error != NULL)
8464 goto done;
8466 const char *repo_path = got_worktree_get_repo_path(worktree);
8467 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8468 if (error != NULL)
8469 goto done;
8471 error = apply_unveil(got_repo_get_path(repo), 0,
8472 got_worktree_get_root_path(worktree));
8473 if (error != NULL)
8474 goto done;
8476 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8477 if (error)
8478 goto done;
8480 if (commit_id_str != NULL) {
8481 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8482 repo, worktree);
8483 if (error != NULL)
8484 goto done;
8486 error = got_repo_match_object_id(&commit_id, NULL,
8487 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8488 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8489 if (error)
8490 goto done;
8493 memset(&ppa, 0, sizeof(ppa));
8494 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8495 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8496 print_patch_progress_stats(&ppa);
8497 done:
8498 got_ref_list_free(&refs);
8499 free(keyword_idstr);
8500 free(commit_id);
8501 if (repo) {
8502 close_error = got_repo_close(repo);
8503 if (error == NULL)
8504 error = close_error;
8506 if (worktree != NULL) {
8507 close_error = got_worktree_close(worktree);
8508 if (error == NULL)
8509 error = close_error;
8511 if (pack_fds) {
8512 const struct got_error *pack_err =
8513 got_repo_pack_fds_close(pack_fds);
8514 if (error == NULL)
8515 error = pack_err;
8517 free(cwd);
8518 return error;
8521 __dead static void
8522 usage_revert(void)
8524 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8525 getprogname());
8526 exit(1);
8529 static const struct got_error *
8530 revert_progress(void *arg, unsigned char status, const char *path)
8532 if (status == GOT_STATUS_UNVERSIONED)
8533 return NULL;
8535 while (path[0] == '/')
8536 path++;
8537 printf("%c %s\n", status, path);
8538 return NULL;
8541 struct choose_patch_arg {
8542 FILE *patch_script_file;
8543 const char *action;
8546 static const struct got_error *
8547 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8548 int nchanges, const char *action)
8550 const struct got_error *err;
8551 char *line = NULL;
8552 size_t linesize = 0;
8553 ssize_t linelen;
8555 switch (status) {
8556 case GOT_STATUS_ADD:
8557 printf("A %s\n%s this addition? [y/n] ", path, action);
8558 break;
8559 case GOT_STATUS_DELETE:
8560 printf("D %s\n%s this deletion? [y/n] ", path, action);
8561 break;
8562 case GOT_STATUS_MODIFY:
8563 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8564 return got_error_from_errno("fseek");
8565 printf(GOT_COMMIT_SEP_STR);
8566 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8567 printf("%s", line);
8568 if (linelen == -1 && ferror(patch_file)) {
8569 err = got_error_from_errno("getline");
8570 free(line);
8571 return err;
8573 free(line);
8574 printf(GOT_COMMIT_SEP_STR);
8575 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8576 path, n, nchanges, action);
8577 break;
8578 default:
8579 return got_error_path(path, GOT_ERR_FILE_STATUS);
8582 fflush(stdout);
8583 return NULL;
8586 static const struct got_error *
8587 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8588 FILE *patch_file, int n, int nchanges)
8590 const struct got_error *err = NULL;
8591 char *line = NULL;
8592 size_t linesize = 0;
8593 ssize_t linelen;
8594 int resp = ' ';
8595 struct choose_patch_arg *a = arg;
8597 *choice = GOT_PATCH_CHOICE_NONE;
8599 if (a->patch_script_file) {
8600 char *nl;
8601 err = show_change(status, path, patch_file, n, nchanges,
8602 a->action);
8603 if (err)
8604 return err;
8605 linelen = getline(&line, &linesize, a->patch_script_file);
8606 if (linelen == -1) {
8607 if (ferror(a->patch_script_file))
8608 return got_error_from_errno("getline");
8609 return NULL;
8611 nl = strchr(line, '\n');
8612 if (nl)
8613 *nl = '\0';
8614 if (strcmp(line, "y") == 0) {
8615 *choice = GOT_PATCH_CHOICE_YES;
8616 printf("y\n");
8617 } else if (strcmp(line, "n") == 0) {
8618 *choice = GOT_PATCH_CHOICE_NO;
8619 printf("n\n");
8620 } else if (strcmp(line, "q") == 0 &&
8621 status == GOT_STATUS_MODIFY) {
8622 *choice = GOT_PATCH_CHOICE_QUIT;
8623 printf("q\n");
8624 } else
8625 printf("invalid response '%s'\n", line);
8626 free(line);
8627 return NULL;
8630 while (resp != 'y' && resp != 'n' && resp != 'q') {
8631 err = show_change(status, path, patch_file, n, nchanges,
8632 a->action);
8633 if (err)
8634 return err;
8635 resp = getchar();
8636 if (resp == '\n')
8637 resp = getchar();
8638 if (status == GOT_STATUS_MODIFY) {
8639 if (resp != 'y' && resp != 'n' && resp != 'q') {
8640 printf("invalid response '%c'\n", resp);
8641 resp = ' ';
8643 } else if (resp != 'y' && resp != 'n') {
8644 printf("invalid response '%c'\n", resp);
8645 resp = ' ';
8649 if (resp == 'y')
8650 *choice = GOT_PATCH_CHOICE_YES;
8651 else if (resp == 'n')
8652 *choice = GOT_PATCH_CHOICE_NO;
8653 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8654 *choice = GOT_PATCH_CHOICE_QUIT;
8656 return NULL;
8659 struct wt_commitable_path_arg {
8660 struct got_pathlist_head *commit_paths;
8661 int *has_changes;
8665 * Shortcut work tree status callback to determine if the set of paths scanned
8666 * has at least one versioned path that is being modified and, if not NULL, is
8667 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8668 * soon as a path is passed with a status that satisfies this criteria.
8670 static const struct got_error *
8671 worktree_has_commitable_path(void *arg, unsigned char status,
8672 unsigned char staged_status, const char *path,
8673 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8674 struct got_object_id *commit_id, int dirfd, const char *de_name)
8676 struct wt_commitable_path_arg *a = arg;
8678 if (status == staged_status && (status == GOT_STATUS_DELETE))
8679 status = GOT_STATUS_NO_CHANGE;
8681 if (!(status == GOT_STATUS_NO_CHANGE ||
8682 status == GOT_STATUS_UNVERSIONED) ||
8683 staged_status != GOT_STATUS_NO_CHANGE) {
8684 if (a->commit_paths != NULL) {
8685 struct got_pathlist_entry *pe;
8687 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8688 if (strncmp(path, pe->path,
8689 pe->path_len) == 0) {
8690 *a->has_changes = 1;
8691 break;
8694 } else
8695 *a->has_changes = 1;
8697 if (*a->has_changes)
8698 return got_error(GOT_ERR_FILE_MODIFIED);
8701 return NULL;
8705 * Check that the changeset of the commit identified by id is
8706 * comprised of at least one modified path that is being committed.
8708 static const struct got_error *
8709 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8710 struct got_object_id *id, struct got_worktree *worktree,
8711 struct got_repository *repo)
8713 const struct got_error *err;
8714 struct got_pathlist_head paths;
8715 struct got_commit_object *commit = NULL, *pcommit = NULL;
8716 struct got_tree_object *tree = NULL, *ptree = NULL;
8717 struct got_object_qid *pid;
8719 TAILQ_INIT(&paths);
8721 err = got_object_open_as_commit(&commit, repo, id);
8722 if (err)
8723 goto done;
8725 err = got_object_open_as_tree(&tree, repo,
8726 got_object_commit_get_tree_id(commit));
8727 if (err)
8728 goto done;
8730 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8731 if (pid != NULL) {
8732 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8733 if (err)
8734 goto done;
8736 err = got_object_open_as_tree(&ptree, repo,
8737 got_object_commit_get_tree_id(pcommit));
8738 if (err)
8739 goto done;
8742 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8743 got_diff_tree_collect_changed_paths, &paths, 0);
8744 if (err)
8745 goto done;
8747 err = got_worktree_status(worktree, &paths, repo, 0,
8748 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8749 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8751 * At least one changed path in the referenced commit is
8752 * modified in the work tree, that's all we need to know!
8754 err = NULL;
8757 done:
8758 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8759 if (commit)
8760 got_object_commit_close(commit);
8761 if (pcommit)
8762 got_object_commit_close(pcommit);
8763 if (tree)
8764 got_object_tree_close(tree);
8765 if (ptree)
8766 got_object_tree_close(ptree);
8767 return err;
8771 * Remove any "logmsg" reference comprised entirely of paths that have
8772 * been reverted in this work tree. If any path in the logmsg ref changeset
8773 * remains in a changed state in the worktree, do not remove the reference.
8775 static const struct got_error *
8776 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8778 const struct got_error *err;
8779 struct got_reflist_head refs;
8780 struct got_reflist_entry *re;
8781 struct got_commit_object *commit = NULL;
8782 struct got_object_id *commit_id = NULL;
8783 struct wt_commitable_path_arg wcpa;
8784 char *uuidstr = NULL;
8786 TAILQ_INIT(&refs);
8788 err = got_worktree_get_uuid(&uuidstr, worktree);
8789 if (err)
8790 goto done;
8792 err = got_ref_list(&refs, repo, "refs/got/worktree",
8793 got_ref_cmp_by_name, repo);
8794 if (err)
8795 goto done;
8797 TAILQ_FOREACH(re, &refs, entry) {
8798 const char *refname;
8799 int has_changes = 0;
8801 refname = got_ref_get_name(re->ref);
8803 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8804 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8805 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8806 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8807 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8808 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8809 else
8810 continue;
8812 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8813 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8814 else
8815 continue;
8817 err = got_repo_match_object_id(&commit_id, NULL, refname,
8818 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8819 if (err)
8820 goto done;
8822 err = got_object_open_as_commit(&commit, repo, commit_id);
8823 if (err)
8824 goto done;
8826 wcpa.commit_paths = NULL;
8827 wcpa.has_changes = &has_changes;
8829 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8830 worktree, repo);
8831 if (err)
8832 goto done;
8834 if (!has_changes) {
8835 err = got_ref_delete(re->ref, repo);
8836 if (err)
8837 goto done;
8840 got_object_commit_close(commit);
8841 commit = NULL;
8842 free(commit_id);
8843 commit_id = NULL;
8846 done:
8847 free(uuidstr);
8848 free(commit_id);
8849 got_ref_list_free(&refs);
8850 if (commit)
8851 got_object_commit_close(commit);
8852 return err;
8855 static const struct got_error *
8856 cmd_revert(int argc, char *argv[])
8858 const struct got_error *error = NULL;
8859 struct got_worktree *worktree = NULL;
8860 struct got_repository *repo = NULL;
8861 char *cwd = NULL, *path = NULL;
8862 struct got_pathlist_head paths;
8863 struct got_pathlist_entry *pe;
8864 int ch, can_recurse = 0, pflag = 0;
8865 FILE *patch_script_file = NULL;
8866 const char *patch_script_path = NULL;
8867 struct choose_patch_arg cpa;
8868 int *pack_fds = NULL;
8870 TAILQ_INIT(&paths);
8872 #ifndef PROFILE
8873 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8874 "unveil", NULL) == -1)
8875 err(1, "pledge");
8876 #endif
8878 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8879 switch (ch) {
8880 case 'F':
8881 patch_script_path = optarg;
8882 break;
8883 case 'p':
8884 pflag = 1;
8885 break;
8886 case 'R':
8887 can_recurse = 1;
8888 break;
8889 default:
8890 usage_revert();
8891 /* NOTREACHED */
8895 argc -= optind;
8896 argv += optind;
8898 if (argc < 1)
8899 usage_revert();
8900 if (patch_script_path && !pflag)
8901 errx(1, "-F option can only be used together with -p option");
8903 cwd = getcwd(NULL, 0);
8904 if (cwd == NULL) {
8905 error = got_error_from_errno("getcwd");
8906 goto done;
8909 error = got_repo_pack_fds_open(&pack_fds);
8910 if (error != NULL)
8911 goto done;
8913 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8914 if (error) {
8915 if (error->code == GOT_ERR_NOT_WORKTREE)
8916 error = wrap_not_worktree_error(error, "revert", cwd);
8917 goto done;
8920 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8921 NULL, pack_fds);
8922 if (error != NULL)
8923 goto done;
8925 if (patch_script_path) {
8926 patch_script_file = fopen(patch_script_path, "re");
8927 if (patch_script_file == NULL) {
8928 error = got_error_from_errno2("fopen",
8929 patch_script_path);
8930 goto done;
8935 * XXX "c" perm needed on repo dir to delete merge references.
8937 error = apply_unveil(got_repo_get_path(repo), 0,
8938 got_worktree_get_root_path(worktree));
8939 if (error)
8940 goto done;
8942 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8943 if (error)
8944 goto done;
8946 if (!can_recurse) {
8947 char *ondisk_path;
8948 struct stat sb;
8949 TAILQ_FOREACH(pe, &paths, entry) {
8950 if (asprintf(&ondisk_path, "%s/%s",
8951 got_worktree_get_root_path(worktree),
8952 pe->path) == -1) {
8953 error = got_error_from_errno("asprintf");
8954 goto done;
8956 if (lstat(ondisk_path, &sb) == -1) {
8957 if (errno == ENOENT) {
8958 free(ondisk_path);
8959 continue;
8961 error = got_error_from_errno2("lstat",
8962 ondisk_path);
8963 free(ondisk_path);
8964 goto done;
8966 free(ondisk_path);
8967 if (S_ISDIR(sb.st_mode)) {
8968 error = got_error_msg(GOT_ERR_BAD_PATH,
8969 "reverting directories requires -R option");
8970 goto done;
8975 cpa.patch_script_file = patch_script_file;
8976 cpa.action = "revert";
8977 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8978 pflag ? choose_patch : NULL, &cpa, repo);
8980 error = rm_logmsg_ref(worktree, repo);
8981 done:
8982 if (patch_script_file && fclose(patch_script_file) == EOF &&
8983 error == NULL)
8984 error = got_error_from_errno2("fclose", patch_script_path);
8985 if (repo) {
8986 const struct got_error *close_err = got_repo_close(repo);
8987 if (error == NULL)
8988 error = close_err;
8990 if (worktree)
8991 got_worktree_close(worktree);
8992 if (pack_fds) {
8993 const struct got_error *pack_err =
8994 got_repo_pack_fds_close(pack_fds);
8995 if (error == NULL)
8996 error = pack_err;
8998 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8999 free(path);
9000 free(cwd);
9001 return error;
9004 __dead static void
9005 usage_commit(void)
9007 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9008 "[-m message] [path ...]\n", getprogname());
9009 exit(1);
9012 struct collect_commit_logmsg_arg {
9013 const char *cmdline_log;
9014 const char *prepared_log;
9015 const char *merged_log;
9016 int non_interactive;
9017 const char *editor;
9018 const char *worktree_path;
9019 const char *branch_name;
9020 const char *repo_path;
9021 char *logmsg_path;
9025 static const struct got_error *
9026 read_prepared_logmsg(char **logmsg, const char *path)
9028 const struct got_error *err = NULL;
9029 FILE *f = NULL;
9030 struct stat sb;
9031 size_t r;
9033 *logmsg = NULL;
9034 memset(&sb, 0, sizeof(sb));
9036 f = fopen(path, "re");
9037 if (f == NULL)
9038 return got_error_from_errno2("fopen", path);
9040 if (fstat(fileno(f), &sb) == -1) {
9041 err = got_error_from_errno2("fstat", path);
9042 goto done;
9044 if (sb.st_size == 0) {
9045 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9046 goto done;
9049 *logmsg = malloc(sb.st_size + 1);
9050 if (*logmsg == NULL) {
9051 err = got_error_from_errno("malloc");
9052 goto done;
9055 r = fread(*logmsg, 1, sb.st_size, f);
9056 if (r != sb.st_size) {
9057 if (ferror(f))
9058 err = got_error_from_errno2("fread", path);
9059 else
9060 err = got_error(GOT_ERR_IO);
9061 goto done;
9063 (*logmsg)[sb.st_size] = '\0';
9064 done:
9065 if (fclose(f) == EOF && err == NULL)
9066 err = got_error_from_errno2("fclose", path);
9067 if (err) {
9068 free(*logmsg);
9069 *logmsg = NULL;
9071 return err;
9074 static const struct got_error *
9075 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9076 const char *diff_path, char **logmsg, void *arg)
9078 char *initial_content = NULL;
9079 struct got_pathlist_entry *pe;
9080 const struct got_error *err = NULL;
9081 char *template = NULL;
9082 char *prepared_msg = NULL, *merged_msg = NULL;
9083 struct collect_commit_logmsg_arg *a = arg;
9084 int initial_content_len;
9085 int fd = -1;
9086 size_t len;
9088 /* if a message was specified on the command line, just use it */
9089 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9090 len = strlen(a->cmdline_log) + 1;
9091 *logmsg = malloc(len + 1);
9092 if (*logmsg == NULL)
9093 return got_error_from_errno("malloc");
9094 strlcpy(*logmsg, a->cmdline_log, len);
9095 return NULL;
9096 } else if (a->prepared_log != NULL && a->non_interactive)
9097 return read_prepared_logmsg(logmsg, a->prepared_log);
9099 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9100 return got_error_from_errno("asprintf");
9102 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9103 if (err)
9104 goto done;
9106 if (a->prepared_log) {
9107 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9108 if (err)
9109 goto done;
9110 } else if (a->merged_log) {
9111 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9112 if (err)
9113 goto done;
9116 initial_content_len = asprintf(&initial_content,
9117 "%s%s\n# changes to be committed on branch %s:\n",
9118 prepared_msg ? prepared_msg : "",
9119 merged_msg ? merged_msg : "", a->branch_name);
9120 if (initial_content_len == -1) {
9121 err = got_error_from_errno("asprintf");
9122 goto done;
9125 if (write(fd, initial_content, initial_content_len) == -1) {
9126 err = got_error_from_errno2("write", a->logmsg_path);
9127 goto done;
9130 TAILQ_FOREACH(pe, commitable_paths, entry) {
9131 struct got_commitable *ct = pe->data;
9132 dprintf(fd, "# %c %s\n",
9133 got_commitable_get_status(ct),
9134 got_commitable_get_path(ct));
9137 if (diff_path) {
9138 dprintf(fd, "# detailed changes can be viewed in %s\n",
9139 diff_path);
9142 if (close(fd) == -1) {
9143 err = got_error_from_errno2("close", a->logmsg_path);
9144 goto done;
9146 fd = -1;
9148 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9149 initial_content_len, a->prepared_log ? 0 : 1);
9150 done:
9151 free(initial_content);
9152 free(template);
9153 free(prepared_msg);
9154 free(merged_msg);
9156 if (fd != -1 && close(fd) == -1 && err == NULL)
9157 err = got_error_from_errno2("close", a->logmsg_path);
9159 /* Editor is done; we can now apply unveil(2) */
9160 if (err == NULL)
9161 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9162 if (err) {
9163 free(*logmsg);
9164 *logmsg = NULL;
9166 return err;
9169 static const struct got_error *
9170 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9171 const char *type, int has_content)
9173 const struct got_error *err = NULL;
9174 char *logmsg = NULL;
9176 err = got_object_commit_get_logmsg(&logmsg, commit);
9177 if (err)
9178 return err;
9180 if (fprintf(f, "%s# log message of %s commit %s:%s",
9181 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9182 err = got_ferror(f, GOT_ERR_IO);
9184 free(logmsg);
9185 return err;
9189 * Lookup "logmsg" references of backed-out and cherrypicked commits
9190 * belonging to the current work tree. If found, and the worktree has
9191 * at least one modified file that was changed in the referenced commit,
9192 * add its log message to a new temporary file at *logmsg_path.
9193 * Add all refs found to matched_refs to be scheduled for removal on
9194 * successful commit.
9196 static const struct got_error *
9197 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9198 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9199 struct got_repository *repo)
9201 const struct got_error *err;
9202 struct got_commit_object *commit = NULL;
9203 struct got_object_id *id = NULL;
9204 struct got_reflist_head refs;
9205 struct got_reflist_entry *re, *re_match;
9206 FILE *f = NULL;
9207 char *uuidstr = NULL;
9208 int added_logmsg = 0;
9210 TAILQ_INIT(&refs);
9212 *logmsg_path = NULL;
9214 err = got_worktree_get_uuid(&uuidstr, worktree);
9215 if (err)
9216 goto done;
9218 err = got_ref_list(&refs, repo, "refs/got/worktree",
9219 got_ref_cmp_by_name, repo);
9220 if (err)
9221 goto done;
9223 TAILQ_FOREACH(re, &refs, entry) {
9224 const char *refname, *type;
9225 struct wt_commitable_path_arg wcpa;
9226 int add_logmsg = 0;
9228 refname = got_ref_get_name(re->ref);
9230 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9231 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9232 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9233 type = "cherrypicked";
9234 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9235 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9236 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9237 type = "backed-out";
9238 } else
9239 continue;
9241 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9242 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9243 else
9244 continue;
9246 err = got_repo_match_object_id(&id, NULL, refname,
9247 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9248 if (err)
9249 goto done;
9251 err = got_object_open_as_commit(&commit, repo, id);
9252 if (err)
9253 goto done;
9255 wcpa.commit_paths = paths;
9256 wcpa.has_changes = &add_logmsg;
9258 err = commit_path_changed_in_worktree(&wcpa, id,
9259 worktree, repo);
9260 if (err)
9261 goto done;
9263 if (add_logmsg) {
9264 if (f == NULL) {
9265 err = got_opentemp_named(logmsg_path, &f,
9266 "got-commit-logmsg", "");
9267 if (err)
9268 goto done;
9270 err = cat_logmsg(f, commit, refname, type,
9271 added_logmsg);
9272 if (err)
9273 goto done;
9274 if (!added_logmsg)
9275 ++added_logmsg;
9277 err = got_reflist_entry_dup(&re_match, re);
9278 if (err)
9279 goto done;
9280 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9283 got_object_commit_close(commit);
9284 commit = NULL;
9285 free(id);
9286 id = NULL;
9289 done:
9290 free(id);
9291 free(uuidstr);
9292 got_ref_list_free(&refs);
9293 if (commit)
9294 got_object_commit_close(commit);
9295 if (f && fclose(f) == EOF && err == NULL)
9296 err = got_error_from_errno("fclose");
9297 if (!added_logmsg) {
9298 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9299 err = got_error_from_errno2("unlink", *logmsg_path);
9300 *logmsg_path = NULL;
9302 return err;
9305 static const struct got_error *
9306 cmd_commit(int argc, char *argv[])
9308 const struct got_error *error = NULL;
9309 struct got_worktree *worktree = NULL;
9310 struct got_repository *repo = NULL;
9311 char *cwd = NULL, *id_str = NULL;
9312 struct got_object_id *id = NULL;
9313 const char *logmsg = NULL;
9314 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9315 struct collect_commit_logmsg_arg cl_arg;
9316 const char *author = NULL;
9317 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9318 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9319 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9320 int show_diff = 1, commit_conflicts = 0;
9321 struct got_pathlist_head paths;
9322 struct got_reflist_head refs;
9323 struct got_reflist_entry *re;
9324 int *pack_fds = NULL;
9326 TAILQ_INIT(&refs);
9327 TAILQ_INIT(&paths);
9328 cl_arg.logmsg_path = NULL;
9330 #ifndef PROFILE
9331 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9332 "unveil", NULL) == -1)
9333 err(1, "pledge");
9334 #endif
9336 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9337 switch (ch) {
9338 case 'A':
9339 author = optarg;
9340 error = valid_author(author);
9341 if (error)
9342 return error;
9343 break;
9344 case 'C':
9345 commit_conflicts = 1;
9346 break;
9347 case 'F':
9348 if (logmsg != NULL)
9349 option_conflict('F', 'm');
9350 prepared_logmsg = realpath(optarg, NULL);
9351 if (prepared_logmsg == NULL)
9352 return got_error_from_errno2("realpath",
9353 optarg);
9354 break;
9355 case 'm':
9356 if (prepared_logmsg)
9357 option_conflict('m', 'F');
9358 logmsg = optarg;
9359 break;
9360 case 'N':
9361 non_interactive = 1;
9362 break;
9363 case 'n':
9364 show_diff = 0;
9365 break;
9366 case 'S':
9367 allow_bad_symlinks = 1;
9368 break;
9369 default:
9370 usage_commit();
9371 /* NOTREACHED */
9375 argc -= optind;
9376 argv += optind;
9378 cwd = getcwd(NULL, 0);
9379 if (cwd == NULL) {
9380 error = got_error_from_errno("getcwd");
9381 goto done;
9384 error = got_repo_pack_fds_open(&pack_fds);
9385 if (error != NULL)
9386 goto done;
9388 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9389 if (error) {
9390 if (error->code == GOT_ERR_NOT_WORKTREE)
9391 error = wrap_not_worktree_error(error, "commit", cwd);
9392 goto done;
9395 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9396 if (error)
9397 goto done;
9398 if (rebase_in_progress) {
9399 error = got_error(GOT_ERR_REBASING);
9400 goto done;
9403 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9404 worktree);
9405 if (error)
9406 goto done;
9408 error = get_gitconfig_path(&gitconfig_path);
9409 if (error)
9410 goto done;
9411 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9412 gitconfig_path, pack_fds);
9413 if (error != NULL)
9414 goto done;
9416 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9417 if (error)
9418 goto done;
9419 if (merge_in_progress) {
9420 error = got_error(GOT_ERR_MERGE_BUSY);
9421 goto done;
9424 error = get_author(&committer, repo, worktree);
9425 if (error)
9426 goto done;
9428 if (author == NULL)
9429 author = committer;
9432 * unveil(2) traverses exec(2); if an editor is used we have
9433 * to apply unveil after the log message has been written.
9435 if (logmsg == NULL || strlen(logmsg) == 0)
9436 error = get_editor(&editor);
9437 else
9438 error = apply_unveil(got_repo_get_path(repo), 0,
9439 got_worktree_get_root_path(worktree));
9440 if (error)
9441 goto done;
9443 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9444 if (error)
9445 goto done;
9447 if (prepared_logmsg == NULL) {
9448 error = lookup_logmsg_ref(&merged_logmsg,
9449 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9450 if (error)
9451 goto done;
9454 cl_arg.editor = editor;
9455 cl_arg.cmdline_log = logmsg;
9456 cl_arg.prepared_log = prepared_logmsg;
9457 cl_arg.merged_log = merged_logmsg;
9458 cl_arg.non_interactive = non_interactive;
9459 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9460 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9461 if (!histedit_in_progress) {
9462 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9463 error = got_error(GOT_ERR_COMMIT_BRANCH);
9464 goto done;
9466 cl_arg.branch_name += 11;
9468 cl_arg.repo_path = got_repo_get_path(repo);
9469 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9470 allow_bad_symlinks, show_diff, commit_conflicts,
9471 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9472 if (error) {
9473 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9474 cl_arg.logmsg_path != NULL)
9475 preserve_logmsg = 1;
9476 goto done;
9479 error = got_object_id_str(&id_str, id);
9480 if (error)
9481 goto done;
9482 printf("Created commit %s\n", id_str);
9484 TAILQ_FOREACH(re, &refs, entry) {
9485 error = got_ref_delete(re->ref, repo);
9486 if (error)
9487 goto done;
9490 done:
9491 if (preserve_logmsg) {
9492 fprintf(stderr, "%s: log message preserved in %s\n",
9493 getprogname(), cl_arg.logmsg_path);
9494 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9495 error == NULL)
9496 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9497 free(cl_arg.logmsg_path);
9498 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9499 error = got_error_from_errno2("unlink", merged_logmsg);
9500 free(merged_logmsg);
9501 if (repo) {
9502 const struct got_error *close_err = got_repo_close(repo);
9503 if (error == NULL)
9504 error = close_err;
9506 if (worktree)
9507 got_worktree_close(worktree);
9508 if (pack_fds) {
9509 const struct got_error *pack_err =
9510 got_repo_pack_fds_close(pack_fds);
9511 if (error == NULL)
9512 error = pack_err;
9514 got_ref_list_free(&refs);
9515 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9516 free(cwd);
9517 free(id_str);
9518 free(gitconfig_path);
9519 free(editor);
9520 free(committer);
9521 free(prepared_logmsg);
9522 return error;
9525 __dead static void
9526 usage_send(void)
9528 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9529 "[-r repository-path] [-t tag] [remote-repository]\n",
9530 getprogname());
9531 exit(1);
9534 static void
9535 print_load_info(int print_colored, int print_found, int print_trees,
9536 int ncolored, int nfound, int ntrees)
9538 if (print_colored) {
9539 printf("%d commit%s colored", ncolored,
9540 ncolored == 1 ? "" : "s");
9542 if (print_found) {
9543 printf("%s%d object%s found",
9544 ncolored > 0 ? "; " : "",
9545 nfound, nfound == 1 ? "" : "s");
9547 if (print_trees) {
9548 printf("; %d tree%s scanned", ntrees,
9549 ntrees == 1 ? "" : "s");
9553 struct got_send_progress_arg {
9554 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9555 int verbosity;
9556 int last_ncolored;
9557 int last_nfound;
9558 int last_ntrees;
9559 int loading_done;
9560 int last_ncommits;
9561 int last_nobj_total;
9562 int last_p_deltify;
9563 int last_p_written;
9564 int last_p_sent;
9565 int printed_something;
9566 int sent_something;
9567 struct got_pathlist_head *delete_branches;
9570 static const struct got_error *
9571 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9572 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9573 int nobj_written, off_t bytes_sent, const char *refname,
9574 const char *errmsg, int success)
9576 struct got_send_progress_arg *a = arg;
9577 char scaled_packsize[FMT_SCALED_STRSIZE];
9578 char scaled_sent[FMT_SCALED_STRSIZE];
9579 int p_deltify = 0, p_written = 0, p_sent = 0;
9580 int print_colored = 0, print_found = 0, print_trees = 0;
9581 int print_searching = 0, print_total = 0;
9582 int print_deltify = 0, print_written = 0, print_sent = 0;
9584 if (a->verbosity < 0)
9585 return NULL;
9587 if (refname) {
9588 const char *status = success ? "accepted" : "rejected";
9590 if (success) {
9591 struct got_pathlist_entry *pe;
9592 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9593 const char *branchname = pe->path;
9594 if (got_path_cmp(branchname, refname,
9595 strlen(branchname), strlen(refname)) == 0) {
9596 status = "deleted";
9597 a->sent_something = 1;
9598 break;
9603 if (a->printed_something)
9604 putchar('\n');
9605 printf("Server has %s %s", status, refname);
9606 if (errmsg)
9607 printf(": %s", errmsg);
9608 a->printed_something = 1;
9609 return NULL;
9612 if (a->last_ncolored != ncolored) {
9613 print_colored = 1;
9614 a->last_ncolored = ncolored;
9617 if (a->last_nfound != nfound) {
9618 print_colored = 1;
9619 print_found = 1;
9620 a->last_nfound = nfound;
9623 if (a->last_ntrees != ntrees) {
9624 print_colored = 1;
9625 print_found = 1;
9626 print_trees = 1;
9627 a->last_ntrees = ntrees;
9630 if ((print_colored || print_found || print_trees) &&
9631 !a->loading_done) {
9632 printf("\r");
9633 print_load_info(print_colored, print_found, print_trees,
9634 ncolored, nfound, ntrees);
9635 a->printed_something = 1;
9636 fflush(stdout);
9637 return NULL;
9638 } else if (!a->loading_done) {
9639 printf("\r");
9640 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9641 printf("\n");
9642 a->loading_done = 1;
9645 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9646 return got_error_from_errno("fmt_scaled");
9647 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9648 return got_error_from_errno("fmt_scaled");
9650 if (a->last_ncommits != ncommits) {
9651 print_searching = 1;
9652 a->last_ncommits = ncommits;
9655 if (a->last_nobj_total != nobj_total) {
9656 print_searching = 1;
9657 print_total = 1;
9658 a->last_nobj_total = nobj_total;
9661 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9662 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9663 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9664 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9665 return got_error(GOT_ERR_NO_SPACE);
9668 if (nobj_deltify > 0 || nobj_written > 0) {
9669 if (nobj_deltify > 0) {
9670 p_deltify = (nobj_deltify * 100) / nobj_total;
9671 if (p_deltify != a->last_p_deltify) {
9672 a->last_p_deltify = p_deltify;
9673 print_searching = 1;
9674 print_total = 1;
9675 print_deltify = 1;
9678 if (nobj_written > 0) {
9679 p_written = (nobj_written * 100) / nobj_total;
9680 if (p_written != a->last_p_written) {
9681 a->last_p_written = p_written;
9682 print_searching = 1;
9683 print_total = 1;
9684 print_deltify = 1;
9685 print_written = 1;
9690 if (bytes_sent > 0) {
9691 p_sent = (bytes_sent * 100) / packfile_size;
9692 if (p_sent != a->last_p_sent) {
9693 a->last_p_sent = p_sent;
9694 print_searching = 1;
9695 print_total = 1;
9696 print_deltify = 1;
9697 print_written = 1;
9698 print_sent = 1;
9700 a->sent_something = 1;
9703 if (print_searching || print_total || print_deltify || print_written ||
9704 print_sent)
9705 printf("\r");
9706 if (print_searching)
9707 printf("packing %d reference%s", ncommits,
9708 ncommits == 1 ? "" : "s");
9709 if (print_total)
9710 printf("; %d object%s", nobj_total,
9711 nobj_total == 1 ? "" : "s");
9712 if (print_deltify)
9713 printf("; deltify: %d%%", p_deltify);
9714 if (print_sent)
9715 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9716 scaled_packsize, p_sent);
9717 else if (print_written)
9718 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9719 scaled_packsize, p_written);
9720 if (print_searching || print_total || print_deltify ||
9721 print_written || print_sent) {
9722 a->printed_something = 1;
9723 fflush(stdout);
9725 return NULL;
9728 static const struct got_error *
9729 cmd_send(int argc, char *argv[])
9731 const struct got_error *error = NULL;
9732 char *cwd = NULL, *repo_path = NULL;
9733 const char *remote_name;
9734 char *proto = NULL, *host = NULL, *port = NULL;
9735 char *repo_name = NULL, *server_path = NULL;
9736 const struct got_remote_repo *remotes;
9737 struct got_remote_repo *remote = NULL;
9738 int nremotes, nbranches = 0, ndelete_branches = 0;
9739 struct got_repository *repo = NULL;
9740 struct got_worktree *worktree = NULL;
9741 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9742 struct got_pathlist_head branches;
9743 struct got_pathlist_head tags;
9744 struct got_reflist_head all_branches;
9745 struct got_reflist_head all_tags;
9746 struct got_pathlist_head delete_args;
9747 struct got_pathlist_head delete_branches;
9748 struct got_reflist_entry *re;
9749 struct got_pathlist_entry *pe;
9750 int i, ch, sendfd = -1, sendstatus;
9751 pid_t sendpid = -1;
9752 struct got_send_progress_arg spa;
9753 int verbosity = 0, overwrite_refs = 0;
9754 int send_all_branches = 0, send_all_tags = 0;
9755 struct got_reference *ref = NULL;
9756 int *pack_fds = NULL;
9758 TAILQ_INIT(&branches);
9759 TAILQ_INIT(&tags);
9760 TAILQ_INIT(&all_branches);
9761 TAILQ_INIT(&all_tags);
9762 TAILQ_INIT(&delete_args);
9763 TAILQ_INIT(&delete_branches);
9765 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9766 switch (ch) {
9767 case 'a':
9768 send_all_branches = 1;
9769 break;
9770 case 'b':
9771 error = got_pathlist_append(&branches, optarg, NULL);
9772 if (error)
9773 return error;
9774 nbranches++;
9775 break;
9776 case 'd':
9777 error = got_pathlist_append(&delete_args, optarg, NULL);
9778 if (error)
9779 return error;
9780 break;
9781 case 'f':
9782 overwrite_refs = 1;
9783 break;
9784 case 'q':
9785 verbosity = -1;
9786 break;
9787 case 'r':
9788 repo_path = realpath(optarg, NULL);
9789 if (repo_path == NULL)
9790 return got_error_from_errno2("realpath",
9791 optarg);
9792 got_path_strip_trailing_slashes(repo_path);
9793 break;
9794 case 'T':
9795 send_all_tags = 1;
9796 break;
9797 case 't':
9798 error = got_pathlist_append(&tags, optarg, NULL);
9799 if (error)
9800 return error;
9801 break;
9802 case 'v':
9803 if (verbosity < 0)
9804 verbosity = 0;
9805 else if (verbosity < 3)
9806 verbosity++;
9807 break;
9808 default:
9809 usage_send();
9810 /* NOTREACHED */
9813 argc -= optind;
9814 argv += optind;
9816 if (send_all_branches && !TAILQ_EMPTY(&branches))
9817 option_conflict('a', 'b');
9818 if (send_all_tags && !TAILQ_EMPTY(&tags))
9819 option_conflict('T', 't');
9822 if (argc == 0)
9823 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9824 else if (argc == 1)
9825 remote_name = argv[0];
9826 else
9827 usage_send();
9829 cwd = getcwd(NULL, 0);
9830 if (cwd == NULL) {
9831 error = got_error_from_errno("getcwd");
9832 goto done;
9835 error = got_repo_pack_fds_open(&pack_fds);
9836 if (error != NULL)
9837 goto done;
9839 if (repo_path == NULL) {
9840 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9841 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9842 goto done;
9843 else
9844 error = NULL;
9845 if (worktree) {
9846 repo_path =
9847 strdup(got_worktree_get_repo_path(worktree));
9848 if (repo_path == NULL)
9849 error = got_error_from_errno("strdup");
9850 if (error)
9851 goto done;
9852 } else {
9853 repo_path = strdup(cwd);
9854 if (repo_path == NULL) {
9855 error = got_error_from_errno("strdup");
9856 goto done;
9861 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9862 if (error)
9863 goto done;
9865 if (worktree) {
9866 worktree_conf = got_worktree_get_gotconfig(worktree);
9867 if (worktree_conf) {
9868 got_gotconfig_get_remotes(&nremotes, &remotes,
9869 worktree_conf);
9870 for (i = 0; i < nremotes; i++) {
9871 if (strcmp(remotes[i].name, remote_name) == 0) {
9872 error = got_repo_remote_repo_dup(&remote,
9873 &remotes[i]);
9874 if (error)
9875 goto done;
9876 break;
9881 if (remote == NULL) {
9882 repo_conf = got_repo_get_gotconfig(repo);
9883 if (repo_conf) {
9884 got_gotconfig_get_remotes(&nremotes, &remotes,
9885 repo_conf);
9886 for (i = 0; i < nremotes; i++) {
9887 if (strcmp(remotes[i].name, remote_name) == 0) {
9888 error = got_repo_remote_repo_dup(&remote,
9889 &remotes[i]);
9890 if (error)
9891 goto done;
9892 break;
9897 if (remote == NULL) {
9898 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9899 for (i = 0; i < nremotes; i++) {
9900 if (strcmp(remotes[i].name, remote_name) == 0) {
9901 error = got_repo_remote_repo_dup(&remote,
9902 &remotes[i]);
9903 if (error)
9904 goto done;
9905 break;
9909 if (remote == NULL) {
9910 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9911 goto done;
9914 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9915 &repo_name, remote->send_url);
9916 if (error)
9917 goto done;
9919 if (strcmp(proto, "git") == 0) {
9920 #ifndef PROFILE
9921 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9922 "sendfd dns inet unveil", NULL) == -1)
9923 err(1, "pledge");
9924 #endif
9925 } else if (strcmp(proto, "git+ssh") == 0 ||
9926 strcmp(proto, "ssh") == 0) {
9927 #ifndef PROFILE
9928 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9929 "sendfd unveil", NULL) == -1)
9930 err(1, "pledge");
9931 #endif
9932 } else if (strcmp(proto, "http") == 0 ||
9933 strcmp(proto, "git+http") == 0) {
9934 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9935 goto done;
9936 } else {
9937 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9938 goto done;
9941 error = got_dial_apply_unveil(proto);
9942 if (error)
9943 goto done;
9945 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9946 if (error)
9947 goto done;
9949 if (send_all_branches) {
9950 error = got_ref_list(&all_branches, repo, "refs/heads",
9951 got_ref_cmp_by_name, NULL);
9952 if (error)
9953 goto done;
9954 TAILQ_FOREACH(re, &all_branches, entry) {
9955 const char *branchname = got_ref_get_name(re->ref);
9956 error = got_pathlist_append(&branches,
9957 branchname, NULL);
9958 if (error)
9959 goto done;
9960 nbranches++;
9962 } else if (nbranches == 0) {
9963 for (i = 0; i < remote->nsend_branches; i++) {
9964 error = got_pathlist_append(&branches,
9965 remote->send_branches[i], NULL);
9966 if (error)
9967 goto done;
9971 if (send_all_tags) {
9972 error = got_ref_list(&all_tags, repo, "refs/tags",
9973 got_ref_cmp_by_name, NULL);
9974 if (error)
9975 goto done;
9976 TAILQ_FOREACH(re, &all_tags, entry) {
9977 const char *tagname = got_ref_get_name(re->ref);
9978 error = got_pathlist_append(&tags,
9979 tagname, NULL);
9980 if (error)
9981 goto done;
9986 * To prevent accidents only branches in refs/heads/ can be deleted
9987 * with 'got send -d'.
9988 * Deleting anything else requires local repository access or Git.
9990 TAILQ_FOREACH(pe, &delete_args, entry) {
9991 const char *branchname = pe->path;
9992 char *s;
9993 struct got_pathlist_entry *new;
9994 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9995 s = strdup(branchname);
9996 if (s == NULL) {
9997 error = got_error_from_errno("strdup");
9998 goto done;
10000 } else {
10001 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10002 error = got_error_from_errno("asprintf");
10003 goto done;
10006 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10007 if (error || new == NULL /* duplicate */)
10008 free(s);
10009 if (error)
10010 goto done;
10011 ndelete_branches++;
10014 if (nbranches == 0 && ndelete_branches == 0) {
10015 struct got_reference *head_ref;
10016 if (worktree)
10017 error = got_ref_open(&head_ref, repo,
10018 got_worktree_get_head_ref_name(worktree), 0);
10019 else
10020 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10021 if (error)
10022 goto done;
10023 if (got_ref_is_symbolic(head_ref)) {
10024 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10025 got_ref_close(head_ref);
10026 if (error)
10027 goto done;
10028 } else
10029 ref = head_ref;
10030 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10031 NULL);
10032 if (error)
10033 goto done;
10034 nbranches++;
10037 if (worktree) {
10038 /* Release work tree lock. */
10039 got_worktree_close(worktree);
10040 worktree = NULL;
10043 if (verbosity >= 0) {
10044 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10045 remote->name, proto, host,
10046 port ? ":" : "", port ? port : "",
10047 *server_path == '/' ? "" : "/", server_path);
10050 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10051 server_path, verbosity);
10052 if (error)
10053 goto done;
10055 memset(&spa, 0, sizeof(spa));
10056 spa.last_scaled_packsize[0] = '\0';
10057 spa.last_p_deltify = -1;
10058 spa.last_p_written = -1;
10059 spa.verbosity = verbosity;
10060 spa.delete_branches = &delete_branches;
10061 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10062 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10063 check_cancelled, NULL);
10064 if (spa.printed_something)
10065 putchar('\n');
10066 if (error)
10067 goto done;
10068 if (!spa.sent_something && verbosity >= 0)
10069 printf("Already up-to-date\n");
10070 done:
10071 if (sendpid > 0) {
10072 if (kill(sendpid, SIGTERM) == -1)
10073 error = got_error_from_errno("kill");
10074 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10075 error = got_error_from_errno("waitpid");
10077 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10078 error = got_error_from_errno("close");
10079 if (repo) {
10080 const struct got_error *close_err = got_repo_close(repo);
10081 if (error == NULL)
10082 error = close_err;
10084 if (worktree)
10085 got_worktree_close(worktree);
10086 if (pack_fds) {
10087 const struct got_error *pack_err =
10088 got_repo_pack_fds_close(pack_fds);
10089 if (error == NULL)
10090 error = pack_err;
10092 if (ref)
10093 got_ref_close(ref);
10094 got_repo_free_remote_repo_data(remote);
10095 free(remote);
10096 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10097 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10098 got_ref_list_free(&all_branches);
10099 got_ref_list_free(&all_tags);
10100 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10101 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10102 free(cwd);
10103 free(repo_path);
10104 free(proto);
10105 free(host);
10106 free(port);
10107 free(server_path);
10108 free(repo_name);
10109 return error;
10113 * Print and if delete is set delete all ref_prefix references.
10114 * If wanted_ref is not NULL, only print or delete this reference.
10116 static const struct got_error *
10117 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10118 const char *wanted_ref, int delete, struct got_worktree *worktree,
10119 struct got_repository *repo)
10121 const struct got_error *err;
10122 struct got_pathlist_head paths;
10123 struct got_reflist_head refs;
10124 struct got_reflist_entry *re;
10125 struct got_reflist_object_id_map *refs_idmap = NULL;
10126 struct got_commit_object *commit = NULL;
10127 struct got_object_id *id = NULL;
10128 const char *header_prefix;
10129 char *uuidstr = NULL;
10130 int found = 0;
10132 TAILQ_INIT(&refs);
10133 TAILQ_INIT(&paths);
10135 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10136 if (err)
10137 goto done;
10139 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10140 if (err)
10141 goto done;
10143 if (worktree != NULL) {
10144 err = got_worktree_get_uuid(&uuidstr, worktree);
10145 if (err)
10146 goto done;
10149 if (wanted_ref) {
10150 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10151 wanted_ref += 11;
10154 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10155 header_prefix = "backout";
10156 else
10157 header_prefix = "cherrypick";
10159 TAILQ_FOREACH(re, &refs, entry) {
10160 const char *refname, *wt;
10162 refname = got_ref_get_name(re->ref);
10164 err = check_cancelled(NULL);
10165 if (err)
10166 goto done;
10168 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10169 refname += prefix_len + 1; /* skip '-' delimiter */
10170 else
10171 continue;
10173 wt = refname;
10175 if (worktree == NULL || strncmp(refname, uuidstr,
10176 GOT_WORKTREE_UUID_STRLEN) == 0)
10177 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10178 else
10179 continue;
10181 err = got_repo_match_object_id(&id, NULL, refname,
10182 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10183 if (err)
10184 goto done;
10186 err = got_object_open_as_commit(&commit, repo, id);
10187 if (err)
10188 goto done;
10190 if (wanted_ref)
10191 found = strncmp(wanted_ref, refname,
10192 strlen(wanted_ref)) == 0;
10193 if (wanted_ref && !found) {
10194 struct got_reflist_head *ci_refs;
10196 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10197 id);
10199 if (ci_refs) {
10200 char *refs_str = NULL;
10201 char const *r = NULL;
10203 err = build_refs_str(&refs_str, ci_refs, id,
10204 repo, 1);
10205 if (err)
10206 goto done;
10208 r = refs_str;
10209 while (r) {
10210 if (strncmp(r, wanted_ref,
10211 strlen(wanted_ref)) == 0) {
10212 found = 1;
10213 break;
10215 r = strchr(r, ' ');
10216 if (r)
10217 ++r;
10219 free(refs_str);
10223 if (wanted_ref == NULL || found) {
10224 if (delete) {
10225 err = got_ref_delete(re->ref, repo);
10226 if (err)
10227 goto done;
10228 printf("Deleted: ");
10229 err = print_commit_oneline(commit, id, repo,
10230 refs_idmap);
10231 } else {
10233 * Print paths modified by commit to help
10234 * associate commits with worktree changes.
10236 err = get_changed_paths(&paths, commit,
10237 repo, NULL);
10238 if (err)
10239 goto done;
10241 err = print_commit(commit, id, repo, NULL,
10242 &paths, NULL, 0, 0, refs_idmap, NULL,
10243 header_prefix);
10244 got_pathlist_free(&paths,
10245 GOT_PATHLIST_FREE_ALL);
10247 if (worktree == NULL)
10248 printf("work tree: %.*s\n\n",
10249 GOT_WORKTREE_UUID_STRLEN, wt);
10251 if (err || found)
10252 goto done;
10255 got_object_commit_close(commit);
10256 commit = NULL;
10257 free(id);
10258 id = NULL;
10261 if (wanted_ref != NULL && !found)
10262 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10264 done:
10265 free(id);
10266 free(uuidstr);
10267 got_ref_list_free(&refs);
10268 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10269 if (refs_idmap)
10270 got_reflist_object_id_map_free(refs_idmap);
10271 if (commit)
10272 got_object_commit_close(commit);
10273 return err;
10277 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10278 * identified by id for log messages to prepopulate the editor on commit.
10280 static const struct got_error *
10281 logmsg_ref(struct got_object_id *id, const char *prefix,
10282 struct got_worktree *worktree, struct got_repository *repo)
10284 const struct got_error *err = NULL;
10285 char *idstr, *ref = NULL, *refname = NULL;
10286 int histedit_in_progress;
10287 int rebase_in_progress, merge_in_progress;
10290 * Silenty refuse to create merge reference if any histedit, merge,
10291 * or rebase operation is in progress.
10293 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10294 worktree);
10295 if (err)
10296 return err;
10297 if (histedit_in_progress)
10298 return NULL;
10300 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10301 if (err)
10302 return err;
10303 if (rebase_in_progress)
10304 return NULL;
10306 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10307 repo);
10308 if (err)
10309 return err;
10310 if (merge_in_progress)
10311 return NULL;
10313 err = got_object_id_str(&idstr, id);
10314 if (err)
10315 return err;
10317 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10318 if (err)
10319 goto done;
10321 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10322 err = got_error_from_errno("asprintf");
10323 goto done;
10326 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10327 -1, repo);
10328 done:
10329 free(ref);
10330 free(idstr);
10331 free(refname);
10332 return err;
10335 __dead static void
10336 usage_cherrypick(void)
10338 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10339 getprogname());
10340 exit(1);
10343 static const struct got_error *
10344 cmd_cherrypick(int argc, char *argv[])
10346 const struct got_error *error = NULL;
10347 struct got_worktree *worktree = NULL;
10348 struct got_repository *repo = NULL;
10349 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10350 struct got_object_id *commit_id = NULL;
10351 struct got_commit_object *commit = NULL;
10352 struct got_object_qid *pid;
10353 int ch, list_refs = 0, remove_refs = 0;
10354 struct got_update_progress_arg upa;
10355 int *pack_fds = NULL;
10357 #ifndef PROFILE
10358 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10359 "unveil", NULL) == -1)
10360 err(1, "pledge");
10361 #endif
10363 while ((ch = getopt(argc, argv, "lX")) != -1) {
10364 switch (ch) {
10365 case 'l':
10366 list_refs = 1;
10367 break;
10368 case 'X':
10369 remove_refs = 1;
10370 break;
10371 default:
10372 usage_cherrypick();
10373 /* NOTREACHED */
10377 argc -= optind;
10378 argv += optind;
10380 if (list_refs || remove_refs) {
10381 if (argc != 0 && argc != 1)
10382 usage_cherrypick();
10383 } else if (argc != 1)
10384 usage_cherrypick();
10385 if (list_refs && remove_refs)
10386 option_conflict('l', 'X');
10388 cwd = getcwd(NULL, 0);
10389 if (cwd == NULL) {
10390 error = got_error_from_errno("getcwd");
10391 goto done;
10394 error = got_repo_pack_fds_open(&pack_fds);
10395 if (error != NULL)
10396 goto done;
10398 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10399 if (error) {
10400 if (list_refs || remove_refs) {
10401 if (error->code != GOT_ERR_NOT_WORKTREE)
10402 goto done;
10403 } else {
10404 if (error->code == GOT_ERR_NOT_WORKTREE)
10405 error = wrap_not_worktree_error(error,
10406 "cherrypick", cwd);
10407 goto done;
10411 error = got_repo_open(&repo,
10412 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10413 NULL, pack_fds);
10414 if (error != NULL)
10415 goto done;
10417 error = apply_unveil(got_repo_get_path(repo), 0,
10418 worktree ? got_worktree_get_root_path(worktree) : NULL);
10419 if (error)
10420 goto done;
10422 if (list_refs || remove_refs) {
10423 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10424 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10425 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10426 goto done;
10429 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10430 if (error != NULL)
10431 goto done;
10433 error = got_repo_match_object_id(&commit_id, NULL,
10434 keyword_idstr != NULL ? keyword_idstr : argv[0],
10435 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10436 if (error)
10437 goto done;
10438 error = got_object_id_str(&commit_id_str, commit_id);
10439 if (error)
10440 goto done;
10442 error = got_object_open_as_commit(&commit, repo, commit_id);
10443 if (error)
10444 goto done;
10445 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10446 memset(&upa, 0, sizeof(upa));
10447 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10448 commit_id, repo, update_progress, &upa, check_cancelled,
10449 NULL);
10450 if (error != NULL)
10451 goto done;
10453 if (upa.did_something) {
10454 error = logmsg_ref(commit_id,
10455 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10456 if (error)
10457 goto done;
10458 printf("Merged commit %s\n", commit_id_str);
10460 print_merge_progress_stats(&upa);
10461 done:
10462 free(cwd);
10463 free(keyword_idstr);
10464 if (commit)
10465 got_object_commit_close(commit);
10466 free(commit_id_str);
10467 if (worktree)
10468 got_worktree_close(worktree);
10469 if (repo) {
10470 const struct got_error *close_err = got_repo_close(repo);
10471 if (error == NULL)
10472 error = close_err;
10474 if (pack_fds) {
10475 const struct got_error *pack_err =
10476 got_repo_pack_fds_close(pack_fds);
10477 if (error == NULL)
10478 error = pack_err;
10481 return error;
10484 __dead static void
10485 usage_backout(void)
10487 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10488 exit(1);
10491 static const struct got_error *
10492 cmd_backout(int argc, char *argv[])
10494 const struct got_error *error = NULL;
10495 struct got_worktree *worktree = NULL;
10496 struct got_repository *repo = NULL;
10497 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10498 struct got_object_id *commit_id = NULL;
10499 struct got_commit_object *commit = NULL;
10500 struct got_object_qid *pid;
10501 int ch, list_refs = 0, remove_refs = 0;
10502 struct got_update_progress_arg upa;
10503 int *pack_fds = NULL;
10505 #ifndef PROFILE
10506 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10507 "unveil", NULL) == -1)
10508 err(1, "pledge");
10509 #endif
10511 while ((ch = getopt(argc, argv, "lX")) != -1) {
10512 switch (ch) {
10513 case 'l':
10514 list_refs = 1;
10515 break;
10516 case 'X':
10517 remove_refs = 1;
10518 break;
10519 default:
10520 usage_backout();
10521 /* NOTREACHED */
10525 argc -= optind;
10526 argv += optind;
10528 if (list_refs || remove_refs) {
10529 if (argc != 0 && argc != 1)
10530 usage_backout();
10531 } else if (argc != 1)
10532 usage_backout();
10533 if (list_refs && remove_refs)
10534 option_conflict('l', 'X');
10536 cwd = getcwd(NULL, 0);
10537 if (cwd == NULL) {
10538 error = got_error_from_errno("getcwd");
10539 goto done;
10542 error = got_repo_pack_fds_open(&pack_fds);
10543 if (error != NULL)
10544 goto done;
10546 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10547 if (error) {
10548 if (list_refs || remove_refs) {
10549 if (error->code != GOT_ERR_NOT_WORKTREE)
10550 goto done;
10551 } else {
10552 if (error->code == GOT_ERR_NOT_WORKTREE)
10553 error = wrap_not_worktree_error(error,
10554 "backout", cwd);
10555 goto done;
10559 error = got_repo_open(&repo,
10560 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10561 NULL, pack_fds);
10562 if (error != NULL)
10563 goto done;
10565 error = apply_unveil(got_repo_get_path(repo), 0,
10566 worktree ? got_worktree_get_root_path(worktree) : NULL);
10567 if (error)
10568 goto done;
10570 if (list_refs || remove_refs) {
10571 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10572 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10573 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10574 goto done;
10577 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10578 if (error != NULL)
10579 goto done;
10581 error = got_repo_match_object_id(&commit_id, NULL,
10582 keyword_idstr != NULL ? keyword_idstr : argv[0],
10583 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10584 if (error)
10585 goto done;
10586 error = got_object_id_str(&commit_id_str, commit_id);
10587 if (error)
10588 goto done;
10590 error = got_object_open_as_commit(&commit, repo, commit_id);
10591 if (error)
10592 goto done;
10593 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10594 if (pid == NULL) {
10595 error = got_error(GOT_ERR_ROOT_COMMIT);
10596 goto done;
10599 memset(&upa, 0, sizeof(upa));
10600 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10601 repo, update_progress, &upa, check_cancelled, NULL);
10602 if (error != NULL)
10603 goto done;
10605 if (upa.did_something) {
10606 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10607 worktree, repo);
10608 if (error)
10609 goto done;
10610 printf("Backed out commit %s\n", commit_id_str);
10612 print_merge_progress_stats(&upa);
10613 done:
10614 free(cwd);
10615 free(keyword_idstr);
10616 if (commit)
10617 got_object_commit_close(commit);
10618 free(commit_id_str);
10619 if (worktree)
10620 got_worktree_close(worktree);
10621 if (repo) {
10622 const struct got_error *close_err = got_repo_close(repo);
10623 if (error == NULL)
10624 error = close_err;
10626 if (pack_fds) {
10627 const struct got_error *pack_err =
10628 got_repo_pack_fds_close(pack_fds);
10629 if (error == NULL)
10630 error = pack_err;
10632 return error;
10635 __dead static void
10636 usage_rebase(void)
10638 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10639 exit(1);
10642 static void
10643 trim_logmsg(char *logmsg, int limit)
10645 char *nl;
10646 size_t len;
10648 len = strlen(logmsg);
10649 if (len > limit)
10650 len = limit;
10651 logmsg[len] = '\0';
10652 nl = strchr(logmsg, '\n');
10653 if (nl)
10654 *nl = '\0';
10657 static const struct got_error *
10658 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10660 const struct got_error *err;
10661 char *logmsg0 = NULL;
10662 const char *s;
10664 err = got_object_commit_get_logmsg(&logmsg0, commit);
10665 if (err)
10666 return err;
10668 s = logmsg0;
10669 while (isspace((unsigned char)s[0]))
10670 s++;
10672 *logmsg = strdup(s);
10673 if (*logmsg == NULL) {
10674 err = got_error_from_errno("strdup");
10675 goto done;
10678 trim_logmsg(*logmsg, limit);
10679 done:
10680 free(logmsg0);
10681 return err;
10684 static const struct got_error *
10685 show_rebase_merge_conflict(struct got_object_id *id,
10686 struct got_repository *repo)
10688 const struct got_error *err;
10689 struct got_commit_object *commit = NULL;
10690 char *id_str = NULL, *logmsg = NULL;
10692 err = got_object_open_as_commit(&commit, repo, id);
10693 if (err)
10694 return err;
10696 err = got_object_id_str(&id_str, id);
10697 if (err)
10698 goto done;
10700 id_str[12] = '\0';
10702 err = get_short_logmsg(&logmsg, 42, commit);
10703 if (err)
10704 goto done;
10706 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10707 done:
10708 free(id_str);
10709 got_object_commit_close(commit);
10710 free(logmsg);
10711 return err;
10714 static const struct got_error *
10715 show_rebase_progress(struct got_commit_object *commit,
10716 struct got_object_id *old_id, struct got_object_id *new_id)
10718 const struct got_error *err;
10719 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10721 err = got_object_id_str(&old_id_str, old_id);
10722 if (err)
10723 goto done;
10725 if (new_id) {
10726 err = got_object_id_str(&new_id_str, new_id);
10727 if (err)
10728 goto done;
10731 old_id_str[12] = '\0';
10732 if (new_id_str)
10733 new_id_str[12] = '\0';
10735 err = get_short_logmsg(&logmsg, 42, commit);
10736 if (err)
10737 goto done;
10739 printf("%s -> %s: %s\n", old_id_str,
10740 new_id_str ? new_id_str : "no-op change", logmsg);
10741 done:
10742 free(old_id_str);
10743 free(new_id_str);
10744 free(logmsg);
10745 return err;
10748 static const struct got_error *
10749 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10750 struct got_reference *branch, struct got_reference *tmp_branch,
10751 struct got_repository *repo, int create_backup)
10753 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10754 return got_worktree_rebase_complete(worktree, fileindex,
10755 tmp_branch, branch, repo, create_backup);
10758 static const struct got_error *
10759 rebase_commit(struct got_pathlist_head *merged_paths,
10760 struct got_worktree *worktree, struct got_fileindex *fileindex,
10761 struct got_reference *tmp_branch, const char *committer,
10762 struct got_object_id *commit_id, int allow_conflict,
10763 struct got_repository *repo)
10765 const struct got_error *error;
10766 struct got_commit_object *commit;
10767 struct got_object_id *new_commit_id;
10769 error = got_object_open_as_commit(&commit, repo, commit_id);
10770 if (error)
10771 return error;
10773 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10774 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10775 allow_conflict, repo);
10776 if (error) {
10777 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10778 goto done;
10779 error = show_rebase_progress(commit, commit_id, NULL);
10780 } else {
10781 error = show_rebase_progress(commit, commit_id, new_commit_id);
10782 free(new_commit_id);
10784 done:
10785 got_object_commit_close(commit);
10786 return error;
10789 struct check_path_prefix_arg {
10790 const char *path_prefix;
10791 size_t len;
10792 int errcode;
10795 static const struct got_error *
10796 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10797 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10798 struct got_object_id *id1, struct got_object_id *id2,
10799 const char *path1, const char *path2,
10800 mode_t mode1, mode_t mode2, struct got_repository *repo)
10802 struct check_path_prefix_arg *a = arg;
10804 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10805 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10806 return got_error(a->errcode);
10808 return NULL;
10811 static const struct got_error *
10812 check_path_prefix(struct got_object_id *parent_id,
10813 struct got_object_id *commit_id, const char *path_prefix,
10814 int errcode, struct got_repository *repo)
10816 const struct got_error *err;
10817 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10818 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10819 struct check_path_prefix_arg cpp_arg;
10821 if (got_path_is_root_dir(path_prefix))
10822 return NULL;
10824 err = got_object_open_as_commit(&commit, repo, commit_id);
10825 if (err)
10826 goto done;
10828 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10829 if (err)
10830 goto done;
10832 err = got_object_open_as_tree(&tree1, repo,
10833 got_object_commit_get_tree_id(parent_commit));
10834 if (err)
10835 goto done;
10837 err = got_object_open_as_tree(&tree2, repo,
10838 got_object_commit_get_tree_id(commit));
10839 if (err)
10840 goto done;
10842 cpp_arg.path_prefix = path_prefix;
10843 while (cpp_arg.path_prefix[0] == '/')
10844 cpp_arg.path_prefix++;
10845 cpp_arg.len = strlen(cpp_arg.path_prefix);
10846 cpp_arg.errcode = errcode;
10847 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10848 check_path_prefix_in_diff, &cpp_arg, 0);
10849 done:
10850 if (tree1)
10851 got_object_tree_close(tree1);
10852 if (tree2)
10853 got_object_tree_close(tree2);
10854 if (commit)
10855 got_object_commit_close(commit);
10856 if (parent_commit)
10857 got_object_commit_close(parent_commit);
10858 return err;
10861 static const struct got_error *
10862 collect_commits(struct got_object_id_queue *commits,
10863 struct got_object_id *initial_commit_id,
10864 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10865 const char *path_prefix, int path_prefix_errcode,
10866 struct got_repository *repo)
10868 const struct got_error *err = NULL;
10869 struct got_commit_graph *graph = NULL;
10870 struct got_object_id parent_id, commit_id;
10871 struct got_object_qid *qid;
10873 err = got_commit_graph_open(&graph, "/", 1);
10874 if (err)
10875 return err;
10877 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10878 check_cancelled, NULL);
10879 if (err)
10880 goto done;
10882 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10883 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10884 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10885 check_cancelled, NULL);
10886 if (err) {
10887 if (err->code == GOT_ERR_ITER_COMPLETED) {
10888 err = got_error_msg(GOT_ERR_ANCESTRY,
10889 "ran out of commits to rebase before "
10890 "youngest common ancestor commit has "
10891 "been reached?!?");
10893 goto done;
10894 } else {
10895 err = check_path_prefix(&parent_id, &commit_id,
10896 path_prefix, path_prefix_errcode, repo);
10897 if (err)
10898 goto done;
10900 err = got_object_qid_alloc(&qid, &commit_id);
10901 if (err)
10902 goto done;
10903 STAILQ_INSERT_HEAD(commits, qid, entry);
10905 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10908 done:
10909 got_commit_graph_close(graph);
10910 return err;
10913 static const struct got_error *
10914 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10916 const struct got_error *err = NULL;
10917 time_t committer_time;
10918 struct tm tm;
10919 char datebuf[11]; /* YYYY-MM-DD + NUL */
10920 char *author0 = NULL, *author, *smallerthan;
10921 char *logmsg0 = NULL, *logmsg, *newline;
10923 committer_time = got_object_commit_get_committer_time(commit);
10924 if (gmtime_r(&committer_time, &tm) == NULL)
10925 return got_error_from_errno("gmtime_r");
10926 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10927 return got_error(GOT_ERR_NO_SPACE);
10929 author0 = strdup(got_object_commit_get_author(commit));
10930 if (author0 == NULL)
10931 return got_error_from_errno("strdup");
10932 author = author0;
10933 smallerthan = strchr(author, '<');
10934 if (smallerthan && smallerthan[1] != '\0')
10935 author = smallerthan + 1;
10936 author[strcspn(author, "@>")] = '\0';
10938 err = got_object_commit_get_logmsg(&logmsg0, commit);
10939 if (err)
10940 goto done;
10941 logmsg = logmsg0;
10942 while (*logmsg == '\n')
10943 logmsg++;
10944 newline = strchr(logmsg, '\n');
10945 if (newline)
10946 *newline = '\0';
10948 if (asprintf(brief_str, "%s %s %s",
10949 datebuf, author, logmsg) == -1)
10950 err = got_error_from_errno("asprintf");
10951 done:
10952 free(author0);
10953 free(logmsg0);
10954 return err;
10957 static const struct got_error *
10958 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10959 struct got_repository *repo)
10961 const struct got_error *err;
10962 char *id_str;
10964 err = got_object_id_str(&id_str, id);
10965 if (err)
10966 return err;
10968 err = got_ref_delete(ref, repo);
10969 if (err)
10970 goto done;
10972 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10973 done:
10974 free(id_str);
10975 return err;
10978 static const struct got_error *
10979 print_backup_ref(const char *branch_name, const char *new_id_str,
10980 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10981 struct got_reflist_object_id_map *refs_idmap,
10982 struct got_repository *repo)
10984 const struct got_error *err = NULL;
10985 struct got_reflist_head *refs;
10986 char *refs_str = NULL;
10987 struct got_object_id *new_commit_id = NULL;
10988 struct got_commit_object *new_commit = NULL;
10989 char *new_commit_brief_str = NULL;
10990 struct got_object_id *yca_id = NULL;
10991 struct got_commit_object *yca_commit = NULL;
10992 char *yca_id_str = NULL, *yca_brief_str = NULL;
10993 char *custom_refs_str;
10995 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10996 return got_error_from_errno("asprintf");
10998 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10999 0, 0, refs_idmap, custom_refs_str, NULL);
11000 if (err)
11001 goto done;
11003 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11004 if (err)
11005 goto done;
11007 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11008 if (refs) {
11009 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11010 if (err)
11011 goto done;
11014 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11015 if (err)
11016 goto done;
11018 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11019 if (err)
11020 goto done;
11022 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11023 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11024 if (err)
11025 goto done;
11027 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11028 refs_str ? " (" : "", refs_str ? refs_str : "",
11029 refs_str ? ")" : "", new_commit_brief_str);
11030 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11031 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11032 free(refs_str);
11033 refs_str = NULL;
11035 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11036 if (err)
11037 goto done;
11039 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11040 if (err)
11041 goto done;
11043 err = got_object_id_str(&yca_id_str, yca_id);
11044 if (err)
11045 goto done;
11047 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11048 if (refs) {
11049 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11050 if (err)
11051 goto done;
11053 printf("history forked at %s%s%s%s\n %s\n",
11054 yca_id_str,
11055 refs_str ? " (" : "", refs_str ? refs_str : "",
11056 refs_str ? ")" : "", yca_brief_str);
11058 done:
11059 free(custom_refs_str);
11060 free(new_commit_id);
11061 free(refs_str);
11062 free(yca_id);
11063 free(yca_id_str);
11064 free(yca_brief_str);
11065 if (new_commit)
11066 got_object_commit_close(new_commit);
11067 if (yca_commit)
11068 got_object_commit_close(yca_commit);
11070 return err;
11073 static const struct got_error *
11074 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11075 struct got_repository *repo)
11077 const struct got_error *err;
11078 struct got_reflist_head refs;
11079 struct got_reflist_entry *re;
11080 char *uuidstr = NULL;
11081 static char msg[160];
11083 TAILQ_INIT(&refs);
11085 err = got_worktree_get_uuid(&uuidstr, worktree);
11086 if (err)
11087 goto done;
11089 err = got_ref_list(&refs, repo, "refs/got/worktree",
11090 got_ref_cmp_by_name, repo);
11091 if (err)
11092 goto done;
11094 TAILQ_FOREACH(re, &refs, entry) {
11095 const char *cmd, *refname, *type;
11097 refname = got_ref_get_name(re->ref);
11099 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11100 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11101 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11102 cmd = "cherrypick";
11103 type = "cherrypicked";
11104 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11105 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11106 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11107 cmd = "backout";
11108 type = "backed-out";
11109 } else
11110 continue;
11112 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11113 continue;
11115 snprintf(msg, sizeof(msg),
11116 "work tree has references created by %s commits which "
11117 "must be removed with 'got %s -X' before running the %s "
11118 "command", type, cmd, caller);
11119 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11120 goto done;
11123 done:
11124 free(uuidstr);
11125 got_ref_list_free(&refs);
11126 return err;
11129 static const struct got_error *
11130 process_backup_refs(const char *backup_ref_prefix,
11131 const char *wanted_branch_name,
11132 int delete, struct got_repository *repo)
11134 const struct got_error *err;
11135 struct got_reflist_head refs, backup_refs;
11136 struct got_reflist_entry *re;
11137 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11138 struct got_object_id *old_commit_id = NULL;
11139 char *branch_name = NULL;
11140 struct got_commit_object *old_commit = NULL;
11141 struct got_reflist_object_id_map *refs_idmap = NULL;
11142 int wanted_branch_found = 0;
11144 TAILQ_INIT(&refs);
11145 TAILQ_INIT(&backup_refs);
11147 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11148 if (err)
11149 return err;
11151 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11152 if (err)
11153 goto done;
11155 if (wanted_branch_name) {
11156 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11157 wanted_branch_name += 11;
11160 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11161 got_ref_cmp_by_commit_timestamp_descending, repo);
11162 if (err)
11163 goto done;
11165 TAILQ_FOREACH(re, &backup_refs, entry) {
11166 const char *refname = got_ref_get_name(re->ref);
11167 char *slash;
11169 err = check_cancelled(NULL);
11170 if (err)
11171 break;
11173 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11174 if (err)
11175 break;
11177 err = got_object_open_as_commit(&old_commit, repo,
11178 old_commit_id);
11179 if (err)
11180 break;
11182 if (strncmp(backup_ref_prefix, refname,
11183 backup_ref_prefix_len) == 0)
11184 refname += backup_ref_prefix_len;
11186 while (refname[0] == '/')
11187 refname++;
11189 branch_name = strdup(refname);
11190 if (branch_name == NULL) {
11191 err = got_error_from_errno("strdup");
11192 break;
11194 slash = strrchr(branch_name, '/');
11195 if (slash) {
11196 *slash = '\0';
11197 refname += strlen(branch_name) + 1;
11200 if (wanted_branch_name == NULL ||
11201 strcmp(wanted_branch_name, branch_name) == 0) {
11202 wanted_branch_found = 1;
11203 if (delete) {
11204 err = delete_backup_ref(re->ref,
11205 old_commit_id, repo);
11206 } else {
11207 err = print_backup_ref(branch_name, refname,
11208 old_commit_id, old_commit, refs_idmap,
11209 repo);
11211 if (err)
11212 break;
11215 free(old_commit_id);
11216 old_commit_id = NULL;
11217 free(branch_name);
11218 branch_name = NULL;
11219 got_object_commit_close(old_commit);
11220 old_commit = NULL;
11223 if (wanted_branch_name && !wanted_branch_found) {
11224 err = got_error_fmt(GOT_ERR_NOT_REF,
11225 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11227 done:
11228 if (refs_idmap)
11229 got_reflist_object_id_map_free(refs_idmap);
11230 got_ref_list_free(&refs);
11231 got_ref_list_free(&backup_refs);
11232 free(old_commit_id);
11233 free(branch_name);
11234 if (old_commit)
11235 got_object_commit_close(old_commit);
11236 return err;
11239 static const struct got_error *
11240 abort_progress(void *arg, unsigned char status, const char *path)
11243 * Unversioned files should not clutter progress output when
11244 * an operation is aborted.
11246 if (status == GOT_STATUS_UNVERSIONED)
11247 return NULL;
11249 return update_progress(arg, status, path);
11252 static const struct got_error *
11253 find_merge_commit_yca(struct got_object_id **new_yca_id,
11254 struct got_object_id *branch_head_commit_id,
11255 struct got_object_id *yca_id,
11256 struct got_object_id *base_commit_id,
11257 struct got_repository *repo)
11259 const struct got_error *err = NULL;
11260 struct got_commit_graph *graph = NULL;
11261 struct got_commit_object *commit = NULL;
11263 *new_yca_id = NULL;
11265 err = got_commit_graph_open(&graph, "/", 1);
11266 if (err)
11267 return err;
11269 err = got_commit_graph_bfsort(graph, base_commit_id,
11270 repo, check_cancelled, NULL);
11271 if (err)
11272 goto done;
11274 for (;;) {
11275 struct got_object_id id;
11277 err = got_commit_graph_iter_next(&id, graph, repo,
11278 check_cancelled, NULL);
11279 if (err) {
11280 if (err->code == GOT_ERR_ITER_COMPLETED)
11281 err = NULL;
11282 break;
11285 err = got_object_open_as_commit(&commit, repo, &id);
11286 if (err)
11287 break;
11289 if (got_object_commit_get_nparents(commit) > 1) {
11290 /* Search for a better YCA using toposort. */
11291 err = got_commit_graph_find_youngest_common_ancestor(
11292 new_yca_id, base_commit_id, branch_head_commit_id,
11293 0, 1, repo, check_cancelled, NULL);
11294 break;
11297 if (got_object_id_cmp(&id, yca_id) == 0)
11298 break;
11299 got_object_commit_close(commit);
11300 commit = NULL;
11302 done:
11303 got_commit_graph_close(graph);
11304 if (commit)
11305 got_object_commit_close(commit);
11306 return err;
11309 static const struct got_error *
11310 cmd_rebase(int argc, char *argv[])
11312 const struct got_error *error = NULL;
11313 struct got_worktree *worktree = NULL;
11314 struct got_repository *repo = NULL;
11315 struct got_fileindex *fileindex = NULL;
11316 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11317 struct got_reference *branch = NULL;
11318 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11319 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11320 struct got_object_id *resume_commit_id = NULL;
11321 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11322 struct got_object_id *head_commit_id = NULL;
11323 struct got_reference *head_ref = NULL;
11324 struct got_commit_object *commit = NULL;
11325 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11326 int histedit_in_progress = 0, merge_in_progress = 0;
11327 int create_backup = 1, list_backups = 0, delete_backups = 0;
11328 int allow_conflict = 0;
11329 struct got_object_id_queue commits;
11330 struct got_pathlist_head merged_paths;
11331 const struct got_object_id_queue *parent_ids;
11332 struct got_object_qid *qid, *pid;
11333 struct got_update_progress_arg upa;
11334 int *pack_fds = NULL;
11336 STAILQ_INIT(&commits);
11337 TAILQ_INIT(&merged_paths);
11338 memset(&upa, 0, sizeof(upa));
11340 #ifndef PROFILE
11341 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11342 "unveil", NULL) == -1)
11343 err(1, "pledge");
11344 #endif
11346 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11347 switch (ch) {
11348 case 'a':
11349 abort_rebase = 1;
11350 break;
11351 case 'C':
11352 allow_conflict = 1;
11353 break;
11354 case 'c':
11355 continue_rebase = 1;
11356 break;
11357 case 'l':
11358 list_backups = 1;
11359 break;
11360 case 'X':
11361 delete_backups = 1;
11362 break;
11363 default:
11364 usage_rebase();
11365 /* NOTREACHED */
11369 argc -= optind;
11370 argv += optind;
11372 if (list_backups) {
11373 if (abort_rebase)
11374 option_conflict('l', 'a');
11375 if (allow_conflict)
11376 option_conflict('l', 'C');
11377 if (continue_rebase)
11378 option_conflict('l', 'c');
11379 if (delete_backups)
11380 option_conflict('l', 'X');
11381 if (argc != 0 && argc != 1)
11382 usage_rebase();
11383 } else if (delete_backups) {
11384 if (abort_rebase)
11385 option_conflict('X', 'a');
11386 if (allow_conflict)
11387 option_conflict('X', 'C');
11388 if (continue_rebase)
11389 option_conflict('X', 'c');
11390 if (list_backups)
11391 option_conflict('l', 'X');
11392 if (argc != 0 && argc != 1)
11393 usage_rebase();
11394 } else if (allow_conflict) {
11395 if (abort_rebase)
11396 option_conflict('C', 'a');
11397 if (!continue_rebase)
11398 errx(1, "-C option requires -c");
11399 } else {
11400 if (abort_rebase && continue_rebase)
11401 usage_rebase();
11402 else if (abort_rebase || continue_rebase) {
11403 if (argc != 0)
11404 usage_rebase();
11405 } else if (argc != 1)
11406 usage_rebase();
11409 cwd = getcwd(NULL, 0);
11410 if (cwd == NULL) {
11411 error = got_error_from_errno("getcwd");
11412 goto done;
11415 error = got_repo_pack_fds_open(&pack_fds);
11416 if (error != NULL)
11417 goto done;
11419 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11420 if (error) {
11421 if (list_backups || delete_backups) {
11422 if (error->code != GOT_ERR_NOT_WORKTREE)
11423 goto done;
11424 } else {
11425 if (error->code == GOT_ERR_NOT_WORKTREE)
11426 error = wrap_not_worktree_error(error,
11427 "rebase", cwd);
11428 goto done;
11432 error = get_gitconfig_path(&gitconfig_path);
11433 if (error)
11434 goto done;
11435 error = got_repo_open(&repo,
11436 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11437 gitconfig_path, pack_fds);
11438 if (error != NULL)
11439 goto done;
11441 if (worktree != NULL && !list_backups && !delete_backups) {
11442 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11443 if (error)
11444 goto done;
11447 error = get_author(&committer, repo, worktree);
11448 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11449 goto done;
11451 error = apply_unveil(got_repo_get_path(repo), 0,
11452 worktree ? got_worktree_get_root_path(worktree) : NULL);
11453 if (error)
11454 goto done;
11456 if (list_backups || delete_backups) {
11457 error = process_backup_refs(
11458 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11459 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11460 goto done; /* nothing else to do */
11463 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11464 worktree);
11465 if (error)
11466 goto done;
11467 if (histedit_in_progress) {
11468 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11469 goto done;
11472 error = got_worktree_merge_in_progress(&merge_in_progress,
11473 worktree, repo);
11474 if (error)
11475 goto done;
11476 if (merge_in_progress) {
11477 error = got_error(GOT_ERR_MERGE_BUSY);
11478 goto done;
11481 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11482 if (error)
11483 goto done;
11485 if (abort_rebase) {
11486 if (!rebase_in_progress) {
11487 error = got_error(GOT_ERR_NOT_REBASING);
11488 goto done;
11490 error = got_worktree_rebase_continue(&resume_commit_id,
11491 &new_base_branch, &tmp_branch, &branch, &fileindex,
11492 worktree, repo);
11493 if (error)
11494 goto done;
11495 printf("Switching work tree to %s\n",
11496 got_ref_get_symref_target(new_base_branch));
11497 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11498 new_base_branch, abort_progress, &upa);
11499 if (error)
11500 goto done;
11501 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11502 print_merge_progress_stats(&upa);
11503 goto done; /* nothing else to do */
11506 if (continue_rebase) {
11507 if (!rebase_in_progress) {
11508 error = got_error(GOT_ERR_NOT_REBASING);
11509 goto done;
11511 error = got_worktree_rebase_continue(&resume_commit_id,
11512 &new_base_branch, &tmp_branch, &branch, &fileindex,
11513 worktree, repo);
11514 if (error)
11515 goto done;
11517 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11518 committer, resume_commit_id, allow_conflict, repo);
11519 if (error)
11520 goto done;
11522 yca_id = got_object_id_dup(resume_commit_id);
11523 if (yca_id == NULL) {
11524 error = got_error_from_errno("got_object_id_dup");
11525 goto done;
11527 } else {
11528 error = got_ref_open(&branch, repo, argv[0], 0);
11529 if (error != NULL)
11530 goto done;
11531 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11532 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11533 "will not rebase a branch which lives outside "
11534 "the \"refs/heads/\" reference namespace");
11535 goto done;
11539 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11540 if (error)
11541 goto done;
11543 if (!continue_rebase) {
11544 struct got_object_id *base_commit_id;
11546 error = got_ref_open(&head_ref, repo,
11547 got_worktree_get_head_ref_name(worktree), 0);
11548 if (error)
11549 goto done;
11550 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11551 if (error)
11552 goto done;
11553 base_commit_id = got_worktree_get_base_commit_id(worktree);
11554 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11555 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11556 goto done;
11559 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11560 base_commit_id, branch_head_commit_id, 1, 0,
11561 repo, check_cancelled, NULL);
11562 if (error) {
11563 if (error->code == GOT_ERR_ANCESTRY) {
11564 error = got_error_msg(GOT_ERR_ANCESTRY,
11565 "specified branch shares no common "
11566 "ancestry with work tree's branch");
11568 goto done;
11572 * If a merge commit appears between the new base branch tip
11573 * and a YCA found via first-parent traversal then we might
11574 * find a better YCA using topologically sorted commits.
11576 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11577 struct got_object_id *better_yca_id;
11578 error = find_merge_commit_yca(&better_yca_id,
11579 branch_head_commit_id, yca_id,
11580 base_commit_id, repo);
11581 if (error)
11582 goto done;
11583 if (better_yca_id) {
11584 free(yca_id);
11585 yca_id = better_yca_id;
11589 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11590 struct got_pathlist_head paths;
11591 printf("%s is already based on %s\n",
11592 got_ref_get_name(branch),
11593 got_worktree_get_head_ref_name(worktree));
11594 error = switch_head_ref(branch, branch_head_commit_id,
11595 worktree, repo);
11596 if (error)
11597 goto done;
11598 error = got_worktree_set_base_commit_id(worktree, repo,
11599 branch_head_commit_id);
11600 if (error)
11601 goto done;
11602 TAILQ_INIT(&paths);
11603 error = got_pathlist_append(&paths, "", NULL);
11604 if (error)
11605 goto done;
11606 error = got_worktree_checkout_files(worktree,
11607 &paths, repo, update_progress, &upa,
11608 check_cancelled, NULL);
11609 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11610 if (error)
11611 goto done;
11612 if (upa.did_something) {
11613 char *id_str;
11614 error = got_object_id_str(&id_str,
11615 branch_head_commit_id);
11616 if (error)
11617 goto done;
11618 printf("Updated to %s: %s\n",
11619 got_worktree_get_head_ref_name(worktree),
11620 id_str);
11621 free(id_str);
11622 } else
11623 printf("Already up-to-date\n");
11624 print_update_progress_stats(&upa);
11625 goto done;
11629 commit_id = branch_head_commit_id;
11630 error = got_object_open_as_commit(&commit, repo, commit_id);
11631 if (error)
11632 goto done;
11634 parent_ids = got_object_commit_get_parent_ids(commit);
11635 pid = STAILQ_FIRST(parent_ids);
11636 if (pid) {
11637 error = collect_commits(&commits, commit_id, &pid->id,
11638 yca_id, got_worktree_get_path_prefix(worktree),
11639 GOT_ERR_REBASE_PATH, repo);
11640 if (error)
11641 goto done;
11644 got_object_commit_close(commit);
11645 commit = NULL;
11647 if (!continue_rebase) {
11648 error = got_worktree_rebase_prepare(&new_base_branch,
11649 &tmp_branch, &fileindex, worktree, branch, repo);
11650 if (error)
11651 goto done;
11654 if (STAILQ_EMPTY(&commits)) {
11655 if (continue_rebase) {
11656 error = rebase_complete(worktree, fileindex,
11657 branch, tmp_branch, repo, create_backup);
11658 goto done;
11659 } else {
11660 /* Fast-forward the reference of the branch. */
11661 struct got_object_id *new_head_commit_id;
11662 char *id_str;
11663 error = got_ref_resolve(&new_head_commit_id, repo,
11664 new_base_branch);
11665 if (error)
11666 goto done;
11667 error = got_object_id_str(&id_str, new_head_commit_id);
11668 if (error)
11669 goto done;
11670 printf("Forwarding %s to commit %s\n",
11671 got_ref_get_name(branch), id_str);
11672 free(id_str);
11673 error = got_ref_change_ref(branch,
11674 new_head_commit_id);
11675 if (error)
11676 goto done;
11677 /* No backup needed since objects did not change. */
11678 create_backup = 0;
11682 pid = NULL;
11683 STAILQ_FOREACH(qid, &commits, entry) {
11685 commit_id = &qid->id;
11686 parent_id = pid ? &pid->id : yca_id;
11687 pid = qid;
11689 memset(&upa, 0, sizeof(upa));
11690 error = got_worktree_rebase_merge_files(&merged_paths,
11691 worktree, fileindex, parent_id, commit_id, repo,
11692 update_progress, &upa, check_cancelled, NULL);
11693 if (error)
11694 goto done;
11696 print_merge_progress_stats(&upa);
11697 if (upa.conflicts > 0 || upa.missing > 0 ||
11698 upa.not_deleted > 0 || upa.unversioned > 0) {
11699 if (upa.conflicts > 0) {
11700 error = show_rebase_merge_conflict(&qid->id,
11701 repo);
11702 if (error)
11703 goto done;
11705 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11706 break;
11709 error = rebase_commit(&merged_paths, worktree, fileindex,
11710 tmp_branch, committer, commit_id, 0, repo);
11711 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11712 if (error)
11713 goto done;
11716 if (upa.conflicts > 0 || upa.missing > 0 ||
11717 upa.not_deleted > 0 || upa.unversioned > 0) {
11718 error = got_worktree_rebase_postpone(worktree, fileindex);
11719 if (error)
11720 goto done;
11721 if (upa.conflicts > 0 && upa.missing == 0 &&
11722 upa.not_deleted == 0 && upa.unversioned == 0) {
11723 error = got_error_msg(GOT_ERR_CONFLICTS,
11724 "conflicts must be resolved before rebasing "
11725 "can continue");
11726 } else if (upa.conflicts > 0) {
11727 error = got_error_msg(GOT_ERR_CONFLICTS,
11728 "conflicts must be resolved before rebasing "
11729 "can continue; changes destined for some "
11730 "files were not yet merged and should be "
11731 "merged manually if required before the "
11732 "rebase operation is continued");
11733 } else {
11734 error = got_error_msg(GOT_ERR_CONFLICTS,
11735 "changes destined for some files were not "
11736 "yet merged and should be merged manually "
11737 "if required before the rebase operation "
11738 "is continued");
11740 } else
11741 error = rebase_complete(worktree, fileindex, branch,
11742 tmp_branch, repo, create_backup);
11743 done:
11744 free(cwd);
11745 free(committer);
11746 free(gitconfig_path);
11747 got_object_id_queue_free(&commits);
11748 free(branch_head_commit_id);
11749 free(resume_commit_id);
11750 free(head_commit_id);
11751 free(yca_id);
11752 if (commit)
11753 got_object_commit_close(commit);
11754 if (branch)
11755 got_ref_close(branch);
11756 if (new_base_branch)
11757 got_ref_close(new_base_branch);
11758 if (tmp_branch)
11759 got_ref_close(tmp_branch);
11760 if (head_ref)
11761 got_ref_close(head_ref);
11762 if (worktree)
11763 got_worktree_close(worktree);
11764 if (repo) {
11765 const struct got_error *close_err = got_repo_close(repo);
11766 if (error == NULL)
11767 error = close_err;
11769 if (pack_fds) {
11770 const struct got_error *pack_err =
11771 got_repo_pack_fds_close(pack_fds);
11772 if (error == NULL)
11773 error = pack_err;
11775 return error;
11778 __dead static void
11779 usage_histedit(void)
11781 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11782 "[branch]\n", getprogname());
11783 exit(1);
11786 #define GOT_HISTEDIT_PICK 'p'
11787 #define GOT_HISTEDIT_EDIT 'e'
11788 #define GOT_HISTEDIT_FOLD 'f'
11789 #define GOT_HISTEDIT_DROP 'd'
11790 #define GOT_HISTEDIT_MESG 'm'
11792 static const struct got_histedit_cmd {
11793 unsigned char code;
11794 const char *name;
11795 const char *desc;
11796 } got_histedit_cmds[] = {
11797 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11798 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11799 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11800 "be used" },
11801 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11802 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11805 struct got_histedit_list_entry {
11806 TAILQ_ENTRY(got_histedit_list_entry) entry;
11807 struct got_object_id *commit_id;
11808 const struct got_histedit_cmd *cmd;
11809 char *logmsg;
11811 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11813 static const struct got_error *
11814 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11815 FILE *f, struct got_repository *repo)
11817 const struct got_error *err = NULL;
11818 char *logmsg = NULL, *id_str = NULL;
11819 struct got_commit_object *commit = NULL;
11820 int n;
11822 err = got_object_open_as_commit(&commit, repo, commit_id);
11823 if (err)
11824 goto done;
11826 err = get_short_logmsg(&logmsg, 34, commit);
11827 if (err)
11828 goto done;
11830 err = got_object_id_str(&id_str, commit_id);
11831 if (err)
11832 goto done;
11834 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11835 if (n < 0)
11836 err = got_ferror(f, GOT_ERR_IO);
11837 done:
11838 if (commit)
11839 got_object_commit_close(commit);
11840 free(id_str);
11841 free(logmsg);
11842 return err;
11845 static const struct got_error *
11846 histedit_write_commit_list(struct got_object_id_queue *commits,
11847 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11848 int edit_only, struct got_repository *repo)
11850 const struct got_error *err = NULL;
11851 struct got_object_qid *qid;
11852 const char *histedit_cmd = NULL;
11854 if (STAILQ_EMPTY(commits))
11855 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11857 STAILQ_FOREACH(qid, commits, entry) {
11858 histedit_cmd = got_histedit_cmds[0].name;
11859 if (drop_only)
11860 histedit_cmd = "drop";
11861 else if (edit_only)
11862 histedit_cmd = "edit";
11863 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11864 histedit_cmd = "fold";
11865 else if (edit_logmsg_only)
11866 histedit_cmd = "mesg";
11867 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11868 if (err)
11869 break;
11872 return err;
11875 static const struct got_error *
11876 write_cmd_list(FILE *f, const char *branch_name,
11877 struct got_object_id_queue *commits)
11879 const struct got_error *err = NULL;
11880 size_t i;
11881 int n;
11882 char *id_str;
11883 struct got_object_qid *qid;
11885 qid = STAILQ_FIRST(commits);
11886 err = got_object_id_str(&id_str, &qid->id);
11887 if (err)
11888 return err;
11890 n = fprintf(f,
11891 "# Editing the history of branch '%s' starting at\n"
11892 "# commit %s\n"
11893 "# Commits will be processed in order from top to "
11894 "bottom of this file.\n", branch_name, id_str);
11895 if (n < 0) {
11896 err = got_ferror(f, GOT_ERR_IO);
11897 goto done;
11900 n = fprintf(f, "# Available histedit commands:\n");
11901 if (n < 0) {
11902 err = got_ferror(f, GOT_ERR_IO);
11903 goto done;
11906 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11907 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11908 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11909 cmd->desc);
11910 if (n < 0) {
11911 err = got_ferror(f, GOT_ERR_IO);
11912 break;
11915 done:
11916 free(id_str);
11917 return err;
11920 static const struct got_error *
11921 histedit_syntax_error(int lineno)
11923 static char msg[42];
11924 int ret;
11926 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11927 lineno);
11928 if (ret < 0 || (size_t)ret >= sizeof(msg))
11929 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11931 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11934 static const struct got_error *
11935 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11936 char *logmsg, struct got_repository *repo)
11938 const struct got_error *err;
11939 struct got_commit_object *folded_commit = NULL;
11940 char *id_str, *folded_logmsg = NULL;
11942 err = got_object_id_str(&id_str, hle->commit_id);
11943 if (err)
11944 return err;
11946 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11947 if (err)
11948 goto done;
11950 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11951 if (err)
11952 goto done;
11953 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11954 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11955 folded_logmsg) == -1) {
11956 err = got_error_from_errno("asprintf");
11958 done:
11959 if (folded_commit)
11960 got_object_commit_close(folded_commit);
11961 free(id_str);
11962 free(folded_logmsg);
11963 return err;
11966 static struct got_histedit_list_entry *
11967 get_folded_commits(struct got_histedit_list_entry *hle)
11969 struct got_histedit_list_entry *prev, *folded = NULL;
11971 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11972 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11973 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11974 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11975 folded = prev;
11976 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11979 return folded;
11982 static const struct got_error *
11983 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11984 struct got_repository *repo)
11986 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11987 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11988 const struct got_error *err = NULL;
11989 struct got_commit_object *commit = NULL;
11990 int logmsg_len;
11991 int fd = -1;
11992 struct got_histedit_list_entry *folded = NULL;
11994 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11995 if (err)
11996 return err;
11998 folded = get_folded_commits(hle);
11999 if (folded) {
12000 while (folded != hle) {
12001 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12002 folded = TAILQ_NEXT(folded, entry);
12003 continue;
12005 err = append_folded_commit_msg(&new_msg, folded,
12006 logmsg, repo);
12007 if (err)
12008 goto done;
12009 free(logmsg);
12010 logmsg = new_msg;
12011 folded = TAILQ_NEXT(folded, entry);
12015 err = got_object_id_str(&id_str, hle->commit_id);
12016 if (err)
12017 goto done;
12018 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12019 if (err)
12020 goto done;
12021 logmsg_len = asprintf(&new_msg,
12022 "%s\n# original log message of commit %s: %s",
12023 logmsg ? logmsg : "", id_str, orig_logmsg);
12024 if (logmsg_len == -1) {
12025 err = got_error_from_errno("asprintf");
12026 goto done;
12028 free(logmsg);
12029 logmsg = new_msg;
12031 err = got_object_id_str(&id_str, hle->commit_id);
12032 if (err)
12033 goto done;
12035 err = got_opentemp_named_fd(&logmsg_path, &fd,
12036 GOT_TMPDIR_STR "/got-logmsg", "");
12037 if (err)
12038 goto done;
12040 if (write(fd, logmsg, logmsg_len) == -1) {
12041 err = got_error_from_errno2("write", logmsg_path);
12042 goto done;
12044 if (close(fd) == -1) {
12045 err = got_error_from_errno2("close", logmsg_path);
12046 goto done;
12048 fd = -1;
12050 err = get_editor(&editor);
12051 if (err)
12052 goto done;
12054 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12055 logmsg_len, 0);
12056 if (err) {
12057 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12058 goto done;
12059 err = NULL;
12060 hle->logmsg = strdup(new_msg);
12061 if (hle->logmsg == NULL)
12062 err = got_error_from_errno("strdup");
12064 done:
12065 if (fd != -1 && close(fd) == -1 && err == NULL)
12066 err = got_error_from_errno2("close", logmsg_path);
12067 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12068 err = got_error_from_errno2("unlink", logmsg_path);
12069 free(logmsg_path);
12070 free(logmsg);
12071 free(orig_logmsg);
12072 free(editor);
12073 if (commit)
12074 got_object_commit_close(commit);
12075 return err;
12078 static const struct got_error *
12079 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12080 FILE *f, struct got_repository *repo)
12082 const struct got_error *err = NULL;
12083 char *line = NULL, *p, *end;
12084 size_t i, linesize = 0;
12085 ssize_t linelen;
12086 int lineno = 0;
12087 const struct got_histedit_cmd *cmd;
12088 struct got_object_id *commit_id = NULL;
12089 struct got_histedit_list_entry *hle = NULL;
12091 for (;;) {
12092 linelen = getline(&line, &linesize, f);
12093 if (linelen == -1) {
12094 const struct got_error *getline_err;
12095 if (feof(f))
12096 break;
12097 getline_err = got_error_from_errno("getline");
12098 err = got_ferror(f, getline_err->code);
12099 break;
12101 lineno++;
12102 p = line;
12103 while (isspace((unsigned char)p[0]))
12104 p++;
12105 if (p[0] == '#' || p[0] == '\0')
12106 continue;
12107 cmd = NULL;
12108 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12109 cmd = &got_histedit_cmds[i];
12110 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12111 isspace((unsigned char)p[strlen(cmd->name)])) {
12112 p += strlen(cmd->name);
12113 break;
12115 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12116 p++;
12117 break;
12120 if (i == nitems(got_histedit_cmds)) {
12121 err = histedit_syntax_error(lineno);
12122 break;
12124 while (isspace((unsigned char)p[0]))
12125 p++;
12126 end = p;
12127 while (end[0] && !isspace((unsigned char)end[0]))
12128 end++;
12129 *end = '\0';
12130 err = got_object_resolve_id_str(&commit_id, repo, p);
12131 if (err) {
12132 /* override error code */
12133 err = histedit_syntax_error(lineno);
12134 break;
12136 hle = malloc(sizeof(*hle));
12137 if (hle == NULL) {
12138 err = got_error_from_errno("malloc");
12139 break;
12141 hle->cmd = cmd;
12142 hle->commit_id = commit_id;
12143 hle->logmsg = NULL;
12144 commit_id = NULL;
12145 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12148 free(line);
12149 free(commit_id);
12150 return err;
12153 static const struct got_error *
12154 histedit_check_script(struct got_histedit_list *histedit_cmds,
12155 struct got_object_id_queue *commits, struct got_repository *repo)
12157 const struct got_error *err = NULL;
12158 struct got_object_qid *qid;
12159 struct got_histedit_list_entry *hle;
12160 static char msg[92];
12161 char *id_str;
12163 if (TAILQ_EMPTY(histedit_cmds))
12164 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12165 "histedit script contains no commands");
12166 if (STAILQ_EMPTY(commits))
12167 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12169 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12170 struct got_histedit_list_entry *hle2;
12171 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12172 if (hle == hle2)
12173 continue;
12174 if (got_object_id_cmp(hle->commit_id,
12175 hle2->commit_id) != 0)
12176 continue;
12177 err = got_object_id_str(&id_str, hle->commit_id);
12178 if (err)
12179 return err;
12180 snprintf(msg, sizeof(msg), "commit %s is listed "
12181 "more than once in histedit script", id_str);
12182 free(id_str);
12183 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12187 STAILQ_FOREACH(qid, commits, entry) {
12188 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12189 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12190 break;
12192 if (hle == NULL) {
12193 err = got_object_id_str(&id_str, &qid->id);
12194 if (err)
12195 return err;
12196 snprintf(msg, sizeof(msg),
12197 "commit %s missing from histedit script", id_str);
12198 free(id_str);
12199 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12203 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12204 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12205 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12206 "last commit in histedit script cannot be folded");
12208 return NULL;
12211 static const struct got_error *
12212 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12213 const char *path, struct got_object_id_queue *commits,
12214 struct got_repository *repo)
12216 const struct got_error *err = NULL;
12217 struct stat st, st2;
12218 struct timespec timeout;
12219 char *editor;
12220 FILE *f = NULL;
12222 err = get_editor(&editor);
12223 if (err)
12224 return err;
12226 if (stat(path, &st) == -1) {
12227 err = got_error_from_errno2("stat", path);
12228 goto done;
12231 if (spawn_editor(editor, path) == -1) {
12232 err = got_error_from_errno("failed spawning editor");
12233 goto done;
12236 timeout.tv_sec = 0;
12237 timeout.tv_nsec = 1;
12238 nanosleep(&timeout, NULL);
12240 if (stat(path, &st2) == -1) {
12241 err = got_error_from_errno2("stat", path);
12242 goto done;
12245 if (st.st_size == st2.st_size &&
12246 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12247 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12248 "no changes made to histedit script, aborting");
12249 goto done;
12252 f = fopen(path, "re");
12253 if (f == NULL) {
12254 err = got_error_from_errno("fopen");
12255 goto done;
12257 err = histedit_parse_list(histedit_cmds, f, repo);
12258 if (err)
12259 goto done;
12261 err = histedit_check_script(histedit_cmds, commits, repo);
12262 done:
12263 if (f && fclose(f) == EOF && err == NULL)
12264 err = got_error_from_errno("fclose");
12265 free(editor);
12266 return err;
12269 static const struct got_error *
12270 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12271 struct got_object_id_queue *, const char *, const char *,
12272 struct got_repository *);
12274 static const struct got_error *
12275 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12276 struct got_object_id_queue *commits, const char *branch_name,
12277 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12278 struct got_repository *repo)
12280 const struct got_error *err;
12281 FILE *f = NULL;
12282 char *path = NULL;
12284 err = got_opentemp_named(&path, &f, "got-histedit", "");
12285 if (err)
12286 return err;
12288 err = write_cmd_list(f, branch_name, commits);
12289 if (err)
12290 goto done;
12292 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12293 fold_only, drop_only, edit_only, repo);
12294 if (err)
12295 goto done;
12297 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12298 rewind(f);
12299 err = histedit_parse_list(histedit_cmds, f, repo);
12300 } else {
12301 if (fclose(f) == EOF) {
12302 err = got_error_from_errno("fclose");
12303 goto done;
12305 f = NULL;
12306 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12307 if (err) {
12308 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12309 err->code != GOT_ERR_HISTEDIT_CMD)
12310 goto done;
12311 err = histedit_edit_list_retry(histedit_cmds, err,
12312 commits, path, branch_name, repo);
12315 done:
12316 if (f && fclose(f) == EOF && err == NULL)
12317 err = got_error_from_errno("fclose");
12318 if (path && unlink(path) != 0 && err == NULL)
12319 err = got_error_from_errno2("unlink", path);
12320 free(path);
12321 return err;
12324 static const struct got_error *
12325 histedit_save_list(struct got_histedit_list *histedit_cmds,
12326 struct got_worktree *worktree, struct got_repository *repo)
12328 const struct got_error *err = NULL;
12329 char *path = NULL;
12330 FILE *f = NULL;
12331 struct got_histedit_list_entry *hle;
12333 err = got_worktree_get_histedit_script_path(&path, worktree);
12334 if (err)
12335 return err;
12337 f = fopen(path, "we");
12338 if (f == NULL) {
12339 err = got_error_from_errno2("fopen", path);
12340 goto done;
12342 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12343 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12344 repo);
12345 if (err)
12346 break;
12348 done:
12349 if (f && fclose(f) == EOF && err == NULL)
12350 err = got_error_from_errno("fclose");
12351 free(path);
12352 return err;
12355 static void
12356 histedit_free_list(struct got_histedit_list *histedit_cmds)
12358 struct got_histedit_list_entry *hle;
12360 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12361 TAILQ_REMOVE(histedit_cmds, hle, entry);
12362 free(hle);
12366 static const struct got_error *
12367 histedit_load_list(struct got_histedit_list *histedit_cmds,
12368 const char *path, struct got_repository *repo)
12370 const struct got_error *err = NULL;
12371 FILE *f = NULL;
12373 f = fopen(path, "re");
12374 if (f == NULL) {
12375 err = got_error_from_errno2("fopen", path);
12376 goto done;
12379 err = histedit_parse_list(histedit_cmds, f, repo);
12380 done:
12381 if (f && fclose(f) == EOF && err == NULL)
12382 err = got_error_from_errno("fclose");
12383 return err;
12386 static const struct got_error *
12387 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12388 const struct got_error *edit_err, struct got_object_id_queue *commits,
12389 const char *path, const char *branch_name, struct got_repository *repo)
12391 const struct got_error *err = NULL, *prev_err = edit_err;
12392 int resp = ' ';
12394 while (resp != 'c' && resp != 'r' && resp != 'a') {
12395 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12396 "or (a)bort: ", getprogname(), prev_err->msg);
12397 resp = getchar();
12398 if (resp == '\n')
12399 resp = getchar();
12400 if (resp == 'c') {
12401 histedit_free_list(histedit_cmds);
12402 err = histedit_run_editor(histedit_cmds, path, commits,
12403 repo);
12404 if (err) {
12405 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12406 err->code != GOT_ERR_HISTEDIT_CMD)
12407 break;
12408 prev_err = err;
12409 resp = ' ';
12410 continue;
12412 break;
12413 } else if (resp == 'r') {
12414 histedit_free_list(histedit_cmds);
12415 err = histedit_edit_script(histedit_cmds,
12416 commits, branch_name, 0, 0, 0, 0, repo);
12417 if (err) {
12418 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12419 err->code != GOT_ERR_HISTEDIT_CMD)
12420 break;
12421 prev_err = err;
12422 resp = ' ';
12423 continue;
12425 break;
12426 } else if (resp == 'a') {
12427 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12428 break;
12429 } else
12430 printf("invalid response '%c'\n", resp);
12433 return err;
12436 static const struct got_error *
12437 histedit_complete(struct got_worktree *worktree,
12438 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12439 struct got_reference *branch, struct got_repository *repo)
12441 printf("Switching work tree to %s\n",
12442 got_ref_get_symref_target(branch));
12443 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12444 branch, repo);
12447 static const struct got_error *
12448 show_histedit_progress(struct got_commit_object *commit,
12449 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12451 const struct got_error *err;
12452 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12454 err = got_object_id_str(&old_id_str, hle->commit_id);
12455 if (err)
12456 goto done;
12458 if (new_id) {
12459 err = got_object_id_str(&new_id_str, new_id);
12460 if (err)
12461 goto done;
12464 old_id_str[12] = '\0';
12465 if (new_id_str)
12466 new_id_str[12] = '\0';
12468 if (hle->logmsg) {
12469 logmsg = strdup(hle->logmsg);
12470 if (logmsg == NULL) {
12471 err = got_error_from_errno("strdup");
12472 goto done;
12474 trim_logmsg(logmsg, 42);
12475 } else {
12476 err = get_short_logmsg(&logmsg, 42, commit);
12477 if (err)
12478 goto done;
12481 switch (hle->cmd->code) {
12482 case GOT_HISTEDIT_PICK:
12483 case GOT_HISTEDIT_EDIT:
12484 case GOT_HISTEDIT_MESG:
12485 printf("%s -> %s: %s\n", old_id_str,
12486 new_id_str ? new_id_str : "no-op change", logmsg);
12487 break;
12488 case GOT_HISTEDIT_DROP:
12489 case GOT_HISTEDIT_FOLD:
12490 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12491 logmsg);
12492 break;
12493 default:
12494 break;
12496 done:
12497 free(old_id_str);
12498 free(new_id_str);
12499 return err;
12502 static const struct got_error *
12503 histedit_commit(struct got_pathlist_head *merged_paths,
12504 struct got_worktree *worktree, struct got_fileindex *fileindex,
12505 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12506 const char *committer, int allow_conflict, struct got_repository *repo)
12508 const struct got_error *err;
12509 struct got_commit_object *commit;
12510 struct got_object_id *new_commit_id;
12512 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12513 && hle->logmsg == NULL) {
12514 err = histedit_edit_logmsg(hle, repo);
12515 if (err)
12516 return err;
12519 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12520 if (err)
12521 return err;
12523 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12524 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12525 hle->logmsg, allow_conflict, repo);
12526 if (err) {
12527 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12528 goto done;
12529 err = show_histedit_progress(commit, hle, NULL);
12530 } else {
12531 err = show_histedit_progress(commit, hle, new_commit_id);
12532 free(new_commit_id);
12534 done:
12535 got_object_commit_close(commit);
12536 return err;
12539 static const struct got_error *
12540 histedit_skip_commit(struct got_histedit_list_entry *hle,
12541 struct got_worktree *worktree, struct got_repository *repo)
12543 const struct got_error *error;
12544 struct got_commit_object *commit;
12546 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12547 repo);
12548 if (error)
12549 return error;
12551 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12552 if (error)
12553 return error;
12555 error = show_histedit_progress(commit, hle, NULL);
12556 got_object_commit_close(commit);
12557 return error;
12560 static const struct got_error *
12561 check_local_changes(void *arg, unsigned char status,
12562 unsigned char staged_status, const char *path,
12563 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12564 struct got_object_id *commit_id, int dirfd, const char *de_name)
12566 int *have_local_changes = arg;
12568 switch (status) {
12569 case GOT_STATUS_ADD:
12570 case GOT_STATUS_DELETE:
12571 case GOT_STATUS_MODIFY:
12572 case GOT_STATUS_CONFLICT:
12573 *have_local_changes = 1;
12574 return got_error(GOT_ERR_CANCELLED);
12575 default:
12576 break;
12579 switch (staged_status) {
12580 case GOT_STATUS_ADD:
12581 case GOT_STATUS_DELETE:
12582 case GOT_STATUS_MODIFY:
12583 *have_local_changes = 1;
12584 return got_error(GOT_ERR_CANCELLED);
12585 default:
12586 break;
12589 return NULL;
12592 static const struct got_error *
12593 cmd_histedit(int argc, char *argv[])
12595 const struct got_error *error = NULL;
12596 struct got_worktree *worktree = NULL;
12597 struct got_fileindex *fileindex = NULL;
12598 struct got_repository *repo = NULL;
12599 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12600 struct got_reference *branch = NULL;
12601 struct got_reference *tmp_branch = NULL;
12602 struct got_object_id *resume_commit_id = NULL;
12603 struct got_object_id *base_commit_id = NULL;
12604 struct got_object_id *head_commit_id = NULL;
12605 struct got_commit_object *commit = NULL;
12606 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12607 struct got_update_progress_arg upa;
12608 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12609 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12610 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12611 const char *edit_script_path = NULL;
12612 struct got_object_id_queue commits;
12613 struct got_pathlist_head merged_paths;
12614 const struct got_object_id_queue *parent_ids;
12615 struct got_object_qid *pid;
12616 struct got_histedit_list histedit_cmds;
12617 struct got_histedit_list_entry *hle;
12618 int *pack_fds = NULL;
12620 STAILQ_INIT(&commits);
12621 TAILQ_INIT(&histedit_cmds);
12622 TAILQ_INIT(&merged_paths);
12623 memset(&upa, 0, sizeof(upa));
12625 #ifndef PROFILE
12626 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12627 "unveil", NULL) == -1)
12628 err(1, "pledge");
12629 #endif
12631 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12632 switch (ch) {
12633 case 'a':
12634 abort_edit = 1;
12635 break;
12636 case 'C':
12637 allow_conflict = 1;
12638 break;
12639 case 'c':
12640 continue_edit = 1;
12641 break;
12642 case 'd':
12643 drop_only = 1;
12644 break;
12645 case 'e':
12646 edit_only = 1;
12647 break;
12648 case 'F':
12649 edit_script_path = optarg;
12650 break;
12651 case 'f':
12652 fold_only = 1;
12653 break;
12654 case 'l':
12655 list_backups = 1;
12656 break;
12657 case 'm':
12658 edit_logmsg_only = 1;
12659 break;
12660 case 'X':
12661 delete_backups = 1;
12662 break;
12663 default:
12664 usage_histedit();
12665 /* NOTREACHED */
12669 argc -= optind;
12670 argv += optind;
12672 if (abort_edit && allow_conflict)
12673 option_conflict('a', 'C');
12674 if (abort_edit && continue_edit)
12675 option_conflict('a', 'c');
12676 if (edit_script_path && allow_conflict)
12677 option_conflict('F', 'C');
12678 if (edit_script_path && edit_logmsg_only)
12679 option_conflict('F', 'm');
12680 if (abort_edit && edit_logmsg_only)
12681 option_conflict('a', 'm');
12682 if (edit_logmsg_only && allow_conflict)
12683 option_conflict('m', 'C');
12684 if (continue_edit && edit_logmsg_only)
12685 option_conflict('c', 'm');
12686 if (abort_edit && fold_only)
12687 option_conflict('a', 'f');
12688 if (fold_only && allow_conflict)
12689 option_conflict('f', 'C');
12690 if (continue_edit && fold_only)
12691 option_conflict('c', 'f');
12692 if (fold_only && edit_logmsg_only)
12693 option_conflict('f', 'm');
12694 if (edit_script_path && fold_only)
12695 option_conflict('F', 'f');
12696 if (abort_edit && edit_only)
12697 option_conflict('a', 'e');
12698 if (continue_edit && edit_only)
12699 option_conflict('c', 'e');
12700 if (edit_only && edit_logmsg_only)
12701 option_conflict('e', 'm');
12702 if (edit_script_path && edit_only)
12703 option_conflict('F', 'e');
12704 if (fold_only && edit_only)
12705 option_conflict('f', 'e');
12706 if (drop_only && abort_edit)
12707 option_conflict('d', 'a');
12708 if (drop_only && allow_conflict)
12709 option_conflict('d', 'C');
12710 if (drop_only && continue_edit)
12711 option_conflict('d', 'c');
12712 if (drop_only && edit_logmsg_only)
12713 option_conflict('d', 'm');
12714 if (drop_only && edit_only)
12715 option_conflict('d', 'e');
12716 if (drop_only && edit_script_path)
12717 option_conflict('d', 'F');
12718 if (drop_only && fold_only)
12719 option_conflict('d', 'f');
12720 if (list_backups) {
12721 if (abort_edit)
12722 option_conflict('l', 'a');
12723 if (allow_conflict)
12724 option_conflict('l', 'C');
12725 if (continue_edit)
12726 option_conflict('l', 'c');
12727 if (edit_script_path)
12728 option_conflict('l', 'F');
12729 if (edit_logmsg_only)
12730 option_conflict('l', 'm');
12731 if (drop_only)
12732 option_conflict('l', 'd');
12733 if (fold_only)
12734 option_conflict('l', 'f');
12735 if (edit_only)
12736 option_conflict('l', 'e');
12737 if (delete_backups)
12738 option_conflict('l', 'X');
12739 if (argc != 0 && argc != 1)
12740 usage_histedit();
12741 } else if (delete_backups) {
12742 if (abort_edit)
12743 option_conflict('X', 'a');
12744 if (allow_conflict)
12745 option_conflict('X', 'C');
12746 if (continue_edit)
12747 option_conflict('X', 'c');
12748 if (drop_only)
12749 option_conflict('X', 'd');
12750 if (edit_script_path)
12751 option_conflict('X', 'F');
12752 if (edit_logmsg_only)
12753 option_conflict('X', 'm');
12754 if (fold_only)
12755 option_conflict('X', 'f');
12756 if (edit_only)
12757 option_conflict('X', 'e');
12758 if (list_backups)
12759 option_conflict('X', 'l');
12760 if (argc != 0 && argc != 1)
12761 usage_histedit();
12762 } else if (allow_conflict && !continue_edit)
12763 errx(1, "-C option requires -c");
12764 else if (argc != 0)
12765 usage_histedit();
12768 * This command cannot apply unveil(2) in all cases because the
12769 * user may choose to run an editor to edit the histedit script
12770 * and to edit individual commit log messages.
12771 * unveil(2) traverses exec(2); if an editor is used we have to
12772 * apply unveil after edit script and log messages have been written.
12773 * XXX TODO: Make use of unveil(2) where possible.
12776 cwd = getcwd(NULL, 0);
12777 if (cwd == NULL) {
12778 error = got_error_from_errno("getcwd");
12779 goto done;
12782 error = got_repo_pack_fds_open(&pack_fds);
12783 if (error != NULL)
12784 goto done;
12786 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12787 if (error) {
12788 if (list_backups || delete_backups) {
12789 if (error->code != GOT_ERR_NOT_WORKTREE)
12790 goto done;
12791 } else {
12792 if (error->code == GOT_ERR_NOT_WORKTREE)
12793 error = wrap_not_worktree_error(error,
12794 "histedit", cwd);
12795 goto done;
12799 if (list_backups || delete_backups) {
12800 error = got_repo_open(&repo,
12801 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12802 NULL, pack_fds);
12803 if (error != NULL)
12804 goto done;
12805 error = apply_unveil(got_repo_get_path(repo), 0,
12806 worktree ? got_worktree_get_root_path(worktree) : NULL);
12807 if (error)
12808 goto done;
12809 error = process_backup_refs(
12810 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12811 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12812 goto done; /* nothing else to do */
12815 error = get_gitconfig_path(&gitconfig_path);
12816 if (error)
12817 goto done;
12818 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12819 gitconfig_path, pack_fds);
12820 if (error != NULL)
12821 goto done;
12823 if (worktree != NULL && !list_backups && !delete_backups) {
12824 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12825 if (error)
12826 goto done;
12829 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12830 if (error)
12831 goto done;
12832 if (rebase_in_progress) {
12833 error = got_error(GOT_ERR_REBASING);
12834 goto done;
12837 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12838 repo);
12839 if (error)
12840 goto done;
12841 if (merge_in_progress) {
12842 error = got_error(GOT_ERR_MERGE_BUSY);
12843 goto done;
12846 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12847 if (error)
12848 goto done;
12850 if (edit_in_progress && edit_logmsg_only) {
12851 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12852 "histedit operation is in progress in this "
12853 "work tree and must be continued or aborted "
12854 "before the -m option can be used");
12855 goto done;
12857 if (edit_in_progress && drop_only) {
12858 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12859 "histedit operation is in progress in this "
12860 "work tree and must be continued or aborted "
12861 "before the -d option can be used");
12862 goto done;
12864 if (edit_in_progress && fold_only) {
12865 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12866 "histedit operation is in progress in this "
12867 "work tree and must be continued or aborted "
12868 "before the -f option can be used");
12869 goto done;
12871 if (edit_in_progress && edit_only) {
12872 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12873 "histedit operation is in progress in this "
12874 "work tree and must be continued or aborted "
12875 "before the -e option can be used");
12876 goto done;
12879 if (edit_in_progress && abort_edit) {
12880 error = got_worktree_histedit_continue(&resume_commit_id,
12881 &tmp_branch, &branch, &base_commit_id, &fileindex,
12882 worktree, repo);
12883 if (error)
12884 goto done;
12885 printf("Switching work tree to %s\n",
12886 got_ref_get_symref_target(branch));
12887 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12888 branch, base_commit_id, abort_progress, &upa);
12889 if (error)
12890 goto done;
12891 printf("Histedit of %s aborted\n",
12892 got_ref_get_symref_target(branch));
12893 print_merge_progress_stats(&upa);
12894 goto done; /* nothing else to do */
12895 } else if (abort_edit) {
12896 error = got_error(GOT_ERR_NOT_HISTEDIT);
12897 goto done;
12900 error = get_author(&committer, repo, worktree);
12901 if (error)
12902 goto done;
12904 if (continue_edit) {
12905 char *path;
12907 if (!edit_in_progress) {
12908 error = got_error(GOT_ERR_NOT_HISTEDIT);
12909 goto done;
12912 error = got_worktree_get_histedit_script_path(&path, worktree);
12913 if (error)
12914 goto done;
12916 error = histedit_load_list(&histedit_cmds, path, repo);
12917 free(path);
12918 if (error)
12919 goto done;
12921 error = got_worktree_histedit_continue(&resume_commit_id,
12922 &tmp_branch, &branch, &base_commit_id, &fileindex,
12923 worktree, repo);
12924 if (error)
12925 goto done;
12927 error = got_ref_resolve(&head_commit_id, repo, branch);
12928 if (error)
12929 goto done;
12931 error = got_object_open_as_commit(&commit, repo,
12932 head_commit_id);
12933 if (error)
12934 goto done;
12935 parent_ids = got_object_commit_get_parent_ids(commit);
12936 pid = STAILQ_FIRST(parent_ids);
12937 if (pid == NULL) {
12938 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12939 goto done;
12941 error = collect_commits(&commits, head_commit_id, &pid->id,
12942 base_commit_id, got_worktree_get_path_prefix(worktree),
12943 GOT_ERR_HISTEDIT_PATH, repo);
12944 got_object_commit_close(commit);
12945 commit = NULL;
12946 if (error)
12947 goto done;
12948 } else {
12949 if (edit_in_progress) {
12950 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12951 goto done;
12954 error = got_ref_open(&branch, repo,
12955 got_worktree_get_head_ref_name(worktree), 0);
12956 if (error != NULL)
12957 goto done;
12959 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12960 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12961 "will not edit commit history of a branch outside "
12962 "the \"refs/heads/\" reference namespace");
12963 goto done;
12966 error = got_ref_resolve(&head_commit_id, repo, branch);
12967 got_ref_close(branch);
12968 branch = NULL;
12969 if (error)
12970 goto done;
12972 error = got_object_open_as_commit(&commit, repo,
12973 head_commit_id);
12974 if (error)
12975 goto done;
12976 parent_ids = got_object_commit_get_parent_ids(commit);
12977 pid = STAILQ_FIRST(parent_ids);
12978 if (pid == NULL) {
12979 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12980 goto done;
12982 error = collect_commits(&commits, head_commit_id, &pid->id,
12983 got_worktree_get_base_commit_id(worktree),
12984 got_worktree_get_path_prefix(worktree),
12985 GOT_ERR_HISTEDIT_PATH, repo);
12986 got_object_commit_close(commit);
12987 commit = NULL;
12988 if (error)
12989 goto done;
12991 if (STAILQ_EMPTY(&commits)) {
12992 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12993 goto done;
12996 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12997 &base_commit_id, &fileindex, worktree, repo);
12998 if (error)
12999 goto done;
13001 if (edit_script_path) {
13002 error = histedit_load_list(&histedit_cmds,
13003 edit_script_path, repo);
13004 if (error) {
13005 got_worktree_histedit_abort(worktree, fileindex,
13006 repo, branch, base_commit_id,
13007 abort_progress, &upa);
13008 print_merge_progress_stats(&upa);
13009 goto done;
13011 } else {
13012 const char *branch_name;
13013 branch_name = got_ref_get_symref_target(branch);
13014 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13015 branch_name += 11;
13016 error = histedit_edit_script(&histedit_cmds, &commits,
13017 branch_name, edit_logmsg_only, fold_only,
13018 drop_only, edit_only, repo);
13019 if (error) {
13020 got_worktree_histedit_abort(worktree, fileindex,
13021 repo, branch, base_commit_id,
13022 abort_progress, &upa);
13023 print_merge_progress_stats(&upa);
13024 goto done;
13029 error = histedit_save_list(&histedit_cmds, worktree,
13030 repo);
13031 if (error) {
13032 got_worktree_histedit_abort(worktree, fileindex,
13033 repo, branch, base_commit_id,
13034 abort_progress, &upa);
13035 print_merge_progress_stats(&upa);
13036 goto done;
13041 error = histedit_check_script(&histedit_cmds, &commits, repo);
13042 if (error)
13043 goto done;
13045 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13046 if (resume_commit_id) {
13047 if (got_object_id_cmp(hle->commit_id,
13048 resume_commit_id) != 0)
13049 continue;
13051 resume_commit_id = NULL;
13052 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13053 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13054 error = histedit_skip_commit(hle, worktree,
13055 repo);
13056 if (error)
13057 goto done;
13058 } else {
13059 struct got_pathlist_head paths;
13060 int have_changes = 0;
13062 TAILQ_INIT(&paths);
13063 error = got_pathlist_append(&paths, "", NULL);
13064 if (error)
13065 goto done;
13066 error = got_worktree_status(worktree, &paths,
13067 repo, 0, check_local_changes, &have_changes,
13068 check_cancelled, NULL);
13069 got_pathlist_free(&paths,
13070 GOT_PATHLIST_FREE_NONE);
13071 if (error) {
13072 if (error->code != GOT_ERR_CANCELLED)
13073 goto done;
13074 if (sigint_received || sigpipe_received)
13075 goto done;
13077 if (have_changes) {
13078 error = histedit_commit(NULL, worktree,
13079 fileindex, tmp_branch, hle,
13080 committer, allow_conflict, repo);
13081 if (error)
13082 goto done;
13083 } else {
13084 error = got_object_open_as_commit(
13085 &commit, repo, hle->commit_id);
13086 if (error)
13087 goto done;
13088 error = show_histedit_progress(commit,
13089 hle, NULL);
13090 got_object_commit_close(commit);
13091 commit = NULL;
13092 if (error)
13093 goto done;
13096 continue;
13099 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13100 error = histedit_skip_commit(hle, worktree, repo);
13101 if (error)
13102 goto done;
13103 continue;
13105 error = got_object_open_as_commit(&commit, repo,
13106 hle->commit_id);
13107 if (error)
13108 goto done;
13109 parent_ids = got_object_commit_get_parent_ids(commit);
13110 pid = STAILQ_FIRST(parent_ids);
13112 error = got_worktree_histedit_merge_files(&merged_paths,
13113 worktree, fileindex, &pid->id, hle->commit_id, repo,
13114 update_progress, &upa, check_cancelled, NULL);
13115 if (error)
13116 goto done;
13117 got_object_commit_close(commit);
13118 commit = NULL;
13120 print_merge_progress_stats(&upa);
13121 if (upa.conflicts > 0 || upa.missing > 0 ||
13122 upa.not_deleted > 0 || upa.unversioned > 0) {
13123 if (upa.conflicts > 0) {
13124 error = show_rebase_merge_conflict(
13125 hle->commit_id, repo);
13126 if (error)
13127 goto done;
13129 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13130 break;
13133 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13134 char *id_str;
13135 error = got_object_id_str(&id_str, hle->commit_id);
13136 if (error)
13137 goto done;
13138 printf("Stopping histedit for amending commit %s\n",
13139 id_str);
13140 free(id_str);
13141 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13142 error = got_worktree_histedit_postpone(worktree,
13143 fileindex);
13144 goto done;
13145 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13146 error = histedit_skip_commit(hle, worktree, repo);
13147 if (error)
13148 goto done;
13149 continue;
13150 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13151 error = histedit_edit_logmsg(hle, repo);
13152 if (error)
13153 goto done;
13156 error = histedit_commit(&merged_paths, worktree, fileindex,
13157 tmp_branch, hle, committer, allow_conflict, repo);
13158 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13159 if (error)
13160 goto done;
13163 if (upa.conflicts > 0 || upa.missing > 0 ||
13164 upa.not_deleted > 0 || upa.unversioned > 0) {
13165 error = got_worktree_histedit_postpone(worktree, fileindex);
13166 if (error)
13167 goto done;
13168 if (upa.conflicts > 0 && upa.missing == 0 &&
13169 upa.not_deleted == 0 && upa.unversioned == 0) {
13170 error = got_error_msg(GOT_ERR_CONFLICTS,
13171 "conflicts must be resolved before histedit "
13172 "can continue");
13173 } else if (upa.conflicts > 0) {
13174 error = got_error_msg(GOT_ERR_CONFLICTS,
13175 "conflicts must be resolved before histedit "
13176 "can continue; changes destined for some "
13177 "files were not yet merged and should be "
13178 "merged manually if required before the "
13179 "histedit operation is continued");
13180 } else {
13181 error = got_error_msg(GOT_ERR_CONFLICTS,
13182 "changes destined for some files were not "
13183 "yet merged and should be merged manually "
13184 "if required before the histedit operation "
13185 "is continued");
13187 } else
13188 error = histedit_complete(worktree, fileindex, tmp_branch,
13189 branch, repo);
13190 done:
13191 free(cwd);
13192 free(committer);
13193 free(gitconfig_path);
13194 got_object_id_queue_free(&commits);
13195 histedit_free_list(&histedit_cmds);
13196 free(head_commit_id);
13197 free(base_commit_id);
13198 free(resume_commit_id);
13199 if (commit)
13200 got_object_commit_close(commit);
13201 if (branch)
13202 got_ref_close(branch);
13203 if (tmp_branch)
13204 got_ref_close(tmp_branch);
13205 if (worktree)
13206 got_worktree_close(worktree);
13207 if (repo) {
13208 const struct got_error *close_err = got_repo_close(repo);
13209 if (error == NULL)
13210 error = close_err;
13212 if (pack_fds) {
13213 const struct got_error *pack_err =
13214 got_repo_pack_fds_close(pack_fds);
13215 if (error == NULL)
13216 error = pack_err;
13218 return error;
13221 __dead static void
13222 usage_integrate(void)
13224 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13225 exit(1);
13228 static const struct got_error *
13229 cmd_integrate(int argc, char *argv[])
13231 const struct got_error *error = NULL;
13232 struct got_repository *repo = NULL;
13233 struct got_worktree *worktree = NULL;
13234 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13235 const char *branch_arg = NULL;
13236 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13237 struct got_fileindex *fileindex = NULL;
13238 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13239 int ch;
13240 struct got_update_progress_arg upa;
13241 int *pack_fds = NULL;
13243 #ifndef PROFILE
13244 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13245 "unveil", NULL) == -1)
13246 err(1, "pledge");
13247 #endif
13249 while ((ch = getopt(argc, argv, "")) != -1) {
13250 switch (ch) {
13251 default:
13252 usage_integrate();
13253 /* NOTREACHED */
13257 argc -= optind;
13258 argv += optind;
13260 if (argc != 1)
13261 usage_integrate();
13262 branch_arg = argv[0];
13264 cwd = getcwd(NULL, 0);
13265 if (cwd == NULL) {
13266 error = got_error_from_errno("getcwd");
13267 goto done;
13270 error = got_repo_pack_fds_open(&pack_fds);
13271 if (error != NULL)
13272 goto done;
13274 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13275 if (error) {
13276 if (error->code == GOT_ERR_NOT_WORKTREE)
13277 error = wrap_not_worktree_error(error, "integrate",
13278 cwd);
13279 goto done;
13282 error = check_rebase_or_histedit_in_progress(worktree);
13283 if (error)
13284 goto done;
13286 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13287 NULL, pack_fds);
13288 if (error != NULL)
13289 goto done;
13291 error = apply_unveil(got_repo_get_path(repo), 0,
13292 got_worktree_get_root_path(worktree));
13293 if (error)
13294 goto done;
13296 error = check_merge_in_progress(worktree, repo);
13297 if (error)
13298 goto done;
13300 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13301 error = got_error_from_errno("asprintf");
13302 goto done;
13305 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13306 &base_branch_ref, worktree, refname, repo);
13307 if (error)
13308 goto done;
13310 refname = strdup(got_ref_get_name(branch_ref));
13311 if (refname == NULL) {
13312 error = got_error_from_errno("strdup");
13313 got_worktree_integrate_abort(worktree, fileindex, repo,
13314 branch_ref, base_branch_ref);
13315 goto done;
13317 base_refname = strdup(got_ref_get_name(base_branch_ref));
13318 if (base_refname == NULL) {
13319 error = got_error_from_errno("strdup");
13320 got_worktree_integrate_abort(worktree, fileindex, repo,
13321 branch_ref, base_branch_ref);
13322 goto done;
13324 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13325 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13326 got_worktree_integrate_abort(worktree, fileindex, repo,
13327 branch_ref, base_branch_ref);
13328 goto done;
13331 error = got_ref_resolve(&commit_id, repo, branch_ref);
13332 if (error)
13333 goto done;
13335 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13336 if (error)
13337 goto done;
13339 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13340 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13341 "specified branch has already been integrated");
13342 got_worktree_integrate_abort(worktree, fileindex, repo,
13343 branch_ref, base_branch_ref);
13344 goto done;
13347 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13348 if (error) {
13349 if (error->code == GOT_ERR_ANCESTRY)
13350 error = got_error(GOT_ERR_REBASE_REQUIRED);
13351 got_worktree_integrate_abort(worktree, fileindex, repo,
13352 branch_ref, base_branch_ref);
13353 goto done;
13356 memset(&upa, 0, sizeof(upa));
13357 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13358 branch_ref, base_branch_ref, update_progress, &upa,
13359 check_cancelled, NULL);
13360 if (error)
13361 goto done;
13363 printf("Integrated %s into %s\n", refname, base_refname);
13364 print_update_progress_stats(&upa);
13365 done:
13366 if (repo) {
13367 const struct got_error *close_err = got_repo_close(repo);
13368 if (error == NULL)
13369 error = close_err;
13371 if (worktree)
13372 got_worktree_close(worktree);
13373 if (pack_fds) {
13374 const struct got_error *pack_err =
13375 got_repo_pack_fds_close(pack_fds);
13376 if (error == NULL)
13377 error = pack_err;
13379 free(cwd);
13380 free(base_commit_id);
13381 free(commit_id);
13382 free(refname);
13383 free(base_refname);
13384 return error;
13387 __dead static void
13388 usage_merge(void)
13390 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13391 exit(1);
13394 static const struct got_error *
13395 cmd_merge(int argc, char *argv[])
13397 const struct got_error *error = NULL;
13398 struct got_worktree *worktree = NULL;
13399 struct got_repository *repo = NULL;
13400 struct got_fileindex *fileindex = NULL;
13401 char *cwd = NULL, *id_str = NULL, *author = NULL;
13402 char *gitconfig_path = NULL;
13403 struct got_reference *branch = NULL, *wt_branch = NULL;
13404 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13405 struct got_object_id *wt_branch_tip = NULL;
13406 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13407 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13408 struct got_update_progress_arg upa;
13409 struct got_object_id *merge_commit_id = NULL;
13410 char *branch_name = NULL;
13411 int *pack_fds = NULL;
13413 memset(&upa, 0, sizeof(upa));
13415 #ifndef PROFILE
13416 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13417 "unveil", NULL) == -1)
13418 err(1, "pledge");
13419 #endif
13421 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13422 switch (ch) {
13423 case 'a':
13424 abort_merge = 1;
13425 break;
13426 case 'C':
13427 allow_conflict = 1;
13428 break;
13429 case 'c':
13430 continue_merge = 1;
13431 break;
13432 case 'M':
13433 prefer_fast_forward = 0;
13434 break;
13435 case 'n':
13436 interrupt_merge = 1;
13437 break;
13438 default:
13439 usage_merge();
13440 /* NOTREACHED */
13444 argc -= optind;
13445 argv += optind;
13447 if (abort_merge) {
13448 if (continue_merge)
13449 option_conflict('a', 'c');
13450 if (!prefer_fast_forward)
13451 option_conflict('a', 'M');
13452 if (interrupt_merge)
13453 option_conflict('a', 'n');
13454 } else if (continue_merge) {
13455 if (!prefer_fast_forward)
13456 option_conflict('c', 'M');
13457 if (interrupt_merge)
13458 option_conflict('c', 'n');
13460 if (allow_conflict) {
13461 if (!continue_merge)
13462 errx(1, "-C option requires -c");
13464 if (abort_merge || continue_merge) {
13465 if (argc != 0)
13466 usage_merge();
13467 } else if (argc != 1)
13468 usage_merge();
13470 cwd = getcwd(NULL, 0);
13471 if (cwd == NULL) {
13472 error = got_error_from_errno("getcwd");
13473 goto done;
13476 error = got_repo_pack_fds_open(&pack_fds);
13477 if (error != NULL)
13478 goto done;
13480 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13481 if (error) {
13482 if (error->code == GOT_ERR_NOT_WORKTREE)
13483 error = wrap_not_worktree_error(error,
13484 "merge", cwd);
13485 goto done;
13488 error = get_gitconfig_path(&gitconfig_path);
13489 if (error)
13490 goto done;
13491 error = got_repo_open(&repo,
13492 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13493 gitconfig_path, pack_fds);
13494 if (error != NULL)
13495 goto done;
13497 if (worktree != NULL) {
13498 error = worktree_has_logmsg_ref("merge", worktree, repo);
13499 if (error)
13500 goto done;
13503 error = apply_unveil(got_repo_get_path(repo), 0,
13504 worktree ? got_worktree_get_root_path(worktree) : NULL);
13505 if (error)
13506 goto done;
13508 error = check_rebase_or_histedit_in_progress(worktree);
13509 if (error)
13510 goto done;
13512 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13513 repo);
13514 if (error)
13515 goto done;
13517 if (merge_in_progress && !(abort_merge || continue_merge)) {
13518 error = got_error(GOT_ERR_MERGE_BUSY);
13519 goto done;
13522 if (!merge_in_progress && (abort_merge || continue_merge)) {
13523 error = got_error(GOT_ERR_NOT_MERGING);
13524 goto done;
13527 if (abort_merge) {
13528 error = got_worktree_merge_continue(&branch_name,
13529 &branch_tip, &fileindex, worktree, repo);
13530 if (error)
13531 goto done;
13532 error = got_worktree_merge_abort(worktree, fileindex, repo,
13533 abort_progress, &upa);
13534 if (error)
13535 goto done;
13536 printf("Merge of %s aborted\n", branch_name);
13537 goto done; /* nothing else to do */
13540 if (strncmp(got_worktree_get_head_ref_name(worktree),
13541 "refs/heads/", 11) != 0) {
13542 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13543 "work tree's current branch %s is outside the "
13544 "\"refs/heads/\" reference namespace; "
13545 "update -b required",
13546 got_worktree_get_head_ref_name(worktree));
13547 goto done;
13550 error = get_author(&author, repo, worktree);
13551 if (error)
13552 goto done;
13554 error = got_ref_open(&wt_branch, repo,
13555 got_worktree_get_head_ref_name(worktree), 0);
13556 if (error)
13557 goto done;
13558 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13559 if (error)
13560 goto done;
13562 if (continue_merge) {
13563 struct got_object_id *base_commit_id;
13564 base_commit_id = got_worktree_get_base_commit_id(worktree);
13565 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13566 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13567 goto done;
13569 error = got_worktree_merge_continue(&branch_name,
13570 &branch_tip, &fileindex, worktree, repo);
13571 if (error)
13572 goto done;
13573 } else {
13574 error = got_ref_open(&branch, repo, argv[0], 0);
13575 if (error != NULL)
13576 goto done;
13577 branch_name = strdup(got_ref_get_name(branch));
13578 if (branch_name == NULL) {
13579 error = got_error_from_errno("strdup");
13580 goto done;
13582 error = got_ref_resolve(&branch_tip, repo, branch);
13583 if (error)
13584 goto done;
13587 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13588 wt_branch_tip, branch_tip, 0, 0, repo,
13589 check_cancelled, NULL);
13590 if (error && error->code != GOT_ERR_ANCESTRY)
13591 goto done;
13593 if (!continue_merge) {
13594 error = check_path_prefix(wt_branch_tip, branch_tip,
13595 got_worktree_get_path_prefix(worktree),
13596 GOT_ERR_MERGE_PATH, repo);
13597 if (error)
13598 goto done;
13599 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13600 if (error)
13601 goto done;
13602 if (prefer_fast_forward && yca_id &&
13603 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13604 struct got_pathlist_head paths;
13605 if (interrupt_merge) {
13606 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13607 "there are no changes to merge since %s "
13608 "is already based on %s; merge cannot be "
13609 "interrupted for amending; -n",
13610 branch_name, got_ref_get_name(wt_branch));
13611 goto done;
13613 printf("Forwarding %s to %s\n",
13614 got_ref_get_name(wt_branch), branch_name);
13615 error = got_ref_change_ref(wt_branch, branch_tip);
13616 if (error)
13617 goto done;
13618 error = got_ref_write(wt_branch, repo);
13619 if (error)
13620 goto done;
13621 error = got_worktree_set_base_commit_id(worktree, repo,
13622 branch_tip);
13623 if (error)
13624 goto done;
13625 TAILQ_INIT(&paths);
13626 error = got_pathlist_append(&paths, "", NULL);
13627 if (error)
13628 goto done;
13629 error = got_worktree_checkout_files(worktree,
13630 &paths, repo, update_progress, &upa,
13631 check_cancelled, NULL);
13632 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13633 if (error)
13634 goto done;
13635 if (upa.did_something) {
13636 char *id_str;
13637 error = got_object_id_str(&id_str, branch_tip);
13638 if (error)
13639 goto done;
13640 printf("Updated to commit %s\n", id_str);
13641 free(id_str);
13642 } else
13643 printf("Already up-to-date\n");
13644 print_update_progress_stats(&upa);
13645 goto done;
13647 error = got_worktree_merge_write_refs(worktree, branch, repo);
13648 if (error)
13649 goto done;
13651 error = got_worktree_merge_branch(worktree, fileindex,
13652 yca_id, branch_tip, repo, update_progress, &upa,
13653 check_cancelled, NULL);
13654 if (error)
13655 goto done;
13656 print_merge_progress_stats(&upa);
13657 if (!upa.did_something) {
13658 error = got_worktree_merge_abort(worktree, fileindex,
13659 repo, abort_progress, &upa);
13660 if (error)
13661 goto done;
13662 printf("Already up-to-date\n");
13663 goto done;
13667 if (interrupt_merge) {
13668 error = got_worktree_merge_postpone(worktree, fileindex);
13669 if (error)
13670 goto done;
13671 printf("Merge of %s interrupted on request\n", branch_name);
13672 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13673 upa.not_deleted > 0 || upa.unversioned > 0) {
13674 error = got_worktree_merge_postpone(worktree, fileindex);
13675 if (error)
13676 goto done;
13677 if (upa.conflicts > 0 && upa.missing == 0 &&
13678 upa.not_deleted == 0 && upa.unversioned == 0) {
13679 error = got_error_msg(GOT_ERR_CONFLICTS,
13680 "conflicts must be resolved before merging "
13681 "can continue");
13682 } else if (upa.conflicts > 0) {
13683 error = got_error_msg(GOT_ERR_CONFLICTS,
13684 "conflicts must be resolved before merging "
13685 "can continue; changes destined for some "
13686 "files were not yet merged and "
13687 "should be merged manually if required before the "
13688 "merge operation is continued");
13689 } else {
13690 error = got_error_msg(GOT_ERR_CONFLICTS,
13691 "changes destined for some "
13692 "files were not yet merged and should be "
13693 "merged manually if required before the "
13694 "merge operation is continued");
13696 goto done;
13697 } else {
13698 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13699 fileindex, author, NULL, 1, branch_tip, branch_name,
13700 allow_conflict, repo, continue_merge ? print_status : NULL,
13701 NULL);
13702 if (error)
13703 goto done;
13704 error = got_worktree_merge_complete(worktree, fileindex, repo);
13705 if (error)
13706 goto done;
13707 error = got_object_id_str(&id_str, merge_commit_id);
13708 if (error)
13709 goto done;
13710 printf("Merged %s into %s: %s\n", branch_name,
13711 got_worktree_get_head_ref_name(worktree),
13712 id_str);
13715 done:
13716 free(gitconfig_path);
13717 free(id_str);
13718 free(merge_commit_id);
13719 free(author);
13720 free(branch_tip);
13721 free(branch_name);
13722 free(yca_id);
13723 if (branch)
13724 got_ref_close(branch);
13725 if (wt_branch)
13726 got_ref_close(wt_branch);
13727 if (worktree)
13728 got_worktree_close(worktree);
13729 if (repo) {
13730 const struct got_error *close_err = got_repo_close(repo);
13731 if (error == NULL)
13732 error = close_err;
13734 if (pack_fds) {
13735 const struct got_error *pack_err =
13736 got_repo_pack_fds_close(pack_fds);
13737 if (error == NULL)
13738 error = pack_err;
13740 return error;
13743 __dead static void
13744 usage_stage(void)
13746 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13747 "[path ...]\n", getprogname());
13748 exit(1);
13751 static const struct got_error *
13752 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13753 const char *path, struct got_object_id *blob_id,
13754 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13755 int dirfd, const char *de_name)
13757 const struct got_error *err = NULL;
13758 char *id_str = NULL;
13760 if (staged_status != GOT_STATUS_ADD &&
13761 staged_status != GOT_STATUS_MODIFY &&
13762 staged_status != GOT_STATUS_DELETE)
13763 return NULL;
13765 if (staged_status == GOT_STATUS_ADD ||
13766 staged_status == GOT_STATUS_MODIFY)
13767 err = got_object_id_str(&id_str, staged_blob_id);
13768 else
13769 err = got_object_id_str(&id_str, blob_id);
13770 if (err)
13771 return err;
13773 printf("%s %c %s\n", id_str, staged_status, path);
13774 free(id_str);
13775 return NULL;
13778 static const struct got_error *
13779 cmd_stage(int argc, char *argv[])
13781 const struct got_error *error = NULL;
13782 struct got_repository *repo = NULL;
13783 struct got_worktree *worktree = NULL;
13784 char *cwd = NULL;
13785 struct got_pathlist_head paths;
13786 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13787 FILE *patch_script_file = NULL;
13788 const char *patch_script_path = NULL;
13789 struct choose_patch_arg cpa;
13790 int *pack_fds = NULL;
13792 TAILQ_INIT(&paths);
13794 #ifndef PROFILE
13795 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13796 "unveil", NULL) == -1)
13797 err(1, "pledge");
13798 #endif
13800 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13801 switch (ch) {
13802 case 'F':
13803 patch_script_path = optarg;
13804 break;
13805 case 'l':
13806 list_stage = 1;
13807 break;
13808 case 'p':
13809 pflag = 1;
13810 break;
13811 case 'S':
13812 allow_bad_symlinks = 1;
13813 break;
13814 default:
13815 usage_stage();
13816 /* NOTREACHED */
13820 argc -= optind;
13821 argv += optind;
13823 if (list_stage && (pflag || patch_script_path))
13824 errx(1, "-l option cannot be used with other options");
13825 if (patch_script_path && !pflag)
13826 errx(1, "-F option can only be used together with -p option");
13828 cwd = getcwd(NULL, 0);
13829 if (cwd == NULL) {
13830 error = got_error_from_errno("getcwd");
13831 goto done;
13834 error = got_repo_pack_fds_open(&pack_fds);
13835 if (error != NULL)
13836 goto done;
13838 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13839 if (error) {
13840 if (error->code == GOT_ERR_NOT_WORKTREE)
13841 error = wrap_not_worktree_error(error, "stage", cwd);
13842 goto done;
13845 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13846 NULL, pack_fds);
13847 if (error != NULL)
13848 goto done;
13850 if (patch_script_path) {
13851 patch_script_file = fopen(patch_script_path, "re");
13852 if (patch_script_file == NULL) {
13853 error = got_error_from_errno2("fopen",
13854 patch_script_path);
13855 goto done;
13858 error = apply_unveil(got_repo_get_path(repo), 0,
13859 got_worktree_get_root_path(worktree));
13860 if (error)
13861 goto done;
13863 error = check_merge_in_progress(worktree, repo);
13864 if (error)
13865 goto done;
13867 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13868 if (error)
13869 goto done;
13871 if (list_stage)
13872 error = got_worktree_status(worktree, &paths, repo, 0,
13873 print_stage, NULL, check_cancelled, NULL);
13874 else {
13875 cpa.patch_script_file = patch_script_file;
13876 cpa.action = "stage";
13877 error = got_worktree_stage(worktree, &paths,
13878 pflag ? NULL : print_status, NULL,
13879 pflag ? choose_patch : NULL, &cpa,
13880 allow_bad_symlinks, repo);
13882 done:
13883 if (patch_script_file && fclose(patch_script_file) == EOF &&
13884 error == NULL)
13885 error = got_error_from_errno2("fclose", patch_script_path);
13886 if (repo) {
13887 const struct got_error *close_err = got_repo_close(repo);
13888 if (error == NULL)
13889 error = close_err;
13891 if (worktree)
13892 got_worktree_close(worktree);
13893 if (pack_fds) {
13894 const struct got_error *pack_err =
13895 got_repo_pack_fds_close(pack_fds);
13896 if (error == NULL)
13897 error = pack_err;
13899 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13900 free(cwd);
13901 return error;
13904 __dead static void
13905 usage_unstage(void)
13907 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13908 "[path ...]\n", getprogname());
13909 exit(1);
13913 static const struct got_error *
13914 cmd_unstage(int argc, char *argv[])
13916 const struct got_error *error = NULL;
13917 struct got_repository *repo = NULL;
13918 struct got_worktree *worktree = NULL;
13919 char *cwd = NULL;
13920 struct got_pathlist_head paths;
13921 int ch, pflag = 0;
13922 struct got_update_progress_arg upa;
13923 FILE *patch_script_file = NULL;
13924 const char *patch_script_path = NULL;
13925 struct choose_patch_arg cpa;
13926 int *pack_fds = NULL;
13928 TAILQ_INIT(&paths);
13930 #ifndef PROFILE
13931 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13932 "unveil", NULL) == -1)
13933 err(1, "pledge");
13934 #endif
13936 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13937 switch (ch) {
13938 case 'F':
13939 patch_script_path = optarg;
13940 break;
13941 case 'p':
13942 pflag = 1;
13943 break;
13944 default:
13945 usage_unstage();
13946 /* NOTREACHED */
13950 argc -= optind;
13951 argv += optind;
13953 if (patch_script_path && !pflag)
13954 errx(1, "-F option can only be used together with -p option");
13956 cwd = getcwd(NULL, 0);
13957 if (cwd == NULL) {
13958 error = got_error_from_errno("getcwd");
13959 goto done;
13962 error = got_repo_pack_fds_open(&pack_fds);
13963 if (error != NULL)
13964 goto done;
13966 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13967 if (error) {
13968 if (error->code == GOT_ERR_NOT_WORKTREE)
13969 error = wrap_not_worktree_error(error, "unstage", cwd);
13970 goto done;
13973 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13974 NULL, pack_fds);
13975 if (error != NULL)
13976 goto done;
13978 if (patch_script_path) {
13979 patch_script_file = fopen(patch_script_path, "re");
13980 if (patch_script_file == NULL) {
13981 error = got_error_from_errno2("fopen",
13982 patch_script_path);
13983 goto done;
13987 error = apply_unveil(got_repo_get_path(repo), 0,
13988 got_worktree_get_root_path(worktree));
13989 if (error)
13990 goto done;
13992 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13993 if (error)
13994 goto done;
13996 cpa.patch_script_file = patch_script_file;
13997 cpa.action = "unstage";
13998 memset(&upa, 0, sizeof(upa));
13999 error = got_worktree_unstage(worktree, &paths, update_progress,
14000 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14001 if (!error)
14002 print_merge_progress_stats(&upa);
14003 done:
14004 if (patch_script_file && fclose(patch_script_file) == EOF &&
14005 error == NULL)
14006 error = got_error_from_errno2("fclose", patch_script_path);
14007 if (repo) {
14008 const struct got_error *close_err = got_repo_close(repo);
14009 if (error == NULL)
14010 error = close_err;
14012 if (worktree)
14013 got_worktree_close(worktree);
14014 if (pack_fds) {
14015 const struct got_error *pack_err =
14016 got_repo_pack_fds_close(pack_fds);
14017 if (error == NULL)
14018 error = pack_err;
14020 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14021 free(cwd);
14022 return error;
14025 __dead static void
14026 usage_cat(void)
14028 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14029 "arg ...\n", getprogname());
14030 exit(1);
14033 static const struct got_error *
14034 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14036 const struct got_error *err;
14037 struct got_blob_object *blob;
14038 int fd = -1;
14040 fd = got_opentempfd();
14041 if (fd == -1)
14042 return got_error_from_errno("got_opentempfd");
14044 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14045 if (err)
14046 goto done;
14048 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14049 done:
14050 if (fd != -1 && close(fd) == -1 && err == NULL)
14051 err = got_error_from_errno("close");
14052 if (blob)
14053 got_object_blob_close(blob);
14054 return err;
14057 static const struct got_error *
14058 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14060 const struct got_error *err;
14061 struct got_tree_object *tree;
14062 int nentries, i;
14064 err = got_object_open_as_tree(&tree, repo, id);
14065 if (err)
14066 return err;
14068 nentries = got_object_tree_get_nentries(tree);
14069 for (i = 0; i < nentries; i++) {
14070 struct got_tree_entry *te;
14071 char *id_str;
14072 if (sigint_received || sigpipe_received)
14073 break;
14074 te = got_object_tree_get_entry(tree, i);
14075 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14076 if (err)
14077 break;
14078 fprintf(outfile, "%s %.7o %s\n", id_str,
14079 got_tree_entry_get_mode(te),
14080 got_tree_entry_get_name(te));
14081 free(id_str);
14084 got_object_tree_close(tree);
14085 return err;
14088 static const struct got_error *
14089 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14091 const struct got_error *err;
14092 struct got_commit_object *commit;
14093 const struct got_object_id_queue *parent_ids;
14094 struct got_object_qid *pid;
14095 char *id_str = NULL;
14096 const char *logmsg = NULL;
14097 char gmtoff[6];
14099 err = got_object_open_as_commit(&commit, repo, id);
14100 if (err)
14101 return err;
14103 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14104 if (err)
14105 goto done;
14107 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14108 parent_ids = got_object_commit_get_parent_ids(commit);
14109 fprintf(outfile, "numparents %d\n",
14110 got_object_commit_get_nparents(commit));
14111 STAILQ_FOREACH(pid, parent_ids, entry) {
14112 char *pid_str;
14113 err = got_object_id_str(&pid_str, &pid->id);
14114 if (err)
14115 goto done;
14116 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14117 free(pid_str);
14119 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14120 got_object_commit_get_author_gmtoff(commit));
14121 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14122 got_object_commit_get_author(commit),
14123 (long long)got_object_commit_get_author_time(commit),
14124 gmtoff);
14126 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14127 got_object_commit_get_committer_gmtoff(commit));
14128 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14129 got_object_commit_get_committer(commit),
14130 (long long)got_object_commit_get_committer_time(commit),
14131 gmtoff);
14133 logmsg = got_object_commit_get_logmsg_raw(commit);
14134 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14135 fprintf(outfile, "%s", logmsg);
14136 done:
14137 free(id_str);
14138 got_object_commit_close(commit);
14139 return err;
14142 static const struct got_error *
14143 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14145 const struct got_error *err;
14146 struct got_tag_object *tag;
14147 char *id_str = NULL;
14148 const char *tagmsg = NULL;
14149 char gmtoff[6];
14151 err = got_object_open_as_tag(&tag, repo, id);
14152 if (err)
14153 return err;
14155 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14156 if (err)
14157 goto done;
14159 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14161 switch (got_object_tag_get_object_type(tag)) {
14162 case GOT_OBJ_TYPE_BLOB:
14163 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14164 GOT_OBJ_LABEL_BLOB);
14165 break;
14166 case GOT_OBJ_TYPE_TREE:
14167 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14168 GOT_OBJ_LABEL_TREE);
14169 break;
14170 case GOT_OBJ_TYPE_COMMIT:
14171 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14172 GOT_OBJ_LABEL_COMMIT);
14173 break;
14174 case GOT_OBJ_TYPE_TAG:
14175 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14176 GOT_OBJ_LABEL_TAG);
14177 break;
14178 default:
14179 break;
14182 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14183 got_object_tag_get_name(tag));
14185 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14186 got_object_tag_get_tagger_gmtoff(tag));
14187 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14188 got_object_tag_get_tagger(tag),
14189 (long long)got_object_tag_get_tagger_time(tag),
14190 gmtoff);
14192 tagmsg = got_object_tag_get_message(tag);
14193 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14194 fprintf(outfile, "%s", tagmsg);
14195 done:
14196 free(id_str);
14197 got_object_tag_close(tag);
14198 return err;
14201 static const struct got_error *
14202 cmd_cat(int argc, char *argv[])
14204 const struct got_error *error;
14205 struct got_repository *repo = NULL;
14206 struct got_worktree *worktree = NULL;
14207 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14208 char *keyword_idstr = NULL;
14209 const char *commit_id_str = NULL;
14210 struct got_object_id *id = NULL, *commit_id = NULL;
14211 struct got_commit_object *commit = NULL;
14212 int ch, obj_type, i, force_path = 0;
14213 struct got_reflist_head refs;
14214 int *pack_fds = NULL;
14216 TAILQ_INIT(&refs);
14218 #ifndef PROFILE
14219 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14220 NULL) == -1)
14221 err(1, "pledge");
14222 #endif
14224 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14225 switch (ch) {
14226 case 'c':
14227 commit_id_str = optarg;
14228 break;
14229 case 'P':
14230 force_path = 1;
14231 break;
14232 case 'r':
14233 repo_path = realpath(optarg, NULL);
14234 if (repo_path == NULL)
14235 return got_error_from_errno2("realpath",
14236 optarg);
14237 got_path_strip_trailing_slashes(repo_path);
14238 break;
14239 default:
14240 usage_cat();
14241 /* NOTREACHED */
14245 argc -= optind;
14246 argv += optind;
14248 cwd = getcwd(NULL, 0);
14249 if (cwd == NULL) {
14250 error = got_error_from_errno("getcwd");
14251 goto done;
14254 error = got_repo_pack_fds_open(&pack_fds);
14255 if (error != NULL)
14256 goto done;
14258 if (repo_path == NULL) {
14259 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14260 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14261 goto done;
14262 if (worktree) {
14263 repo_path = strdup(
14264 got_worktree_get_repo_path(worktree));
14265 if (repo_path == NULL) {
14266 error = got_error_from_errno("strdup");
14267 goto done;
14270 if (commit_id_str == NULL) {
14271 /* Release work tree lock. */
14272 got_worktree_close(worktree);
14273 worktree = NULL;
14278 if (repo_path == NULL) {
14279 repo_path = strdup(cwd);
14280 if (repo_path == NULL)
14281 return got_error_from_errno("strdup");
14284 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14285 free(repo_path);
14286 if (error != NULL)
14287 goto done;
14289 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14290 if (error)
14291 goto done;
14293 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14294 if (error)
14295 goto done;
14297 if (commit_id_str != NULL) {
14298 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14299 repo, worktree);
14300 if (error != NULL)
14301 goto done;
14302 if (keyword_idstr != NULL)
14303 commit_id_str = keyword_idstr;
14304 if (worktree != NULL) {
14305 got_worktree_close(worktree);
14306 worktree = NULL;
14308 } else
14309 commit_id_str = GOT_REF_HEAD;
14310 error = got_repo_match_object_id(&commit_id, NULL,
14311 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14312 if (error)
14313 goto done;
14315 error = got_object_open_as_commit(&commit, repo, commit_id);
14316 if (error)
14317 goto done;
14319 for (i = 0; i < argc; i++) {
14320 if (force_path) {
14321 error = got_object_id_by_path(&id, repo, commit,
14322 argv[i]);
14323 if (error)
14324 break;
14325 } else {
14326 error = got_repo_match_object_id(&id, &label, argv[i],
14327 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14328 repo);
14329 if (error) {
14330 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14331 error->code != GOT_ERR_NOT_REF)
14332 break;
14333 error = got_object_id_by_path(&id, repo,
14334 commit, argv[i]);
14335 if (error)
14336 break;
14340 error = got_object_get_type(&obj_type, repo, id);
14341 if (error)
14342 break;
14344 switch (obj_type) {
14345 case GOT_OBJ_TYPE_BLOB:
14346 error = cat_blob(id, repo, stdout);
14347 break;
14348 case GOT_OBJ_TYPE_TREE:
14349 error = cat_tree(id, repo, stdout);
14350 break;
14351 case GOT_OBJ_TYPE_COMMIT:
14352 error = cat_commit(id, repo, stdout);
14353 break;
14354 case GOT_OBJ_TYPE_TAG:
14355 error = cat_tag(id, repo, stdout);
14356 break;
14357 default:
14358 error = got_error(GOT_ERR_OBJ_TYPE);
14359 break;
14361 if (error)
14362 break;
14363 free(label);
14364 label = NULL;
14365 free(id);
14366 id = NULL;
14368 done:
14369 free(label);
14370 free(id);
14371 free(commit_id);
14372 free(keyword_idstr);
14373 if (commit)
14374 got_object_commit_close(commit);
14375 if (worktree)
14376 got_worktree_close(worktree);
14377 if (repo) {
14378 const struct got_error *close_err = got_repo_close(repo);
14379 if (error == NULL)
14380 error = close_err;
14382 if (pack_fds) {
14383 const struct got_error *pack_err =
14384 got_repo_pack_fds_close(pack_fds);
14385 if (error == NULL)
14386 error = pack_err;
14389 got_ref_list_free(&refs);
14390 return error;
14393 __dead static void
14394 usage_info(void)
14396 fprintf(stderr, "usage: %s info [path ...]\n",
14397 getprogname());
14398 exit(1);
14401 static const struct got_error *
14402 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14403 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14404 struct got_object_id *commit_id)
14406 const struct got_error *err = NULL;
14407 char *id_str = NULL;
14408 char datebuf[128];
14409 struct tm mytm, *tm;
14410 struct got_pathlist_head *paths = arg;
14411 struct got_pathlist_entry *pe;
14414 * Clear error indication from any of the path arguments which
14415 * would cause this file index entry to be displayed.
14417 TAILQ_FOREACH(pe, paths, entry) {
14418 if (got_path_cmp(path, pe->path, strlen(path),
14419 pe->path_len) == 0 ||
14420 got_path_is_child(path, pe->path, pe->path_len))
14421 pe->data = NULL; /* no error */
14424 printf(GOT_COMMIT_SEP_STR);
14425 if (S_ISLNK(mode))
14426 printf("symlink: %s\n", path);
14427 else if (S_ISREG(mode)) {
14428 printf("file: %s\n", path);
14429 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14430 } else if (S_ISDIR(mode))
14431 printf("directory: %s\n", path);
14432 else
14433 printf("something: %s\n", path);
14435 tm = localtime_r(&mtime, &mytm);
14436 if (tm == NULL)
14437 return NULL;
14438 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14439 return got_error(GOT_ERR_NO_SPACE);
14440 printf("timestamp: %s\n", datebuf);
14442 if (blob_id) {
14443 err = got_object_id_str(&id_str, blob_id);
14444 if (err)
14445 return err;
14446 printf("based on blob: %s\n", id_str);
14447 free(id_str);
14450 if (staged_blob_id) {
14451 err = got_object_id_str(&id_str, staged_blob_id);
14452 if (err)
14453 return err;
14454 printf("based on staged blob: %s\n", id_str);
14455 free(id_str);
14458 if (commit_id) {
14459 err = got_object_id_str(&id_str, commit_id);
14460 if (err)
14461 return err;
14462 printf("based on commit: %s\n", id_str);
14463 free(id_str);
14466 return NULL;
14469 static const struct got_error *
14470 cmd_info(int argc, char *argv[])
14472 const struct got_error *error = NULL;
14473 struct got_worktree *worktree = NULL;
14474 char *cwd = NULL, *id_str = NULL;
14475 struct got_pathlist_head paths;
14476 char *uuidstr = NULL;
14477 int ch, show_files = 0;
14479 TAILQ_INIT(&paths);
14481 #ifndef PROFILE
14482 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14483 NULL) == -1)
14484 err(1, "pledge");
14485 #endif
14487 while ((ch = getopt(argc, argv, "")) != -1) {
14488 switch (ch) {
14489 default:
14490 usage_info();
14491 /* NOTREACHED */
14495 argc -= optind;
14496 argv += optind;
14498 cwd = getcwd(NULL, 0);
14499 if (cwd == NULL) {
14500 error = got_error_from_errno("getcwd");
14501 goto done;
14504 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14505 if (error) {
14506 if (error->code == GOT_ERR_NOT_WORKTREE)
14507 error = wrap_not_worktree_error(error, "info", cwd);
14508 goto done;
14511 #ifndef PROFILE
14512 /* Remove "wpath cpath proc exec sendfd" promises. */
14513 if (pledge("stdio rpath flock unveil", NULL) == -1)
14514 err(1, "pledge");
14515 #endif
14516 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14517 if (error)
14518 goto done;
14520 if (argc >= 1) {
14521 error = get_worktree_paths_from_argv(&paths, argc, argv,
14522 worktree);
14523 if (error)
14524 goto done;
14525 show_files = 1;
14528 error = got_object_id_str(&id_str,
14529 got_worktree_get_base_commit_id(worktree));
14530 if (error)
14531 goto done;
14533 error = got_worktree_get_uuid(&uuidstr, worktree);
14534 if (error)
14535 goto done;
14537 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14538 printf("work tree base commit: %s\n", id_str);
14539 printf("work tree path prefix: %s\n",
14540 got_worktree_get_path_prefix(worktree));
14541 printf("work tree branch reference: %s\n",
14542 got_worktree_get_head_ref_name(worktree));
14543 printf("work tree UUID: %s\n", uuidstr);
14544 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14546 if (show_files) {
14547 struct got_pathlist_entry *pe;
14548 TAILQ_FOREACH(pe, &paths, entry) {
14549 if (pe->path_len == 0)
14550 continue;
14552 * Assume this path will fail. This will be corrected
14553 * in print_path_info() in case the path does suceeed.
14555 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14557 error = got_worktree_path_info(worktree, &paths,
14558 print_path_info, &paths, check_cancelled, NULL);
14559 if (error)
14560 goto done;
14561 TAILQ_FOREACH(pe, &paths, entry) {
14562 if (pe->data != NULL) {
14563 const struct got_error *perr;
14565 perr = pe->data;
14566 error = got_error_fmt(perr->code, "%s",
14567 pe->path);
14568 break;
14572 done:
14573 if (worktree)
14574 got_worktree_close(worktree);
14575 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14576 free(cwd);
14577 free(id_str);
14578 free(uuidstr);
14579 return error;