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 path_dir = realpath(argv[0], NULL);
838 if (path_dir == NULL) {
839 error = got_error_from_errno2("realpath", argv[0]);
840 goto done;
842 got_path_strip_trailing_slashes(path_dir);
844 error = get_editor(&editor);
845 if (error)
846 goto done;
848 if (unveil(path_dir, "r") != 0) {
849 error = got_error_from_errno2("unveil", path_dir);
850 goto done;
852 if (unveil(editor, "x") != 0) {
853 error = got_error_from_errno2("unveil", editor);
854 goto done;
856 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
857 if (error)
858 goto done;
860 error = get_author(&author, repo, NULL);
861 if (error)
862 return error;
864 /*
865 * Don't let the user create a branch name with a leading '-'.
866 * While technically a valid reference name, this case is usually
867 * an unintended typo.
868 */
869 if (branch_name && branch_name[0] == '-')
870 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
872 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
873 if (error && error->code != GOT_ERR_NOT_REF)
874 goto done;
876 if (branch_name)
877 n = strlcat(refname, branch_name, sizeof(refname));
878 else if (head_ref && got_ref_is_symbolic(head_ref))
879 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
880 sizeof(refname));
881 else
882 n = strlcat(refname, "main", sizeof(refname));
883 if (n >= sizeof(refname)) {
884 error = got_error(GOT_ERR_NO_SPACE);
885 goto done;
888 error = got_ref_open(&branch_ref, repo, refname, 0);
889 if (error) {
890 if (error->code != GOT_ERR_NOT_REF)
891 goto done;
892 } else {
893 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
894 "import target branch already exists");
895 goto done;
898 if (logmsg == NULL || *logmsg == '\0') {
899 free(logmsg);
900 error = collect_import_msg(&logmsg, &logmsg_path, editor,
901 path_dir, refname);
902 if (error) {
903 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
904 logmsg_path != NULL)
905 preserve_logmsg = 1;
906 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0 ||
1650 strcmp(proto, "git+http") == 0 ||
1651 strcmp(proto, "http") == 0 ||
1652 strcmp(proto, "git+https") == 0 ||
1653 strcmp(proto, "https") == 0) {
1654 #ifndef PROFILE
1655 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1656 "sendfd unveil", NULL) == -1)
1657 err(1, "pledge");
1658 #endif
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 #ifndef PROFILE
1702 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1703 NULL) == -1)
1704 err(1, "pledge");
1705 #endif
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 strcmp(proto, "git+http") == 0 ||
2533 strcmp(proto, "http") == 0 ||
2534 strcmp(proto, "git+https") == 0 ||
2535 strcmp(proto, "https") == 0) {
2536 #ifndef PROFILE
2537 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2538 "sendfd unveil", NULL) == -1)
2539 err(1, "pledge");
2540 #endif
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;
2577 #ifndef PROFILE
2578 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2579 NULL) == -1)
2580 err(1, "pledge");
2581 #endif
2582 if (!have_bflag) {
2584 * If set, get this remote's HEAD ref target so
2585 * if it has changed on the server we can fetch it.
2587 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2588 got_ref_cmp_by_name, repo);
2589 if (error)
2590 goto done;
2592 TAILQ_FOREACH(re, &remote_refs, entry) {
2593 const char *remote_refname, *remote_target;
2594 size_t remote_name_len;
2596 if (!got_ref_is_symbolic(re->ref))
2597 continue;
2599 remote_name_len = strlen(remote->name);
2600 remote_refname = got_ref_get_name(re->ref);
2602 /* we only want refs/remotes/$remote->name/HEAD */
2603 if (strncmp(remote_refname + 13, remote->name,
2604 remote_name_len) != 0)
2605 continue;
2607 if (strcmp(remote_refname + remote_name_len + 14,
2608 GOT_REF_HEAD) != 0)
2609 continue;
2612 * Take the name itself because we already
2613 * only match with refs/heads/ in fetch_pack().
2615 remote_target = got_ref_get_symref_target(re->ref);
2616 remote_head = remote_target + remote_name_len + 14;
2617 break;
2620 if (head_refname &&
2621 strncmp(head_refname, "refs/heads/", 11) == 0)
2622 worktree_branch = head_refname;
2625 fpa.last_scaled_size[0] = '\0';
2626 fpa.last_p_indexed = -1;
2627 fpa.last_p_resolved = -1;
2628 fpa.verbosity = verbosity;
2629 fpa.repo = repo;
2630 fpa.create_configs = 0;
2631 fpa.configs_created = 0;
2632 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2634 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2635 remote->mirror_references, fetch_all_branches, &wanted_branches,
2636 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2637 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2638 if (error)
2639 goto done;
2641 if (list_refs_only) {
2642 error = list_remote_refs(&symrefs, &refs);
2643 goto done;
2646 if (pack_hash == NULL) {
2647 if (verbosity >= 0)
2648 printf("Already up-to-date\n");
2649 } else if (verbosity >= 0) {
2650 error = got_object_id_str(&id_str, pack_hash);
2651 if (error)
2652 goto done;
2653 printf("\nFetched %s.pack\n", id_str);
2654 free(id_str);
2655 id_str = NULL;
2658 /* Update references provided with the pack file. */
2659 TAILQ_FOREACH(pe, &refs, entry) {
2660 const char *refname = pe->path;
2661 struct got_object_id *id = pe->data;
2662 struct got_reference *ref;
2663 char *remote_refname;
2665 if (is_wanted_ref(&wanted_refs, refname) &&
2666 !remote->mirror_references) {
2667 error = update_wanted_ref(refname, id,
2668 remote->name, verbosity, repo);
2669 if (error)
2670 goto done;
2671 continue;
2674 if (remote->mirror_references ||
2675 strncmp("refs/tags/", refname, 10) == 0) {
2676 error = got_ref_open(&ref, repo, refname, 1);
2677 if (error) {
2678 if (error->code != GOT_ERR_NOT_REF)
2679 goto done;
2680 error = create_ref(refname, id, verbosity,
2681 repo);
2682 if (error)
2683 goto done;
2684 } else {
2685 error = update_ref(ref, id, replace_tags,
2686 verbosity, repo);
2687 unlock_err = got_ref_unlock(ref);
2688 if (unlock_err && error == NULL)
2689 error = unlock_err;
2690 got_ref_close(ref);
2691 if (error)
2692 goto done;
2694 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2695 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2696 remote_name, refname + 11) == -1) {
2697 error = got_error_from_errno("asprintf");
2698 goto done;
2701 error = got_ref_open(&ref, repo, remote_refname, 1);
2702 if (error) {
2703 if (error->code != GOT_ERR_NOT_REF)
2704 goto done;
2705 error = create_ref(remote_refname, id,
2706 verbosity, repo);
2707 if (error)
2708 goto done;
2709 } else {
2710 error = update_ref(ref, id, replace_tags,
2711 verbosity, repo);
2712 unlock_err = got_ref_unlock(ref);
2713 if (unlock_err && error == NULL)
2714 error = unlock_err;
2715 got_ref_close(ref);
2716 if (error)
2717 goto done;
2720 /* Also create a local branch if none exists yet. */
2721 error = got_ref_open(&ref, repo, refname, 1);
2722 if (error) {
2723 if (error->code != GOT_ERR_NOT_REF)
2724 goto done;
2725 error = create_ref(refname, id, verbosity,
2726 repo);
2727 if (error)
2728 goto done;
2729 } else {
2730 unlock_err = got_ref_unlock(ref);
2731 if (unlock_err && error == NULL)
2732 error = unlock_err;
2733 got_ref_close(ref);
2737 if (delete_refs) {
2738 error = delete_missing_refs(&refs, &symrefs, remote,
2739 verbosity, repo);
2740 if (error)
2741 goto done;
2744 if (!remote->mirror_references) {
2745 /* Update remote HEAD reference if the server provided one. */
2746 TAILQ_FOREACH(pe, &symrefs, entry) {
2747 struct got_reference *target_ref;
2748 const char *refname = pe->path;
2749 const char *target = pe->data;
2750 char *remote_refname = NULL, *remote_target = NULL;
2752 if (strcmp(refname, GOT_REF_HEAD) != 0)
2753 continue;
2755 if (strncmp("refs/heads/", target, 11) != 0)
2756 continue;
2758 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2759 remote->name, refname) == -1) {
2760 error = got_error_from_errno("asprintf");
2761 goto done;
2763 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2764 remote->name, target + 11) == -1) {
2765 error = got_error_from_errno("asprintf");
2766 free(remote_refname);
2767 goto done;
2770 error = got_ref_open(&target_ref, repo, remote_target,
2771 0);
2772 if (error) {
2773 free(remote_refname);
2774 free(remote_target);
2775 if (error->code == GOT_ERR_NOT_REF) {
2776 error = NULL;
2777 continue;
2779 goto done;
2781 error = update_symref(remote_refname, target_ref,
2782 verbosity, repo);
2783 free(remote_refname);
2784 free(remote_target);
2785 got_ref_close(target_ref);
2786 if (error)
2787 goto done;
2790 done:
2791 if (fetchpid > 0) {
2792 if (kill(fetchpid, SIGTERM) == -1)
2793 error = got_error_from_errno("kill");
2794 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2795 error = got_error_from_errno("waitpid");
2797 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2798 error = got_error_from_errno("close");
2799 if (repo) {
2800 const struct got_error *close_err = got_repo_close(repo);
2801 if (error == NULL)
2802 error = close_err;
2804 if (worktree)
2805 got_worktree_close(worktree);
2806 if (pack_fds) {
2807 const struct got_error *pack_err =
2808 got_repo_pack_fds_close(pack_fds);
2809 if (error == NULL)
2810 error = pack_err;
2812 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2813 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2814 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2815 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2816 got_ref_list_free(&remote_refs);
2817 got_repo_free_remote_repo_data(remote);
2818 free(remote);
2819 free(head_refname);
2820 free(id_str);
2821 free(cwd);
2822 free(repo_path);
2823 free(pack_hash);
2824 free(proto);
2825 free(host);
2826 free(port);
2827 free(server_path);
2828 free(repo_name);
2829 return error;
2833 __dead static void
2834 usage_checkout(void)
2836 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2837 "[-p path-prefix] repository-path [work-tree-path]\n",
2838 getprogname());
2839 exit(1);
2842 static void
2843 show_worktree_base_ref_warning(void)
2845 fprintf(stderr, "%s: warning: could not create a reference "
2846 "to the work tree's base commit; the commit could be "
2847 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2848 "repository writable and running 'got update' will prevent this\n",
2849 getprogname());
2852 struct got_checkout_progress_arg {
2853 const char *worktree_path;
2854 int had_base_commit_ref_error;
2855 int verbosity;
2858 static const struct got_error *
2859 checkout_progress(void *arg, unsigned char status, const char *path)
2861 struct got_checkout_progress_arg *a = arg;
2863 /* Base commit bump happens silently. */
2864 if (status == GOT_STATUS_BUMP_BASE)
2865 return NULL;
2867 if (status == GOT_STATUS_BASE_REF_ERR) {
2868 a->had_base_commit_ref_error = 1;
2869 return NULL;
2872 while (path[0] == '/')
2873 path++;
2875 if (a->verbosity >= 0)
2876 printf("%c %s/%s\n", status, a->worktree_path, path);
2878 return NULL;
2881 static const struct got_error *
2882 check_cancelled(void *arg)
2884 if (sigint_received || sigpipe_received)
2885 return got_error(GOT_ERR_CANCELLED);
2886 return NULL;
2889 static const struct got_error *
2890 check_linear_ancestry(struct got_object_id *commit_id,
2891 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2892 struct got_repository *repo)
2894 const struct got_error *err = NULL;
2895 struct got_object_id *yca_id;
2897 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2898 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2899 if (err)
2900 return err;
2902 if (yca_id == NULL)
2903 return got_error(GOT_ERR_ANCESTRY);
2906 * Require a straight line of history between the target commit
2907 * and the work tree's base commit.
2909 * Non-linear situations such as this require a rebase:
2911 * (commit) D F (base_commit)
2912 * \ /
2913 * C E
2914 * \ /
2915 * B (yca)
2916 * |
2917 * A
2919 * 'got update' only handles linear cases:
2920 * Update forwards in time: A (base/yca) - B - C - D (commit)
2921 * Update backwards in time: D (base) - C - B - A (commit/yca)
2923 if (allow_forwards_in_time_only) {
2924 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2925 return got_error(GOT_ERR_ANCESTRY);
2926 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2927 got_object_id_cmp(base_commit_id, yca_id) != 0)
2928 return got_error(GOT_ERR_ANCESTRY);
2930 free(yca_id);
2931 return NULL;
2934 static const struct got_error *
2935 check_same_branch(struct got_object_id *commit_id,
2936 struct got_reference *head_ref, struct got_repository *repo)
2938 const struct got_error *err = NULL;
2939 struct got_commit_graph *graph = NULL;
2940 struct got_object_id *head_commit_id = NULL;
2942 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2943 if (err)
2944 goto done;
2946 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2947 goto done;
2949 err = got_commit_graph_open(&graph, "/", 1);
2950 if (err)
2951 goto done;
2953 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2954 check_cancelled, NULL);
2955 if (err)
2956 goto done;
2958 for (;;) {
2959 struct got_object_id id;
2961 err = got_commit_graph_iter_next(&id, graph, repo,
2962 check_cancelled, NULL);
2963 if (err) {
2964 if (err->code == GOT_ERR_ITER_COMPLETED)
2965 err = got_error(GOT_ERR_ANCESTRY);
2966 break;
2969 if (got_object_id_cmp(&id, commit_id) == 0)
2970 break;
2972 done:
2973 if (graph)
2974 got_commit_graph_close(graph);
2975 free(head_commit_id);
2976 return err;
2979 static const struct got_error *
2980 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2982 static char msg[512];
2983 const char *branch_name;
2985 if (got_ref_is_symbolic(ref))
2986 branch_name = got_ref_get_symref_target(ref);
2987 else
2988 branch_name = got_ref_get_name(ref);
2990 if (strncmp("refs/heads/", branch_name, 11) == 0)
2991 branch_name += 11;
2993 snprintf(msg, sizeof(msg),
2994 "target commit is not contained in branch '%s'; "
2995 "the branch to use must be specified with -b; "
2996 "if necessary a new branch can be created for "
2997 "this commit with 'got branch -c %s BRANCH_NAME'",
2998 branch_name, commit_id_str);
3000 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3003 static const struct got_error *
3004 cmd_checkout(int argc, char *argv[])
3006 const struct got_error *close_err, *error = NULL;
3007 struct got_repository *repo = NULL;
3008 struct got_reference *head_ref = NULL, *ref = NULL;
3009 struct got_worktree *worktree = NULL;
3010 char *repo_path = NULL;
3011 char *worktree_path = NULL;
3012 const char *path_prefix = "";
3013 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3014 char *commit_id_str = NULL, *keyword_idstr = NULL;
3015 struct got_object_id *commit_id = NULL;
3016 char *cwd = NULL;
3017 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3018 struct got_pathlist_head paths;
3019 struct got_checkout_progress_arg cpa;
3020 int *pack_fds = NULL;
3022 TAILQ_INIT(&paths);
3024 #ifndef PROFILE
3025 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3026 "unveil", NULL) == -1)
3027 err(1, "pledge");
3028 #endif
3030 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3031 switch (ch) {
3032 case 'b':
3033 branch_name = optarg;
3034 break;
3035 case 'c':
3036 commit_id_str = strdup(optarg);
3037 if (commit_id_str == NULL)
3038 return got_error_from_errno("strdup");
3039 break;
3040 case 'E':
3041 allow_nonempty = 1;
3042 break;
3043 case 'p':
3044 path_prefix = optarg;
3045 break;
3046 case 'q':
3047 verbosity = -1;
3048 break;
3049 default:
3050 usage_checkout();
3051 /* NOTREACHED */
3055 argc -= optind;
3056 argv += optind;
3058 if (argc == 1) {
3059 char *base, *dotgit;
3060 const char *path;
3061 repo_path = realpath(argv[0], NULL);
3062 if (repo_path == NULL)
3063 return got_error_from_errno2("realpath", argv[0]);
3064 cwd = getcwd(NULL, 0);
3065 if (cwd == NULL) {
3066 error = got_error_from_errno("getcwd");
3067 goto done;
3069 if (path_prefix[0])
3070 path = path_prefix;
3071 else
3072 path = repo_path;
3073 error = got_path_basename(&base, path);
3074 if (error)
3075 goto done;
3076 dotgit = strstr(base, ".git");
3077 if (dotgit)
3078 *dotgit = '\0';
3079 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3080 error = got_error_from_errno("asprintf");
3081 free(base);
3082 goto done;
3084 free(base);
3085 } else if (argc == 2) {
3086 repo_path = realpath(argv[0], NULL);
3087 if (repo_path == NULL) {
3088 error = got_error_from_errno2("realpath", argv[0]);
3089 goto done;
3091 worktree_path = realpath(argv[1], NULL);
3092 if (worktree_path == NULL) {
3093 if (errno != ENOENT) {
3094 error = got_error_from_errno2("realpath",
3095 argv[1]);
3096 goto done;
3098 worktree_path = strdup(argv[1]);
3099 if (worktree_path == NULL) {
3100 error = got_error_from_errno("strdup");
3101 goto done;
3104 } else
3105 usage_checkout();
3107 got_path_strip_trailing_slashes(repo_path);
3108 got_path_strip_trailing_slashes(worktree_path);
3110 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3111 got_path_is_child(repo_path, worktree_path,
3112 strlen(worktree_path))) {
3113 error = got_error_fmt(GOT_ERR_BAD_PATH,
3114 "work tree and repository paths may not overlap: %s",
3115 worktree_path);
3116 goto done;
3119 error = got_repo_pack_fds_open(&pack_fds);
3120 if (error != NULL)
3121 goto done;
3123 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3124 if (error != NULL)
3125 goto done;
3127 /* Pre-create work tree path for unveil(2) */
3128 error = got_path_mkdir(worktree_path);
3129 if (error) {
3130 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3131 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3132 goto done;
3133 if (!allow_nonempty &&
3134 !got_path_dir_is_empty(worktree_path)) {
3135 error = got_error_path(worktree_path,
3136 GOT_ERR_DIR_NOT_EMPTY);
3137 goto done;
3141 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3142 if (error)
3143 goto done;
3145 error = got_ref_open(&head_ref, repo, branch_name, 0);
3146 if (error != NULL)
3147 goto done;
3149 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3150 GOT_WORKTREE_GOT_DIR, repo);
3151 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3152 goto done;
3154 error = got_worktree_open(&worktree, worktree_path,
3155 GOT_WORKTREE_GOT_DIR);
3156 if (error != NULL)
3157 goto done;
3159 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3160 path_prefix);
3161 if (error != NULL)
3162 goto done;
3163 if (!same_path_prefix) {
3164 error = got_error(GOT_ERR_PATH_PREFIX);
3165 goto done;
3168 if (commit_id_str) {
3169 struct got_reflist_head refs;
3170 TAILQ_INIT(&refs);
3171 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3172 NULL);
3173 if (error)
3174 goto done;
3176 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3177 repo, worktree);
3178 if (error != NULL)
3179 goto done;
3180 if (keyword_idstr != NULL) {
3181 free(commit_id_str);
3182 commit_id_str = keyword_idstr;
3185 error = got_repo_match_object_id(&commit_id, NULL,
3186 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3187 got_ref_list_free(&refs);
3188 if (error)
3189 goto done;
3190 error = check_linear_ancestry(commit_id,
3191 got_worktree_get_base_commit_id(worktree), 0, repo);
3192 if (error != NULL) {
3193 if (error->code == GOT_ERR_ANCESTRY) {
3194 error = checkout_ancestry_error(
3195 head_ref, commit_id_str);
3197 goto done;
3199 error = check_same_branch(commit_id, head_ref, repo);
3200 if (error) {
3201 if (error->code == GOT_ERR_ANCESTRY) {
3202 error = checkout_ancestry_error(
3203 head_ref, commit_id_str);
3205 goto done;
3207 error = got_worktree_set_base_commit_id(worktree, repo,
3208 commit_id);
3209 if (error)
3210 goto done;
3211 /* Expand potentially abbreviated commit ID string. */
3212 free(commit_id_str);
3213 error = got_object_id_str(&commit_id_str, commit_id);
3214 if (error)
3215 goto done;
3216 } else {
3217 commit_id = got_object_id_dup(
3218 got_worktree_get_base_commit_id(worktree));
3219 if (commit_id == NULL) {
3220 error = got_error_from_errno("got_object_id_dup");
3221 goto done;
3223 error = got_object_id_str(&commit_id_str, commit_id);
3224 if (error)
3225 goto done;
3228 error = got_pathlist_append(&paths, "", NULL);
3229 if (error)
3230 goto done;
3231 cpa.worktree_path = worktree_path;
3232 cpa.had_base_commit_ref_error = 0;
3233 cpa.verbosity = verbosity;
3234 error = got_worktree_checkout_files(worktree, &paths, repo,
3235 checkout_progress, &cpa, check_cancelled, NULL);
3236 if (error != NULL)
3237 goto done;
3239 if (got_ref_is_symbolic(head_ref)) {
3240 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3241 if (error)
3242 goto done;
3243 refname = got_ref_get_name(ref);
3244 } else
3245 refname = got_ref_get_name(head_ref);
3246 printf("Checked out %s: %s\n", refname, commit_id_str);
3247 printf("Now shut up and hack\n");
3248 if (cpa.had_base_commit_ref_error)
3249 show_worktree_base_ref_warning();
3250 done:
3251 if (pack_fds) {
3252 const struct got_error *pack_err =
3253 got_repo_pack_fds_close(pack_fds);
3254 if (error == NULL)
3255 error = pack_err;
3257 if (head_ref)
3258 got_ref_close(head_ref);
3259 if (ref)
3260 got_ref_close(ref);
3261 if (repo) {
3262 close_err = got_repo_close(repo);
3263 if (error == NULL)
3264 error = close_err;
3266 if (worktree != NULL) {
3267 close_err = got_worktree_close(worktree);
3268 if (error == NULL)
3269 error = close_err;
3271 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3272 free(commit_id_str);
3273 free(commit_id);
3274 free(repo_path);
3275 free(worktree_path);
3276 free(cwd);
3277 return error;
3280 struct got_update_progress_arg {
3281 int did_something;
3282 int conflicts;
3283 int obstructed;
3284 int not_updated;
3285 int missing;
3286 int not_deleted;
3287 int unversioned;
3288 int verbosity;
3291 static void
3292 print_update_progress_stats(struct got_update_progress_arg *upa)
3294 if (!upa->did_something)
3295 return;
3297 if (upa->conflicts > 0)
3298 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3299 if (upa->obstructed > 0)
3300 printf("File paths obstructed by a non-regular file: %d\n",
3301 upa->obstructed);
3302 if (upa->not_updated > 0)
3303 printf("Files not updated because of existing merge "
3304 "conflicts: %d\n", upa->not_updated);
3308 * The meaning of some status codes differs between merge-style operations and
3309 * update operations. For example, the ! status code means "file was missing"
3310 * if changes were merged into the work tree, and "missing file was restored"
3311 * if the work tree was updated. This function should be used by any operation
3312 * which merges changes into the work tree without updating the work tree.
3314 static void
3315 print_merge_progress_stats(struct got_update_progress_arg *upa)
3317 if (!upa->did_something)
3318 return;
3320 if (upa->conflicts > 0)
3321 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3322 if (upa->obstructed > 0)
3323 printf("File paths obstructed by a non-regular file: %d\n",
3324 upa->obstructed);
3325 if (upa->missing > 0)
3326 printf("Files which had incoming changes but could not be "
3327 "found in the work tree: %d\n", upa->missing);
3328 if (upa->not_deleted > 0)
3329 printf("Files not deleted due to differences in deleted "
3330 "content: %d\n", upa->not_deleted);
3331 if (upa->unversioned > 0)
3332 printf("Files not merged because an unversioned file was "
3333 "found in the work tree: %d\n", upa->unversioned);
3336 __dead static void
3337 usage_update(void)
3339 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3340 "[path ...]\n", getprogname());
3341 exit(1);
3344 static const struct got_error *
3345 update_progress(void *arg, unsigned char status, const char *path)
3347 struct got_update_progress_arg *upa = arg;
3349 if (status == GOT_STATUS_EXISTS ||
3350 status == GOT_STATUS_BASE_REF_ERR)
3351 return NULL;
3353 upa->did_something = 1;
3355 /* Base commit bump happens silently. */
3356 if (status == GOT_STATUS_BUMP_BASE)
3357 return NULL;
3359 if (status == GOT_STATUS_CONFLICT)
3360 upa->conflicts++;
3361 if (status == GOT_STATUS_OBSTRUCTED)
3362 upa->obstructed++;
3363 if (status == GOT_STATUS_CANNOT_UPDATE)
3364 upa->not_updated++;
3365 if (status == GOT_STATUS_MISSING)
3366 upa->missing++;
3367 if (status == GOT_STATUS_CANNOT_DELETE)
3368 upa->not_deleted++;
3369 if (status == GOT_STATUS_UNVERSIONED)
3370 upa->unversioned++;
3372 while (path[0] == '/')
3373 path++;
3374 if (upa->verbosity >= 0)
3375 printf("%c %s\n", status, path);
3377 return NULL;
3380 static const struct got_error *
3381 switch_head_ref(struct got_reference *head_ref,
3382 struct got_object_id *commit_id, struct got_worktree *worktree,
3383 struct got_repository *repo)
3385 const struct got_error *err = NULL;
3386 char *base_id_str;
3387 int ref_has_moved = 0;
3389 /* Trivial case: switching between two different references. */
3390 if (strcmp(got_ref_get_name(head_ref),
3391 got_worktree_get_head_ref_name(worktree)) != 0) {
3392 printf("Switching work tree from %s to %s\n",
3393 got_worktree_get_head_ref_name(worktree),
3394 got_ref_get_name(head_ref));
3395 return got_worktree_set_head_ref(worktree, head_ref);
3398 err = check_linear_ancestry(commit_id,
3399 got_worktree_get_base_commit_id(worktree), 0, repo);
3400 if (err) {
3401 if (err->code != GOT_ERR_ANCESTRY)
3402 return err;
3403 ref_has_moved = 1;
3405 if (!ref_has_moved)
3406 return NULL;
3408 /* Switching to a rebased branch with the same reference name. */
3409 err = got_object_id_str(&base_id_str,
3410 got_worktree_get_base_commit_id(worktree));
3411 if (err)
3412 return err;
3413 printf("Reference %s now points at a different branch\n",
3414 got_worktree_get_head_ref_name(worktree));
3415 printf("Switching work tree from %s to %s\n", base_id_str,
3416 got_worktree_get_head_ref_name(worktree));
3417 return NULL;
3420 static const struct got_error *
3421 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3423 const struct got_error *err;
3424 int in_progress;
3426 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3427 if (err)
3428 return err;
3429 if (in_progress)
3430 return got_error(GOT_ERR_REBASING);
3432 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3433 if (err)
3434 return err;
3435 if (in_progress)
3436 return got_error(GOT_ERR_HISTEDIT_BUSY);
3438 return NULL;
3441 static const struct got_error *
3442 check_merge_in_progress(struct got_worktree *worktree,
3443 struct got_repository *repo)
3445 const struct got_error *err;
3446 int in_progress;
3448 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3449 if (err)
3450 return err;
3451 if (in_progress)
3452 return got_error(GOT_ERR_MERGE_BUSY);
3454 return NULL;
3457 static const struct got_error *
3458 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3459 char *argv[], struct got_worktree *worktree)
3461 const struct got_error *err = NULL;
3462 char *path;
3463 struct got_pathlist_entry *new;
3464 int i;
3466 if (argc == 0) {
3467 path = strdup("");
3468 if (path == NULL)
3469 return got_error_from_errno("strdup");
3470 return got_pathlist_append(paths, path, NULL);
3473 for (i = 0; i < argc; i++) {
3474 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3475 if (err)
3476 break;
3477 err = got_pathlist_insert(&new, paths, path, NULL);
3478 if (err || new == NULL /* duplicate */) {
3479 free(path);
3480 if (err)
3481 break;
3485 return err;
3488 static const struct got_error *
3489 wrap_not_worktree_error(const struct got_error *orig_err,
3490 const char *cmdname, const char *path)
3492 const struct got_error *err;
3493 struct got_repository *repo;
3494 static char msg[512];
3495 int *pack_fds = NULL;
3497 err = got_repo_pack_fds_open(&pack_fds);
3498 if (err)
3499 return err;
3501 err = got_repo_open(&repo, path, NULL, pack_fds);
3502 if (err)
3503 return orig_err;
3505 snprintf(msg, sizeof(msg),
3506 "'got %s' needs a work tree in addition to a git repository\n"
3507 "Work trees can be checked out from this Git repository with "
3508 "'got checkout'.\n"
3509 "The got(1) manual page contains more information.", cmdname);
3510 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3511 if (repo) {
3512 const struct got_error *close_err = got_repo_close(repo);
3513 if (err == NULL)
3514 err = close_err;
3516 if (pack_fds) {
3517 const struct got_error *pack_err =
3518 got_repo_pack_fds_close(pack_fds);
3519 if (err == NULL)
3520 err = pack_err;
3522 return err;
3525 static const struct got_error *
3526 cmd_update(int argc, char *argv[])
3528 const struct got_error *close_err, *error = NULL;
3529 struct got_repository *repo = NULL;
3530 struct got_worktree *worktree = NULL;
3531 char *worktree_path = NULL;
3532 struct got_object_id *commit_id = NULL;
3533 char *commit_id_str = NULL;
3534 const char *branch_name = NULL;
3535 struct got_reference *head_ref = NULL;
3536 struct got_pathlist_head paths;
3537 struct got_pathlist_entry *pe;
3538 int ch, verbosity = 0;
3539 struct got_update_progress_arg upa;
3540 int *pack_fds = NULL;
3542 TAILQ_INIT(&paths);
3544 #ifndef PROFILE
3545 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3546 "unveil", NULL) == -1)
3547 err(1, "pledge");
3548 #endif
3550 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3551 switch (ch) {
3552 case 'b':
3553 branch_name = optarg;
3554 break;
3555 case 'c':
3556 commit_id_str = strdup(optarg);
3557 if (commit_id_str == NULL)
3558 return got_error_from_errno("strdup");
3559 break;
3560 case 'q':
3561 verbosity = -1;
3562 break;
3563 default:
3564 usage_update();
3565 /* NOTREACHED */
3569 argc -= optind;
3570 argv += optind;
3572 worktree_path = getcwd(NULL, 0);
3573 if (worktree_path == NULL) {
3574 error = got_error_from_errno("getcwd");
3575 goto done;
3578 error = got_repo_pack_fds_open(&pack_fds);
3579 if (error != NULL)
3580 goto done;
3582 error = got_worktree_open(&worktree, worktree_path,
3583 GOT_WORKTREE_GOT_DIR);
3584 if (error) {
3585 if (error->code == GOT_ERR_NOT_WORKTREE)
3586 error = wrap_not_worktree_error(error, "update",
3587 worktree_path);
3588 goto done;
3591 error = check_rebase_or_histedit_in_progress(worktree);
3592 if (error)
3593 goto done;
3595 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3596 NULL, pack_fds);
3597 if (error != NULL)
3598 goto done;
3600 error = apply_unveil(got_repo_get_path(repo), 0,
3601 got_worktree_get_root_path(worktree));
3602 if (error)
3603 goto done;
3605 error = check_merge_in_progress(worktree, repo);
3606 if (error)
3607 goto done;
3609 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3610 if (error)
3611 goto done;
3613 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3614 got_worktree_get_head_ref_name(worktree), 0);
3615 if (error != NULL)
3616 goto done;
3617 if (commit_id_str == NULL) {
3618 error = got_ref_resolve(&commit_id, repo, head_ref);
3619 if (error != NULL)
3620 goto done;
3621 error = got_object_id_str(&commit_id_str, commit_id);
3622 if (error != NULL)
3623 goto done;
3624 } else {
3625 struct got_reflist_head refs;
3626 char *keyword_idstr = NULL;
3628 TAILQ_INIT(&refs);
3630 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3631 NULL);
3632 if (error)
3633 goto done;
3635 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3636 repo, worktree);
3637 if (error != NULL)
3638 goto done;
3639 if (keyword_idstr != NULL) {
3640 free(commit_id_str);
3641 commit_id_str = keyword_idstr;
3644 error = got_repo_match_object_id(&commit_id, NULL,
3645 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3646 got_ref_list_free(&refs);
3647 free(commit_id_str);
3648 commit_id_str = NULL;
3649 if (error)
3650 goto done;
3651 error = got_object_id_str(&commit_id_str, commit_id);
3652 if (error)
3653 goto done;
3656 if (branch_name) {
3657 struct got_object_id *head_commit_id;
3658 TAILQ_FOREACH(pe, &paths, entry) {
3659 if (pe->path_len == 0)
3660 continue;
3661 error = got_error_msg(GOT_ERR_BAD_PATH,
3662 "switching between branches requires that "
3663 "the entire work tree gets updated");
3664 goto done;
3666 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3667 if (error)
3668 goto done;
3669 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3670 repo);
3671 free(head_commit_id);
3672 if (error != NULL)
3673 goto done;
3674 error = check_same_branch(commit_id, head_ref, repo);
3675 if (error)
3676 goto done;
3677 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3678 if (error)
3679 goto done;
3680 } else {
3681 error = check_linear_ancestry(commit_id,
3682 got_worktree_get_base_commit_id(worktree), 0, repo);
3683 if (error != NULL) {
3684 if (error->code == GOT_ERR_ANCESTRY)
3685 error = got_error(GOT_ERR_BRANCH_MOVED);
3686 goto done;
3688 error = check_same_branch(commit_id, head_ref, repo);
3689 if (error)
3690 goto done;
3693 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3694 commit_id) != 0) {
3695 error = got_worktree_set_base_commit_id(worktree, repo,
3696 commit_id);
3697 if (error)
3698 goto done;
3701 memset(&upa, 0, sizeof(upa));
3702 upa.verbosity = verbosity;
3703 error = got_worktree_checkout_files(worktree, &paths, repo,
3704 update_progress, &upa, check_cancelled, NULL);
3705 if (error != NULL)
3706 goto done;
3708 if (upa.did_something) {
3709 printf("Updated to %s: %s\n",
3710 got_worktree_get_head_ref_name(worktree), commit_id_str);
3711 } else
3712 printf("Already up-to-date\n");
3714 print_update_progress_stats(&upa);
3715 done:
3716 if (pack_fds) {
3717 const struct got_error *pack_err =
3718 got_repo_pack_fds_close(pack_fds);
3719 if (error == NULL)
3720 error = pack_err;
3722 if (repo) {
3723 close_err = got_repo_close(repo);
3724 if (error == NULL)
3725 error = close_err;
3727 if (worktree != NULL) {
3728 close_err = got_worktree_close(worktree);
3729 if (error == NULL)
3730 error = close_err;
3732 if (head_ref != NULL)
3733 got_ref_close(head_ref);
3734 free(worktree_path);
3735 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3736 free(commit_id);
3737 free(commit_id_str);
3738 return error;
3741 static const struct got_error *
3742 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3743 const char *path, int diff_context, int ignore_whitespace,
3744 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3745 struct got_repository *repo, FILE *outfile)
3747 const struct got_error *err = NULL;
3748 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3749 FILE *f1 = NULL, *f2 = NULL;
3750 int fd1 = -1, fd2 = -1;
3752 fd1 = got_opentempfd();
3753 if (fd1 == -1)
3754 return got_error_from_errno("got_opentempfd");
3755 fd2 = got_opentempfd();
3756 if (fd2 == -1) {
3757 err = got_error_from_errno("got_opentempfd");
3758 goto done;
3761 if (blob_id1) {
3762 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3763 fd1);
3764 if (err)
3765 goto done;
3768 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3769 if (err)
3770 goto done;
3772 f1 = got_opentemp();
3773 if (f1 == NULL) {
3774 err = got_error_from_errno("got_opentemp");
3775 goto done;
3777 f2 = got_opentemp();
3778 if (f2 == NULL) {
3779 err = got_error_from_errno("got_opentemp");
3780 goto done;
3783 while (path[0] == '/')
3784 path++;
3785 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3786 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3787 force_text_diff, dsa, outfile);
3788 done:
3789 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3790 err = got_error_from_errno("close");
3791 if (blob1)
3792 got_object_blob_close(blob1);
3793 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3794 err = got_error_from_errno("close");
3795 if (blob2)
3796 got_object_blob_close(blob2);
3797 if (f1 && fclose(f1) == EOF && err == NULL)
3798 err = got_error_from_errno("fclose");
3799 if (f2 && fclose(f2) == EOF && err == NULL)
3800 err = got_error_from_errno("fclose");
3801 return err;
3804 static const struct got_error *
3805 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3806 const char *path, int diff_context, int ignore_whitespace,
3807 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3808 struct got_repository *repo, FILE *outfile)
3810 const struct got_error *err = NULL;
3811 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3812 struct got_diff_blob_output_unidiff_arg arg;
3813 FILE *f1 = NULL, *f2 = NULL;
3814 int fd1 = -1, fd2 = -1;
3816 if (tree_id1) {
3817 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3818 if (err)
3819 goto done;
3820 fd1 = got_opentempfd();
3821 if (fd1 == -1) {
3822 err = got_error_from_errno("got_opentempfd");
3823 goto done;
3827 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3828 if (err)
3829 goto done;
3831 f1 = got_opentemp();
3832 if (f1 == NULL) {
3833 err = got_error_from_errno("got_opentemp");
3834 goto done;
3837 f2 = got_opentemp();
3838 if (f2 == NULL) {
3839 err = got_error_from_errno("got_opentemp");
3840 goto done;
3842 fd2 = got_opentempfd();
3843 if (fd2 == -1) {
3844 err = got_error_from_errno("got_opentempfd");
3845 goto done;
3847 arg.diff_context = diff_context;
3848 arg.ignore_whitespace = ignore_whitespace;
3849 arg.force_text_diff = force_text_diff;
3850 arg.diffstat = dsa;
3851 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3852 arg.outfile = outfile;
3853 arg.lines = NULL;
3854 arg.nlines = 0;
3855 while (path[0] == '/')
3856 path++;
3857 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3858 got_diff_blob_output_unidiff, &arg, 1);
3859 done:
3860 if (tree1)
3861 got_object_tree_close(tree1);
3862 if (tree2)
3863 got_object_tree_close(tree2);
3864 if (f1 && fclose(f1) == EOF && err == NULL)
3865 err = got_error_from_errno("fclose");
3866 if (f2 && fclose(f2) == EOF && err == NULL)
3867 err = got_error_from_errno("fclose");
3868 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3869 err = got_error_from_errno("close");
3870 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3871 err = got_error_from_errno("close");
3872 return err;
3875 static const struct got_error *
3876 get_changed_paths(struct got_pathlist_head *paths,
3877 struct got_commit_object *commit, struct got_repository *repo,
3878 struct got_diffstat_cb_arg *dsa)
3880 const struct got_error *err = NULL;
3881 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3882 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3883 struct got_object_qid *qid;
3884 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3885 FILE *f1 = NULL, *f2 = NULL;
3886 int fd1 = -1, fd2 = -1;
3888 if (dsa) {
3889 cb = got_diff_tree_compute_diffstat;
3891 f1 = got_opentemp();
3892 if (f1 == NULL) {
3893 err = got_error_from_errno("got_opentemp");
3894 goto done;
3896 f2 = got_opentemp();
3897 if (f2 == NULL) {
3898 err = got_error_from_errno("got_opentemp");
3899 goto done;
3901 fd1 = got_opentempfd();
3902 if (fd1 == -1) {
3903 err = got_error_from_errno("got_opentempfd");
3904 goto done;
3906 fd2 = got_opentempfd();
3907 if (fd2 == -1) {
3908 err = got_error_from_errno("got_opentempfd");
3909 goto done;
3913 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3914 if (qid != NULL) {
3915 struct got_commit_object *pcommit;
3916 err = got_object_open_as_commit(&pcommit, repo,
3917 &qid->id);
3918 if (err)
3919 return err;
3921 tree_id1 = got_object_id_dup(
3922 got_object_commit_get_tree_id(pcommit));
3923 if (tree_id1 == NULL) {
3924 got_object_commit_close(pcommit);
3925 return got_error_from_errno("got_object_id_dup");
3927 got_object_commit_close(pcommit);
3931 if (tree_id1) {
3932 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3933 if (err)
3934 goto done;
3937 tree_id2 = got_object_commit_get_tree_id(commit);
3938 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3939 if (err)
3940 goto done;
3942 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3943 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3944 done:
3945 if (tree1)
3946 got_object_tree_close(tree1);
3947 if (tree2)
3948 got_object_tree_close(tree2);
3949 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3950 err = got_error_from_errno("close");
3951 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3952 err = got_error_from_errno("close");
3953 if (f1 && fclose(f1) == EOF && err == NULL)
3954 err = got_error_from_errno("fclose");
3955 if (f2 && fclose(f2) == EOF && err == NULL)
3956 err = got_error_from_errno("fclose");
3957 free(tree_id1);
3958 return err;
3961 static const struct got_error *
3962 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3963 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3964 struct got_repository *repo, FILE *outfile)
3966 const struct got_error *err = NULL;
3967 struct got_commit_object *pcommit = NULL;
3968 char *id_str1 = NULL, *id_str2 = NULL;
3969 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3970 struct got_object_qid *qid;
3972 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3973 if (qid != NULL) {
3974 err = got_object_open_as_commit(&pcommit, repo,
3975 &qid->id);
3976 if (err)
3977 return err;
3978 err = got_object_id_str(&id_str1, &qid->id);
3979 if (err)
3980 goto done;
3983 err = got_object_id_str(&id_str2, id);
3984 if (err)
3985 goto done;
3987 if (path && path[0] != '\0') {
3988 int obj_type;
3989 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3990 if (err)
3991 goto done;
3992 if (pcommit) {
3993 err = got_object_id_by_path(&obj_id1, repo,
3994 pcommit, path);
3995 if (err) {
3996 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3997 free(obj_id2);
3998 goto done;
4002 err = got_object_get_type(&obj_type, repo, obj_id2);
4003 if (err) {
4004 free(obj_id2);
4005 goto done;
4007 fprintf(outfile,
4008 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4009 fprintf(outfile, "commit - %s\n",
4010 id_str1 ? id_str1 : "/dev/null");
4011 fprintf(outfile, "commit + %s\n", id_str2);
4012 switch (obj_type) {
4013 case GOT_OBJ_TYPE_BLOB:
4014 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4015 0, 0, dsa, repo, outfile);
4016 break;
4017 case GOT_OBJ_TYPE_TREE:
4018 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4019 0, 0, dsa, repo, outfile);
4020 break;
4021 default:
4022 err = got_error(GOT_ERR_OBJ_TYPE);
4023 break;
4025 free(obj_id1);
4026 free(obj_id2);
4027 } else {
4028 obj_id2 = got_object_commit_get_tree_id(commit);
4029 if (pcommit)
4030 obj_id1 = got_object_commit_get_tree_id(pcommit);
4031 fprintf(outfile,
4032 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4033 fprintf(outfile, "commit - %s\n",
4034 id_str1 ? id_str1 : "/dev/null");
4035 fprintf(outfile, "commit + %s\n", id_str2);
4036 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4037 dsa, repo, outfile);
4039 done:
4040 free(id_str1);
4041 free(id_str2);
4042 if (pcommit)
4043 got_object_commit_close(pcommit);
4044 return err;
4047 static char *
4048 get_datestr(time_t *time, char *datebuf)
4050 struct tm mytm, *tm;
4051 char *p, *s;
4053 tm = gmtime_r(time, &mytm);
4054 if (tm == NULL)
4055 return NULL;
4056 s = asctime_r(tm, datebuf);
4057 if (s == NULL)
4058 return NULL;
4059 p = strchr(s, '\n');
4060 if (p)
4061 *p = '\0';
4062 return s;
4065 static const struct got_error *
4066 match_commit(int *have_match, struct got_object_id *id,
4067 struct got_commit_object *commit, regex_t *regex)
4069 const struct got_error *err = NULL;
4070 regmatch_t regmatch;
4071 char *id_str = NULL, *logmsg = NULL;
4073 *have_match = 0;
4075 err = got_object_id_str(&id_str, id);
4076 if (err)
4077 return err;
4079 err = got_object_commit_get_logmsg(&logmsg, commit);
4080 if (err)
4081 goto done;
4083 if (regexec(regex, got_object_commit_get_author(commit), 1,
4084 &regmatch, 0) == 0 ||
4085 regexec(regex, got_object_commit_get_committer(commit), 1,
4086 &regmatch, 0) == 0 ||
4087 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4088 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4089 *have_match = 1;
4090 done:
4091 free(id_str);
4092 free(logmsg);
4093 return err;
4096 static void
4097 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4098 regex_t *regex)
4100 regmatch_t regmatch;
4101 struct got_pathlist_entry *pe;
4103 *have_match = 0;
4105 TAILQ_FOREACH(pe, changed_paths, entry) {
4106 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4107 *have_match = 1;
4108 break;
4113 static const struct got_error *
4114 match_patch(int *have_match, struct got_commit_object *commit,
4115 struct got_object_id *id, const char *path, int diff_context,
4116 struct got_repository *repo, regex_t *regex, FILE *f)
4118 const struct got_error *err = NULL;
4119 char *line = NULL;
4120 size_t linesize = 0;
4121 regmatch_t regmatch;
4123 *have_match = 0;
4125 err = got_opentemp_truncate(f);
4126 if (err)
4127 return err;
4129 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4130 if (err)
4131 goto done;
4133 if (fseeko(f, 0L, SEEK_SET) == -1) {
4134 err = got_error_from_errno("fseeko");
4135 goto done;
4138 while (getline(&line, &linesize, f) != -1) {
4139 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4140 *have_match = 1;
4141 break;
4144 done:
4145 free(line);
4146 return err;
4149 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4151 static const struct got_error*
4152 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4153 struct got_object_id *id, struct got_repository *repo,
4154 int local_only)
4156 static const struct got_error *err = NULL;
4157 struct got_reflist_entry *re;
4158 char *s;
4159 const char *name;
4161 *refs_str = NULL;
4163 TAILQ_FOREACH(re, refs, entry) {
4164 struct got_tag_object *tag = NULL;
4165 struct got_object_id *ref_id;
4166 int cmp;
4168 name = got_ref_get_name(re->ref);
4169 if (strcmp(name, GOT_REF_HEAD) == 0)
4170 continue;
4171 if (strncmp(name, "refs/", 5) == 0)
4172 name += 5;
4173 if (strncmp(name, "got/", 4) == 0)
4174 continue;
4175 if (strncmp(name, "heads/", 6) == 0)
4176 name += 6;
4177 if (strncmp(name, "remotes/", 8) == 0) {
4178 if (local_only)
4179 continue;
4180 name += 8;
4181 s = strstr(name, "/" GOT_REF_HEAD);
4182 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4183 continue;
4185 err = got_ref_resolve(&ref_id, repo, re->ref);
4186 if (err)
4187 break;
4188 if (strncmp(name, "tags/", 5) == 0) {
4189 err = got_object_open_as_tag(&tag, repo, ref_id);
4190 if (err) {
4191 if (err->code != GOT_ERR_OBJ_TYPE) {
4192 free(ref_id);
4193 break;
4195 /* Ref points at something other than a tag. */
4196 err = NULL;
4197 tag = NULL;
4200 cmp = got_object_id_cmp(tag ?
4201 got_object_tag_get_object_id(tag) : ref_id, id);
4202 free(ref_id);
4203 if (tag)
4204 got_object_tag_close(tag);
4205 if (cmp != 0)
4206 continue;
4207 s = *refs_str;
4208 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4209 s ? ", " : "", name) == -1) {
4210 err = got_error_from_errno("asprintf");
4211 free(s);
4212 *refs_str = NULL;
4213 break;
4215 free(s);
4218 return err;
4221 static const struct got_error *
4222 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4223 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4225 const struct got_error *err = NULL;
4226 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4227 char *comma, *s, *nl;
4228 struct got_reflist_head *refs;
4229 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4230 struct tm tm;
4231 time_t committer_time;
4233 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4234 if (refs) {
4235 err = build_refs_str(&ref_str, refs, id, repo, 1);
4236 if (err)
4237 return err;
4239 /* Display the first matching ref only. */
4240 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4241 *comma = '\0';
4244 if (ref_str == NULL) {
4245 err = got_object_id_str(&id_str, id);
4246 if (err)
4247 return err;
4250 committer_time = got_object_commit_get_committer_time(commit);
4251 if (gmtime_r(&committer_time, &tm) == NULL) {
4252 err = got_error_from_errno("gmtime_r");
4253 goto done;
4255 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4256 err = got_error(GOT_ERR_NO_SPACE);
4257 goto done;
4260 err = got_object_commit_get_logmsg(&logmsg0, commit);
4261 if (err)
4262 goto done;
4264 s = logmsg0;
4265 while (isspace((unsigned char)s[0]))
4266 s++;
4268 nl = strchr(s, '\n');
4269 if (nl) {
4270 *nl = '\0';
4273 if (ref_str)
4274 printf("%s%-7s %s\n", datebuf, ref_str, s);
4275 else
4276 printf("%s%.7s %s\n", datebuf, id_str, s);
4278 if (fflush(stdout) != 0 && err == NULL)
4279 err = got_error_from_errno("fflush");
4280 done:
4281 free(id_str);
4282 free(ref_str);
4283 free(logmsg0);
4284 return err;
4287 static const struct got_error *
4288 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4290 struct got_pathlist_entry *pe;
4292 if (header != NULL)
4293 printf("%s\n", header);
4295 TAILQ_FOREACH(pe, dsa->paths, entry) {
4296 struct got_diff_changed_path *cp = pe->data;
4297 int pad = dsa->max_path_len - pe->path_len + 1;
4299 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4300 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4302 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4303 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4304 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4306 if (fflush(stdout) != 0)
4307 return got_error_from_errno("fflush");
4309 return NULL;
4312 static const struct got_error *
4313 printfile(FILE *f)
4315 char buf[8192];
4316 size_t r;
4318 if (fseeko(f, 0L, SEEK_SET) == -1)
4319 return got_error_from_errno("fseek");
4321 for (;;) {
4322 r = fread(buf, 1, sizeof(buf), f);
4323 if (r == 0) {
4324 if (ferror(f))
4325 return got_error_from_errno("fread");
4326 if (feof(f))
4327 break;
4329 if (fwrite(buf, 1, r, stdout) != r)
4330 return got_ferror(stdout, GOT_ERR_IO);
4333 return NULL;
4336 static const struct got_error *
4337 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4338 struct got_repository *repo, const char *path,
4339 struct got_pathlist_head *changed_paths,
4340 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4341 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4342 const char *prefix)
4344 const struct got_error *err = NULL;
4345 FILE *f = NULL;
4346 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4347 char datebuf[26];
4348 time_t committer_time;
4349 const char *author, *committer;
4350 char *refs_str = NULL;
4352 err = got_object_id_str(&id_str, id);
4353 if (err)
4354 return err;
4356 if (custom_refs_str == NULL) {
4357 struct got_reflist_head *refs;
4358 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4359 if (refs) {
4360 err = build_refs_str(&refs_str, refs, id, repo, 0);
4361 if (err)
4362 goto done;
4366 printf(GOT_COMMIT_SEP_STR);
4367 if (custom_refs_str)
4368 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4369 custom_refs_str);
4370 else
4371 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4372 refs_str ? " (" : "", refs_str ? refs_str : "",
4373 refs_str ? ")" : "");
4374 free(id_str);
4375 id_str = NULL;
4376 free(refs_str);
4377 refs_str = NULL;
4378 printf("from: %s\n", got_object_commit_get_author(commit));
4379 author = got_object_commit_get_author(commit);
4380 committer = got_object_commit_get_committer(commit);
4381 if (strcmp(author, committer) != 0)
4382 printf("via: %s\n", committer);
4383 committer_time = got_object_commit_get_committer_time(commit);
4384 datestr = get_datestr(&committer_time, datebuf);
4385 if (datestr)
4386 printf("date: %s UTC\n", datestr);
4387 if (got_object_commit_get_nparents(commit) > 1) {
4388 const struct got_object_id_queue *parent_ids;
4389 struct got_object_qid *qid;
4390 int n = 1;
4391 parent_ids = got_object_commit_get_parent_ids(commit);
4392 STAILQ_FOREACH(qid, parent_ids, entry) {
4393 err = got_object_id_str(&id_str, &qid->id);
4394 if (err)
4395 goto done;
4396 printf("parent %d: %s\n", n++, id_str);
4397 free(id_str);
4398 id_str = NULL;
4402 err = got_object_commit_get_logmsg(&logmsg0, commit);
4403 if (err)
4404 goto done;
4406 logmsg = logmsg0;
4407 do {
4408 line = strsep(&logmsg, "\n");
4409 if (line)
4410 printf(" %s\n", line);
4411 } while (line);
4412 free(logmsg0);
4414 if (changed_paths && diffstat == NULL) {
4415 struct got_pathlist_entry *pe;
4417 TAILQ_FOREACH(pe, changed_paths, entry) {
4418 struct got_diff_changed_path *cp = pe->data;
4420 printf(" %c %s\n", cp->status, pe->path);
4422 printf("\n");
4424 if (show_patch) {
4425 if (diffstat) {
4426 f = got_opentemp();
4427 if (f == NULL) {
4428 err = got_error_from_errno("got_opentemp");
4429 goto done;
4433 err = print_patch(commit, id, path, diff_context, diffstat,
4434 repo, diffstat == NULL ? stdout : f);
4435 if (err)
4436 goto done;
4438 if (diffstat) {
4439 err = print_diffstat(diffstat, NULL);
4440 if (err)
4441 goto done;
4442 if (show_patch) {
4443 err = printfile(f);
4444 if (err)
4445 goto done;
4448 if (show_patch)
4449 printf("\n");
4451 if (fflush(stdout) != 0 && err == NULL)
4452 err = got_error_from_errno("fflush");
4453 done:
4454 if (f && fclose(f) == EOF && err == NULL)
4455 err = got_error_from_errno("fclose");
4456 free(id_str);
4457 free(refs_str);
4458 return err;
4461 static const struct got_error *
4462 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4463 struct got_repository *repo, const char *path, int show_changed_paths,
4464 int show_diffstat, int show_patch, const char *search_pattern,
4465 int diff_context, int limit, int log_branches, int reverse_display_order,
4466 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4467 FILE *tmpfile)
4469 const struct got_error *err;
4470 struct got_commit_graph *graph;
4471 regex_t regex;
4472 int have_match;
4473 struct got_object_id_queue reversed_commits;
4474 struct got_object_qid *qid;
4475 struct got_commit_object *commit;
4476 struct got_pathlist_head changed_paths;
4478 STAILQ_INIT(&reversed_commits);
4479 TAILQ_INIT(&changed_paths);
4481 if (search_pattern && regcomp(&regex, search_pattern,
4482 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4483 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4485 err = got_commit_graph_open(&graph, path, !log_branches);
4486 if (err)
4487 return err;
4488 if (log_branches && toposort) {
4489 err = got_commit_graph_toposort(graph, root_id, repo,
4490 check_cancelled, NULL);
4491 } else {
4492 err = got_commit_graph_bfsort(graph, root_id, repo,
4493 check_cancelled, NULL);
4495 if (err)
4496 goto done;
4497 for (;;) {
4498 struct got_object_id id;
4499 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4500 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4502 if (sigint_received || sigpipe_received)
4503 break;
4505 err = got_commit_graph_iter_next(&id, graph, repo,
4506 check_cancelled, NULL);
4507 if (err) {
4508 if (err->code == GOT_ERR_ITER_COMPLETED)
4509 err = NULL;
4510 break;
4513 err = got_object_open_as_commit(&commit, repo, &id);
4514 if (err)
4515 break;
4517 if (((show_changed_paths && !show_diffstat) ||
4518 (show_diffstat && !show_patch))
4519 && !reverse_display_order) {
4520 err = get_changed_paths(&changed_paths, commit, repo,
4521 show_diffstat ? &dsa : NULL);
4522 if (err)
4523 break;
4526 if (search_pattern) {
4527 err = match_commit(&have_match, &id, commit, &regex);
4528 if (err) {
4529 got_object_commit_close(commit);
4530 break;
4532 if (have_match == 0 && show_changed_paths)
4533 match_changed_paths(&have_match,
4534 &changed_paths, &regex);
4535 if (have_match == 0 && show_patch) {
4536 err = match_patch(&have_match, commit, &id,
4537 path, diff_context, repo, &regex, tmpfile);
4538 if (err)
4539 break;
4541 if (have_match == 0) {
4542 got_object_commit_close(commit);
4543 got_pathlist_free(&changed_paths,
4544 GOT_PATHLIST_FREE_ALL);
4545 continue;
4549 if (reverse_display_order) {
4550 err = got_object_qid_alloc(&qid, &id);
4551 if (err)
4552 break;
4553 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4554 got_object_commit_close(commit);
4555 } else {
4556 if (one_line)
4557 err = print_commit_oneline(commit, &id,
4558 repo, refs_idmap);
4559 else
4560 err = print_commit(commit, &id, repo, path,
4561 (show_changed_paths || show_diffstat) ?
4562 &changed_paths : NULL,
4563 show_diffstat ? &dsa : NULL, show_patch,
4564 diff_context, refs_idmap, NULL, NULL);
4565 got_object_commit_close(commit);
4566 if (err)
4567 break;
4569 if ((limit && --limit == 0) ||
4570 (end_id && got_object_id_cmp(&id, end_id) == 0))
4571 break;
4573 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4575 if (reverse_display_order) {
4576 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4577 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4578 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4580 err = got_object_open_as_commit(&commit, repo,
4581 &qid->id);
4582 if (err)
4583 break;
4584 if ((show_changed_paths && !show_diffstat) ||
4585 (show_diffstat && !show_patch)) {
4586 err = get_changed_paths(&changed_paths, commit,
4587 repo, show_diffstat ? &dsa : NULL);
4588 if (err)
4589 break;
4591 if (one_line)
4592 err = print_commit_oneline(commit, &qid->id,
4593 repo, refs_idmap);
4594 else
4595 err = print_commit(commit, &qid->id, repo, path,
4596 (show_changed_paths || show_diffstat) ?
4597 &changed_paths : NULL,
4598 show_diffstat ? &dsa : NULL, show_patch,
4599 diff_context, refs_idmap, NULL, NULL);
4600 got_object_commit_close(commit);
4601 if (err)
4602 break;
4603 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4606 done:
4607 while (!STAILQ_EMPTY(&reversed_commits)) {
4608 qid = STAILQ_FIRST(&reversed_commits);
4609 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4610 got_object_qid_free(qid);
4612 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4613 if (search_pattern)
4614 regfree(&regex);
4615 got_commit_graph_close(graph);
4616 return err;
4619 __dead static void
4620 usage_log(void)
4622 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4623 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4624 "[path]\n", getprogname());
4625 exit(1);
4628 static int
4629 get_default_log_limit(void)
4631 const char *got_default_log_limit;
4632 long long n;
4633 const char *errstr;
4635 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4636 if (got_default_log_limit == NULL)
4637 return 0;
4638 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4639 if (errstr != NULL)
4640 return 0;
4641 return n;
4644 static const struct got_error *
4645 cmd_log(int argc, char *argv[])
4647 const struct got_error *error;
4648 struct got_repository *repo = NULL;
4649 struct got_worktree *worktree = NULL;
4650 struct got_object_id *start_id = NULL, *end_id = NULL;
4651 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4652 char *keyword_idstr = NULL;
4653 const char *start_commit = NULL, *end_commit = NULL;
4654 const char *search_pattern = NULL;
4655 int diff_context = -1, ch;
4656 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4657 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4658 int toposort = 0;
4659 const char *errstr;
4660 struct got_reflist_head refs;
4661 struct got_reflist_object_id_map *refs_idmap = NULL;
4662 FILE *tmpfile = NULL;
4663 int *pack_fds = NULL;
4665 TAILQ_INIT(&refs);
4667 #ifndef PROFILE
4668 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4669 NULL)
4670 == -1)
4671 err(1, "pledge");
4672 #endif
4674 limit = get_default_log_limit();
4676 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4677 switch (ch) {
4678 case 'b':
4679 log_branches = 1;
4680 break;
4681 case 'C':
4682 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4683 &errstr);
4684 if (errstr != NULL)
4685 errx(1, "number of context lines is %s: %s",
4686 errstr, optarg);
4687 break;
4688 case 'c':
4689 start_commit = optarg;
4690 break;
4691 case 'd':
4692 show_diffstat = 1;
4693 break;
4694 case 'l':
4695 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4696 if (errstr != NULL)
4697 errx(1, "number of commits is %s: %s",
4698 errstr, optarg);
4699 break;
4700 case 'P':
4701 show_changed_paths = 1;
4702 break;
4703 case 'p':
4704 show_patch = 1;
4705 break;
4706 case 'R':
4707 reverse_display_order = 1;
4708 break;
4709 case 'r':
4710 repo_path = realpath(optarg, NULL);
4711 if (repo_path == NULL)
4712 return got_error_from_errno2("realpath",
4713 optarg);
4714 got_path_strip_trailing_slashes(repo_path);
4715 break;
4716 case 'S':
4717 search_pattern = optarg;
4718 break;
4719 case 's':
4720 one_line = 1;
4721 break;
4722 case 't':
4723 toposort = 1;
4724 break;
4725 case 'x':
4726 end_commit = optarg;
4727 break;
4728 default:
4729 usage_log();
4730 /* NOTREACHED */
4734 argc -= optind;
4735 argv += optind;
4737 if (diff_context == -1)
4738 diff_context = 3;
4739 else if (!show_patch)
4740 errx(1, "-C requires -p");
4742 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4743 errx(1, "cannot use -s with -d, -p or -P");
4745 cwd = getcwd(NULL, 0);
4746 if (cwd == NULL) {
4747 error = got_error_from_errno("getcwd");
4748 goto done;
4751 error = got_repo_pack_fds_open(&pack_fds);
4752 if (error != NULL)
4753 goto done;
4755 if (repo_path == NULL) {
4756 error = got_worktree_open(&worktree, cwd,
4757 GOT_WORKTREE_GOT_DIR);
4758 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4759 goto done;
4760 error = NULL;
4763 if (argc == 1) {
4764 if (worktree) {
4765 error = got_worktree_resolve_path(&path, worktree,
4766 argv[0]);
4767 if (error)
4768 goto done;
4769 } else {
4770 path = strdup(argv[0]);
4771 if (path == NULL) {
4772 error = got_error_from_errno("strdup");
4773 goto done;
4776 } else if (argc != 0)
4777 usage_log();
4779 if (repo_path == NULL) {
4780 repo_path = worktree ?
4781 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4783 if (repo_path == NULL) {
4784 error = got_error_from_errno("strdup");
4785 goto done;
4788 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4789 if (error != NULL)
4790 goto done;
4792 error = apply_unveil(got_repo_get_path(repo), 1,
4793 worktree ? got_worktree_get_root_path(worktree) : NULL);
4794 if (error)
4795 goto done;
4797 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4798 if (error)
4799 goto done;
4801 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4802 if (error)
4803 goto done;
4805 if (start_commit == NULL) {
4806 struct got_reference *head_ref;
4807 struct got_commit_object *commit = NULL;
4808 error = got_ref_open(&head_ref, repo,
4809 worktree ? got_worktree_get_head_ref_name(worktree)
4810 : GOT_REF_HEAD, 0);
4811 if (error != NULL)
4812 goto done;
4813 error = got_ref_resolve(&start_id, repo, head_ref);
4814 got_ref_close(head_ref);
4815 if (error != NULL)
4816 goto done;
4817 error = got_object_open_as_commit(&commit, repo,
4818 start_id);
4819 if (error != NULL)
4820 goto done;
4821 got_object_commit_close(commit);
4822 } else {
4823 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4824 repo, worktree);
4825 if (error != NULL)
4826 goto done;
4827 if (keyword_idstr != NULL)
4828 start_commit = keyword_idstr;
4830 error = got_repo_match_object_id(&start_id, NULL,
4831 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4832 if (error != NULL)
4833 goto done;
4835 if (end_commit != NULL) {
4836 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4837 repo, worktree);
4838 if (error != NULL)
4839 goto done;
4840 if (keyword_idstr != NULL)
4841 end_commit = keyword_idstr;
4843 error = got_repo_match_object_id(&end_id, NULL,
4844 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4845 if (error != NULL)
4846 goto done;
4849 if (worktree) {
4851 * If a path was specified on the command line it was resolved
4852 * to a path in the work tree above. Prepend the work tree's
4853 * path prefix to obtain the corresponding in-repository path.
4855 if (path) {
4856 const char *prefix;
4857 prefix = got_worktree_get_path_prefix(worktree);
4858 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4859 (path[0] != '\0') ? "/" : "", path) == -1) {
4860 error = got_error_from_errno("asprintf");
4861 goto done;
4864 } else
4865 error = got_repo_map_path(&in_repo_path, repo,
4866 path ? path : "");
4867 if (error != NULL)
4868 goto done;
4869 if (in_repo_path) {
4870 free(path);
4871 path = in_repo_path;
4874 if (worktree) {
4875 /* Release work tree lock. */
4876 got_worktree_close(worktree);
4877 worktree = NULL;
4880 if (search_pattern && show_patch) {
4881 tmpfile = got_opentemp();
4882 if (tmpfile == NULL) {
4883 error = got_error_from_errno("got_opentemp");
4884 goto done;
4888 error = print_commits(start_id, end_id, repo, path ? path : "",
4889 show_changed_paths, show_diffstat, show_patch, search_pattern,
4890 diff_context, limit, log_branches, reverse_display_order,
4891 refs_idmap, one_line, toposort, tmpfile);
4892 done:
4893 free(path);
4894 free(repo_path);
4895 free(cwd);
4896 free(start_id);
4897 free(end_id);
4898 free(keyword_idstr);
4899 if (worktree)
4900 got_worktree_close(worktree);
4901 if (repo) {
4902 const struct got_error *close_err = got_repo_close(repo);
4903 if (error == NULL)
4904 error = close_err;
4906 if (pack_fds) {
4907 const struct got_error *pack_err =
4908 got_repo_pack_fds_close(pack_fds);
4909 if (error == NULL)
4910 error = pack_err;
4912 if (refs_idmap)
4913 got_reflist_object_id_map_free(refs_idmap);
4914 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4915 error = got_error_from_errno("fclose");
4916 got_ref_list_free(&refs);
4917 return error;
4920 __dead static void
4921 usage_diff(void)
4923 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4924 "[-r repository-path] [object1 object2 | path ...]\n",
4925 getprogname());
4926 exit(1);
4929 struct print_diff_arg {
4930 struct got_repository *repo;
4931 struct got_worktree *worktree;
4932 struct got_diffstat_cb_arg *diffstat;
4933 int diff_context;
4934 const char *id_str;
4935 int header_shown;
4936 int diff_staged;
4937 enum got_diff_algorithm diff_algo;
4938 int ignore_whitespace;
4939 int force_text_diff;
4940 FILE *f1;
4941 FILE *f2;
4942 FILE *outfile;
4946 * Create a file which contains the target path of a symlink so we can feed
4947 * it as content to the diff engine.
4949 static const struct got_error *
4950 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4951 const char *abspath)
4953 const struct got_error *err = NULL;
4954 char target_path[PATH_MAX];
4955 ssize_t target_len, outlen;
4957 *fd = -1;
4959 if (dirfd != -1) {
4960 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4961 if (target_len == -1)
4962 return got_error_from_errno2("readlinkat", abspath);
4963 } else {
4964 target_len = readlink(abspath, target_path, PATH_MAX);
4965 if (target_len == -1)
4966 return got_error_from_errno2("readlink", abspath);
4969 *fd = got_opentempfd();
4970 if (*fd == -1)
4971 return got_error_from_errno("got_opentempfd");
4973 outlen = write(*fd, target_path, target_len);
4974 if (outlen == -1) {
4975 err = got_error_from_errno("got_opentempfd");
4976 goto done;
4979 if (lseek(*fd, 0, SEEK_SET) == -1) {
4980 err = got_error_from_errno2("lseek", abspath);
4981 goto done;
4983 done:
4984 if (err) {
4985 close(*fd);
4986 *fd = -1;
4988 return err;
4991 static const struct got_error *
4992 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4993 const char *path, struct got_object_id *blob_id,
4994 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4995 int dirfd, const char *de_name)
4997 struct print_diff_arg *a = arg;
4998 const struct got_error *err = NULL;
4999 struct got_blob_object *blob1 = NULL;
5000 int fd = -1, fd1 = -1, fd2 = -1;
5001 FILE *f2 = NULL;
5002 char *abspath = NULL, *label1 = NULL;
5003 struct stat sb;
5004 off_t size1 = 0;
5005 int f2_exists = 0;
5007 memset(&sb, 0, sizeof(sb));
5009 if (a->diff_staged) {
5010 if (staged_status != GOT_STATUS_MODIFY &&
5011 staged_status != GOT_STATUS_ADD &&
5012 staged_status != GOT_STATUS_DELETE)
5013 return NULL;
5014 } else {
5015 if (staged_status == GOT_STATUS_DELETE)
5016 return NULL;
5017 if (status == GOT_STATUS_NONEXISTENT)
5018 return got_error_set_errno(ENOENT, path);
5019 if (status != GOT_STATUS_MODIFY &&
5020 status != GOT_STATUS_ADD &&
5021 status != GOT_STATUS_DELETE &&
5022 status != GOT_STATUS_CONFLICT)
5023 return NULL;
5026 err = got_opentemp_truncate(a->f1);
5027 if (err)
5028 return got_error_from_errno("got_opentemp_truncate");
5029 err = got_opentemp_truncate(a->f2);
5030 if (err)
5031 return got_error_from_errno("got_opentemp_truncate");
5033 if (!a->header_shown) {
5034 if (fprintf(a->outfile, "diff %s%s\n",
5035 a->diff_staged ? "-s " : "",
5036 got_worktree_get_root_path(a->worktree)) < 0) {
5037 err = got_error_from_errno("fprintf");
5038 goto done;
5040 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5041 err = got_error_from_errno("fprintf");
5042 goto done;
5044 if (fprintf(a->outfile, "path + %s%s\n",
5045 got_worktree_get_root_path(a->worktree),
5046 a->diff_staged ? " (staged changes)" : "") < 0) {
5047 err = got_error_from_errno("fprintf");
5048 goto done;
5050 a->header_shown = 1;
5053 if (a->diff_staged) {
5054 const char *label1 = NULL, *label2 = NULL;
5055 switch (staged_status) {
5056 case GOT_STATUS_MODIFY:
5057 label1 = path;
5058 label2 = path;
5059 break;
5060 case GOT_STATUS_ADD:
5061 label2 = path;
5062 break;
5063 case GOT_STATUS_DELETE:
5064 label1 = path;
5065 break;
5066 default:
5067 return got_error(GOT_ERR_FILE_STATUS);
5069 fd1 = got_opentempfd();
5070 if (fd1 == -1) {
5071 err = got_error_from_errno("got_opentempfd");
5072 goto done;
5074 fd2 = got_opentempfd();
5075 if (fd2 == -1) {
5076 err = got_error_from_errno("got_opentempfd");
5077 goto done;
5079 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5080 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5081 a->diff_algo, a->diff_context, a->ignore_whitespace,
5082 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5083 goto done;
5086 fd1 = got_opentempfd();
5087 if (fd1 == -1) {
5088 err = got_error_from_errno("got_opentempfd");
5089 goto done;
5092 if (staged_status == GOT_STATUS_ADD ||
5093 staged_status == GOT_STATUS_MODIFY) {
5094 char *id_str;
5095 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5096 8192, fd1);
5097 if (err)
5098 goto done;
5099 err = got_object_id_str(&id_str, staged_blob_id);
5100 if (err)
5101 goto done;
5102 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5103 err = got_error_from_errno("asprintf");
5104 free(id_str);
5105 goto done;
5107 free(id_str);
5108 } else if (status != GOT_STATUS_ADD) {
5109 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5110 fd1);
5111 if (err)
5112 goto done;
5115 if (status != GOT_STATUS_DELETE) {
5116 if (asprintf(&abspath, "%s/%s",
5117 got_worktree_get_root_path(a->worktree), path) == -1) {
5118 err = got_error_from_errno("asprintf");
5119 goto done;
5122 if (dirfd != -1) {
5123 fd = openat(dirfd, de_name,
5124 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5125 if (fd == -1) {
5126 if (!got_err_open_nofollow_on_symlink()) {
5127 err = got_error_from_errno2("openat",
5128 abspath);
5129 goto done;
5131 err = get_symlink_target_file(&fd, dirfd,
5132 de_name, abspath);
5133 if (err)
5134 goto done;
5136 } else {
5137 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5138 if (fd == -1) {
5139 if (!got_err_open_nofollow_on_symlink()) {
5140 err = got_error_from_errno2("open",
5141 abspath);
5142 goto done;
5144 err = get_symlink_target_file(&fd, dirfd,
5145 de_name, abspath);
5146 if (err)
5147 goto done;
5150 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5151 err = got_error_from_errno2("fstatat", abspath);
5152 goto done;
5154 f2 = fdopen(fd, "r");
5155 if (f2 == NULL) {
5156 err = got_error_from_errno2("fdopen", abspath);
5157 goto done;
5159 fd = -1;
5160 f2_exists = 1;
5163 if (blob1) {
5164 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5165 a->f1, blob1);
5166 if (err)
5167 goto done;
5170 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5171 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5172 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5173 done:
5174 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5175 err = got_error_from_errno("close");
5176 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5177 err = got_error_from_errno("close");
5178 if (blob1)
5179 got_object_blob_close(blob1);
5180 if (fd != -1 && close(fd) == -1 && err == NULL)
5181 err = got_error_from_errno("close");
5182 if (f2 && fclose(f2) == EOF && err == NULL)
5183 err = got_error_from_errno("fclose");
5184 free(abspath);
5185 return err;
5188 static const struct got_error *
5189 cmd_diff(int argc, char *argv[])
5191 const struct got_error *error;
5192 struct got_repository *repo = NULL;
5193 struct got_worktree *worktree = NULL;
5194 char *cwd = NULL, *repo_path = NULL;
5195 const char *commit_args[2] = { NULL, NULL };
5196 int ncommit_args = 0;
5197 struct got_object_id *ids[2] = { NULL, NULL };
5198 char *labels[2] = { NULL, NULL };
5199 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5200 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5201 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5202 const char *errstr;
5203 struct got_reflist_head refs;
5204 struct got_pathlist_head diffstat_paths, paths;
5205 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5206 int fd1 = -1, fd2 = -1;
5207 int *pack_fds = NULL;
5208 struct got_diffstat_cb_arg dsa;
5210 memset(&dsa, 0, sizeof(dsa));
5212 TAILQ_INIT(&refs);
5213 TAILQ_INIT(&paths);
5214 TAILQ_INIT(&diffstat_paths);
5216 #ifndef PROFILE
5217 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5218 NULL) == -1)
5219 err(1, "pledge");
5220 #endif
5222 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5223 switch (ch) {
5224 case 'a':
5225 force_text_diff = 1;
5226 break;
5227 case 'C':
5228 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5229 &errstr);
5230 if (errstr != NULL)
5231 errx(1, "number of context lines is %s: %s",
5232 errstr, optarg);
5233 break;
5234 case 'c':
5235 if (ncommit_args >= 2)
5236 errx(1, "too many -c options used");
5237 commit_args[ncommit_args++] = optarg;
5238 break;
5239 case 'd':
5240 show_diffstat = 1;
5241 break;
5242 case 'P':
5243 force_path = 1;
5244 break;
5245 case 'r':
5246 repo_path = realpath(optarg, NULL);
5247 if (repo_path == NULL)
5248 return got_error_from_errno2("realpath",
5249 optarg);
5250 got_path_strip_trailing_slashes(repo_path);
5251 rflag = 1;
5252 break;
5253 case 's':
5254 diff_staged = 1;
5255 break;
5256 case 'w':
5257 ignore_whitespace = 1;
5258 break;
5259 default:
5260 usage_diff();
5261 /* NOTREACHED */
5265 argc -= optind;
5266 argv += optind;
5268 cwd = getcwd(NULL, 0);
5269 if (cwd == NULL) {
5270 error = got_error_from_errno("getcwd");
5271 goto done;
5274 error = got_repo_pack_fds_open(&pack_fds);
5275 if (error != NULL)
5276 goto done;
5278 if (repo_path == NULL) {
5279 error = got_worktree_open(&worktree, cwd,
5280 GOT_WORKTREE_GOT_DIR);
5281 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5282 goto done;
5283 else
5284 error = NULL;
5285 if (worktree) {
5286 repo_path =
5287 strdup(got_worktree_get_repo_path(worktree));
5288 if (repo_path == NULL) {
5289 error = got_error_from_errno("strdup");
5290 goto done;
5292 } else {
5293 repo_path = strdup(cwd);
5294 if (repo_path == NULL) {
5295 error = got_error_from_errno("strdup");
5296 goto done;
5301 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5302 free(repo_path);
5303 if (error != NULL)
5304 goto done;
5306 if (show_diffstat) {
5307 dsa.paths = &diffstat_paths;
5308 dsa.force_text = force_text_diff;
5309 dsa.ignore_ws = ignore_whitespace;
5310 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5313 if (rflag || worktree == NULL || ncommit_args > 0) {
5314 if (force_path) {
5315 error = got_error_msg(GOT_ERR_NOT_IMPL,
5316 "-P option can only be used when diffing "
5317 "a work tree");
5318 goto done;
5320 if (diff_staged) {
5321 error = got_error_msg(GOT_ERR_NOT_IMPL,
5322 "-s option can only be used when diffing "
5323 "a work tree");
5324 goto done;
5328 error = apply_unveil(got_repo_get_path(repo), 1,
5329 worktree ? got_worktree_get_root_path(worktree) : NULL);
5330 if (error)
5331 goto done;
5333 if ((!force_path && argc == 2) || ncommit_args > 0) {
5334 int obj_type = (ncommit_args > 0 ?
5335 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5336 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5337 NULL);
5338 if (error)
5339 goto done;
5340 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5341 const char *arg;
5342 char *keyword_idstr = NULL;
5344 if (ncommit_args > 0)
5345 arg = commit_args[i];
5346 else
5347 arg = argv[i];
5349 error = got_keyword_to_idstr(&keyword_idstr, arg,
5350 repo, worktree);
5351 if (error != NULL)
5352 goto done;
5353 if (keyword_idstr != NULL)
5354 arg = keyword_idstr;
5356 error = got_repo_match_object_id(&ids[i], &labels[i],
5357 arg, obj_type, &refs, repo);
5358 free(keyword_idstr);
5359 if (error) {
5360 if (error->code != GOT_ERR_NOT_REF &&
5361 error->code != GOT_ERR_NO_OBJ)
5362 goto done;
5363 if (ncommit_args > 0)
5364 goto done;
5365 error = NULL;
5366 break;
5371 f1 = got_opentemp();
5372 if (f1 == NULL) {
5373 error = got_error_from_errno("got_opentemp");
5374 goto done;
5377 f2 = got_opentemp();
5378 if (f2 == NULL) {
5379 error = got_error_from_errno("got_opentemp");
5380 goto done;
5383 outfile = got_opentemp();
5384 if (outfile == NULL) {
5385 error = got_error_from_errno("got_opentemp");
5386 goto done;
5389 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5390 struct print_diff_arg arg;
5391 char *id_str;
5393 if (worktree == NULL) {
5394 if (argc == 2 && ids[0] == NULL) {
5395 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5396 goto done;
5397 } else if (argc == 2 && ids[1] == NULL) {
5398 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5399 goto done;
5400 } else if (argc > 0) {
5401 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5402 "%s", "specified paths cannot be resolved");
5403 goto done;
5404 } else {
5405 error = got_error(GOT_ERR_NOT_WORKTREE);
5406 goto done;
5410 error = get_worktree_paths_from_argv(&paths, argc, argv,
5411 worktree);
5412 if (error)
5413 goto done;
5415 error = got_object_id_str(&id_str,
5416 got_worktree_get_base_commit_id(worktree));
5417 if (error)
5418 goto done;
5419 arg.repo = repo;
5420 arg.worktree = worktree;
5421 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5422 arg.diff_context = diff_context;
5423 arg.id_str = id_str;
5424 arg.header_shown = 0;
5425 arg.diff_staged = diff_staged;
5426 arg.ignore_whitespace = ignore_whitespace;
5427 arg.force_text_diff = force_text_diff;
5428 arg.diffstat = show_diffstat ? &dsa : NULL;
5429 arg.f1 = f1;
5430 arg.f2 = f2;
5431 arg.outfile = outfile;
5433 error = got_worktree_status(worktree, &paths, repo, 0,
5434 print_diff, &arg, check_cancelled, NULL);
5435 free(id_str);
5436 if (error)
5437 goto done;
5439 if (show_diffstat && dsa.nfiles > 0) {
5440 char *header;
5442 if (asprintf(&header, "diffstat %s%s",
5443 diff_staged ? "-s " : "",
5444 got_worktree_get_root_path(worktree)) == -1) {
5445 error = got_error_from_errno("asprintf");
5446 goto done;
5449 error = print_diffstat(&dsa, header);
5450 free(header);
5451 if (error)
5452 goto done;
5455 error = printfile(outfile);
5456 goto done;
5459 if (ncommit_args == 1) {
5460 struct got_commit_object *commit;
5461 error = got_object_open_as_commit(&commit, repo, ids[0]);
5462 if (error)
5463 goto done;
5465 labels[1] = labels[0];
5466 ids[1] = ids[0];
5467 if (got_object_commit_get_nparents(commit) > 0) {
5468 const struct got_object_id_queue *pids;
5469 struct got_object_qid *pid;
5470 pids = got_object_commit_get_parent_ids(commit);
5471 pid = STAILQ_FIRST(pids);
5472 ids[0] = got_object_id_dup(&pid->id);
5473 if (ids[0] == NULL) {
5474 error = got_error_from_errno(
5475 "got_object_id_dup");
5476 got_object_commit_close(commit);
5477 goto done;
5479 error = got_object_id_str(&labels[0], ids[0]);
5480 if (error) {
5481 got_object_commit_close(commit);
5482 goto done;
5484 } else {
5485 ids[0] = NULL;
5486 labels[0] = strdup("/dev/null");
5487 if (labels[0] == NULL) {
5488 error = got_error_from_errno("strdup");
5489 got_object_commit_close(commit);
5490 goto done;
5494 got_object_commit_close(commit);
5497 if (ncommit_args == 0 && argc > 2) {
5498 error = got_error_msg(GOT_ERR_BAD_PATH,
5499 "path arguments cannot be used when diffing two objects");
5500 goto done;
5503 if (ids[0]) {
5504 error = got_object_get_type(&type1, repo, ids[0]);
5505 if (error)
5506 goto done;
5509 error = got_object_get_type(&type2, repo, ids[1]);
5510 if (error)
5511 goto done;
5512 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5513 error = got_error(GOT_ERR_OBJ_TYPE);
5514 goto done;
5516 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5517 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5518 "path arguments cannot be used when diffing blobs");
5519 goto done;
5522 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5523 char *in_repo_path;
5524 struct got_pathlist_entry *new;
5525 if (worktree) {
5526 const char *prefix;
5527 char *p;
5528 error = got_worktree_resolve_path(&p, worktree,
5529 argv[i]);
5530 if (error)
5531 goto done;
5532 prefix = got_worktree_get_path_prefix(worktree);
5533 while (prefix[0] == '/')
5534 prefix++;
5535 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5536 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5537 p) == -1) {
5538 error = got_error_from_errno("asprintf");
5539 free(p);
5540 goto done;
5542 free(p);
5543 } else {
5544 char *mapped_path, *s;
5545 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5546 if (error)
5547 goto done;
5548 s = mapped_path;
5549 while (s[0] == '/')
5550 s++;
5551 in_repo_path = strdup(s);
5552 if (in_repo_path == NULL) {
5553 error = got_error_from_errno("asprintf");
5554 free(mapped_path);
5555 goto done;
5557 free(mapped_path);
5560 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5561 if (error || new == NULL /* duplicate */)
5562 free(in_repo_path);
5563 if (error)
5564 goto done;
5567 if (worktree) {
5568 /* Release work tree lock. */
5569 got_worktree_close(worktree);
5570 worktree = NULL;
5573 fd1 = got_opentempfd();
5574 if (fd1 == -1) {
5575 error = got_error_from_errno("got_opentempfd");
5576 goto done;
5579 fd2 = got_opentempfd();
5580 if (fd2 == -1) {
5581 error = got_error_from_errno("got_opentempfd");
5582 goto done;
5585 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5586 case GOT_OBJ_TYPE_BLOB:
5587 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5588 fd1, fd2, ids[0], ids[1], NULL, NULL,
5589 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5590 ignore_whitespace, force_text_diff,
5591 show_diffstat ? &dsa : NULL, repo, outfile);
5592 break;
5593 case GOT_OBJ_TYPE_TREE:
5594 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5595 ids[0], ids[1], &paths, "", "",
5596 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5597 ignore_whitespace, force_text_diff,
5598 show_diffstat ? &dsa : NULL, repo, outfile);
5599 break;
5600 case GOT_OBJ_TYPE_COMMIT:
5601 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5602 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5603 fd1, fd2, ids[0], ids[1], &paths,
5604 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5605 ignore_whitespace, force_text_diff,
5606 show_diffstat ? &dsa : NULL, repo, outfile);
5607 break;
5608 default:
5609 error = got_error(GOT_ERR_OBJ_TYPE);
5611 if (error)
5612 goto done;
5614 if (show_diffstat && dsa.nfiles > 0) {
5615 char *header = NULL;
5617 if (asprintf(&header, "diffstat %s %s",
5618 labels[0], labels[1]) == -1) {
5619 error = got_error_from_errno("asprintf");
5620 goto done;
5623 error = print_diffstat(&dsa, header);
5624 free(header);
5625 if (error)
5626 goto done;
5629 error = printfile(outfile);
5631 done:
5632 free(labels[0]);
5633 free(labels[1]);
5634 free(ids[0]);
5635 free(ids[1]);
5636 if (worktree)
5637 got_worktree_close(worktree);
5638 if (repo) {
5639 const struct got_error *close_err = got_repo_close(repo);
5640 if (error == NULL)
5641 error = close_err;
5643 if (pack_fds) {
5644 const struct got_error *pack_err =
5645 got_repo_pack_fds_close(pack_fds);
5646 if (error == NULL)
5647 error = pack_err;
5649 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5650 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5651 got_ref_list_free(&refs);
5652 if (outfile && fclose(outfile) == EOF && error == NULL)
5653 error = got_error_from_errno("fclose");
5654 if (f1 && fclose(f1) == EOF && error == NULL)
5655 error = got_error_from_errno("fclose");
5656 if (f2 && fclose(f2) == EOF && error == NULL)
5657 error = got_error_from_errno("fclose");
5658 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5659 error = got_error_from_errno("close");
5660 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5661 error = got_error_from_errno("close");
5662 return error;
5665 __dead static void
5666 usage_blame(void)
5668 fprintf(stderr,
5669 "usage: %s blame [-c commit] [-r repository-path] path\n",
5670 getprogname());
5671 exit(1);
5674 struct blame_line {
5675 int annotated;
5676 char *id_str;
5677 char *committer;
5678 char datebuf[11]; /* YYYY-MM-DD + NUL */
5681 struct blame_cb_args {
5682 struct blame_line *lines;
5683 int nlines;
5684 int nlines_prec;
5685 int lineno_cur;
5686 off_t *line_offsets;
5687 FILE *f;
5688 struct got_repository *repo;
5691 static const struct got_error *
5692 blame_cb(void *arg, int nlines, int lineno,
5693 struct got_commit_object *commit, struct got_object_id *id)
5695 const struct got_error *err = NULL;
5696 struct blame_cb_args *a = arg;
5697 struct blame_line *bline;
5698 char *line = NULL;
5699 size_t linesize = 0;
5700 off_t offset;
5701 struct tm tm;
5702 time_t committer_time;
5704 if (nlines != a->nlines ||
5705 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5706 return got_error(GOT_ERR_RANGE);
5708 if (sigint_received)
5709 return got_error(GOT_ERR_ITER_COMPLETED);
5711 if (lineno == -1)
5712 return NULL; /* no change in this commit */
5714 /* Annotate this line. */
5715 bline = &a->lines[lineno - 1];
5716 if (bline->annotated)
5717 return NULL;
5718 err = got_object_id_str(&bline->id_str, id);
5719 if (err)
5720 return err;
5722 bline->committer = strdup(got_object_commit_get_committer(commit));
5723 if (bline->committer == NULL) {
5724 err = got_error_from_errno("strdup");
5725 goto done;
5728 committer_time = got_object_commit_get_committer_time(commit);
5729 if (gmtime_r(&committer_time, &tm) == NULL)
5730 return got_error_from_errno("gmtime_r");
5731 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5732 &tm) == 0) {
5733 err = got_error(GOT_ERR_NO_SPACE);
5734 goto done;
5736 bline->annotated = 1;
5738 /* Print lines annotated so far. */
5739 bline = &a->lines[a->lineno_cur - 1];
5740 if (!bline->annotated)
5741 goto done;
5743 offset = a->line_offsets[a->lineno_cur - 1];
5744 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5745 err = got_error_from_errno("fseeko");
5746 goto done;
5749 while (a->lineno_cur <= a->nlines && bline->annotated) {
5750 char *smallerthan, *at, *nl, *committer;
5751 size_t len;
5753 if (getline(&line, &linesize, a->f) == -1) {
5754 if (ferror(a->f))
5755 err = got_error_from_errno("getline");
5756 break;
5759 committer = bline->committer;
5760 smallerthan = strchr(committer, '<');
5761 if (smallerthan && smallerthan[1] != '\0')
5762 committer = smallerthan + 1;
5763 at = strchr(committer, '@');
5764 if (at)
5765 *at = '\0';
5766 len = strlen(committer);
5767 if (len >= 9)
5768 committer[8] = '\0';
5770 nl = strchr(line, '\n');
5771 if (nl)
5772 *nl = '\0';
5773 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5774 bline->id_str, bline->datebuf, committer, line);
5776 a->lineno_cur++;
5777 bline = &a->lines[a->lineno_cur - 1];
5779 done:
5780 free(line);
5781 return err;
5784 static const struct got_error *
5785 cmd_blame(int argc, char *argv[])
5787 const struct got_error *error;
5788 struct got_repository *repo = NULL;
5789 struct got_worktree *worktree = NULL;
5790 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5791 char *link_target = NULL;
5792 struct got_object_id *obj_id = NULL;
5793 struct got_object_id *commit_id = NULL;
5794 struct got_commit_object *commit = NULL;
5795 struct got_blob_object *blob = NULL;
5796 char *commit_id_str = NULL, *keyword_idstr = NULL;
5797 struct blame_cb_args bca;
5798 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5799 off_t filesize;
5800 int *pack_fds = NULL;
5801 FILE *f1 = NULL, *f2 = NULL;
5803 fd1 = got_opentempfd();
5804 if (fd1 == -1)
5805 return got_error_from_errno("got_opentempfd");
5807 memset(&bca, 0, sizeof(bca));
5809 #ifndef PROFILE
5810 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5811 NULL) == -1)
5812 err(1, "pledge");
5813 #endif
5815 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5816 switch (ch) {
5817 case 'c':
5818 commit_id_str = optarg;
5819 break;
5820 case 'r':
5821 repo_path = realpath(optarg, NULL);
5822 if (repo_path == NULL)
5823 return got_error_from_errno2("realpath",
5824 optarg);
5825 got_path_strip_trailing_slashes(repo_path);
5826 break;
5827 default:
5828 usage_blame();
5829 /* NOTREACHED */
5833 argc -= optind;
5834 argv += optind;
5836 if (argc == 1)
5837 path = argv[0];
5838 else
5839 usage_blame();
5841 cwd = getcwd(NULL, 0);
5842 if (cwd == NULL) {
5843 error = got_error_from_errno("getcwd");
5844 goto done;
5847 error = got_repo_pack_fds_open(&pack_fds);
5848 if (error != NULL)
5849 goto done;
5851 if (repo_path == NULL) {
5852 error = got_worktree_open(&worktree, cwd,
5853 GOT_WORKTREE_GOT_DIR);
5854 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5855 goto done;
5856 else
5857 error = NULL;
5858 if (worktree) {
5859 repo_path =
5860 strdup(got_worktree_get_repo_path(worktree));
5861 if (repo_path == NULL) {
5862 error = got_error_from_errno("strdup");
5863 if (error)
5864 goto done;
5866 } else {
5867 repo_path = strdup(cwd);
5868 if (repo_path == NULL) {
5869 error = got_error_from_errno("strdup");
5870 goto done;
5875 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5876 if (error != NULL)
5877 goto done;
5879 if (worktree) {
5880 const char *prefix = got_worktree_get_path_prefix(worktree);
5881 char *p;
5883 error = got_worktree_resolve_path(&p, worktree, path);
5884 if (error)
5885 goto done;
5886 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5887 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5888 p) == -1) {
5889 error = got_error_from_errno("asprintf");
5890 free(p);
5891 goto done;
5893 free(p);
5894 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5895 } else {
5896 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5897 if (error)
5898 goto done;
5899 error = got_repo_map_path(&in_repo_path, repo, path);
5901 if (error)
5902 goto done;
5904 if (commit_id_str == NULL) {
5905 struct got_reference *head_ref;
5906 error = got_ref_open(&head_ref, repo, worktree ?
5907 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5908 if (error != NULL)
5909 goto done;
5910 error = got_ref_resolve(&commit_id, repo, head_ref);
5911 got_ref_close(head_ref);
5912 if (error != NULL)
5913 goto done;
5914 } else {
5915 struct got_reflist_head refs;
5917 TAILQ_INIT(&refs);
5918 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5919 NULL);
5920 if (error)
5921 goto done;
5923 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5924 repo, worktree);
5925 if (error != NULL)
5926 goto done;
5927 if (keyword_idstr != NULL)
5928 commit_id_str = keyword_idstr;
5930 error = got_repo_match_object_id(&commit_id, NULL,
5931 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5932 got_ref_list_free(&refs);
5933 if (error)
5934 goto done;
5937 if (worktree) {
5938 /* Release work tree lock. */
5939 got_worktree_close(worktree);
5940 worktree = NULL;
5943 error = got_object_open_as_commit(&commit, repo, commit_id);
5944 if (error)
5945 goto done;
5947 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5948 commit, repo);
5949 if (error)
5950 goto done;
5952 error = got_object_id_by_path(&obj_id, repo, commit,
5953 link_target ? link_target : in_repo_path);
5954 if (error)
5955 goto done;
5957 error = got_object_get_type(&obj_type, repo, obj_id);
5958 if (error)
5959 goto done;
5961 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5962 error = got_error_path(link_target ? link_target : in_repo_path,
5963 GOT_ERR_OBJ_TYPE);
5964 goto done;
5967 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5968 if (error)
5969 goto done;
5970 bca.f = got_opentemp();
5971 if (bca.f == NULL) {
5972 error = got_error_from_errno("got_opentemp");
5973 goto done;
5975 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5976 &bca.line_offsets, bca.f, blob);
5977 if (error || bca.nlines == 0)
5978 goto done;
5980 /* Don't include \n at EOF in the blame line count. */
5981 if (bca.line_offsets[bca.nlines - 1] == filesize)
5982 bca.nlines--;
5984 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5985 if (bca.lines == NULL) {
5986 error = got_error_from_errno("calloc");
5987 goto done;
5989 bca.lineno_cur = 1;
5990 bca.nlines_prec = 0;
5991 i = bca.nlines;
5992 while (i > 0) {
5993 i /= 10;
5994 bca.nlines_prec++;
5996 bca.repo = repo;
5998 fd2 = got_opentempfd();
5999 if (fd2 == -1) {
6000 error = got_error_from_errno("got_opentempfd");
6001 goto done;
6003 fd3 = got_opentempfd();
6004 if (fd3 == -1) {
6005 error = got_error_from_errno("got_opentempfd");
6006 goto done;
6008 f1 = got_opentemp();
6009 if (f1 == NULL) {
6010 error = got_error_from_errno("got_opentemp");
6011 goto done;
6013 f2 = got_opentemp();
6014 if (f2 == NULL) {
6015 error = got_error_from_errno("got_opentemp");
6016 goto done;
6018 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6019 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6020 check_cancelled, NULL, fd2, fd3, f1, f2);
6021 done:
6022 free(keyword_idstr);
6023 free(in_repo_path);
6024 free(link_target);
6025 free(repo_path);
6026 free(cwd);
6027 free(commit_id);
6028 free(obj_id);
6029 if (commit)
6030 got_object_commit_close(commit);
6032 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6033 error = got_error_from_errno("close");
6034 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6035 error = got_error_from_errno("close");
6036 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6037 error = got_error_from_errno("close");
6038 if (f1 && fclose(f1) == EOF && error == NULL)
6039 error = got_error_from_errno("fclose");
6040 if (f2 && fclose(f2) == EOF && error == NULL)
6041 error = got_error_from_errno("fclose");
6043 if (blob)
6044 got_object_blob_close(blob);
6045 if (worktree)
6046 got_worktree_close(worktree);
6047 if (repo) {
6048 const struct got_error *close_err = got_repo_close(repo);
6049 if (error == NULL)
6050 error = close_err;
6052 if (pack_fds) {
6053 const struct got_error *pack_err =
6054 got_repo_pack_fds_close(pack_fds);
6055 if (error == NULL)
6056 error = pack_err;
6058 if (bca.lines) {
6059 for (i = 0; i < bca.nlines; i++) {
6060 struct blame_line *bline = &bca.lines[i];
6061 free(bline->id_str);
6062 free(bline->committer);
6064 free(bca.lines);
6066 free(bca.line_offsets);
6067 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6068 error = got_error_from_errno("fclose");
6069 return error;
6072 __dead static void
6073 usage_tree(void)
6075 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6076 "[path]\n", getprogname());
6077 exit(1);
6080 static const struct got_error *
6081 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6082 const char *root_path, struct got_repository *repo)
6084 const struct got_error *err = NULL;
6085 int is_root_path = (strcmp(path, root_path) == 0);
6086 const char *modestr = "";
6087 mode_t mode = got_tree_entry_get_mode(te);
6088 char *link_target = NULL;
6090 path += strlen(root_path);
6091 while (path[0] == '/')
6092 path++;
6094 if (got_object_tree_entry_is_submodule(te))
6095 modestr = "$";
6096 else if (S_ISLNK(mode)) {
6097 int i;
6099 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6100 if (err)
6101 return err;
6102 for (i = 0; link_target[i] != '\0'; i++) {
6103 if (!isprint((unsigned char)link_target[i]))
6104 link_target[i] = '?';
6107 modestr = "@";
6109 else if (S_ISDIR(mode))
6110 modestr = "/";
6111 else if (mode & S_IXUSR)
6112 modestr = "*";
6114 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6115 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6116 link_target ? " -> ": "", link_target ? link_target : "");
6118 free(link_target);
6119 return NULL;
6122 static const struct got_error *
6123 print_tree(const char *path, struct got_commit_object *commit,
6124 int show_ids, int recurse, const char *root_path,
6125 struct got_repository *repo)
6127 const struct got_error *err = NULL;
6128 struct got_object_id *tree_id = NULL;
6129 struct got_tree_object *tree = NULL;
6130 int nentries, i;
6132 err = got_object_id_by_path(&tree_id, repo, commit, path);
6133 if (err)
6134 goto done;
6136 err = got_object_open_as_tree(&tree, repo, tree_id);
6137 if (err)
6138 goto done;
6139 nentries = got_object_tree_get_nentries(tree);
6140 for (i = 0; i < nentries; i++) {
6141 struct got_tree_entry *te;
6142 char *id = NULL;
6144 if (sigint_received || sigpipe_received)
6145 break;
6147 te = got_object_tree_get_entry(tree, i);
6148 if (show_ids) {
6149 char *id_str;
6150 err = got_object_id_str(&id_str,
6151 got_tree_entry_get_id(te));
6152 if (err)
6153 goto done;
6154 if (asprintf(&id, "%s ", id_str) == -1) {
6155 err = got_error_from_errno("asprintf");
6156 free(id_str);
6157 goto done;
6159 free(id_str);
6161 err = print_entry(te, id, path, root_path, repo);
6162 free(id);
6163 if (err)
6164 goto done;
6166 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6167 char *child_path;
6168 if (asprintf(&child_path, "%s%s%s", path,
6169 path[0] == '/' && path[1] == '\0' ? "" : "/",
6170 got_tree_entry_get_name(te)) == -1) {
6171 err = got_error_from_errno("asprintf");
6172 goto done;
6174 err = print_tree(child_path, commit, show_ids, 1,
6175 root_path, repo);
6176 free(child_path);
6177 if (err)
6178 goto done;
6181 done:
6182 if (tree)
6183 got_object_tree_close(tree);
6184 free(tree_id);
6185 return err;
6188 static const struct got_error *
6189 cmd_tree(int argc, char *argv[])
6191 const struct got_error *error;
6192 struct got_repository *repo = NULL;
6193 struct got_worktree *worktree = NULL;
6194 const char *path, *refname = NULL;
6195 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6196 struct got_object_id *commit_id = NULL;
6197 struct got_commit_object *commit = NULL;
6198 char *commit_id_str = NULL, *keyword_idstr = NULL;
6199 int show_ids = 0, recurse = 0;
6200 int ch;
6201 int *pack_fds = NULL;
6203 #ifndef PROFILE
6204 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6205 NULL) == -1)
6206 err(1, "pledge");
6207 #endif
6209 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6210 switch (ch) {
6211 case 'c':
6212 commit_id_str = optarg;
6213 break;
6214 case 'i':
6215 show_ids = 1;
6216 break;
6217 case 'R':
6218 recurse = 1;
6219 break;
6220 case 'r':
6221 repo_path = realpath(optarg, NULL);
6222 if (repo_path == NULL)
6223 return got_error_from_errno2("realpath",
6224 optarg);
6225 got_path_strip_trailing_slashes(repo_path);
6226 break;
6227 default:
6228 usage_tree();
6229 /* NOTREACHED */
6233 argc -= optind;
6234 argv += optind;
6236 if (argc == 1)
6237 path = argv[0];
6238 else if (argc > 1)
6239 usage_tree();
6240 else
6241 path = NULL;
6243 cwd = getcwd(NULL, 0);
6244 if (cwd == NULL) {
6245 error = got_error_from_errno("getcwd");
6246 goto done;
6249 error = got_repo_pack_fds_open(&pack_fds);
6250 if (error != NULL)
6251 goto done;
6253 if (repo_path == NULL) {
6254 error = got_worktree_open(&worktree, cwd,
6255 GOT_WORKTREE_GOT_DIR);
6256 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6257 goto done;
6258 else
6259 error = NULL;
6260 if (worktree) {
6261 repo_path =
6262 strdup(got_worktree_get_repo_path(worktree));
6263 if (repo_path == NULL)
6264 error = got_error_from_errno("strdup");
6265 if (error)
6266 goto done;
6267 } else {
6268 repo_path = strdup(cwd);
6269 if (repo_path == NULL) {
6270 error = got_error_from_errno("strdup");
6271 goto done;
6276 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6277 if (error != NULL)
6278 goto done;
6280 if (worktree) {
6281 const char *prefix = got_worktree_get_path_prefix(worktree);
6282 char *p;
6284 if (path == NULL || got_path_is_root_dir(path))
6285 path = "";
6286 error = got_worktree_resolve_path(&p, worktree, path);
6287 if (error)
6288 goto done;
6289 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6290 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6291 p) == -1) {
6292 error = got_error_from_errno("asprintf");
6293 free(p);
6294 goto done;
6296 free(p);
6297 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6298 if (error)
6299 goto done;
6300 } else {
6301 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6302 if (error)
6303 goto done;
6304 if (path == NULL)
6305 path = "/";
6306 error = got_repo_map_path(&in_repo_path, repo, path);
6307 if (error != NULL)
6308 goto done;
6311 if (commit_id_str == NULL) {
6312 struct got_reference *head_ref;
6313 if (worktree)
6314 refname = got_worktree_get_head_ref_name(worktree);
6315 else
6316 refname = GOT_REF_HEAD;
6317 error = got_ref_open(&head_ref, repo, refname, 0);
6318 if (error != NULL)
6319 goto done;
6320 error = got_ref_resolve(&commit_id, repo, head_ref);
6321 got_ref_close(head_ref);
6322 if (error != NULL)
6323 goto done;
6324 } else {
6325 struct got_reflist_head refs;
6327 TAILQ_INIT(&refs);
6328 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6329 NULL);
6330 if (error)
6331 goto done;
6333 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6334 repo, worktree);
6335 if (error != NULL)
6336 goto done;
6337 if (keyword_idstr != NULL)
6338 commit_id_str = keyword_idstr;
6340 error = got_repo_match_object_id(&commit_id, NULL,
6341 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6342 got_ref_list_free(&refs);
6343 if (error)
6344 goto done;
6347 if (worktree) {
6348 /* Release work tree lock. */
6349 got_worktree_close(worktree);
6350 worktree = NULL;
6353 error = got_object_open_as_commit(&commit, repo, commit_id);
6354 if (error)
6355 goto done;
6357 error = print_tree(in_repo_path, commit, show_ids, recurse,
6358 in_repo_path, repo);
6359 done:
6360 free(keyword_idstr);
6361 free(in_repo_path);
6362 free(repo_path);
6363 free(cwd);
6364 free(commit_id);
6365 if (commit)
6366 got_object_commit_close(commit);
6367 if (worktree)
6368 got_worktree_close(worktree);
6369 if (repo) {
6370 const struct got_error *close_err = got_repo_close(repo);
6371 if (error == NULL)
6372 error = close_err;
6374 if (pack_fds) {
6375 const struct got_error *pack_err =
6376 got_repo_pack_fds_close(pack_fds);
6377 if (error == NULL)
6378 error = pack_err;
6380 return error;
6383 __dead static void
6384 usage_status(void)
6386 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6387 "[-s status-codes] [path ...]\n", getprogname());
6388 exit(1);
6391 struct got_status_arg {
6392 char *status_codes;
6393 int suppress;
6396 static const struct got_error *
6397 print_status(void *arg, unsigned char status, unsigned char staged_status,
6398 const char *path, struct got_object_id *blob_id,
6399 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6400 int dirfd, const char *de_name)
6402 struct got_status_arg *st = arg;
6404 if (status == staged_status && (status == GOT_STATUS_DELETE))
6405 status = GOT_STATUS_NO_CHANGE;
6406 if (st != NULL && st->status_codes) {
6407 size_t ncodes = strlen(st->status_codes);
6408 int i, j = 0;
6410 for (i = 0; i < ncodes ; i++) {
6411 if (st->suppress) {
6412 if (status == st->status_codes[i] ||
6413 staged_status == st->status_codes[i]) {
6414 j++;
6415 continue;
6417 } else {
6418 if (status == st->status_codes[i] ||
6419 staged_status == st->status_codes[i])
6420 break;
6424 if (st->suppress && j == 0)
6425 goto print;
6427 if (i == ncodes)
6428 return NULL;
6430 print:
6431 printf("%c%c %s\n", status, staged_status, path);
6432 return NULL;
6435 static const struct got_error *
6436 show_operation_in_progress(struct got_worktree *worktree,
6437 struct got_repository *repo)
6439 const struct got_error *err;
6440 char *new_base_branch_name = NULL;
6441 char *branch_name = NULL;
6442 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6444 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6445 if (err)
6446 return err;
6447 if (rebase_in_progress) {
6448 err = got_worktree_rebase_info(&new_base_branch_name,
6449 &branch_name, worktree, repo);
6450 if (err)
6451 return err;
6452 printf("Work tree is rebasing %s onto %s\n",
6453 branch_name, new_base_branch_name);
6456 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6457 worktree);
6458 if (err)
6459 return err;
6460 if (histedit_in_progress) {
6461 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6462 if (err)
6463 return err;
6464 printf("Work tree is editing the history of %s\n", branch_name);
6467 err = got_worktree_merge_in_progress(&merge_in_progress,
6468 worktree, repo);
6469 if (err)
6470 return err;
6471 if (merge_in_progress) {
6472 err = got_worktree_merge_info(&branch_name, worktree,
6473 repo);
6474 if (err)
6475 return err;
6476 printf("Work tree is merging %s into %s\n", branch_name,
6477 got_worktree_get_head_ref_name(worktree));
6480 free(new_base_branch_name);
6481 free(branch_name);
6482 return NULL;
6485 static const struct got_error *
6486 cmd_status(int argc, char *argv[])
6488 const struct got_error *close_err, *error = NULL;
6489 struct got_repository *repo = NULL;
6490 struct got_worktree *worktree = NULL;
6491 struct got_status_arg st;
6492 char *cwd = NULL;
6493 struct got_pathlist_head paths;
6494 int ch, i, no_ignores = 0;
6495 int *pack_fds = NULL;
6497 TAILQ_INIT(&paths);
6499 memset(&st, 0, sizeof(st));
6500 st.status_codes = NULL;
6501 st.suppress = 0;
6503 #ifndef PROFILE
6504 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6505 NULL) == -1)
6506 err(1, "pledge");
6507 #endif
6509 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6510 switch (ch) {
6511 case 'I':
6512 no_ignores = 1;
6513 break;
6514 case 'S':
6515 if (st.status_codes != NULL && st.suppress == 0)
6516 option_conflict('S', 's');
6517 st.suppress = 1;
6518 /* fallthrough */
6519 case 's':
6520 for (i = 0; optarg[i] != '\0'; i++) {
6521 switch (optarg[i]) {
6522 case GOT_STATUS_MODIFY:
6523 case GOT_STATUS_ADD:
6524 case GOT_STATUS_DELETE:
6525 case GOT_STATUS_CONFLICT:
6526 case GOT_STATUS_MISSING:
6527 case GOT_STATUS_OBSTRUCTED:
6528 case GOT_STATUS_UNVERSIONED:
6529 case GOT_STATUS_MODE_CHANGE:
6530 case GOT_STATUS_NONEXISTENT:
6531 break;
6532 default:
6533 errx(1, "invalid status code '%c'",
6534 optarg[i]);
6537 if (ch == 's' && st.suppress)
6538 option_conflict('s', 'S');
6539 st.status_codes = optarg;
6540 break;
6541 default:
6542 usage_status();
6543 /* NOTREACHED */
6547 argc -= optind;
6548 argv += optind;
6550 cwd = getcwd(NULL, 0);
6551 if (cwd == NULL) {
6552 error = got_error_from_errno("getcwd");
6553 goto done;
6556 error = got_repo_pack_fds_open(&pack_fds);
6557 if (error != NULL)
6558 goto done;
6560 error = got_worktree_open(&worktree, cwd,
6561 GOT_WORKTREE_GOT_DIR);
6562 if (error) {
6563 if (error->code == GOT_ERR_NOT_WORKTREE)
6564 error = wrap_not_worktree_error(error, "status", cwd);
6565 goto done;
6568 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6569 NULL, pack_fds);
6570 if (error != NULL)
6571 goto done;
6573 error = apply_unveil(got_repo_get_path(repo), 1,
6574 got_worktree_get_root_path(worktree));
6575 if (error)
6576 goto done;
6578 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6579 if (error)
6580 goto done;
6582 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6583 print_status, &st, check_cancelled, NULL);
6584 if (error)
6585 goto done;
6587 error = show_operation_in_progress(worktree, repo);
6588 done:
6589 if (pack_fds) {
6590 const struct got_error *pack_err =
6591 got_repo_pack_fds_close(pack_fds);
6592 if (error == NULL)
6593 error = pack_err;
6595 if (repo) {
6596 close_err = got_repo_close(repo);
6597 if (error == NULL)
6598 error = close_err;
6600 if (worktree != NULL) {
6601 close_err = got_worktree_close(worktree);
6602 if (error == NULL)
6603 error = close_err;
6606 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6607 free(cwd);
6608 return error;
6611 __dead static void
6612 usage_ref(void)
6614 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6615 "[-s reference] [name]\n", getprogname());
6616 exit(1);
6619 static const struct got_error *
6620 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6622 static const struct got_error *err = NULL;
6623 struct got_reflist_head refs;
6624 struct got_reflist_entry *re;
6626 TAILQ_INIT(&refs);
6627 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6628 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6629 repo);
6630 if (err)
6631 return err;
6633 TAILQ_FOREACH(re, &refs, entry) {
6634 char *refstr;
6635 refstr = got_ref_to_str(re->ref);
6636 if (refstr == NULL) {
6637 err = got_error_from_errno("got_ref_to_str");
6638 break;
6640 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6641 free(refstr);
6644 got_ref_list_free(&refs);
6645 return err;
6648 static const struct got_error *
6649 delete_ref_by_name(struct got_repository *repo, const char *refname)
6651 const struct got_error *err;
6652 struct got_reference *ref;
6654 err = got_ref_open(&ref, repo, refname, 0);
6655 if (err)
6656 return err;
6658 err = delete_ref(repo, ref);
6659 got_ref_close(ref);
6660 return err;
6663 static const struct got_error *
6664 add_ref(struct got_repository *repo, const char *refname, const char *target)
6666 const struct got_error *err = NULL;
6667 struct got_object_id *id = NULL;
6668 struct got_reference *ref = NULL;
6669 struct got_reflist_head refs;
6672 * Don't let the user create a reference name with a leading '-'.
6673 * While technically a valid reference name, this case is usually
6674 * an unintended typo.
6676 if (refname[0] == '-')
6677 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6679 TAILQ_INIT(&refs);
6680 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6681 if (err)
6682 goto done;
6683 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6684 &refs, repo);
6685 got_ref_list_free(&refs);
6686 if (err)
6687 goto done;
6689 err = got_ref_alloc(&ref, refname, id);
6690 if (err)
6691 goto done;
6693 err = got_ref_write(ref, repo);
6694 done:
6695 if (ref)
6696 got_ref_close(ref);
6697 free(id);
6698 return err;
6701 static const struct got_error *
6702 add_symref(struct got_repository *repo, const char *refname, const char *target)
6704 const struct got_error *err = NULL;
6705 struct got_reference *ref = NULL;
6706 struct got_reference *target_ref = NULL;
6709 * Don't let the user create a reference name with a leading '-'.
6710 * While technically a valid reference name, this case is usually
6711 * an unintended typo.
6713 if (refname[0] == '-')
6714 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6716 err = got_ref_open(&target_ref, repo, target, 0);
6717 if (err)
6718 return err;
6720 err = got_ref_alloc_symref(&ref, refname, target_ref);
6721 if (err)
6722 goto done;
6724 err = got_ref_write(ref, repo);
6725 done:
6726 if (target_ref)
6727 got_ref_close(target_ref);
6728 if (ref)
6729 got_ref_close(ref);
6730 return err;
6733 static const struct got_error *
6734 cmd_ref(int argc, char *argv[])
6736 const struct got_error *error = NULL;
6737 struct got_repository *repo = NULL;
6738 struct got_worktree *worktree = NULL;
6739 char *cwd = NULL, *repo_path = NULL;
6740 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6741 const char *obj_arg = NULL, *symref_target= NULL;
6742 char *refname = NULL, *keyword_idstr = NULL;
6743 int *pack_fds = NULL;
6745 #ifndef PROFILE
6746 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6747 "sendfd unveil", NULL) == -1)
6748 err(1, "pledge");
6749 #endif
6751 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6752 switch (ch) {
6753 case 'c':
6754 obj_arg = optarg;
6755 break;
6756 case 'd':
6757 do_delete = 1;
6758 break;
6759 case 'l':
6760 do_list = 1;
6761 break;
6762 case 'r':
6763 repo_path = realpath(optarg, NULL);
6764 if (repo_path == NULL)
6765 return got_error_from_errno2("realpath",
6766 optarg);
6767 got_path_strip_trailing_slashes(repo_path);
6768 break;
6769 case 's':
6770 symref_target = optarg;
6771 break;
6772 case 't':
6773 sort_by_time = 1;
6774 break;
6775 default:
6776 usage_ref();
6777 /* NOTREACHED */
6781 if (obj_arg && do_list)
6782 option_conflict('c', 'l');
6783 if (obj_arg && do_delete)
6784 option_conflict('c', 'd');
6785 if (obj_arg && symref_target)
6786 option_conflict('c', 's');
6787 if (symref_target && do_delete)
6788 option_conflict('s', 'd');
6789 if (symref_target && do_list)
6790 option_conflict('s', 'l');
6791 if (do_delete && do_list)
6792 option_conflict('d', 'l');
6793 if (sort_by_time && !do_list)
6794 errx(1, "-t option requires -l option");
6796 argc -= optind;
6797 argv += optind;
6799 if (do_list) {
6800 if (argc != 0 && argc != 1)
6801 usage_ref();
6802 if (argc == 1) {
6803 refname = strdup(argv[0]);
6804 if (refname == NULL) {
6805 error = got_error_from_errno("strdup");
6806 goto done;
6809 } else {
6810 if (argc != 1)
6811 usage_ref();
6812 refname = strdup(argv[0]);
6813 if (refname == NULL) {
6814 error = got_error_from_errno("strdup");
6815 goto done;
6819 if (refname)
6820 got_path_strip_trailing_slashes(refname);
6822 cwd = getcwd(NULL, 0);
6823 if (cwd == NULL) {
6824 error = got_error_from_errno("getcwd");
6825 goto done;
6828 error = got_repo_pack_fds_open(&pack_fds);
6829 if (error != NULL)
6830 goto done;
6832 if (repo_path == NULL) {
6833 error = got_worktree_open(&worktree, cwd,
6834 GOT_WORKTREE_GOT_DIR);
6835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6836 goto done;
6837 else
6838 error = NULL;
6839 if (worktree) {
6840 repo_path =
6841 strdup(got_worktree_get_repo_path(worktree));
6842 if (repo_path == NULL)
6843 error = got_error_from_errno("strdup");
6844 if (error)
6845 goto done;
6846 } else {
6847 repo_path = strdup(cwd);
6848 if (repo_path == NULL) {
6849 error = got_error_from_errno("strdup");
6850 goto done;
6855 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6856 if (error != NULL)
6857 goto done;
6859 #ifndef PROFILE
6860 if (do_list) {
6861 /* Remove "cpath" promise. */
6862 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6863 NULL) == -1)
6864 err(1, "pledge");
6866 #endif
6868 error = apply_unveil(got_repo_get_path(repo), do_list,
6869 worktree ? got_worktree_get_root_path(worktree) : NULL);
6870 if (error)
6871 goto done;
6873 if (do_list)
6874 error = list_refs(repo, refname, sort_by_time);
6875 else if (do_delete)
6876 error = delete_ref_by_name(repo, refname);
6877 else if (symref_target)
6878 error = add_symref(repo, refname, symref_target);
6879 else {
6880 if (obj_arg == NULL)
6881 usage_ref();
6883 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6884 repo, worktree);
6885 if (error != NULL)
6886 goto done;
6887 if (keyword_idstr != NULL)
6888 obj_arg = keyword_idstr;
6890 error = add_ref(repo, refname, obj_arg);
6892 done:
6893 free(refname);
6894 if (repo) {
6895 const struct got_error *close_err = got_repo_close(repo);
6896 if (error == NULL)
6897 error = close_err;
6899 if (worktree)
6900 got_worktree_close(worktree);
6901 if (pack_fds) {
6902 const struct got_error *pack_err =
6903 got_repo_pack_fds_close(pack_fds);
6904 if (error == NULL)
6905 error = pack_err;
6907 free(cwd);
6908 free(repo_path);
6909 free(keyword_idstr);
6910 return error;
6913 __dead static void
6914 usage_branch(void)
6916 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6917 "[-r repository-path] [name]\n", getprogname());
6918 exit(1);
6921 static const struct got_error *
6922 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6923 struct got_reference *ref)
6925 const struct got_error *err = NULL;
6926 const char *refname;
6927 char *refstr;
6928 char marker = ' ';
6930 refname = got_ref_get_name(ref);
6931 if (worktree && strcmp(refname,
6932 got_worktree_get_head_ref_name(worktree)) == 0) {
6933 err = got_worktree_get_state(&marker, repo, worktree,
6934 check_cancelled, NULL);
6935 if (err != NULL)
6936 return err;
6939 if (strncmp(refname, "refs/heads/", 11) == 0)
6940 refname += 11;
6941 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6942 refname += 18;
6943 if (strncmp(refname, "refs/remotes/", 13) == 0)
6944 refname += 13;
6946 refstr = got_ref_to_str(ref);
6947 if (refstr == NULL)
6948 return got_error_from_errno("got_ref_to_str");
6950 printf("%c %s: %s\n", marker, refname, refstr);
6951 free(refstr);
6952 return NULL;
6955 static const struct got_error *
6956 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6958 const char *refname;
6960 if (worktree == NULL)
6961 return got_error(GOT_ERR_NOT_WORKTREE);
6963 refname = got_worktree_get_head_ref_name(worktree);
6965 if (strncmp(refname, "refs/heads/", 11) == 0)
6966 refname += 11;
6967 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6968 refname += 18;
6970 printf("%s\n", refname);
6972 return NULL;
6975 static const struct got_error *
6976 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6977 int sort_by_time)
6979 static const struct got_error *err = NULL;
6980 struct got_reflist_head refs;
6981 struct got_reflist_entry *re;
6982 struct got_reference *temp_ref = NULL;
6983 int rebase_in_progress, histedit_in_progress;
6985 TAILQ_INIT(&refs);
6987 if (worktree) {
6988 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6989 worktree);
6990 if (err)
6991 return err;
6993 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6994 worktree);
6995 if (err)
6996 return err;
6998 if (rebase_in_progress || histedit_in_progress) {
6999 err = got_ref_open(&temp_ref, repo,
7000 got_worktree_get_head_ref_name(worktree), 0);
7001 if (err)
7002 return err;
7003 list_branch(repo, worktree, temp_ref);
7004 got_ref_close(temp_ref);
7008 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7009 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7010 repo);
7011 if (err)
7012 return err;
7014 TAILQ_FOREACH(re, &refs, entry)
7015 list_branch(repo, worktree, re->ref);
7017 got_ref_list_free(&refs);
7019 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7020 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7021 repo);
7022 if (err)
7023 return err;
7025 TAILQ_FOREACH(re, &refs, entry)
7026 list_branch(repo, worktree, re->ref);
7028 got_ref_list_free(&refs);
7030 return NULL;
7033 static const struct got_error *
7034 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7035 const char *branch_name)
7037 const struct got_error *err = NULL;
7038 struct got_reference *ref = NULL;
7039 char *refname, *remote_refname = NULL;
7041 if (strncmp(branch_name, "refs/", 5) == 0)
7042 branch_name += 5;
7043 if (strncmp(branch_name, "heads/", 6) == 0)
7044 branch_name += 6;
7045 else if (strncmp(branch_name, "remotes/", 8) == 0)
7046 branch_name += 8;
7048 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7049 return got_error_from_errno("asprintf");
7051 if (asprintf(&remote_refname, "refs/remotes/%s",
7052 branch_name) == -1) {
7053 err = got_error_from_errno("asprintf");
7054 goto done;
7057 err = got_ref_open(&ref, repo, refname, 0);
7058 if (err) {
7059 const struct got_error *err2;
7060 if (err->code != GOT_ERR_NOT_REF)
7061 goto done;
7063 * Keep 'err' intact such that if neither branch exists
7064 * we report "refs/heads" rather than "refs/remotes" in
7065 * our error message.
7067 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7068 if (err2)
7069 goto done;
7070 err = NULL;
7073 if (worktree &&
7074 strcmp(got_worktree_get_head_ref_name(worktree),
7075 got_ref_get_name(ref)) == 0) {
7076 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7077 "will not delete this work tree's current branch");
7078 goto done;
7081 err = delete_ref(repo, ref);
7082 done:
7083 if (ref)
7084 got_ref_close(ref);
7085 free(refname);
7086 free(remote_refname);
7087 return err;
7090 static const struct got_error *
7091 add_branch(struct got_repository *repo, const char *branch_name,
7092 struct got_object_id *base_commit_id)
7094 const struct got_error *err = NULL;
7095 struct got_reference *ref = NULL;
7096 char *refname = NULL;
7099 * Don't let the user create a branch name with a leading '-'.
7100 * While technically a valid reference name, this case is usually
7101 * an unintended typo.
7103 if (branch_name[0] == '-')
7104 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7106 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7107 branch_name += 11;
7109 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7110 err = got_error_from_errno("asprintf");
7111 goto done;
7114 err = got_ref_open(&ref, repo, refname, 0);
7115 if (err == NULL) {
7116 err = got_error(GOT_ERR_BRANCH_EXISTS);
7117 goto done;
7118 } else if (err->code != GOT_ERR_NOT_REF)
7119 goto done;
7121 err = got_ref_alloc(&ref, refname, base_commit_id);
7122 if (err)
7123 goto done;
7125 err = got_ref_write(ref, repo);
7126 done:
7127 if (ref)
7128 got_ref_close(ref);
7129 free(refname);
7130 return err;
7133 static const struct got_error *
7134 cmd_branch(int argc, char *argv[])
7136 const struct got_error *error = NULL;
7137 struct got_repository *repo = NULL;
7138 struct got_worktree *worktree = NULL;
7139 char *cwd = NULL, *repo_path = NULL;
7140 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7141 const char *delref = NULL, *commit_id_arg = NULL;
7142 struct got_reference *ref = NULL;
7143 struct got_pathlist_head paths;
7144 struct got_object_id *commit_id = NULL;
7145 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7146 int *pack_fds = NULL;
7148 TAILQ_INIT(&paths);
7150 #ifndef PROFILE
7151 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7152 "sendfd unveil", NULL) == -1)
7153 err(1, "pledge");
7154 #endif
7156 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7157 switch (ch) {
7158 case 'c':
7159 commit_id_arg = optarg;
7160 break;
7161 case 'd':
7162 delref = optarg;
7163 break;
7164 case 'l':
7165 do_list = 1;
7166 break;
7167 case 'n':
7168 do_update = 0;
7169 break;
7170 case 'r':
7171 repo_path = realpath(optarg, NULL);
7172 if (repo_path == NULL)
7173 return got_error_from_errno2("realpath",
7174 optarg);
7175 got_path_strip_trailing_slashes(repo_path);
7176 break;
7177 case 't':
7178 sort_by_time = 1;
7179 break;
7180 default:
7181 usage_branch();
7182 /* NOTREACHED */
7186 if (do_list && delref)
7187 option_conflict('l', 'd');
7188 if (sort_by_time && !do_list)
7189 errx(1, "-t option requires -l option");
7191 argc -= optind;
7192 argv += optind;
7194 if (!do_list && !delref && argc == 0)
7195 do_show = 1;
7197 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7198 errx(1, "-c option can only be used when creating a branch");
7200 if (do_list || delref) {
7201 if (argc > 0)
7202 usage_branch();
7203 } else if (!do_show && argc != 1)
7204 usage_branch();
7206 cwd = getcwd(NULL, 0);
7207 if (cwd == NULL) {
7208 error = got_error_from_errno("getcwd");
7209 goto done;
7212 error = got_repo_pack_fds_open(&pack_fds);
7213 if (error != NULL)
7214 goto done;
7216 if (repo_path == NULL) {
7217 error = got_worktree_open(&worktree, cwd,
7218 GOT_WORKTREE_GOT_DIR);
7219 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7220 goto done;
7221 else
7222 error = NULL;
7223 if (worktree) {
7224 repo_path =
7225 strdup(got_worktree_get_repo_path(worktree));
7226 if (repo_path == NULL)
7227 error = got_error_from_errno("strdup");
7228 if (error)
7229 goto done;
7230 } else {
7231 repo_path = strdup(cwd);
7232 if (repo_path == NULL) {
7233 error = got_error_from_errno("strdup");
7234 goto done;
7239 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7240 if (error != NULL)
7241 goto done;
7243 #ifndef PROFILE
7244 if (do_list || do_show) {
7245 /* Remove "cpath" promise. */
7246 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7247 NULL) == -1)
7248 err(1, "pledge");
7250 #endif
7252 error = apply_unveil(got_repo_get_path(repo), do_list,
7253 worktree ? got_worktree_get_root_path(worktree) : NULL);
7254 if (error)
7255 goto done;
7257 if (do_show)
7258 error = show_current_branch(repo, worktree);
7259 else if (do_list)
7260 error = list_branches(repo, worktree, sort_by_time);
7261 else if (delref)
7262 error = delete_branch(repo, worktree, delref);
7263 else {
7264 struct got_reflist_head refs;
7265 TAILQ_INIT(&refs);
7266 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7267 NULL);
7268 if (error)
7269 goto done;
7270 if (commit_id_arg == NULL)
7271 commit_id_arg = worktree ?
7272 got_worktree_get_head_ref_name(worktree) :
7273 GOT_REF_HEAD;
7274 else {
7275 error = got_keyword_to_idstr(&keyword_idstr,
7276 commit_id_arg, repo, worktree);
7277 if (error != NULL)
7278 goto done;
7279 if (keyword_idstr != NULL)
7280 commit_id_arg = keyword_idstr;
7282 error = got_repo_match_object_id(&commit_id, NULL,
7283 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7284 got_ref_list_free(&refs);
7285 if (error)
7286 goto done;
7287 error = add_branch(repo, argv[0], commit_id);
7288 if (error)
7289 goto done;
7290 if (worktree && do_update) {
7291 struct got_update_progress_arg upa;
7292 char *branch_refname = NULL;
7294 error = got_object_id_str(&commit_id_str, commit_id);
7295 if (error)
7296 goto done;
7297 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7298 worktree);
7299 if (error)
7300 goto done;
7301 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7302 == -1) {
7303 error = got_error_from_errno("asprintf");
7304 goto done;
7306 error = got_ref_open(&ref, repo, branch_refname, 0);
7307 free(branch_refname);
7308 if (error)
7309 goto done;
7310 error = switch_head_ref(ref, commit_id, worktree,
7311 repo);
7312 if (error)
7313 goto done;
7314 error = got_worktree_set_base_commit_id(worktree, repo,
7315 commit_id);
7316 if (error)
7317 goto done;
7318 memset(&upa, 0, sizeof(upa));
7319 error = got_worktree_checkout_files(worktree, &paths,
7320 repo, update_progress, &upa, check_cancelled,
7321 NULL);
7322 if (error)
7323 goto done;
7324 if (upa.did_something) {
7325 printf("Updated to %s: %s\n",
7326 got_worktree_get_head_ref_name(worktree),
7327 commit_id_str);
7329 print_update_progress_stats(&upa);
7332 done:
7333 free(keyword_idstr);
7334 if (ref)
7335 got_ref_close(ref);
7336 if (repo) {
7337 const struct got_error *close_err = got_repo_close(repo);
7338 if (error == NULL)
7339 error = close_err;
7341 if (worktree)
7342 got_worktree_close(worktree);
7343 if (pack_fds) {
7344 const struct got_error *pack_err =
7345 got_repo_pack_fds_close(pack_fds);
7346 if (error == NULL)
7347 error = pack_err;
7349 free(cwd);
7350 free(repo_path);
7351 free(commit_id);
7352 free(commit_id_str);
7353 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7354 return error;
7358 __dead static void
7359 usage_tag(void)
7361 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7362 "[-r repository-path] [-s signer-id] name\n", getprogname());
7363 exit(1);
7366 #if 0
7367 static const struct got_error *
7368 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7370 const struct got_error *err = NULL;
7371 struct got_reflist_entry *re, *se, *new;
7372 struct got_object_id *re_id, *se_id;
7373 struct got_tag_object *re_tag, *se_tag;
7374 time_t re_time, se_time;
7376 STAILQ_FOREACH(re, tags, entry) {
7377 se = STAILQ_FIRST(sorted);
7378 if (se == NULL) {
7379 err = got_reflist_entry_dup(&new, re);
7380 if (err)
7381 return err;
7382 STAILQ_INSERT_HEAD(sorted, new, entry);
7383 continue;
7384 } else {
7385 err = got_ref_resolve(&re_id, repo, re->ref);
7386 if (err)
7387 break;
7388 err = got_object_open_as_tag(&re_tag, repo, re_id);
7389 free(re_id);
7390 if (err)
7391 break;
7392 re_time = got_object_tag_get_tagger_time(re_tag);
7393 got_object_tag_close(re_tag);
7396 while (se) {
7397 err = got_ref_resolve(&se_id, repo, re->ref);
7398 if (err)
7399 break;
7400 err = got_object_open_as_tag(&se_tag, repo, se_id);
7401 free(se_id);
7402 if (err)
7403 break;
7404 se_time = got_object_tag_get_tagger_time(se_tag);
7405 got_object_tag_close(se_tag);
7407 if (se_time > re_time) {
7408 err = got_reflist_entry_dup(&new, re);
7409 if (err)
7410 return err;
7411 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7412 break;
7414 se = STAILQ_NEXT(se, entry);
7415 continue;
7418 done:
7419 return err;
7421 #endif
7423 static const struct got_error *
7424 get_tag_refname(char **refname, const char *tag_name)
7426 const struct got_error *err;
7428 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7429 *refname = strdup(tag_name);
7430 if (*refname == NULL)
7431 return got_error_from_errno("strdup");
7432 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7433 err = got_error_from_errno("asprintf");
7434 *refname = NULL;
7435 return err;
7438 return NULL;
7441 static const struct got_error *
7442 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7443 const char *allowed_signers, const char *revoked_signers, int verbosity)
7445 static const struct got_error *err = NULL;
7446 struct got_reflist_head refs;
7447 struct got_reflist_entry *re;
7448 char *wanted_refname = NULL;
7449 int bad_sigs = 0;
7451 TAILQ_INIT(&refs);
7453 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7454 if (err)
7455 return err;
7457 if (tag_name) {
7458 struct got_reference *ref;
7459 err = get_tag_refname(&wanted_refname, tag_name);
7460 if (err)
7461 goto done;
7462 /* Wanted tag reference should exist. */
7463 err = got_ref_open(&ref, repo, wanted_refname, 0);
7464 if (err)
7465 goto done;
7466 got_ref_close(ref);
7469 TAILQ_FOREACH(re, &refs, entry) {
7470 const char *refname;
7471 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7472 char datebuf[26];
7473 const char *tagger, *ssh_sig = NULL;
7474 char *sig_msg = NULL;
7475 time_t tagger_time;
7476 struct got_object_id *id;
7477 struct got_tag_object *tag;
7478 struct got_commit_object *commit = NULL;
7480 refname = got_ref_get_name(re->ref);
7481 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7482 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7483 continue;
7484 refname += 10;
7485 refstr = got_ref_to_str(re->ref);
7486 if (refstr == NULL) {
7487 err = got_error_from_errno("got_ref_to_str");
7488 break;
7491 err = got_ref_resolve(&id, repo, re->ref);
7492 if (err)
7493 break;
7494 err = got_object_open_as_tag(&tag, repo, id);
7495 if (err) {
7496 if (err->code != GOT_ERR_OBJ_TYPE) {
7497 free(id);
7498 break;
7500 /* "lightweight" tag */
7501 err = got_object_open_as_commit(&commit, repo, id);
7502 if (err) {
7503 free(id);
7504 break;
7506 tagger = got_object_commit_get_committer(commit);
7507 tagger_time =
7508 got_object_commit_get_committer_time(commit);
7509 err = got_object_id_str(&id_str, id);
7510 free(id);
7511 if (err)
7512 break;
7513 } else {
7514 free(id);
7515 tagger = got_object_tag_get_tagger(tag);
7516 tagger_time = got_object_tag_get_tagger_time(tag);
7517 err = got_object_id_str(&id_str,
7518 got_object_tag_get_object_id(tag));
7519 if (err)
7520 break;
7523 if (tag && verify_tags) {
7524 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7525 got_object_tag_get_message(tag));
7526 if (ssh_sig && allowed_signers == NULL) {
7527 err = got_error_msg(
7528 GOT_ERR_VERIFY_TAG_SIGNATURE,
7529 "SSH signature verification requires "
7530 "setting allowed_signers in "
7531 "got.conf(5)");
7532 break;
7536 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7537 free(refstr);
7538 printf("from: %s\n", tagger);
7539 datestr = get_datestr(&tagger_time, datebuf);
7540 if (datestr)
7541 printf("date: %s UTC\n", datestr);
7542 if (commit)
7543 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7544 else {
7545 switch (got_object_tag_get_object_type(tag)) {
7546 case GOT_OBJ_TYPE_BLOB:
7547 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7548 id_str);
7549 break;
7550 case GOT_OBJ_TYPE_TREE:
7551 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7552 id_str);
7553 break;
7554 case GOT_OBJ_TYPE_COMMIT:
7555 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7556 id_str);
7557 break;
7558 case GOT_OBJ_TYPE_TAG:
7559 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7560 id_str);
7561 break;
7562 default:
7563 break;
7566 free(id_str);
7568 if (ssh_sig) {
7569 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7570 allowed_signers, revoked_signers, verbosity);
7571 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7572 bad_sigs = 1;
7573 else if (err)
7574 break;
7575 printf("signature: %s", sig_msg);
7576 free(sig_msg);
7577 sig_msg = NULL;
7580 if (commit) {
7581 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7582 if (err)
7583 break;
7584 got_object_commit_close(commit);
7585 } else {
7586 tagmsg0 = strdup(got_object_tag_get_message(tag));
7587 got_object_tag_close(tag);
7588 if (tagmsg0 == NULL) {
7589 err = got_error_from_errno("strdup");
7590 break;
7594 tagmsg = tagmsg0;
7595 do {
7596 line = strsep(&tagmsg, "\n");
7597 if (line)
7598 printf(" %s\n", line);
7599 } while (line);
7600 free(tagmsg0);
7602 done:
7603 got_ref_list_free(&refs);
7604 free(wanted_refname);
7606 if (err == NULL && bad_sigs)
7607 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7608 return err;
7611 static const struct got_error *
7612 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7613 const char *tag_name, const char *editor, const char *repo_path)
7615 const struct got_error *err = NULL;
7616 char *template = NULL, *initial_content = NULL;
7617 int initial_content_len;
7618 int fd = -1;
7620 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7621 err = got_error_from_errno("asprintf");
7622 goto done;
7625 initial_content_len = asprintf(&initial_content,
7626 "\n# tagging commit %s as %s\n",
7627 commit_id_str, tag_name);
7628 if (initial_content_len == -1) {
7629 err = got_error_from_errno("asprintf");
7630 goto done;
7633 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7634 if (err)
7635 goto done;
7637 if (write(fd, initial_content, initial_content_len) == -1) {
7638 err = got_error_from_errno2("write", *tagmsg_path);
7639 goto done;
7641 if (close(fd) == -1) {
7642 err = got_error_from_errno2("close", *tagmsg_path);
7643 goto done;
7645 fd = -1;
7647 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7648 initial_content_len, 1);
7649 done:
7650 free(initial_content);
7651 free(template);
7653 if (fd != -1 && close(fd) == -1 && err == NULL)
7654 err = got_error_from_errno2("close", *tagmsg_path);
7656 if (err) {
7657 free(*tagmsg);
7658 *tagmsg = NULL;
7660 return err;
7663 static const struct got_error *
7664 add_tag(struct got_repository *repo, const char *tagger,
7665 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7666 const char *signer_id, const char *editor, int verbosity)
7668 const struct got_error *err = NULL;
7669 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7670 char *label = NULL, *commit_id_str = NULL;
7671 struct got_reference *ref = NULL;
7672 char *refname = NULL, *tagmsg = NULL;
7673 char *tagmsg_path = NULL, *tag_id_str = NULL;
7674 int preserve_tagmsg = 0;
7675 struct got_reflist_head refs;
7677 TAILQ_INIT(&refs);
7680 * Don't let the user create a tag name with a leading '-'.
7681 * While technically a valid reference name, this case is usually
7682 * an unintended typo.
7684 if (tag_name[0] == '-')
7685 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7687 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7688 if (err)
7689 goto done;
7691 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7692 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7693 if (err)
7694 goto done;
7696 err = got_object_id_str(&commit_id_str, commit_id);
7697 if (err)
7698 goto done;
7700 err = get_tag_refname(&refname, tag_name);
7701 if (err)
7702 goto done;
7703 if (strncmp("refs/tags/", tag_name, 10) == 0)
7704 tag_name += 10;
7706 err = got_ref_open(&ref, repo, refname, 0);
7707 if (err == NULL) {
7708 err = got_error(GOT_ERR_TAG_EXISTS);
7709 goto done;
7710 } else if (err->code != GOT_ERR_NOT_REF)
7711 goto done;
7713 if (tagmsg_arg == NULL) {
7714 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7715 tag_name, editor, got_repo_get_path(repo));
7716 if (err) {
7717 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7718 tagmsg_path != NULL)
7719 preserve_tagmsg = 1;
7720 goto done;
7724 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7725 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7726 verbosity);
7727 if (err) {
7728 if (tagmsg_path)
7729 preserve_tagmsg = 1;
7730 goto done;
7733 err = got_ref_alloc(&ref, refname, tag_id);
7734 if (err) {
7735 if (tagmsg_path)
7736 preserve_tagmsg = 1;
7737 goto done;
7740 err = got_ref_write(ref, repo);
7741 if (err) {
7742 if (tagmsg_path)
7743 preserve_tagmsg = 1;
7744 goto done;
7747 err = got_object_id_str(&tag_id_str, tag_id);
7748 if (err) {
7749 if (tagmsg_path)
7750 preserve_tagmsg = 1;
7751 goto done;
7753 printf("Created tag %s\n", tag_id_str);
7754 done:
7755 if (preserve_tagmsg) {
7756 fprintf(stderr, "%s: tag message preserved in %s\n",
7757 getprogname(), tagmsg_path);
7758 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7759 err = got_error_from_errno2("unlink", tagmsg_path);
7760 free(tag_id_str);
7761 if (ref)
7762 got_ref_close(ref);
7763 free(commit_id);
7764 free(commit_id_str);
7765 free(refname);
7766 free(tagmsg);
7767 free(tagmsg_path);
7768 got_ref_list_free(&refs);
7769 return err;
7772 static const struct got_error *
7773 cmd_tag(int argc, char *argv[])
7775 const struct got_error *error = NULL;
7776 struct got_repository *repo = NULL;
7777 struct got_worktree *worktree = NULL;
7778 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7779 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7780 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7781 const char *signer_id = NULL;
7782 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7783 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7784 int *pack_fds = NULL;
7786 #ifndef PROFILE
7787 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7788 "sendfd unveil", NULL) == -1)
7789 err(1, "pledge");
7790 #endif
7792 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7793 switch (ch) {
7794 case 'c':
7795 commit_id_arg = optarg;
7796 break;
7797 case 'l':
7798 do_list = 1;
7799 break;
7800 case 'm':
7801 tagmsg = optarg;
7802 break;
7803 case 'r':
7804 repo_path = realpath(optarg, NULL);
7805 if (repo_path == NULL) {
7806 error = got_error_from_errno2("realpath",
7807 optarg);
7808 goto done;
7810 got_path_strip_trailing_slashes(repo_path);
7811 break;
7812 case 's':
7813 signer_id = optarg;
7814 break;
7815 case 'V':
7816 verify_tags = 1;
7817 break;
7818 case 'v':
7819 if (verbosity < 0)
7820 verbosity = 0;
7821 else if (verbosity < 3)
7822 verbosity++;
7823 break;
7824 default:
7825 usage_tag();
7826 /* NOTREACHED */
7830 argc -= optind;
7831 argv += optind;
7833 if (do_list || verify_tags) {
7834 if (commit_id_arg != NULL)
7835 errx(1,
7836 "-c option can only be used when creating a tag");
7837 if (tagmsg) {
7838 if (do_list)
7839 option_conflict('l', 'm');
7840 else
7841 option_conflict('V', 'm');
7843 if (signer_id) {
7844 if (do_list)
7845 option_conflict('l', 's');
7846 else
7847 option_conflict('V', 's');
7849 if (argc > 1)
7850 usage_tag();
7851 } else if (argc != 1)
7852 usage_tag();
7854 if (argc == 1)
7855 tag_name = argv[0];
7857 cwd = getcwd(NULL, 0);
7858 if (cwd == NULL) {
7859 error = got_error_from_errno("getcwd");
7860 goto done;
7863 error = got_repo_pack_fds_open(&pack_fds);
7864 if (error != NULL)
7865 goto done;
7867 if (repo_path == NULL) {
7868 error = got_worktree_open(&worktree, cwd,
7869 GOT_WORKTREE_GOT_DIR);
7870 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7871 goto done;
7872 else
7873 error = NULL;
7874 if (worktree) {
7875 repo_path =
7876 strdup(got_worktree_get_repo_path(worktree));
7877 if (repo_path == NULL)
7878 error = got_error_from_errno("strdup");
7879 if (error)
7880 goto done;
7881 } else {
7882 repo_path = strdup(cwd);
7883 if (repo_path == NULL) {
7884 error = got_error_from_errno("strdup");
7885 goto done;
7890 if (do_list || verify_tags) {
7891 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7892 if (error != NULL)
7893 goto done;
7894 error = get_allowed_signers(&allowed_signers, repo, worktree);
7895 if (error)
7896 goto done;
7897 error = get_revoked_signers(&revoked_signers, repo, worktree);
7898 if (error)
7899 goto done;
7900 if (worktree) {
7901 /* Release work tree lock. */
7902 got_worktree_close(worktree);
7903 worktree = NULL;
7907 * Remove "cpath" promise unless needed for signature tmpfile
7908 * creation.
7910 if (verify_tags)
7911 got_sigs_apply_unveil();
7912 else {
7913 #ifndef PROFILE
7914 if (pledge("stdio rpath wpath flock proc exec sendfd "
7915 "unveil", NULL) == -1)
7916 err(1, "pledge");
7917 #endif
7919 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7920 if (error)
7921 goto done;
7922 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7923 revoked_signers, verbosity);
7924 } else {
7925 error = get_gitconfig_path(&gitconfig_path);
7926 if (error)
7927 goto done;
7928 error = got_repo_open(&repo, repo_path, gitconfig_path,
7929 pack_fds);
7930 if (error != NULL)
7931 goto done;
7933 error = get_author(&tagger, repo, worktree);
7934 if (error)
7935 goto done;
7936 if (signer_id == NULL)
7937 signer_id = get_signer_id(repo, worktree);
7939 if (tagmsg == NULL) {
7940 error = get_editor(&editor);
7941 if (error)
7942 goto done;
7943 if (unveil(editor, "x") != 0) {
7944 error = got_error_from_errno2("unveil", editor);
7945 goto done;
7948 if (signer_id) {
7949 error = got_sigs_apply_unveil();
7950 if (error)
7951 goto done;
7953 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7954 if (error)
7955 goto done;
7957 if (commit_id_arg == NULL) {
7958 struct got_reference *head_ref;
7959 struct got_object_id *commit_id;
7960 error = got_ref_open(&head_ref, repo,
7961 worktree ? got_worktree_get_head_ref_name(worktree)
7962 : GOT_REF_HEAD, 0);
7963 if (error)
7964 goto done;
7965 error = got_ref_resolve(&commit_id, repo, head_ref);
7966 got_ref_close(head_ref);
7967 if (error)
7968 goto done;
7969 error = got_object_id_str(&commit_id_str, commit_id);
7970 free(commit_id);
7971 if (error)
7972 goto done;
7973 } else {
7974 error = got_keyword_to_idstr(&keyword_idstr,
7975 commit_id_arg, repo, worktree);
7976 if (error != NULL)
7977 goto done;
7978 commit_id_str = keyword_idstr;
7981 if (worktree) {
7982 /* Release work tree lock. */
7983 got_worktree_close(worktree);
7984 worktree = NULL;
7987 error = add_tag(repo, tagger, tag_name,
7988 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7989 signer_id, editor, verbosity);
7991 done:
7992 if (repo) {
7993 const struct got_error *close_err = got_repo_close(repo);
7994 if (error == NULL)
7995 error = close_err;
7997 if (worktree)
7998 got_worktree_close(worktree);
7999 if (pack_fds) {
8000 const struct got_error *pack_err =
8001 got_repo_pack_fds_close(pack_fds);
8002 if (error == NULL)
8003 error = pack_err;
8005 free(cwd);
8006 free(editor);
8007 free(repo_path);
8008 free(gitconfig_path);
8009 free(commit_id_str);
8010 free(tagger);
8011 free(allowed_signers);
8012 free(revoked_signers);
8013 return error;
8016 __dead static void
8017 usage_add(void)
8019 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8020 exit(1);
8023 static const struct got_error *
8024 add_progress(void *arg, unsigned char status, const char *path)
8026 while (path[0] == '/')
8027 path++;
8028 printf("%c %s\n", status, path);
8029 return NULL;
8032 static const struct got_error *
8033 check_paths_contains_dir(int *contains_dir, struct got_worktree *worktree,
8034 struct got_pathlist_head *paths)
8036 const struct got_error *error = NULL;
8037 struct got_pathlist_entry *pe;
8038 struct stat sb;
8039 char *ondisk_path;
8041 *contains_dir = 0;
8043 TAILQ_FOREACH(pe, paths, entry) {
8044 if (asprintf(&ondisk_path, "%s/%s",
8045 got_worktree_get_root_path(worktree),
8046 pe->path) == -1) {
8047 return got_error_from_errno("asprintf");
8049 if (lstat(ondisk_path, &sb) == -1) {
8050 if (errno == ENOENT) {
8051 free(ondisk_path);
8052 continue;
8054 error = got_error_from_errno2("lstat",
8055 ondisk_path);
8056 free(ondisk_path);
8057 return error;
8059 free(ondisk_path);
8060 if (S_ISDIR(sb.st_mode)) {
8061 *contains_dir = 1;
8062 return NULL;
8065 return NULL;
8068 static const struct got_error *
8069 cmd_add(int argc, char *argv[])
8071 const struct got_error *error = NULL;
8072 struct got_repository *repo = NULL;
8073 struct got_worktree *worktree = NULL;
8074 char *cwd = NULL;
8075 struct got_pathlist_head paths;
8076 int ch, contains_dir, can_recurse = 0, no_ignores = 0;
8077 int *pack_fds = NULL;
8079 TAILQ_INIT(&paths);
8081 #ifndef PROFILE
8082 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8083 NULL) == -1)
8084 err(1, "pledge");
8085 #endif
8087 while ((ch = getopt(argc, argv, "IR")) != -1) {
8088 switch (ch) {
8089 case 'I':
8090 no_ignores = 1;
8091 break;
8092 case 'R':
8093 can_recurse = 1;
8094 break;
8095 default:
8096 usage_add();
8097 /* NOTREACHED */
8101 argc -= optind;
8102 argv += optind;
8104 if (argc < 1)
8105 usage_add();
8107 cwd = getcwd(NULL, 0);
8108 if (cwd == NULL) {
8109 error = got_error_from_errno("getcwd");
8110 goto done;
8113 error = got_repo_pack_fds_open(&pack_fds);
8114 if (error != NULL)
8115 goto done;
8117 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8118 if (error) {
8119 if (error->code == GOT_ERR_NOT_WORKTREE)
8120 error = wrap_not_worktree_error(error, "add", cwd);
8121 goto done;
8124 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8125 NULL, pack_fds);
8126 if (error != NULL)
8127 goto done;
8129 error = apply_unveil(got_repo_get_path(repo), 1,
8130 got_worktree_get_root_path(worktree));
8131 if (error)
8132 goto done;
8134 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8135 if (error)
8136 goto done;
8138 if (!can_recurse) {
8139 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
8140 if (error != NULL)
8141 goto done;
8143 if (contains_dir) {
8144 error = got_error_msg(GOT_ERR_BAD_PATH,
8145 "adding directories requires -R option");
8146 goto done;
8150 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8151 NULL, repo, no_ignores);
8152 done:
8153 if (repo) {
8154 const struct got_error *close_err = got_repo_close(repo);
8155 if (error == NULL)
8156 error = close_err;
8158 if (worktree)
8159 got_worktree_close(worktree);
8160 if (pack_fds) {
8161 const struct got_error *pack_err =
8162 got_repo_pack_fds_close(pack_fds);
8163 if (error == NULL)
8164 error = pack_err;
8166 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8167 free(cwd);
8168 return error;
8171 __dead static void
8172 usage_remove(void)
8174 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8175 getprogname());
8176 exit(1);
8179 static const struct got_error *
8180 print_remove_status(void *arg, unsigned char status,
8181 unsigned char staged_status, const char *path)
8183 while (path[0] == '/')
8184 path++;
8185 if (status == GOT_STATUS_NONEXISTENT)
8186 return NULL;
8187 if (status == staged_status && (status == GOT_STATUS_DELETE))
8188 status = GOT_STATUS_NO_CHANGE;
8189 printf("%c%c %s\n", status, staged_status, path);
8190 return NULL;
8193 static const struct got_error *
8194 cmd_remove(int argc, char *argv[])
8196 const struct got_error *error = NULL;
8197 struct got_worktree *worktree = NULL;
8198 struct got_repository *repo = NULL;
8199 const char *status_codes = NULL;
8200 char *cwd = NULL;
8201 struct got_pathlist_head paths;
8202 int contains_dir, ch, i, delete_local_mods = 0, can_recurse = 0;
8203 int ignore_missing_paths = 0, keep_on_disk = 0;
8204 int *pack_fds = NULL;
8206 TAILQ_INIT(&paths);
8208 #ifndef PROFILE
8209 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8210 NULL) == -1)
8211 err(1, "pledge");
8212 #endif
8214 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8215 switch (ch) {
8216 case 'f':
8217 delete_local_mods = 1;
8218 ignore_missing_paths = 1;
8219 break;
8220 case 'k':
8221 keep_on_disk = 1;
8222 break;
8223 case 'R':
8224 can_recurse = 1;
8225 break;
8226 case 's':
8227 for (i = 0; optarg[i] != '\0'; i++) {
8228 switch (optarg[i]) {
8229 case GOT_STATUS_MODIFY:
8230 delete_local_mods = 1;
8231 break;
8232 case GOT_STATUS_MISSING:
8233 ignore_missing_paths = 1;
8234 break;
8235 default:
8236 errx(1, "invalid status code '%c'",
8237 optarg[i]);
8240 status_codes = optarg;
8241 break;
8242 default:
8243 usage_remove();
8244 /* NOTREACHED */
8248 argc -= optind;
8249 argv += optind;
8251 if (argc < 1)
8252 usage_remove();
8254 cwd = getcwd(NULL, 0);
8255 if (cwd == NULL) {
8256 error = got_error_from_errno("getcwd");
8257 goto done;
8260 error = got_repo_pack_fds_open(&pack_fds);
8261 if (error != NULL)
8262 goto done;
8264 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8265 if (error) {
8266 if (error->code == GOT_ERR_NOT_WORKTREE)
8267 error = wrap_not_worktree_error(error, "remove", cwd);
8268 goto done;
8271 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8272 NULL, pack_fds);
8273 if (error)
8274 goto done;
8276 error = apply_unveil(got_repo_get_path(repo), 1,
8277 got_worktree_get_root_path(worktree));
8278 if (error)
8279 goto done;
8281 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8282 if (error)
8283 goto done;
8285 if (!can_recurse) {
8286 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
8287 if (error != NULL)
8288 goto done;
8290 if (contains_dir) {
8291 error = got_error_msg(GOT_ERR_BAD_PATH,
8292 "removing directories requires -R option");
8293 goto done;
8297 error = got_worktree_schedule_delete(worktree, &paths,
8298 delete_local_mods, status_codes, print_remove_status, NULL,
8299 repo, keep_on_disk, ignore_missing_paths);
8300 done:
8301 if (repo) {
8302 const struct got_error *close_err = got_repo_close(repo);
8303 if (error == NULL)
8304 error = close_err;
8306 if (worktree)
8307 got_worktree_close(worktree);
8308 if (pack_fds) {
8309 const struct got_error *pack_err =
8310 got_repo_pack_fds_close(pack_fds);
8311 if (error == NULL)
8312 error = pack_err;
8314 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8315 free(cwd);
8316 return error;
8319 __dead static void
8320 usage_patch(void)
8322 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8323 "[patchfile]\n", getprogname());
8324 exit(1);
8327 static const struct got_error *
8328 patch_from_stdin(int *patchfd)
8330 const struct got_error *err = NULL;
8331 ssize_t r;
8332 char buf[BUFSIZ];
8333 sig_t sighup, sigint, sigquit;
8335 *patchfd = got_opentempfd();
8336 if (*patchfd == -1)
8337 return got_error_from_errno("got_opentempfd");
8339 sighup = signal(SIGHUP, SIG_DFL);
8340 sigint = signal(SIGINT, SIG_DFL);
8341 sigquit = signal(SIGQUIT, SIG_DFL);
8343 for (;;) {
8344 r = read(0, buf, sizeof(buf));
8345 if (r == -1) {
8346 err = got_error_from_errno("read");
8347 break;
8349 if (r == 0)
8350 break;
8351 if (write(*patchfd, buf, r) == -1) {
8352 err = got_error_from_errno("write");
8353 break;
8357 signal(SIGHUP, sighup);
8358 signal(SIGINT, sigint);
8359 signal(SIGQUIT, sigquit);
8361 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8362 err = got_error_from_errno("lseek");
8364 if (err != NULL) {
8365 close(*patchfd);
8366 *patchfd = -1;
8369 return err;
8372 struct got_patch_progress_arg {
8373 int did_something;
8374 int conflicts;
8375 int rejects;
8378 static const struct got_error *
8379 patch_progress(void *arg, const char *old, const char *new,
8380 unsigned char status, const struct got_error *error, int old_from,
8381 int old_lines, int new_from, int new_lines, int offset,
8382 int ws_mangled, const struct got_error *hunk_err)
8384 const char *path = new == NULL ? old : new;
8385 struct got_patch_progress_arg *a = arg;
8387 while (*path == '/')
8388 path++;
8390 if (status != GOT_STATUS_NO_CHANGE &&
8391 status != 0 /* per-hunk progress */) {
8392 printf("%c %s\n", status, path);
8393 a->did_something = 1;
8396 if (hunk_err == NULL) {
8397 if (status == GOT_STATUS_CANNOT_UPDATE)
8398 a->rejects++;
8399 else if (status == GOT_STATUS_CONFLICT)
8400 a->conflicts++;
8403 if (error != NULL)
8404 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8406 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8407 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8408 old_lines, new_from, new_lines);
8409 if (hunk_err != NULL)
8410 printf("%s\n", hunk_err->msg);
8411 else if (offset != 0)
8412 printf("applied with offset %d\n", offset);
8413 else
8414 printf("hunk contains mangled whitespace\n");
8417 return NULL;
8420 static void
8421 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8423 if (!ppa->did_something)
8424 return;
8426 if (ppa->conflicts > 0)
8427 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8429 if (ppa->rejects > 0) {
8430 printf("Files where patch failed to apply: %d\n",
8431 ppa->rejects);
8435 static const struct got_error *
8436 cmd_patch(int argc, char *argv[])
8438 const struct got_error *error = NULL, *close_error = NULL;
8439 struct got_worktree *worktree = NULL;
8440 struct got_repository *repo = NULL;
8441 struct got_reflist_head refs;
8442 struct got_object_id *commit_id = NULL;
8443 const char *commit_id_str = NULL;
8444 struct stat sb;
8445 const char *errstr;
8446 char *cwd = NULL, *keyword_idstr = NULL;
8447 int ch, nop = 0, strip = -1, reverse = 0;
8448 int patchfd;
8449 int *pack_fds = NULL;
8450 struct got_patch_progress_arg ppa;
8452 TAILQ_INIT(&refs);
8454 #ifndef PROFILE
8455 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8456 "unveil", NULL) == -1)
8457 err(1, "pledge");
8458 #endif
8460 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8461 switch (ch) {
8462 case 'c':
8463 commit_id_str = optarg;
8464 break;
8465 case 'n':
8466 nop = 1;
8467 break;
8468 case 'p':
8469 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8470 if (errstr != NULL)
8471 errx(1, "pathname strip count is %s: %s",
8472 errstr, optarg);
8473 break;
8474 case 'R':
8475 reverse = 1;
8476 break;
8477 default:
8478 usage_patch();
8479 /* NOTREACHED */
8483 argc -= optind;
8484 argv += optind;
8486 if (argc == 0) {
8487 error = patch_from_stdin(&patchfd);
8488 if (error)
8489 return error;
8490 } else if (argc == 1) {
8491 patchfd = open(argv[0], O_RDONLY);
8492 if (patchfd == -1) {
8493 error = got_error_from_errno2("open", argv[0]);
8494 return error;
8496 if (fstat(patchfd, &sb) == -1) {
8497 error = got_error_from_errno2("fstat", argv[0]);
8498 goto done;
8500 if (!S_ISREG(sb.st_mode)) {
8501 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8502 goto done;
8504 } else
8505 usage_patch();
8507 if ((cwd = getcwd(NULL, 0)) == NULL) {
8508 error = got_error_from_errno("getcwd");
8509 goto done;
8512 error = got_repo_pack_fds_open(&pack_fds);
8513 if (error != NULL)
8514 goto done;
8516 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8517 if (error != NULL)
8518 goto done;
8520 const char *repo_path = got_worktree_get_repo_path(worktree);
8521 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8522 if (error != NULL)
8523 goto done;
8525 error = apply_unveil(got_repo_get_path(repo), 0,
8526 got_worktree_get_root_path(worktree));
8527 if (error != NULL)
8528 goto done;
8530 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8531 if (error)
8532 goto done;
8534 if (commit_id_str != NULL) {
8535 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8536 repo, worktree);
8537 if (error != NULL)
8538 goto done;
8540 error = got_repo_match_object_id(&commit_id, NULL,
8541 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8542 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8543 if (error)
8544 goto done;
8547 memset(&ppa, 0, sizeof(ppa));
8548 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8549 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8550 print_patch_progress_stats(&ppa);
8551 done:
8552 got_ref_list_free(&refs);
8553 free(keyword_idstr);
8554 free(commit_id);
8555 if (repo) {
8556 close_error = got_repo_close(repo);
8557 if (error == NULL)
8558 error = close_error;
8560 if (worktree != NULL) {
8561 close_error = got_worktree_close(worktree);
8562 if (error == NULL)
8563 error = close_error;
8565 if (pack_fds) {
8566 const struct got_error *pack_err =
8567 got_repo_pack_fds_close(pack_fds);
8568 if (error == NULL)
8569 error = pack_err;
8571 free(cwd);
8572 return error;
8575 __dead static void
8576 usage_revert(void)
8578 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8579 getprogname());
8580 exit(1);
8583 static const struct got_error *
8584 revert_progress(void *arg, unsigned char status, const char *path)
8586 if (status == GOT_STATUS_UNVERSIONED)
8587 return NULL;
8589 while (path[0] == '/')
8590 path++;
8591 printf("%c %s\n", status, path);
8592 return NULL;
8595 struct choose_patch_arg {
8596 FILE *patch_script_file;
8597 const char *action;
8600 static const struct got_error *
8601 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8602 int nchanges, const char *action)
8604 const struct got_error *err;
8605 char *line = NULL;
8606 size_t linesize = 0;
8607 ssize_t linelen;
8609 switch (status) {
8610 case GOT_STATUS_ADD:
8611 printf("A %s\n%s this addition? [y/n] ", path, action);
8612 break;
8613 case GOT_STATUS_DELETE:
8614 printf("D %s\n%s this deletion? [y/n] ", path, action);
8615 break;
8616 case GOT_STATUS_MODIFY:
8617 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8618 return got_error_from_errno("fseek");
8619 printf(GOT_COMMIT_SEP_STR);
8620 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8621 printf("%s", line);
8622 if (linelen == -1 && ferror(patch_file)) {
8623 err = got_error_from_errno("getline");
8624 free(line);
8625 return err;
8627 free(line);
8628 printf(GOT_COMMIT_SEP_STR);
8629 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8630 path, n, nchanges, action);
8631 break;
8632 default:
8633 return got_error_path(path, GOT_ERR_FILE_STATUS);
8636 fflush(stdout);
8637 return NULL;
8640 static const struct got_error *
8641 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8642 FILE *patch_file, int n, int nchanges)
8644 const struct got_error *err = NULL;
8645 char *line = NULL;
8646 size_t linesize = 0;
8647 ssize_t linelen;
8648 int resp = ' ';
8649 struct choose_patch_arg *a = arg;
8651 *choice = GOT_PATCH_CHOICE_NONE;
8653 if (a->patch_script_file) {
8654 char *nl;
8655 err = show_change(status, path, patch_file, n, nchanges,
8656 a->action);
8657 if (err)
8658 return err;
8659 linelen = getline(&line, &linesize, a->patch_script_file);
8660 if (linelen == -1) {
8661 if (ferror(a->patch_script_file))
8662 return got_error_from_errno("getline");
8663 return NULL;
8665 nl = strchr(line, '\n');
8666 if (nl)
8667 *nl = '\0';
8668 if (strcmp(line, "y") == 0) {
8669 *choice = GOT_PATCH_CHOICE_YES;
8670 printf("y\n");
8671 } else if (strcmp(line, "n") == 0) {
8672 *choice = GOT_PATCH_CHOICE_NO;
8673 printf("n\n");
8674 } else if (strcmp(line, "q") == 0 &&
8675 status == GOT_STATUS_MODIFY) {
8676 *choice = GOT_PATCH_CHOICE_QUIT;
8677 printf("q\n");
8678 } else
8679 printf("invalid response '%s'\n", line);
8680 free(line);
8681 return NULL;
8684 while (resp != 'y' && resp != 'n' && resp != 'q') {
8685 err = show_change(status, path, patch_file, n, nchanges,
8686 a->action);
8687 if (err)
8688 return err;
8689 resp = getchar();
8690 if (resp == '\n')
8691 resp = getchar();
8692 if (status == GOT_STATUS_MODIFY) {
8693 if (resp != 'y' && resp != 'n' && resp != 'q') {
8694 printf("invalid response '%c'\n", resp);
8695 resp = ' ';
8697 } else if (resp != 'y' && resp != 'n') {
8698 printf("invalid response '%c'\n", resp);
8699 resp = ' ';
8703 if (resp == 'y')
8704 *choice = GOT_PATCH_CHOICE_YES;
8705 else if (resp == 'n')
8706 *choice = GOT_PATCH_CHOICE_NO;
8707 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8708 *choice = GOT_PATCH_CHOICE_QUIT;
8710 return NULL;
8713 struct wt_commitable_path_arg {
8714 struct got_pathlist_head *commit_paths;
8715 int *has_changes;
8719 * Shortcut work tree status callback to determine if the set of paths scanned
8720 * has at least one versioned path that is being modified and, if not NULL, is
8721 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8722 * soon as a path is passed with a status that satisfies this criteria.
8724 static const struct got_error *
8725 worktree_has_commitable_path(void *arg, unsigned char status,
8726 unsigned char staged_status, const char *path,
8727 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8728 struct got_object_id *commit_id, int dirfd, const char *de_name)
8730 struct wt_commitable_path_arg *a = arg;
8732 if (status == staged_status && (status == GOT_STATUS_DELETE))
8733 status = GOT_STATUS_NO_CHANGE;
8735 if (!(status == GOT_STATUS_NO_CHANGE ||
8736 status == GOT_STATUS_UNVERSIONED) ||
8737 staged_status != GOT_STATUS_NO_CHANGE) {
8738 if (a->commit_paths != NULL) {
8739 struct got_pathlist_entry *pe;
8741 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8742 if (strncmp(path, pe->path,
8743 pe->path_len) == 0) {
8744 *a->has_changes = 1;
8745 break;
8748 } else
8749 *a->has_changes = 1;
8751 if (*a->has_changes)
8752 return got_error(GOT_ERR_FILE_MODIFIED);
8755 return NULL;
8759 * Check that the changeset of the commit identified by id is
8760 * comprised of at least one modified path that is being committed.
8762 static const struct got_error *
8763 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8764 struct got_object_id *id, struct got_worktree *worktree,
8765 struct got_repository *repo)
8767 const struct got_error *err;
8768 struct got_pathlist_head paths;
8769 struct got_commit_object *commit = NULL, *pcommit = NULL;
8770 struct got_tree_object *tree = NULL, *ptree = NULL;
8771 struct got_object_qid *pid;
8773 TAILQ_INIT(&paths);
8775 err = got_object_open_as_commit(&commit, repo, id);
8776 if (err)
8777 goto done;
8779 err = got_object_open_as_tree(&tree, repo,
8780 got_object_commit_get_tree_id(commit));
8781 if (err)
8782 goto done;
8784 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8785 if (pid != NULL) {
8786 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8787 if (err)
8788 goto done;
8790 err = got_object_open_as_tree(&ptree, repo,
8791 got_object_commit_get_tree_id(pcommit));
8792 if (err)
8793 goto done;
8796 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8797 got_diff_tree_collect_changed_paths, &paths, 0);
8798 if (err)
8799 goto done;
8801 err = got_worktree_status(worktree, &paths, repo, 0,
8802 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8803 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8805 * At least one changed path in the referenced commit is
8806 * modified in the work tree, that's all we need to know!
8808 err = NULL;
8811 done:
8812 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8813 if (commit)
8814 got_object_commit_close(commit);
8815 if (pcommit)
8816 got_object_commit_close(pcommit);
8817 if (tree)
8818 got_object_tree_close(tree);
8819 if (ptree)
8820 got_object_tree_close(ptree);
8821 return err;
8825 * Remove any "logmsg" reference comprised entirely of paths that have
8826 * been reverted in this work tree. If any path in the logmsg ref changeset
8827 * remains in a changed state in the worktree, do not remove the reference.
8829 static const struct got_error *
8830 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8832 const struct got_error *err;
8833 struct got_reflist_head refs;
8834 struct got_reflist_entry *re;
8835 struct got_commit_object *commit = NULL;
8836 struct got_object_id *commit_id = NULL;
8837 struct wt_commitable_path_arg wcpa;
8838 char *uuidstr = NULL;
8840 TAILQ_INIT(&refs);
8842 err = got_worktree_get_uuid(&uuidstr, worktree);
8843 if (err)
8844 goto done;
8846 err = got_ref_list(&refs, repo, "refs/got/worktree",
8847 got_ref_cmp_by_name, repo);
8848 if (err)
8849 goto done;
8851 TAILQ_FOREACH(re, &refs, entry) {
8852 const char *refname;
8853 int has_changes = 0;
8855 refname = got_ref_get_name(re->ref);
8857 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8858 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8859 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8860 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8861 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8862 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8863 else
8864 continue;
8866 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8867 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8868 else
8869 continue;
8871 err = got_repo_match_object_id(&commit_id, NULL, refname,
8872 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8873 if (err)
8874 goto done;
8876 err = got_object_open_as_commit(&commit, repo, commit_id);
8877 if (err)
8878 goto done;
8880 wcpa.commit_paths = NULL;
8881 wcpa.has_changes = &has_changes;
8883 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8884 worktree, repo);
8885 if (err)
8886 goto done;
8888 if (!has_changes) {
8889 err = got_ref_delete(re->ref, repo);
8890 if (err)
8891 goto done;
8894 got_object_commit_close(commit);
8895 commit = NULL;
8896 free(commit_id);
8897 commit_id = NULL;
8900 done:
8901 free(uuidstr);
8902 free(commit_id);
8903 got_ref_list_free(&refs);
8904 if (commit)
8905 got_object_commit_close(commit);
8906 return err;
8909 static const struct got_error *
8910 cmd_revert(int argc, char *argv[])
8912 const struct got_error *error = NULL;
8913 struct got_worktree *worktree = NULL;
8914 struct got_repository *repo = NULL;
8915 char *cwd = NULL, *path = NULL;
8916 struct got_pathlist_head paths;
8917 int ch, contains_dir, can_recurse = 0, pflag = 0;
8918 FILE *patch_script_file = NULL;
8919 const char *patch_script_path = NULL;
8920 struct choose_patch_arg cpa;
8921 int *pack_fds = NULL;
8923 TAILQ_INIT(&paths);
8925 #ifndef PROFILE
8926 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8927 "unveil", NULL) == -1)
8928 err(1, "pledge");
8929 #endif
8931 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8932 switch (ch) {
8933 case 'F':
8934 patch_script_path = optarg;
8935 break;
8936 case 'p':
8937 pflag = 1;
8938 break;
8939 case 'R':
8940 can_recurse = 1;
8941 break;
8942 default:
8943 usage_revert();
8944 /* NOTREACHED */
8948 argc -= optind;
8949 argv += optind;
8951 if (argc < 1)
8952 usage_revert();
8953 if (patch_script_path && !pflag)
8954 errx(1, "-F option can only be used together with -p option");
8956 cwd = getcwd(NULL, 0);
8957 if (cwd == NULL) {
8958 error = got_error_from_errno("getcwd");
8959 goto done;
8962 error = got_repo_pack_fds_open(&pack_fds);
8963 if (error != NULL)
8964 goto done;
8966 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8967 if (error) {
8968 if (error->code == GOT_ERR_NOT_WORKTREE)
8969 error = wrap_not_worktree_error(error, "revert", cwd);
8970 goto done;
8973 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8974 NULL, pack_fds);
8975 if (error != NULL)
8976 goto done;
8978 if (patch_script_path) {
8979 patch_script_file = fopen(patch_script_path, "re");
8980 if (patch_script_file == NULL) {
8981 error = got_error_from_errno2("fopen",
8982 patch_script_path);
8983 goto done;
8988 * XXX "c" perm needed on repo dir to delete merge references.
8990 error = apply_unveil(got_repo_get_path(repo), 0,
8991 got_worktree_get_root_path(worktree));
8992 if (error)
8993 goto done;
8995 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8996 if (error)
8997 goto done;
8999 if (!can_recurse) {
9000 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
9001 if (error != NULL)
9002 goto done;
9004 if (contains_dir) {
9005 error = got_error_msg(GOT_ERR_BAD_PATH,
9006 "reverting directories requires -R option");
9007 goto done;
9011 cpa.patch_script_file = patch_script_file;
9012 cpa.action = "revert";
9013 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9014 pflag ? choose_patch : NULL, &cpa, repo);
9016 error = rm_logmsg_ref(worktree, repo);
9017 done:
9018 if (patch_script_file && fclose(patch_script_file) == EOF &&
9019 error == NULL)
9020 error = got_error_from_errno2("fclose", patch_script_path);
9021 if (repo) {
9022 const struct got_error *close_err = got_repo_close(repo);
9023 if (error == NULL)
9024 error = close_err;
9026 if (worktree)
9027 got_worktree_close(worktree);
9028 if (pack_fds) {
9029 const struct got_error *pack_err =
9030 got_repo_pack_fds_close(pack_fds);
9031 if (error == NULL)
9032 error = pack_err;
9034 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9035 free(path);
9036 free(cwd);
9037 return error;
9040 __dead static void
9041 usage_commit(void)
9043 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9044 "[-m message] [path ...]\n", getprogname());
9045 exit(1);
9048 struct collect_commit_logmsg_arg {
9049 const char *cmdline_log;
9050 const char *prepared_log;
9051 const char *merged_log;
9052 int non_interactive;
9053 const char *editor;
9054 const char *worktree_path;
9055 const char *branch_name;
9056 const char *repo_path;
9057 char *logmsg_path;
9061 static const struct got_error *
9062 read_prepared_logmsg(char **logmsg, const char *path)
9064 const struct got_error *err = NULL;
9065 FILE *f = NULL;
9066 struct stat sb;
9067 size_t r;
9069 *logmsg = NULL;
9070 memset(&sb, 0, sizeof(sb));
9072 f = fopen(path, "re");
9073 if (f == NULL)
9074 return got_error_from_errno2("fopen", path);
9076 if (fstat(fileno(f), &sb) == -1) {
9077 err = got_error_from_errno2("fstat", path);
9078 goto done;
9080 if (sb.st_size == 0) {
9081 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9082 goto done;
9085 *logmsg = malloc(sb.st_size + 1);
9086 if (*logmsg == NULL) {
9087 err = got_error_from_errno("malloc");
9088 goto done;
9091 r = fread(*logmsg, 1, sb.st_size, f);
9092 if (r != sb.st_size) {
9093 if (ferror(f))
9094 err = got_error_from_errno2("fread", path);
9095 else
9096 err = got_error(GOT_ERR_IO);
9097 goto done;
9099 (*logmsg)[sb.st_size] = '\0';
9100 done:
9101 if (fclose(f) == EOF && err == NULL)
9102 err = got_error_from_errno2("fclose", path);
9103 if (err) {
9104 free(*logmsg);
9105 *logmsg = NULL;
9107 return err;
9110 static const struct got_error *
9111 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9112 const char *diff_path, char **logmsg, void *arg)
9114 char *initial_content = NULL;
9115 struct got_pathlist_entry *pe;
9116 const struct got_error *err = NULL;
9117 char *template = NULL;
9118 char *prepared_msg = NULL, *merged_msg = NULL;
9119 struct collect_commit_logmsg_arg *a = arg;
9120 int initial_content_len;
9121 int fd = -1;
9122 size_t len;
9124 /* if a message was specified on the command line, just use it */
9125 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9126 len = strlen(a->cmdline_log) + 1;
9127 *logmsg = malloc(len + 1);
9128 if (*logmsg == NULL)
9129 return got_error_from_errno("malloc");
9130 strlcpy(*logmsg, a->cmdline_log, len);
9131 return NULL;
9132 } else if (a->prepared_log != NULL && a->non_interactive)
9133 return read_prepared_logmsg(logmsg, a->prepared_log);
9135 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9136 return got_error_from_errno("asprintf");
9138 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9139 if (err)
9140 goto done;
9142 if (a->prepared_log) {
9143 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9144 if (err)
9145 goto done;
9146 } else if (a->merged_log) {
9147 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9148 if (err)
9149 goto done;
9152 initial_content_len = asprintf(&initial_content,
9153 "%s%s\n# changes to be committed on branch %s:\n",
9154 prepared_msg ? prepared_msg : "",
9155 merged_msg ? merged_msg : "", a->branch_name);
9156 if (initial_content_len == -1) {
9157 err = got_error_from_errno("asprintf");
9158 goto done;
9161 if (write(fd, initial_content, initial_content_len) == -1) {
9162 err = got_error_from_errno2("write", a->logmsg_path);
9163 goto done;
9166 TAILQ_FOREACH(pe, commitable_paths, entry) {
9167 struct got_commitable *ct = pe->data;
9168 dprintf(fd, "# %c %s\n",
9169 got_commitable_get_status(ct),
9170 got_commitable_get_path(ct));
9173 if (diff_path) {
9174 dprintf(fd, "# detailed changes can be viewed in %s\n",
9175 diff_path);
9178 if (close(fd) == -1) {
9179 err = got_error_from_errno2("close", a->logmsg_path);
9180 goto done;
9182 fd = -1;
9184 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9185 initial_content_len, a->prepared_log ? 0 : 1);
9186 done:
9187 free(initial_content);
9188 free(template);
9189 free(prepared_msg);
9190 free(merged_msg);
9192 if (fd != -1 && close(fd) == -1 && err == NULL)
9193 err = got_error_from_errno2("close", a->logmsg_path);
9194 if (err) {
9195 free(*logmsg);
9196 *logmsg = NULL;
9198 return err;
9201 static const struct got_error *
9202 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9203 const char *type, int has_content)
9205 const struct got_error *err = NULL;
9206 char *logmsg = NULL;
9208 err = got_object_commit_get_logmsg(&logmsg, commit);
9209 if (err)
9210 return err;
9212 if (fprintf(f, "%s# log message of %s commit %s:%s",
9213 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9214 err = got_ferror(f, GOT_ERR_IO);
9216 free(logmsg);
9217 return err;
9221 * Lookup "logmsg" references of backed-out and cherrypicked commits
9222 * belonging to the current work tree. If found, and the worktree has
9223 * at least one modified file that was changed in the referenced commit,
9224 * add its log message to a new temporary file at *logmsg_path.
9225 * Add all refs found to matched_refs to be scheduled for removal on
9226 * successful commit.
9228 static const struct got_error *
9229 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9230 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9231 struct got_repository *repo)
9233 const struct got_error *err;
9234 struct got_commit_object *commit = NULL;
9235 struct got_object_id *id = NULL;
9236 struct got_reflist_head refs;
9237 struct got_reflist_entry *re, *re_match;
9238 FILE *f = NULL;
9239 char *uuidstr = NULL;
9240 int added_logmsg = 0;
9242 TAILQ_INIT(&refs);
9244 *logmsg_path = NULL;
9246 err = got_worktree_get_uuid(&uuidstr, worktree);
9247 if (err)
9248 goto done;
9250 err = got_ref_list(&refs, repo, "refs/got/worktree",
9251 got_ref_cmp_by_name, repo);
9252 if (err)
9253 goto done;
9255 TAILQ_FOREACH(re, &refs, entry) {
9256 const char *refname, *type;
9257 struct wt_commitable_path_arg wcpa;
9258 int add_logmsg = 0;
9260 refname = got_ref_get_name(re->ref);
9262 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9263 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9264 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9265 type = "cherrypicked";
9266 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9267 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9268 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9269 type = "backed-out";
9270 } else
9271 continue;
9273 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9274 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9275 else
9276 continue;
9278 err = got_repo_match_object_id(&id, NULL, refname,
9279 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9280 if (err)
9281 goto done;
9283 err = got_object_open_as_commit(&commit, repo, id);
9284 if (err)
9285 goto done;
9287 wcpa.commit_paths = paths;
9288 wcpa.has_changes = &add_logmsg;
9290 err = commit_path_changed_in_worktree(&wcpa, id,
9291 worktree, repo);
9292 if (err)
9293 goto done;
9295 if (add_logmsg) {
9296 if (f == NULL) {
9297 err = got_opentemp_named(logmsg_path, &f,
9298 "got-commit-logmsg", "");
9299 if (err)
9300 goto done;
9302 err = cat_logmsg(f, commit, refname, type,
9303 added_logmsg);
9304 if (err)
9305 goto done;
9306 if (!added_logmsg)
9307 ++added_logmsg;
9309 err = got_reflist_entry_dup(&re_match, re);
9310 if (err)
9311 goto done;
9312 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9315 got_object_commit_close(commit);
9316 commit = NULL;
9317 free(id);
9318 id = NULL;
9321 done:
9322 free(id);
9323 free(uuidstr);
9324 got_ref_list_free(&refs);
9325 if (commit)
9326 got_object_commit_close(commit);
9327 if (f && fclose(f) == EOF && err == NULL)
9328 err = got_error_from_errno("fclose");
9329 if (!added_logmsg) {
9330 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9331 err = got_error_from_errno2("unlink", *logmsg_path);
9332 *logmsg_path = NULL;
9334 return err;
9337 static const struct got_error *
9338 cmd_commit(int argc, char *argv[])
9340 const struct got_error *error = NULL;
9341 struct got_worktree *worktree = NULL;
9342 struct got_repository *repo = NULL;
9343 char *cwd = NULL, *id_str = NULL;
9344 struct got_object_id *id = NULL;
9345 const char *logmsg = NULL;
9346 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9347 struct collect_commit_logmsg_arg cl_arg;
9348 const char *author = NULL;
9349 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9350 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9351 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9352 int show_diff = 1, commit_conflicts = 0;
9353 struct got_pathlist_head paths;
9354 struct got_reflist_head refs;
9355 struct got_reflist_entry *re;
9356 int *pack_fds = NULL;
9358 TAILQ_INIT(&refs);
9359 TAILQ_INIT(&paths);
9360 cl_arg.logmsg_path = NULL;
9362 #ifndef PROFILE
9363 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9364 "unveil", NULL) == -1)
9365 err(1, "pledge");
9366 #endif
9368 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9369 switch (ch) {
9370 case 'A':
9371 author = optarg;
9372 error = valid_author(author);
9373 if (error)
9374 return error;
9375 break;
9376 case 'C':
9377 commit_conflicts = 1;
9378 break;
9379 case 'F':
9380 if (logmsg != NULL)
9381 option_conflict('F', 'm');
9382 prepared_logmsg = realpath(optarg, NULL);
9383 if (prepared_logmsg == NULL)
9384 return got_error_from_errno2("realpath",
9385 optarg);
9386 break;
9387 case 'm':
9388 if (prepared_logmsg)
9389 option_conflict('m', 'F');
9390 logmsg = optarg;
9391 break;
9392 case 'N':
9393 non_interactive = 1;
9394 break;
9395 case 'n':
9396 show_diff = 0;
9397 break;
9398 case 'S':
9399 allow_bad_symlinks = 1;
9400 break;
9401 default:
9402 usage_commit();
9403 /* NOTREACHED */
9407 argc -= optind;
9408 argv += optind;
9410 cwd = getcwd(NULL, 0);
9411 if (cwd == NULL) {
9412 error = got_error_from_errno("getcwd");
9413 goto done;
9416 error = got_repo_pack_fds_open(&pack_fds);
9417 if (error != NULL)
9418 goto done;
9420 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9421 if (error) {
9422 if (error->code == GOT_ERR_NOT_WORKTREE)
9423 error = wrap_not_worktree_error(error, "commit", cwd);
9424 goto done;
9427 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9428 if (error)
9429 goto done;
9430 if (rebase_in_progress) {
9431 error = got_error(GOT_ERR_REBASING);
9432 goto done;
9435 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9436 worktree);
9437 if (error)
9438 goto done;
9440 error = get_gitconfig_path(&gitconfig_path);
9441 if (error)
9442 goto done;
9443 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9444 gitconfig_path, pack_fds);
9445 if (error != NULL)
9446 goto done;
9448 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9449 if (error)
9450 goto done;
9451 if (merge_in_progress) {
9452 error = got_error(GOT_ERR_MERGE_BUSY);
9453 goto done;
9456 error = get_author(&committer, repo, worktree);
9457 if (error)
9458 goto done;
9460 if (author == NULL)
9461 author = committer;
9463 if (logmsg == NULL || strlen(logmsg) == 0) {
9464 error = get_editor(&editor);
9465 if (error)
9466 goto done;
9467 if (unveil(editor, "x") != 0) {
9468 error = got_error_from_errno2("unveil", editor);
9469 goto done;
9472 if (prepared_logmsg) {
9473 if (unveil(prepared_logmsg, "r") != 0) {
9474 error = got_error_from_errno2("unveil",
9475 prepared_logmsg);
9476 goto done;
9480 error = apply_unveil(got_repo_get_path(repo), 0,
9481 got_worktree_get_root_path(worktree));
9482 if (error)
9483 goto done;
9485 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9486 if (error)
9487 goto done;
9489 if (prepared_logmsg == NULL) {
9490 error = lookup_logmsg_ref(&merged_logmsg,
9491 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9492 if (error)
9493 goto done;
9496 cl_arg.editor = editor;
9497 cl_arg.cmdline_log = logmsg;
9498 cl_arg.prepared_log = prepared_logmsg;
9499 cl_arg.merged_log = merged_logmsg;
9500 cl_arg.non_interactive = non_interactive;
9501 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9502 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9503 if (!histedit_in_progress) {
9504 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9505 error = got_error(GOT_ERR_COMMIT_BRANCH);
9506 goto done;
9508 cl_arg.branch_name += 11;
9510 cl_arg.repo_path = got_repo_get_path(repo);
9511 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9512 allow_bad_symlinks, show_diff, commit_conflicts,
9513 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9514 if (error) {
9515 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9516 cl_arg.logmsg_path != NULL)
9517 preserve_logmsg = 1;
9518 goto done;
9521 error = got_object_id_str(&id_str, id);
9522 if (error)
9523 goto done;
9524 printf("Created commit %s\n", id_str);
9526 TAILQ_FOREACH(re, &refs, entry) {
9527 error = got_ref_delete(re->ref, repo);
9528 if (error)
9529 goto done;
9532 done:
9533 if (preserve_logmsg) {
9534 fprintf(stderr, "%s: log message preserved in %s\n",
9535 getprogname(), cl_arg.logmsg_path);
9536 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9537 error == NULL)
9538 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9539 free(cl_arg.logmsg_path);
9540 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9541 error = got_error_from_errno2("unlink", merged_logmsg);
9542 free(merged_logmsg);
9543 if (repo) {
9544 const struct got_error *close_err = got_repo_close(repo);
9545 if (error == NULL)
9546 error = close_err;
9548 if (worktree)
9549 got_worktree_close(worktree);
9550 if (pack_fds) {
9551 const struct got_error *pack_err =
9552 got_repo_pack_fds_close(pack_fds);
9553 if (error == NULL)
9554 error = pack_err;
9556 got_ref_list_free(&refs);
9557 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9558 free(cwd);
9559 free(id_str);
9560 free(gitconfig_path);
9561 free(editor);
9562 free(committer);
9563 free(prepared_logmsg);
9564 return error;
9567 __dead static void
9568 usage_send(void)
9570 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9571 "[-r repository-path] [-t tag] [remote-repository]\n",
9572 getprogname());
9573 exit(1);
9576 static void
9577 print_load_info(int print_colored, int print_found, int print_trees,
9578 int ncolored, int nfound, int ntrees)
9580 if (print_colored) {
9581 printf("%d commit%s colored", ncolored,
9582 ncolored == 1 ? "" : "s");
9584 if (print_found) {
9585 printf("%s%d object%s found",
9586 ncolored > 0 ? "; " : "",
9587 nfound, nfound == 1 ? "" : "s");
9589 if (print_trees) {
9590 printf("; %d tree%s scanned", ntrees,
9591 ntrees == 1 ? "" : "s");
9595 struct got_send_progress_arg {
9596 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9597 int verbosity;
9598 int last_ncolored;
9599 int last_nfound;
9600 int last_ntrees;
9601 int loading_done;
9602 int last_ncommits;
9603 int last_nobj_total;
9604 int last_p_deltify;
9605 int last_p_written;
9606 int last_p_sent;
9607 int printed_something;
9608 int sent_something;
9609 struct got_pathlist_head *delete_branches;
9612 static const struct got_error *
9613 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9614 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9615 int nobj_written, off_t bytes_sent, const char *refname,
9616 const char *errmsg, int success)
9618 struct got_send_progress_arg *a = arg;
9619 char scaled_packsize[FMT_SCALED_STRSIZE];
9620 char scaled_sent[FMT_SCALED_STRSIZE];
9621 int p_deltify = 0, p_written = 0, p_sent = 0;
9622 int print_colored = 0, print_found = 0, print_trees = 0;
9623 int print_searching = 0, print_total = 0;
9624 int print_deltify = 0, print_written = 0, print_sent = 0;
9626 if (a->verbosity < 0)
9627 return NULL;
9629 if (refname) {
9630 const char *status = success ? "accepted" : "rejected";
9632 if (success) {
9633 struct got_pathlist_entry *pe;
9634 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9635 const char *branchname = pe->path;
9636 if (got_path_cmp(branchname, refname,
9637 strlen(branchname), strlen(refname)) == 0) {
9638 status = "deleted";
9639 a->sent_something = 1;
9640 break;
9645 if (a->printed_something)
9646 putchar('\n');
9647 printf("Server has %s %s", status, refname);
9648 if (errmsg)
9649 printf(": %s", errmsg);
9650 a->printed_something = 1;
9651 return NULL;
9654 if (a->last_ncolored != ncolored) {
9655 print_colored = 1;
9656 a->last_ncolored = ncolored;
9659 if (a->last_nfound != nfound) {
9660 print_colored = 1;
9661 print_found = 1;
9662 a->last_nfound = nfound;
9665 if (a->last_ntrees != ntrees) {
9666 print_colored = 1;
9667 print_found = 1;
9668 print_trees = 1;
9669 a->last_ntrees = ntrees;
9672 if ((print_colored || print_found || print_trees) &&
9673 !a->loading_done) {
9674 printf("\r");
9675 print_load_info(print_colored, print_found, print_trees,
9676 ncolored, nfound, ntrees);
9677 a->printed_something = 1;
9678 fflush(stdout);
9679 return NULL;
9680 } else if (!a->loading_done) {
9681 printf("\r");
9682 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9683 printf("\n");
9684 a->loading_done = 1;
9687 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9688 return got_error_from_errno("fmt_scaled");
9689 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9690 return got_error_from_errno("fmt_scaled");
9692 if (a->last_ncommits != ncommits) {
9693 print_searching = 1;
9694 a->last_ncommits = ncommits;
9697 if (a->last_nobj_total != nobj_total) {
9698 print_searching = 1;
9699 print_total = 1;
9700 a->last_nobj_total = nobj_total;
9703 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9704 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9705 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9706 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9707 return got_error(GOT_ERR_NO_SPACE);
9710 if (nobj_deltify > 0 || nobj_written > 0) {
9711 if (nobj_deltify > 0) {
9712 p_deltify = (nobj_deltify * 100) / nobj_total;
9713 if (p_deltify != a->last_p_deltify) {
9714 a->last_p_deltify = p_deltify;
9715 print_searching = 1;
9716 print_total = 1;
9717 print_deltify = 1;
9720 if (nobj_written > 0) {
9721 p_written = (nobj_written * 100) / nobj_total;
9722 if (p_written != a->last_p_written) {
9723 a->last_p_written = p_written;
9724 print_searching = 1;
9725 print_total = 1;
9726 print_deltify = 1;
9727 print_written = 1;
9732 if (bytes_sent > 0) {
9733 p_sent = (bytes_sent * 100) / packfile_size;
9734 if (p_sent != a->last_p_sent) {
9735 a->last_p_sent = p_sent;
9736 print_searching = 1;
9737 print_total = 1;
9738 print_deltify = 1;
9739 print_written = 1;
9740 print_sent = 1;
9742 a->sent_something = 1;
9745 if (print_searching || print_total || print_deltify || print_written ||
9746 print_sent)
9747 printf("\r");
9748 if (print_searching)
9749 printf("packing %d reference%s", ncommits,
9750 ncommits == 1 ? "" : "s");
9751 if (print_total)
9752 printf("; %d object%s", nobj_total,
9753 nobj_total == 1 ? "" : "s");
9754 if (print_deltify)
9755 printf("; deltify: %d%%", p_deltify);
9756 if (print_sent)
9757 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9758 scaled_packsize, p_sent);
9759 else if (print_written)
9760 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9761 scaled_packsize, p_written);
9762 if (print_searching || print_total || print_deltify ||
9763 print_written || print_sent) {
9764 a->printed_something = 1;
9765 fflush(stdout);
9767 return NULL;
9770 static const struct got_error *
9771 cmd_send(int argc, char *argv[])
9773 const struct got_error *error = NULL;
9774 char *cwd = NULL, *repo_path = NULL;
9775 const char *remote_name;
9776 char *proto = NULL, *host = NULL, *port = NULL;
9777 char *repo_name = NULL, *server_path = NULL;
9778 const struct got_remote_repo *remotes;
9779 struct got_remote_repo *remote = NULL;
9780 int nremotes, nbranches = 0, ndelete_branches = 0;
9781 struct got_repository *repo = NULL;
9782 struct got_worktree *worktree = NULL;
9783 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9784 struct got_pathlist_head branches;
9785 struct got_pathlist_head tags;
9786 struct got_reflist_head all_branches;
9787 struct got_reflist_head all_tags;
9788 struct got_pathlist_head delete_args;
9789 struct got_pathlist_head delete_branches;
9790 struct got_reflist_entry *re;
9791 struct got_pathlist_entry *pe;
9792 int i, ch, sendfd = -1, sendstatus;
9793 pid_t sendpid = -1;
9794 struct got_send_progress_arg spa;
9795 int verbosity = 0, overwrite_refs = 0;
9796 int send_all_branches = 0, send_all_tags = 0;
9797 struct got_reference *ref = NULL;
9798 int *pack_fds = NULL;
9800 TAILQ_INIT(&branches);
9801 TAILQ_INIT(&tags);
9802 TAILQ_INIT(&all_branches);
9803 TAILQ_INIT(&all_tags);
9804 TAILQ_INIT(&delete_args);
9805 TAILQ_INIT(&delete_branches);
9807 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9808 switch (ch) {
9809 case 'a':
9810 send_all_branches = 1;
9811 break;
9812 case 'b':
9813 error = got_pathlist_append(&branches, optarg, NULL);
9814 if (error)
9815 return error;
9816 nbranches++;
9817 break;
9818 case 'd':
9819 error = got_pathlist_append(&delete_args, optarg, NULL);
9820 if (error)
9821 return error;
9822 break;
9823 case 'f':
9824 overwrite_refs = 1;
9825 break;
9826 case 'q':
9827 verbosity = -1;
9828 break;
9829 case 'r':
9830 repo_path = realpath(optarg, NULL);
9831 if (repo_path == NULL)
9832 return got_error_from_errno2("realpath",
9833 optarg);
9834 got_path_strip_trailing_slashes(repo_path);
9835 break;
9836 case 'T':
9837 send_all_tags = 1;
9838 break;
9839 case 't':
9840 error = got_pathlist_append(&tags, optarg, NULL);
9841 if (error)
9842 return error;
9843 break;
9844 case 'v':
9845 if (verbosity < 0)
9846 verbosity = 0;
9847 else if (verbosity < 3)
9848 verbosity++;
9849 break;
9850 default:
9851 usage_send();
9852 /* NOTREACHED */
9855 argc -= optind;
9856 argv += optind;
9858 if (send_all_branches && !TAILQ_EMPTY(&branches))
9859 option_conflict('a', 'b');
9860 if (send_all_tags && !TAILQ_EMPTY(&tags))
9861 option_conflict('T', 't');
9864 if (argc == 0)
9865 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9866 else if (argc == 1)
9867 remote_name = argv[0];
9868 else
9869 usage_send();
9871 cwd = getcwd(NULL, 0);
9872 if (cwd == NULL) {
9873 error = got_error_from_errno("getcwd");
9874 goto done;
9877 error = got_repo_pack_fds_open(&pack_fds);
9878 if (error != NULL)
9879 goto done;
9881 if (repo_path == NULL) {
9882 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9883 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9884 goto done;
9885 else
9886 error = NULL;
9887 if (worktree) {
9888 repo_path =
9889 strdup(got_worktree_get_repo_path(worktree));
9890 if (repo_path == NULL)
9891 error = got_error_from_errno("strdup");
9892 if (error)
9893 goto done;
9894 } else {
9895 repo_path = strdup(cwd);
9896 if (repo_path == NULL) {
9897 error = got_error_from_errno("strdup");
9898 goto done;
9903 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9904 if (error)
9905 goto done;
9907 if (worktree) {
9908 worktree_conf = got_worktree_get_gotconfig(worktree);
9909 if (worktree_conf) {
9910 got_gotconfig_get_remotes(&nremotes, &remotes,
9911 worktree_conf);
9912 for (i = 0; i < nremotes; i++) {
9913 if (strcmp(remotes[i].name, remote_name) == 0) {
9914 error = got_repo_remote_repo_dup(&remote,
9915 &remotes[i]);
9916 if (error)
9917 goto done;
9918 break;
9923 if (remote == NULL) {
9924 repo_conf = got_repo_get_gotconfig(repo);
9925 if (repo_conf) {
9926 got_gotconfig_get_remotes(&nremotes, &remotes,
9927 repo_conf);
9928 for (i = 0; i < nremotes; i++) {
9929 if (strcmp(remotes[i].name, remote_name) == 0) {
9930 error = got_repo_remote_repo_dup(&remote,
9931 &remotes[i]);
9932 if (error)
9933 goto done;
9934 break;
9939 if (remote == NULL) {
9940 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9941 for (i = 0; i < nremotes; i++) {
9942 if (strcmp(remotes[i].name, remote_name) == 0) {
9943 error = got_repo_remote_repo_dup(&remote,
9944 &remotes[i]);
9945 if (error)
9946 goto done;
9947 break;
9951 if (remote == NULL) {
9952 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9953 goto done;
9956 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9957 &repo_name, remote->send_url);
9958 if (error)
9959 goto done;
9961 if (strcmp(proto, "git") == 0) {
9962 #ifndef PROFILE
9963 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9964 "sendfd dns inet unveil", NULL) == -1)
9965 err(1, "pledge");
9966 #endif
9967 } else if (strcmp(proto, "git+ssh") == 0 ||
9968 strcmp(proto, "ssh") == 0) {
9969 #ifndef PROFILE
9970 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9971 "sendfd unveil", NULL) == -1)
9972 err(1, "pledge");
9973 #endif
9974 } else if (strcmp(proto, "http") == 0 ||
9975 strcmp(proto, "git+http") == 0) {
9976 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9977 goto done;
9978 } else {
9979 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9980 goto done;
9983 error = got_dial_apply_unveil(proto);
9984 if (error)
9985 goto done;
9987 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9988 if (error)
9989 goto done;
9991 if (send_all_branches) {
9992 error = got_ref_list(&all_branches, repo, "refs/heads",
9993 got_ref_cmp_by_name, NULL);
9994 if (error)
9995 goto done;
9996 TAILQ_FOREACH(re, &all_branches, entry) {
9997 const char *branchname = got_ref_get_name(re->ref);
9998 error = got_pathlist_append(&branches,
9999 branchname, NULL);
10000 if (error)
10001 goto done;
10002 nbranches++;
10004 } else if (nbranches == 0) {
10005 for (i = 0; i < remote->nsend_branches; i++) {
10006 error = got_pathlist_append(&branches,
10007 remote->send_branches[i], NULL);
10008 if (error)
10009 goto done;
10013 if (send_all_tags) {
10014 error = got_ref_list(&all_tags, repo, "refs/tags",
10015 got_ref_cmp_by_name, NULL);
10016 if (error)
10017 goto done;
10018 TAILQ_FOREACH(re, &all_tags, entry) {
10019 const char *tagname = got_ref_get_name(re->ref);
10020 error = got_pathlist_append(&tags,
10021 tagname, NULL);
10022 if (error)
10023 goto done;
10028 * To prevent accidents only branches in refs/heads/ can be deleted
10029 * with 'got send -d'.
10030 * Deleting anything else requires local repository access or Git.
10032 TAILQ_FOREACH(pe, &delete_args, entry) {
10033 const char *branchname = pe->path;
10034 char *s;
10035 struct got_pathlist_entry *new;
10036 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10037 s = strdup(branchname);
10038 if (s == NULL) {
10039 error = got_error_from_errno("strdup");
10040 goto done;
10042 } else {
10043 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10044 error = got_error_from_errno("asprintf");
10045 goto done;
10048 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10049 if (error || new == NULL /* duplicate */)
10050 free(s);
10051 if (error)
10052 goto done;
10053 ndelete_branches++;
10056 if (nbranches == 0 && ndelete_branches == 0) {
10057 struct got_reference *head_ref;
10058 if (worktree)
10059 error = got_ref_open(&head_ref, repo,
10060 got_worktree_get_head_ref_name(worktree), 0);
10061 else
10062 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10063 if (error)
10064 goto done;
10065 if (got_ref_is_symbolic(head_ref)) {
10066 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10067 got_ref_close(head_ref);
10068 if (error)
10069 goto done;
10070 } else
10071 ref = head_ref;
10072 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10073 NULL);
10074 if (error)
10075 goto done;
10076 nbranches++;
10079 if (worktree) {
10080 /* Release work tree lock. */
10081 got_worktree_close(worktree);
10082 worktree = NULL;
10085 if (verbosity >= 0) {
10086 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10087 remote->name, proto, host,
10088 port ? ":" : "", port ? port : "",
10089 *server_path == '/' ? "" : "/", server_path);
10092 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10093 server_path, verbosity);
10094 if (error)
10095 goto done;
10097 memset(&spa, 0, sizeof(spa));
10098 spa.last_scaled_packsize[0] = '\0';
10099 spa.last_p_deltify = -1;
10100 spa.last_p_written = -1;
10101 spa.verbosity = verbosity;
10102 spa.delete_branches = &delete_branches;
10103 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10104 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10105 check_cancelled, NULL);
10106 if (spa.printed_something)
10107 putchar('\n');
10108 if (error)
10109 goto done;
10110 if (!spa.sent_something && verbosity >= 0)
10111 printf("Already up-to-date\n");
10112 done:
10113 if (sendpid > 0) {
10114 if (kill(sendpid, SIGTERM) == -1)
10115 error = got_error_from_errno("kill");
10116 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10117 error = got_error_from_errno("waitpid");
10119 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10120 error = got_error_from_errno("close");
10121 if (repo) {
10122 const struct got_error *close_err = got_repo_close(repo);
10123 if (error == NULL)
10124 error = close_err;
10126 if (worktree)
10127 got_worktree_close(worktree);
10128 if (pack_fds) {
10129 const struct got_error *pack_err =
10130 got_repo_pack_fds_close(pack_fds);
10131 if (error == NULL)
10132 error = pack_err;
10134 if (ref)
10135 got_ref_close(ref);
10136 got_repo_free_remote_repo_data(remote);
10137 free(remote);
10138 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10139 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10140 got_ref_list_free(&all_branches);
10141 got_ref_list_free(&all_tags);
10142 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10143 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10144 free(cwd);
10145 free(repo_path);
10146 free(proto);
10147 free(host);
10148 free(port);
10149 free(server_path);
10150 free(repo_name);
10151 return error;
10155 * Print and if delete is set delete all ref_prefix references.
10156 * If wanted_ref is not NULL, only print or delete this reference.
10158 static const struct got_error *
10159 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10160 const char *wanted_ref, int delete, struct got_worktree *worktree,
10161 struct got_repository *repo)
10163 const struct got_error *err;
10164 struct got_pathlist_head paths;
10165 struct got_reflist_head refs;
10166 struct got_reflist_entry *re;
10167 struct got_reflist_object_id_map *refs_idmap = NULL;
10168 struct got_commit_object *commit = NULL;
10169 struct got_object_id *id = NULL;
10170 const char *header_prefix;
10171 char *uuidstr = NULL;
10172 int found = 0;
10174 TAILQ_INIT(&refs);
10175 TAILQ_INIT(&paths);
10177 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10178 if (err)
10179 goto done;
10181 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10182 if (err)
10183 goto done;
10185 if (worktree != NULL) {
10186 err = got_worktree_get_uuid(&uuidstr, worktree);
10187 if (err)
10188 goto done;
10191 if (wanted_ref) {
10192 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10193 wanted_ref += 11;
10196 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10197 header_prefix = "backout";
10198 else
10199 header_prefix = "cherrypick";
10201 TAILQ_FOREACH(re, &refs, entry) {
10202 const char *refname, *wt;
10204 refname = got_ref_get_name(re->ref);
10206 err = check_cancelled(NULL);
10207 if (err)
10208 goto done;
10210 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10211 refname += prefix_len + 1; /* skip '-' delimiter */
10212 else
10213 continue;
10215 wt = refname;
10217 if (worktree == NULL || strncmp(refname, uuidstr,
10218 GOT_WORKTREE_UUID_STRLEN) == 0)
10219 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10220 else
10221 continue;
10223 err = got_repo_match_object_id(&id, NULL, refname,
10224 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10225 if (err)
10226 goto done;
10228 err = got_object_open_as_commit(&commit, repo, id);
10229 if (err)
10230 goto done;
10232 if (wanted_ref)
10233 found = strncmp(wanted_ref, refname,
10234 strlen(wanted_ref)) == 0;
10235 if (wanted_ref && !found) {
10236 struct got_reflist_head *ci_refs;
10238 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10239 id);
10241 if (ci_refs) {
10242 char *refs_str = NULL;
10243 char const *r = NULL;
10245 err = build_refs_str(&refs_str, ci_refs, id,
10246 repo, 1);
10247 if (err)
10248 goto done;
10250 r = refs_str;
10251 while (r) {
10252 if (strncmp(r, wanted_ref,
10253 strlen(wanted_ref)) == 0) {
10254 found = 1;
10255 break;
10257 r = strchr(r, ' ');
10258 if (r)
10259 ++r;
10261 free(refs_str);
10265 if (wanted_ref == NULL || found) {
10266 if (delete) {
10267 err = got_ref_delete(re->ref, repo);
10268 if (err)
10269 goto done;
10270 printf("Deleted: ");
10271 err = print_commit_oneline(commit, id, repo,
10272 refs_idmap);
10273 } else {
10275 * Print paths modified by commit to help
10276 * associate commits with worktree changes.
10278 err = get_changed_paths(&paths, commit,
10279 repo, NULL);
10280 if (err)
10281 goto done;
10283 err = print_commit(commit, id, repo, NULL,
10284 &paths, NULL, 0, 0, refs_idmap, NULL,
10285 header_prefix);
10286 got_pathlist_free(&paths,
10287 GOT_PATHLIST_FREE_ALL);
10289 if (worktree == NULL)
10290 printf("work tree: %.*s\n\n",
10291 GOT_WORKTREE_UUID_STRLEN, wt);
10293 if (err || found)
10294 goto done;
10297 got_object_commit_close(commit);
10298 commit = NULL;
10299 free(id);
10300 id = NULL;
10303 if (wanted_ref != NULL && !found)
10304 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10306 done:
10307 free(id);
10308 free(uuidstr);
10309 got_ref_list_free(&refs);
10310 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10311 if (refs_idmap)
10312 got_reflist_object_id_map_free(refs_idmap);
10313 if (commit)
10314 got_object_commit_close(commit);
10315 return err;
10319 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10320 * identified by id for log messages to prepopulate the editor on commit.
10322 static const struct got_error *
10323 logmsg_ref(struct got_object_id *id, const char *prefix,
10324 struct got_worktree *worktree, struct got_repository *repo)
10326 const struct got_error *err = NULL;
10327 char *idstr, *ref = NULL, *refname = NULL;
10328 int histedit_in_progress;
10329 int rebase_in_progress, merge_in_progress;
10332 * Silenty refuse to create merge reference if any histedit, merge,
10333 * or rebase operation is in progress.
10335 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10336 worktree);
10337 if (err)
10338 return err;
10339 if (histedit_in_progress)
10340 return NULL;
10342 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10343 if (err)
10344 return err;
10345 if (rebase_in_progress)
10346 return NULL;
10348 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10349 repo);
10350 if (err)
10351 return err;
10352 if (merge_in_progress)
10353 return NULL;
10355 err = got_object_id_str(&idstr, id);
10356 if (err)
10357 return err;
10359 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10360 if (err)
10361 goto done;
10363 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10364 err = got_error_from_errno("asprintf");
10365 goto done;
10368 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10369 -1, repo);
10370 done:
10371 free(ref);
10372 free(idstr);
10373 free(refname);
10374 return err;
10377 __dead static void
10378 usage_cherrypick(void)
10380 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10381 getprogname());
10382 exit(1);
10385 static const struct got_error *
10386 cmd_cherrypick(int argc, char *argv[])
10388 const struct got_error *error = NULL;
10389 struct got_worktree *worktree = NULL;
10390 struct got_repository *repo = NULL;
10391 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10392 struct got_object_id *commit_id = NULL;
10393 struct got_commit_object *commit = NULL;
10394 struct got_object_qid *pid;
10395 int ch, list_refs = 0, remove_refs = 0;
10396 struct got_update_progress_arg upa;
10397 int *pack_fds = NULL;
10399 #ifndef PROFILE
10400 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10401 "unveil", NULL) == -1)
10402 err(1, "pledge");
10403 #endif
10405 while ((ch = getopt(argc, argv, "lX")) != -1) {
10406 switch (ch) {
10407 case 'l':
10408 list_refs = 1;
10409 break;
10410 case 'X':
10411 remove_refs = 1;
10412 break;
10413 default:
10414 usage_cherrypick();
10415 /* NOTREACHED */
10419 argc -= optind;
10420 argv += optind;
10422 if (list_refs || remove_refs) {
10423 if (argc != 0 && argc != 1)
10424 usage_cherrypick();
10425 } else if (argc != 1)
10426 usage_cherrypick();
10427 if (list_refs && remove_refs)
10428 option_conflict('l', 'X');
10430 cwd = getcwd(NULL, 0);
10431 if (cwd == NULL) {
10432 error = got_error_from_errno("getcwd");
10433 goto done;
10436 error = got_repo_pack_fds_open(&pack_fds);
10437 if (error != NULL)
10438 goto done;
10440 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10441 if (error) {
10442 if (list_refs || remove_refs) {
10443 if (error->code != GOT_ERR_NOT_WORKTREE)
10444 goto done;
10445 } else {
10446 if (error->code == GOT_ERR_NOT_WORKTREE)
10447 error = wrap_not_worktree_error(error,
10448 "cherrypick", cwd);
10449 goto done;
10453 error = got_repo_open(&repo,
10454 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10455 NULL, pack_fds);
10456 if (error != NULL)
10457 goto done;
10459 error = apply_unveil(got_repo_get_path(repo), 0,
10460 worktree ? got_worktree_get_root_path(worktree) : NULL);
10461 if (error)
10462 goto done;
10464 if (list_refs || remove_refs) {
10465 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10466 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10467 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10468 goto done;
10471 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10472 if (error != NULL)
10473 goto done;
10475 error = got_repo_match_object_id(&commit_id, NULL,
10476 keyword_idstr != NULL ? keyword_idstr : argv[0],
10477 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10478 if (error)
10479 goto done;
10480 error = got_object_id_str(&commit_id_str, commit_id);
10481 if (error)
10482 goto done;
10484 error = got_object_open_as_commit(&commit, repo, commit_id);
10485 if (error)
10486 goto done;
10487 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10488 memset(&upa, 0, sizeof(upa));
10489 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10490 commit_id, repo, update_progress, &upa, check_cancelled,
10491 NULL);
10492 if (error != NULL)
10493 goto done;
10495 if (upa.did_something) {
10496 error = logmsg_ref(commit_id,
10497 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10498 if (error)
10499 goto done;
10500 printf("Merged commit %s\n", commit_id_str);
10502 print_merge_progress_stats(&upa);
10503 done:
10504 free(cwd);
10505 free(keyword_idstr);
10506 if (commit)
10507 got_object_commit_close(commit);
10508 free(commit_id_str);
10509 if (worktree)
10510 got_worktree_close(worktree);
10511 if (repo) {
10512 const struct got_error *close_err = got_repo_close(repo);
10513 if (error == NULL)
10514 error = close_err;
10516 if (pack_fds) {
10517 const struct got_error *pack_err =
10518 got_repo_pack_fds_close(pack_fds);
10519 if (error == NULL)
10520 error = pack_err;
10523 return error;
10526 __dead static void
10527 usage_backout(void)
10529 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10530 exit(1);
10533 static const struct got_error *
10534 cmd_backout(int argc, char *argv[])
10536 const struct got_error *error = NULL;
10537 struct got_worktree *worktree = NULL;
10538 struct got_repository *repo = NULL;
10539 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10540 struct got_object_id *commit_id = NULL;
10541 struct got_commit_object *commit = NULL;
10542 struct got_object_qid *pid;
10543 int ch, list_refs = 0, remove_refs = 0;
10544 struct got_update_progress_arg upa;
10545 int *pack_fds = NULL;
10547 #ifndef PROFILE
10548 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10549 "unveil", NULL) == -1)
10550 err(1, "pledge");
10551 #endif
10553 while ((ch = getopt(argc, argv, "lX")) != -1) {
10554 switch (ch) {
10555 case 'l':
10556 list_refs = 1;
10557 break;
10558 case 'X':
10559 remove_refs = 1;
10560 break;
10561 default:
10562 usage_backout();
10563 /* NOTREACHED */
10567 argc -= optind;
10568 argv += optind;
10570 if (list_refs || remove_refs) {
10571 if (argc != 0 && argc != 1)
10572 usage_backout();
10573 } else if (argc != 1)
10574 usage_backout();
10575 if (list_refs && remove_refs)
10576 option_conflict('l', 'X');
10578 cwd = getcwd(NULL, 0);
10579 if (cwd == NULL) {
10580 error = got_error_from_errno("getcwd");
10581 goto done;
10584 error = got_repo_pack_fds_open(&pack_fds);
10585 if (error != NULL)
10586 goto done;
10588 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10589 if (error) {
10590 if (list_refs || remove_refs) {
10591 if (error->code != GOT_ERR_NOT_WORKTREE)
10592 goto done;
10593 } else {
10594 if (error->code == GOT_ERR_NOT_WORKTREE)
10595 error = wrap_not_worktree_error(error,
10596 "backout", cwd);
10597 goto done;
10601 error = got_repo_open(&repo,
10602 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10603 NULL, pack_fds);
10604 if (error != NULL)
10605 goto done;
10607 error = apply_unveil(got_repo_get_path(repo), 0,
10608 worktree ? got_worktree_get_root_path(worktree) : NULL);
10609 if (error)
10610 goto done;
10612 if (list_refs || remove_refs) {
10613 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10614 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10615 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10616 goto done;
10619 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10620 if (error != NULL)
10621 goto done;
10623 error = got_repo_match_object_id(&commit_id, NULL,
10624 keyword_idstr != NULL ? keyword_idstr : argv[0],
10625 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10626 if (error)
10627 goto done;
10628 error = got_object_id_str(&commit_id_str, commit_id);
10629 if (error)
10630 goto done;
10632 error = got_object_open_as_commit(&commit, repo, commit_id);
10633 if (error)
10634 goto done;
10635 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10636 if (pid == NULL) {
10637 error = got_error(GOT_ERR_ROOT_COMMIT);
10638 goto done;
10641 memset(&upa, 0, sizeof(upa));
10642 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10643 repo, update_progress, &upa, check_cancelled, NULL);
10644 if (error != NULL)
10645 goto done;
10647 if (upa.did_something) {
10648 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10649 worktree, repo);
10650 if (error)
10651 goto done;
10652 printf("Backed out commit %s\n", commit_id_str);
10654 print_merge_progress_stats(&upa);
10655 done:
10656 free(cwd);
10657 free(keyword_idstr);
10658 if (commit)
10659 got_object_commit_close(commit);
10660 free(commit_id_str);
10661 if (worktree)
10662 got_worktree_close(worktree);
10663 if (repo) {
10664 const struct got_error *close_err = got_repo_close(repo);
10665 if (error == NULL)
10666 error = close_err;
10668 if (pack_fds) {
10669 const struct got_error *pack_err =
10670 got_repo_pack_fds_close(pack_fds);
10671 if (error == NULL)
10672 error = pack_err;
10674 return error;
10677 __dead static void
10678 usage_rebase(void)
10680 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10681 exit(1);
10684 static void
10685 trim_logmsg(char *logmsg, int limit)
10687 char *nl;
10688 size_t len;
10690 len = strlen(logmsg);
10691 if (len > limit)
10692 len = limit;
10693 logmsg[len] = '\0';
10694 nl = strchr(logmsg, '\n');
10695 if (nl)
10696 *nl = '\0';
10699 static const struct got_error *
10700 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10702 const struct got_error *err;
10703 char *logmsg0 = NULL;
10704 const char *s;
10706 err = got_object_commit_get_logmsg(&logmsg0, commit);
10707 if (err)
10708 return err;
10710 s = logmsg0;
10711 while (isspace((unsigned char)s[0]))
10712 s++;
10714 *logmsg = strdup(s);
10715 if (*logmsg == NULL) {
10716 err = got_error_from_errno("strdup");
10717 goto done;
10720 trim_logmsg(*logmsg, limit);
10721 done:
10722 free(logmsg0);
10723 return err;
10726 static const struct got_error *
10727 show_rebase_merge_conflict(struct got_object_id *id,
10728 struct got_repository *repo)
10730 const struct got_error *err;
10731 struct got_commit_object *commit = NULL;
10732 char *id_str = NULL, *logmsg = NULL;
10734 err = got_object_open_as_commit(&commit, repo, id);
10735 if (err)
10736 return err;
10738 err = got_object_id_str(&id_str, id);
10739 if (err)
10740 goto done;
10742 id_str[12] = '\0';
10744 err = get_short_logmsg(&logmsg, 42, commit);
10745 if (err)
10746 goto done;
10748 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10749 done:
10750 free(id_str);
10751 got_object_commit_close(commit);
10752 free(logmsg);
10753 return err;
10756 static const struct got_error *
10757 show_rebase_progress(struct got_commit_object *commit,
10758 struct got_object_id *old_id, struct got_object_id *new_id)
10760 const struct got_error *err;
10761 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10763 err = got_object_id_str(&old_id_str, old_id);
10764 if (err)
10765 goto done;
10767 if (new_id) {
10768 err = got_object_id_str(&new_id_str, new_id);
10769 if (err)
10770 goto done;
10773 old_id_str[12] = '\0';
10774 if (new_id_str)
10775 new_id_str[12] = '\0';
10777 err = get_short_logmsg(&logmsg, 42, commit);
10778 if (err)
10779 goto done;
10781 printf("%s -> %s: %s\n", old_id_str,
10782 new_id_str ? new_id_str : "no-op change", logmsg);
10783 done:
10784 free(old_id_str);
10785 free(new_id_str);
10786 free(logmsg);
10787 return err;
10790 static const struct got_error *
10791 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10792 struct got_reference *branch, struct got_reference *tmp_branch,
10793 struct got_repository *repo, int create_backup)
10795 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10796 return got_worktree_rebase_complete(worktree, fileindex,
10797 tmp_branch, branch, repo, create_backup);
10800 static const struct got_error *
10801 rebase_commit(struct got_pathlist_head *merged_paths,
10802 struct got_worktree *worktree, struct got_fileindex *fileindex,
10803 struct got_reference *tmp_branch, const char *committer,
10804 struct got_object_id *commit_id, int allow_conflict,
10805 struct got_repository *repo)
10807 const struct got_error *error;
10808 struct got_commit_object *commit;
10809 struct got_object_id *new_commit_id;
10811 error = got_object_open_as_commit(&commit, repo, commit_id);
10812 if (error)
10813 return error;
10815 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10816 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10817 allow_conflict, repo);
10818 if (error) {
10819 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10820 goto done;
10821 error = show_rebase_progress(commit, commit_id, NULL);
10822 } else {
10823 error = show_rebase_progress(commit, commit_id, new_commit_id);
10824 free(new_commit_id);
10826 done:
10827 got_object_commit_close(commit);
10828 return error;
10831 struct check_path_prefix_arg {
10832 const char *path_prefix;
10833 size_t len;
10834 int errcode;
10837 static const struct got_error *
10838 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10839 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10840 struct got_object_id *id1, struct got_object_id *id2,
10841 const char *path1, const char *path2,
10842 mode_t mode1, mode_t mode2, struct got_repository *repo)
10844 struct check_path_prefix_arg *a = arg;
10846 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10847 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10848 return got_error(a->errcode);
10850 return NULL;
10853 static const struct got_error *
10854 check_path_prefix(struct got_object_id *parent_id,
10855 struct got_object_id *commit_id, const char *path_prefix,
10856 int errcode, struct got_repository *repo)
10858 const struct got_error *err;
10859 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10860 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10861 struct check_path_prefix_arg cpp_arg;
10863 if (got_path_is_root_dir(path_prefix))
10864 return NULL;
10866 err = got_object_open_as_commit(&commit, repo, commit_id);
10867 if (err)
10868 goto done;
10870 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10871 if (err)
10872 goto done;
10874 err = got_object_open_as_tree(&tree1, repo,
10875 got_object_commit_get_tree_id(parent_commit));
10876 if (err)
10877 goto done;
10879 err = got_object_open_as_tree(&tree2, repo,
10880 got_object_commit_get_tree_id(commit));
10881 if (err)
10882 goto done;
10884 cpp_arg.path_prefix = path_prefix;
10885 while (cpp_arg.path_prefix[0] == '/')
10886 cpp_arg.path_prefix++;
10887 cpp_arg.len = strlen(cpp_arg.path_prefix);
10888 cpp_arg.errcode = errcode;
10889 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10890 check_path_prefix_in_diff, &cpp_arg, 0);
10891 done:
10892 if (tree1)
10893 got_object_tree_close(tree1);
10894 if (tree2)
10895 got_object_tree_close(tree2);
10896 if (commit)
10897 got_object_commit_close(commit);
10898 if (parent_commit)
10899 got_object_commit_close(parent_commit);
10900 return err;
10903 static const struct got_error *
10904 collect_commits(struct got_object_id_queue *commits,
10905 struct got_object_id *initial_commit_id,
10906 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10907 const char *path_prefix, int path_prefix_errcode,
10908 struct got_repository *repo)
10910 const struct got_error *err = NULL;
10911 struct got_commit_graph *graph = NULL;
10912 struct got_object_id parent_id, commit_id;
10913 struct got_object_qid *qid;
10915 err = got_commit_graph_open(&graph, "/", 1);
10916 if (err)
10917 return err;
10919 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10920 check_cancelled, NULL);
10921 if (err)
10922 goto done;
10924 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10925 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10926 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10927 check_cancelled, NULL);
10928 if (err) {
10929 if (err->code == GOT_ERR_ITER_COMPLETED) {
10930 err = got_error_msg(GOT_ERR_ANCESTRY,
10931 "ran out of commits to rebase before "
10932 "youngest common ancestor commit has "
10933 "been reached?!?");
10935 goto done;
10936 } else {
10937 err = check_path_prefix(&parent_id, &commit_id,
10938 path_prefix, path_prefix_errcode, repo);
10939 if (err)
10940 goto done;
10942 err = got_object_qid_alloc(&qid, &commit_id);
10943 if (err)
10944 goto done;
10945 STAILQ_INSERT_HEAD(commits, qid, entry);
10947 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10950 done:
10951 got_commit_graph_close(graph);
10952 return err;
10955 static const struct got_error *
10956 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10958 const struct got_error *err = NULL;
10959 time_t committer_time;
10960 struct tm tm;
10961 char datebuf[11]; /* YYYY-MM-DD + NUL */
10962 char *author0 = NULL, *author, *smallerthan;
10963 char *logmsg0 = NULL, *logmsg, *newline;
10965 committer_time = got_object_commit_get_committer_time(commit);
10966 if (gmtime_r(&committer_time, &tm) == NULL)
10967 return got_error_from_errno("gmtime_r");
10968 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10969 return got_error(GOT_ERR_NO_SPACE);
10971 author0 = strdup(got_object_commit_get_author(commit));
10972 if (author0 == NULL)
10973 return got_error_from_errno("strdup");
10974 author = author0;
10975 smallerthan = strchr(author, '<');
10976 if (smallerthan && smallerthan[1] != '\0')
10977 author = smallerthan + 1;
10978 author[strcspn(author, "@>")] = '\0';
10980 err = got_object_commit_get_logmsg(&logmsg0, commit);
10981 if (err)
10982 goto done;
10983 logmsg = logmsg0;
10984 while (*logmsg == '\n')
10985 logmsg++;
10986 newline = strchr(logmsg, '\n');
10987 if (newline)
10988 *newline = '\0';
10990 if (asprintf(brief_str, "%s %s %s",
10991 datebuf, author, logmsg) == -1)
10992 err = got_error_from_errno("asprintf");
10993 done:
10994 free(author0);
10995 free(logmsg0);
10996 return err;
10999 static const struct got_error *
11000 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11001 struct got_repository *repo)
11003 const struct got_error *err;
11004 char *id_str;
11006 err = got_object_id_str(&id_str, id);
11007 if (err)
11008 return err;
11010 err = got_ref_delete(ref, repo);
11011 if (err)
11012 goto done;
11014 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11015 done:
11016 free(id_str);
11017 return err;
11020 static const struct got_error *
11021 print_backup_ref(const char *branch_name, const char *new_id_str,
11022 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11023 struct got_reflist_object_id_map *refs_idmap,
11024 struct got_repository *repo)
11026 const struct got_error *err = NULL;
11027 struct got_reflist_head *refs;
11028 char *refs_str = NULL;
11029 struct got_object_id *new_commit_id = NULL;
11030 struct got_commit_object *new_commit = NULL;
11031 char *new_commit_brief_str = NULL;
11032 struct got_object_id *yca_id = NULL;
11033 struct got_commit_object *yca_commit = NULL;
11034 char *yca_id_str = NULL, *yca_brief_str = NULL;
11035 char *custom_refs_str;
11037 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11038 return got_error_from_errno("asprintf");
11040 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11041 0, 0, refs_idmap, custom_refs_str, NULL);
11042 if (err)
11043 goto done;
11045 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11046 if (err)
11047 goto done;
11049 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11050 if (refs) {
11051 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11052 if (err)
11053 goto done;
11056 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11057 if (err)
11058 goto done;
11060 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11061 if (err)
11062 goto done;
11064 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11065 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11066 if (err)
11067 goto done;
11069 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11070 refs_str ? " (" : "", refs_str ? refs_str : "",
11071 refs_str ? ")" : "", new_commit_brief_str);
11072 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11073 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11074 free(refs_str);
11075 refs_str = NULL;
11077 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11078 if (err)
11079 goto done;
11081 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11082 if (err)
11083 goto done;
11085 err = got_object_id_str(&yca_id_str, yca_id);
11086 if (err)
11087 goto done;
11089 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11090 if (refs) {
11091 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11092 if (err)
11093 goto done;
11095 printf("history forked at %s%s%s%s\n %s\n",
11096 yca_id_str,
11097 refs_str ? " (" : "", refs_str ? refs_str : "",
11098 refs_str ? ")" : "", yca_brief_str);
11100 done:
11101 free(custom_refs_str);
11102 free(new_commit_id);
11103 free(refs_str);
11104 free(yca_id);
11105 free(yca_id_str);
11106 free(yca_brief_str);
11107 if (new_commit)
11108 got_object_commit_close(new_commit);
11109 if (yca_commit)
11110 got_object_commit_close(yca_commit);
11112 return err;
11115 static const struct got_error *
11116 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11117 struct got_repository *repo)
11119 const struct got_error *err;
11120 struct got_reflist_head refs;
11121 struct got_reflist_entry *re;
11122 char *uuidstr = NULL;
11123 static char msg[160];
11125 TAILQ_INIT(&refs);
11127 err = got_worktree_get_uuid(&uuidstr, worktree);
11128 if (err)
11129 goto done;
11131 err = got_ref_list(&refs, repo, "refs/got/worktree",
11132 got_ref_cmp_by_name, repo);
11133 if (err)
11134 goto done;
11136 TAILQ_FOREACH(re, &refs, entry) {
11137 const char *cmd, *refname, *type;
11139 refname = got_ref_get_name(re->ref);
11141 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11142 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11143 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11144 cmd = "cherrypick";
11145 type = "cherrypicked";
11146 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11147 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11148 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11149 cmd = "backout";
11150 type = "backed-out";
11151 } else
11152 continue;
11154 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11155 continue;
11157 snprintf(msg, sizeof(msg),
11158 "work tree has references created by %s commits which "
11159 "must be removed with 'got %s -X' before running the %s "
11160 "command", type, cmd, caller);
11161 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11162 goto done;
11165 done:
11166 free(uuidstr);
11167 got_ref_list_free(&refs);
11168 return err;
11171 static const struct got_error *
11172 process_backup_refs(const char *backup_ref_prefix,
11173 const char *wanted_branch_name,
11174 int delete, struct got_repository *repo)
11176 const struct got_error *err;
11177 struct got_reflist_head refs, backup_refs;
11178 struct got_reflist_entry *re;
11179 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11180 struct got_object_id *old_commit_id = NULL;
11181 char *branch_name = NULL;
11182 struct got_commit_object *old_commit = NULL;
11183 struct got_reflist_object_id_map *refs_idmap = NULL;
11184 int wanted_branch_found = 0;
11186 TAILQ_INIT(&refs);
11187 TAILQ_INIT(&backup_refs);
11189 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11190 if (err)
11191 return err;
11193 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11194 if (err)
11195 goto done;
11197 if (wanted_branch_name) {
11198 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11199 wanted_branch_name += 11;
11202 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11203 got_ref_cmp_by_commit_timestamp_descending, repo);
11204 if (err)
11205 goto done;
11207 TAILQ_FOREACH(re, &backup_refs, entry) {
11208 const char *refname = got_ref_get_name(re->ref);
11209 char *slash;
11211 err = check_cancelled(NULL);
11212 if (err)
11213 break;
11215 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11216 if (err)
11217 break;
11219 err = got_object_open_as_commit(&old_commit, repo,
11220 old_commit_id);
11221 if (err)
11222 break;
11224 if (strncmp(backup_ref_prefix, refname,
11225 backup_ref_prefix_len) == 0)
11226 refname += backup_ref_prefix_len;
11228 while (refname[0] == '/')
11229 refname++;
11231 branch_name = strdup(refname);
11232 if (branch_name == NULL) {
11233 err = got_error_from_errno("strdup");
11234 break;
11236 slash = strrchr(branch_name, '/');
11237 if (slash) {
11238 *slash = '\0';
11239 refname += strlen(branch_name) + 1;
11242 if (wanted_branch_name == NULL ||
11243 strcmp(wanted_branch_name, branch_name) == 0) {
11244 wanted_branch_found = 1;
11245 if (delete) {
11246 err = delete_backup_ref(re->ref,
11247 old_commit_id, repo);
11248 } else {
11249 err = print_backup_ref(branch_name, refname,
11250 old_commit_id, old_commit, refs_idmap,
11251 repo);
11253 if (err)
11254 break;
11257 free(old_commit_id);
11258 old_commit_id = NULL;
11259 free(branch_name);
11260 branch_name = NULL;
11261 got_object_commit_close(old_commit);
11262 old_commit = NULL;
11265 if (wanted_branch_name && !wanted_branch_found) {
11266 err = got_error_fmt(GOT_ERR_NOT_REF,
11267 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11269 done:
11270 if (refs_idmap)
11271 got_reflist_object_id_map_free(refs_idmap);
11272 got_ref_list_free(&refs);
11273 got_ref_list_free(&backup_refs);
11274 free(old_commit_id);
11275 free(branch_name);
11276 if (old_commit)
11277 got_object_commit_close(old_commit);
11278 return err;
11281 static const struct got_error *
11282 abort_progress(void *arg, unsigned char status, const char *path)
11285 * Unversioned files should not clutter progress output when
11286 * an operation is aborted.
11288 if (status == GOT_STATUS_UNVERSIONED)
11289 return NULL;
11291 return update_progress(arg, status, path);
11294 static const struct got_error *
11295 find_merge_commit_yca(struct got_object_id **new_yca_id,
11296 struct got_object_id *branch_head_commit_id,
11297 struct got_object_id *yca_id,
11298 struct got_object_id *base_commit_id,
11299 struct got_repository *repo)
11301 const struct got_error *err = NULL;
11302 struct got_commit_graph *graph = NULL;
11303 struct got_commit_object *commit = NULL;
11305 *new_yca_id = NULL;
11307 err = got_commit_graph_open(&graph, "/", 1);
11308 if (err)
11309 return err;
11311 err = got_commit_graph_bfsort(graph, base_commit_id,
11312 repo, check_cancelled, NULL);
11313 if (err)
11314 goto done;
11316 for (;;) {
11317 struct got_object_id id;
11319 err = got_commit_graph_iter_next(&id, graph, repo,
11320 check_cancelled, NULL);
11321 if (err) {
11322 if (err->code == GOT_ERR_ITER_COMPLETED)
11323 err = NULL;
11324 break;
11327 err = got_object_open_as_commit(&commit, repo, &id);
11328 if (err)
11329 break;
11331 if (got_object_commit_get_nparents(commit) > 1) {
11332 /* Search for a better YCA using toposort. */
11333 err = got_commit_graph_find_youngest_common_ancestor(
11334 new_yca_id, base_commit_id, branch_head_commit_id,
11335 0, 1, repo, check_cancelled, NULL);
11336 break;
11339 if (got_object_id_cmp(&id, yca_id) == 0)
11340 break;
11341 got_object_commit_close(commit);
11342 commit = NULL;
11344 done:
11345 got_commit_graph_close(graph);
11346 if (commit)
11347 got_object_commit_close(commit);
11348 return err;
11351 static const struct got_error *
11352 cmd_rebase(int argc, char *argv[])
11354 const struct got_error *error = NULL;
11355 struct got_worktree *worktree = NULL;
11356 struct got_repository *repo = NULL;
11357 struct got_fileindex *fileindex = NULL;
11358 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11359 struct got_reference *branch = NULL;
11360 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11361 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11362 struct got_object_id *resume_commit_id = NULL;
11363 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11364 struct got_object_id *head_commit_id = NULL;
11365 struct got_reference *head_ref = NULL;
11366 struct got_commit_object *commit = NULL;
11367 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11368 int histedit_in_progress = 0, merge_in_progress = 0;
11369 int create_backup = 1, list_backups = 0, delete_backups = 0;
11370 int allow_conflict = 0;
11371 struct got_object_id_queue commits;
11372 struct got_pathlist_head merged_paths;
11373 const struct got_object_id_queue *parent_ids;
11374 struct got_object_qid *qid, *pid;
11375 struct got_update_progress_arg upa;
11376 int *pack_fds = NULL;
11378 STAILQ_INIT(&commits);
11379 TAILQ_INIT(&merged_paths);
11380 memset(&upa, 0, sizeof(upa));
11382 #ifndef PROFILE
11383 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11384 "unveil", NULL) == -1)
11385 err(1, "pledge");
11386 #endif
11388 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11389 switch (ch) {
11390 case 'a':
11391 abort_rebase = 1;
11392 break;
11393 case 'C':
11394 allow_conflict = 1;
11395 break;
11396 case 'c':
11397 continue_rebase = 1;
11398 break;
11399 case 'l':
11400 list_backups = 1;
11401 break;
11402 case 'X':
11403 delete_backups = 1;
11404 break;
11405 default:
11406 usage_rebase();
11407 /* NOTREACHED */
11411 argc -= optind;
11412 argv += optind;
11414 if (list_backups) {
11415 if (abort_rebase)
11416 option_conflict('l', 'a');
11417 if (allow_conflict)
11418 option_conflict('l', 'C');
11419 if (continue_rebase)
11420 option_conflict('l', 'c');
11421 if (delete_backups)
11422 option_conflict('l', 'X');
11423 if (argc != 0 && argc != 1)
11424 usage_rebase();
11425 } else if (delete_backups) {
11426 if (abort_rebase)
11427 option_conflict('X', 'a');
11428 if (allow_conflict)
11429 option_conflict('X', 'C');
11430 if (continue_rebase)
11431 option_conflict('X', 'c');
11432 if (list_backups)
11433 option_conflict('l', 'X');
11434 if (argc != 0 && argc != 1)
11435 usage_rebase();
11436 } else if (allow_conflict) {
11437 if (abort_rebase)
11438 option_conflict('C', 'a');
11439 if (!continue_rebase)
11440 errx(1, "-C option requires -c");
11441 } else {
11442 if (abort_rebase && continue_rebase)
11443 usage_rebase();
11444 else if (abort_rebase || continue_rebase) {
11445 if (argc != 0)
11446 usage_rebase();
11447 } else if (argc != 1)
11448 usage_rebase();
11451 cwd = getcwd(NULL, 0);
11452 if (cwd == NULL) {
11453 error = got_error_from_errno("getcwd");
11454 goto done;
11457 error = got_repo_pack_fds_open(&pack_fds);
11458 if (error != NULL)
11459 goto done;
11461 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11462 if (error) {
11463 if (list_backups || delete_backups) {
11464 if (error->code != GOT_ERR_NOT_WORKTREE)
11465 goto done;
11466 } else {
11467 if (error->code == GOT_ERR_NOT_WORKTREE)
11468 error = wrap_not_worktree_error(error,
11469 "rebase", cwd);
11470 goto done;
11474 error = get_gitconfig_path(&gitconfig_path);
11475 if (error)
11476 goto done;
11477 error = got_repo_open(&repo,
11478 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11479 gitconfig_path, pack_fds);
11480 if (error != NULL)
11481 goto done;
11483 if (worktree != NULL && !list_backups && !delete_backups) {
11484 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11485 if (error)
11486 goto done;
11489 error = get_author(&committer, repo, worktree);
11490 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11491 goto done;
11493 error = apply_unveil(got_repo_get_path(repo), 0,
11494 worktree ? got_worktree_get_root_path(worktree) : NULL);
11495 if (error)
11496 goto done;
11498 if (list_backups || delete_backups) {
11499 error = process_backup_refs(
11500 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11501 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11502 goto done; /* nothing else to do */
11505 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11506 worktree);
11507 if (error)
11508 goto done;
11509 if (histedit_in_progress) {
11510 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11511 goto done;
11514 error = got_worktree_merge_in_progress(&merge_in_progress,
11515 worktree, repo);
11516 if (error)
11517 goto done;
11518 if (merge_in_progress) {
11519 error = got_error(GOT_ERR_MERGE_BUSY);
11520 goto done;
11523 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11524 if (error)
11525 goto done;
11527 if (abort_rebase) {
11528 if (!rebase_in_progress) {
11529 error = got_error(GOT_ERR_NOT_REBASING);
11530 goto done;
11532 error = got_worktree_rebase_continue(&resume_commit_id,
11533 &new_base_branch, &tmp_branch, &branch, &fileindex,
11534 worktree, repo);
11535 if (error)
11536 goto done;
11537 printf("Switching work tree to %s\n",
11538 got_ref_get_symref_target(new_base_branch));
11539 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11540 new_base_branch, abort_progress, &upa);
11541 if (error)
11542 goto done;
11543 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11544 print_merge_progress_stats(&upa);
11545 goto done; /* nothing else to do */
11548 if (continue_rebase) {
11549 if (!rebase_in_progress) {
11550 error = got_error(GOT_ERR_NOT_REBASING);
11551 goto done;
11553 error = got_worktree_rebase_continue(&resume_commit_id,
11554 &new_base_branch, &tmp_branch, &branch, &fileindex,
11555 worktree, repo);
11556 if (error)
11557 goto done;
11559 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11560 committer, resume_commit_id, allow_conflict, repo);
11561 if (error)
11562 goto done;
11564 yca_id = got_object_id_dup(resume_commit_id);
11565 if (yca_id == NULL) {
11566 error = got_error_from_errno("got_object_id_dup");
11567 goto done;
11569 } else {
11570 error = got_ref_open(&branch, repo, argv[0], 0);
11571 if (error != NULL)
11572 goto done;
11573 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11574 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11575 "will not rebase a branch which lives outside "
11576 "the \"refs/heads/\" reference namespace");
11577 goto done;
11581 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11582 if (error)
11583 goto done;
11585 if (!continue_rebase) {
11586 struct got_object_id *base_commit_id;
11588 error = got_ref_open(&head_ref, repo,
11589 got_worktree_get_head_ref_name(worktree), 0);
11590 if (error)
11591 goto done;
11592 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11593 if (error)
11594 goto done;
11595 base_commit_id = got_worktree_get_base_commit_id(worktree);
11596 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11597 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11598 goto done;
11601 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11602 base_commit_id, branch_head_commit_id, 1, 0,
11603 repo, check_cancelled, NULL);
11604 if (error) {
11605 if (error->code == GOT_ERR_ANCESTRY) {
11606 error = got_error_msg(GOT_ERR_ANCESTRY,
11607 "specified branch shares no common "
11608 "ancestry with work tree's branch");
11610 goto done;
11614 * If a merge commit appears between the new base branch tip
11615 * and a YCA found via first-parent traversal then we might
11616 * find a better YCA using topologically sorted commits.
11618 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11619 struct got_object_id *better_yca_id;
11620 error = find_merge_commit_yca(&better_yca_id,
11621 branch_head_commit_id, yca_id,
11622 base_commit_id, repo);
11623 if (error)
11624 goto done;
11625 if (better_yca_id) {
11626 free(yca_id);
11627 yca_id = better_yca_id;
11631 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11632 struct got_pathlist_head paths;
11633 printf("%s is already based on %s\n",
11634 got_ref_get_name(branch),
11635 got_worktree_get_head_ref_name(worktree));
11636 error = switch_head_ref(branch, branch_head_commit_id,
11637 worktree, repo);
11638 if (error)
11639 goto done;
11640 error = got_worktree_set_base_commit_id(worktree, repo,
11641 branch_head_commit_id);
11642 if (error)
11643 goto done;
11644 TAILQ_INIT(&paths);
11645 error = got_pathlist_append(&paths, "", NULL);
11646 if (error)
11647 goto done;
11648 error = got_worktree_checkout_files(worktree,
11649 &paths, repo, update_progress, &upa,
11650 check_cancelled, NULL);
11651 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11652 if (error)
11653 goto done;
11654 if (upa.did_something) {
11655 char *id_str;
11656 error = got_object_id_str(&id_str,
11657 branch_head_commit_id);
11658 if (error)
11659 goto done;
11660 printf("Updated to %s: %s\n",
11661 got_worktree_get_head_ref_name(worktree),
11662 id_str);
11663 free(id_str);
11664 } else
11665 printf("Already up-to-date\n");
11666 print_update_progress_stats(&upa);
11667 goto done;
11671 commit_id = branch_head_commit_id;
11672 error = got_object_open_as_commit(&commit, repo, commit_id);
11673 if (error)
11674 goto done;
11676 parent_ids = got_object_commit_get_parent_ids(commit);
11677 pid = STAILQ_FIRST(parent_ids);
11678 if (pid) {
11679 error = collect_commits(&commits, commit_id, &pid->id,
11680 yca_id, got_worktree_get_path_prefix(worktree),
11681 GOT_ERR_REBASE_PATH, repo);
11682 if (error)
11683 goto done;
11686 got_object_commit_close(commit);
11687 commit = NULL;
11689 if (!continue_rebase) {
11690 error = got_worktree_rebase_prepare(&new_base_branch,
11691 &tmp_branch, &fileindex, worktree, branch, repo);
11692 if (error)
11693 goto done;
11696 if (STAILQ_EMPTY(&commits)) {
11697 if (continue_rebase) {
11698 error = rebase_complete(worktree, fileindex,
11699 branch, tmp_branch, repo, create_backup);
11700 goto done;
11701 } else {
11702 /* Fast-forward the reference of the branch. */
11703 struct got_object_id *new_head_commit_id;
11704 char *id_str;
11705 error = got_ref_resolve(&new_head_commit_id, repo,
11706 new_base_branch);
11707 if (error)
11708 goto done;
11709 error = got_object_id_str(&id_str, new_head_commit_id);
11710 if (error)
11711 goto done;
11712 printf("Forwarding %s to commit %s\n",
11713 got_ref_get_name(branch), id_str);
11714 free(id_str);
11715 error = got_ref_change_ref(branch,
11716 new_head_commit_id);
11717 if (error)
11718 goto done;
11719 /* No backup needed since objects did not change. */
11720 create_backup = 0;
11724 pid = NULL;
11725 STAILQ_FOREACH(qid, &commits, entry) {
11727 commit_id = &qid->id;
11728 parent_id = pid ? &pid->id : yca_id;
11729 pid = qid;
11731 memset(&upa, 0, sizeof(upa));
11732 error = got_worktree_rebase_merge_files(&merged_paths,
11733 worktree, fileindex, parent_id, commit_id, repo,
11734 update_progress, &upa, check_cancelled, NULL);
11735 if (error)
11736 goto done;
11738 print_merge_progress_stats(&upa);
11739 if (upa.conflicts > 0 || upa.missing > 0 ||
11740 upa.not_deleted > 0 || upa.unversioned > 0) {
11741 if (upa.conflicts > 0) {
11742 error = show_rebase_merge_conflict(&qid->id,
11743 repo);
11744 if (error)
11745 goto done;
11747 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11748 break;
11751 error = rebase_commit(&merged_paths, worktree, fileindex,
11752 tmp_branch, committer, commit_id, 0, repo);
11753 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11754 if (error)
11755 goto done;
11758 if (upa.conflicts > 0 || upa.missing > 0 ||
11759 upa.not_deleted > 0 || upa.unversioned > 0) {
11760 error = got_worktree_rebase_postpone(worktree, fileindex);
11761 if (error)
11762 goto done;
11763 if (upa.conflicts > 0 && upa.missing == 0 &&
11764 upa.not_deleted == 0 && upa.unversioned == 0) {
11765 error = got_error_msg(GOT_ERR_CONFLICTS,
11766 "conflicts must be resolved before rebasing "
11767 "can continue");
11768 } else if (upa.conflicts > 0) {
11769 error = got_error_msg(GOT_ERR_CONFLICTS,
11770 "conflicts must be resolved before rebasing "
11771 "can continue; changes destined for some "
11772 "files were not yet merged and should be "
11773 "merged manually if required before the "
11774 "rebase operation is continued");
11775 } else {
11776 error = got_error_msg(GOT_ERR_CONFLICTS,
11777 "changes destined for some files were not "
11778 "yet merged and should be merged manually "
11779 "if required before the rebase operation "
11780 "is continued");
11782 } else
11783 error = rebase_complete(worktree, fileindex, branch,
11784 tmp_branch, repo, create_backup);
11785 done:
11786 free(cwd);
11787 free(committer);
11788 free(gitconfig_path);
11789 got_object_id_queue_free(&commits);
11790 free(branch_head_commit_id);
11791 free(resume_commit_id);
11792 free(head_commit_id);
11793 free(yca_id);
11794 if (commit)
11795 got_object_commit_close(commit);
11796 if (branch)
11797 got_ref_close(branch);
11798 if (new_base_branch)
11799 got_ref_close(new_base_branch);
11800 if (tmp_branch)
11801 got_ref_close(tmp_branch);
11802 if (head_ref)
11803 got_ref_close(head_ref);
11804 if (worktree)
11805 got_worktree_close(worktree);
11806 if (repo) {
11807 const struct got_error *close_err = got_repo_close(repo);
11808 if (error == NULL)
11809 error = close_err;
11811 if (pack_fds) {
11812 const struct got_error *pack_err =
11813 got_repo_pack_fds_close(pack_fds);
11814 if (error == NULL)
11815 error = pack_err;
11817 return error;
11820 __dead static void
11821 usage_histedit(void)
11823 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11824 "[branch]\n", getprogname());
11825 exit(1);
11828 #define GOT_HISTEDIT_PICK 'p'
11829 #define GOT_HISTEDIT_EDIT 'e'
11830 #define GOT_HISTEDIT_FOLD 'f'
11831 #define GOT_HISTEDIT_DROP 'd'
11832 #define GOT_HISTEDIT_MESG 'm'
11834 static const struct got_histedit_cmd {
11835 unsigned char code;
11836 const char *name;
11837 const char *desc;
11838 } got_histedit_cmds[] = {
11839 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11840 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11841 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11842 "be used" },
11843 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11844 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11847 struct got_histedit_list_entry {
11848 TAILQ_ENTRY(got_histedit_list_entry) entry;
11849 struct got_object_id *commit_id;
11850 const struct got_histedit_cmd *cmd;
11851 char *logmsg;
11853 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11855 static const struct got_error *
11856 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11857 FILE *f, struct got_repository *repo)
11859 const struct got_error *err = NULL;
11860 char *logmsg = NULL, *id_str = NULL;
11861 struct got_commit_object *commit = NULL;
11862 int n;
11864 err = got_object_open_as_commit(&commit, repo, commit_id);
11865 if (err)
11866 goto done;
11868 err = get_short_logmsg(&logmsg, 34, commit);
11869 if (err)
11870 goto done;
11872 err = got_object_id_str(&id_str, commit_id);
11873 if (err)
11874 goto done;
11876 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11877 if (n < 0)
11878 err = got_ferror(f, GOT_ERR_IO);
11879 done:
11880 if (commit)
11881 got_object_commit_close(commit);
11882 free(id_str);
11883 free(logmsg);
11884 return err;
11887 static const struct got_error *
11888 histedit_write_commit_list(struct got_object_id_queue *commits,
11889 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11890 int edit_only, struct got_repository *repo)
11892 const struct got_error *err = NULL;
11893 struct got_object_qid *qid;
11894 const char *histedit_cmd = NULL;
11896 if (STAILQ_EMPTY(commits))
11897 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11899 STAILQ_FOREACH(qid, commits, entry) {
11900 histedit_cmd = got_histedit_cmds[0].name;
11901 if (drop_only)
11902 histedit_cmd = "drop";
11903 else if (edit_only)
11904 histedit_cmd = "edit";
11905 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11906 histedit_cmd = "fold";
11907 else if (edit_logmsg_only)
11908 histedit_cmd = "mesg";
11909 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11910 if (err)
11911 break;
11914 return err;
11917 static const struct got_error *
11918 write_cmd_list(FILE *f, const char *branch_name,
11919 struct got_object_id_queue *commits)
11921 const struct got_error *err = NULL;
11922 size_t i;
11923 int n;
11924 char *id_str;
11925 struct got_object_qid *qid;
11927 qid = STAILQ_FIRST(commits);
11928 err = got_object_id_str(&id_str, &qid->id);
11929 if (err)
11930 return err;
11932 n = fprintf(f,
11933 "# Editing the history of branch '%s' starting at\n"
11934 "# commit %s\n"
11935 "# Commits will be processed in order from top to "
11936 "bottom of this file.\n", branch_name, id_str);
11937 if (n < 0) {
11938 err = got_ferror(f, GOT_ERR_IO);
11939 goto done;
11942 n = fprintf(f, "# Available histedit commands:\n");
11943 if (n < 0) {
11944 err = got_ferror(f, GOT_ERR_IO);
11945 goto done;
11948 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11949 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11950 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11951 cmd->desc);
11952 if (n < 0) {
11953 err = got_ferror(f, GOT_ERR_IO);
11954 break;
11957 done:
11958 free(id_str);
11959 return err;
11962 static const struct got_error *
11963 histedit_syntax_error(int lineno)
11965 static char msg[42];
11966 int ret;
11968 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11969 lineno);
11970 if (ret < 0 || (size_t)ret >= sizeof(msg))
11971 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11973 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11976 static const struct got_error *
11977 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11978 char *logmsg, struct got_repository *repo)
11980 const struct got_error *err;
11981 struct got_commit_object *folded_commit = NULL;
11982 char *id_str, *folded_logmsg = NULL;
11984 err = got_object_id_str(&id_str, hle->commit_id);
11985 if (err)
11986 return err;
11988 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11989 if (err)
11990 goto done;
11992 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11993 if (err)
11994 goto done;
11995 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11996 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11997 folded_logmsg) == -1) {
11998 err = got_error_from_errno("asprintf");
12000 done:
12001 if (folded_commit)
12002 got_object_commit_close(folded_commit);
12003 free(id_str);
12004 free(folded_logmsg);
12005 return err;
12008 static struct got_histedit_list_entry *
12009 get_folded_commits(struct got_histedit_list_entry *hle)
12011 struct got_histedit_list_entry *prev, *folded = NULL;
12013 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12014 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12015 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12016 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12017 folded = prev;
12018 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12021 return folded;
12024 static const struct got_error *
12025 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12026 const char *editor, struct got_repository *repo)
12028 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12029 char *logmsg = NULL, *new_msg = NULL;
12030 const struct got_error *err = NULL;
12031 struct got_commit_object *commit = NULL;
12032 int logmsg_len;
12033 int fd = -1;
12034 struct got_histedit_list_entry *folded = NULL;
12036 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12037 if (err)
12038 return err;
12040 folded = get_folded_commits(hle);
12041 if (folded) {
12042 while (folded != hle) {
12043 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12044 folded = TAILQ_NEXT(folded, entry);
12045 continue;
12047 err = append_folded_commit_msg(&new_msg, folded,
12048 logmsg, repo);
12049 if (err)
12050 goto done;
12051 free(logmsg);
12052 logmsg = new_msg;
12053 folded = TAILQ_NEXT(folded, entry);
12057 err = got_object_id_str(&id_str, hle->commit_id);
12058 if (err)
12059 goto done;
12060 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12061 if (err)
12062 goto done;
12063 logmsg_len = asprintf(&new_msg,
12064 "%s\n# original log message of commit %s: %s",
12065 logmsg ? logmsg : "", id_str, orig_logmsg);
12066 if (logmsg_len == -1) {
12067 err = got_error_from_errno("asprintf");
12068 goto done;
12070 free(logmsg);
12071 logmsg = new_msg;
12073 err = got_object_id_str(&id_str, hle->commit_id);
12074 if (err)
12075 goto done;
12077 err = got_opentemp_named_fd(&logmsg_path, &fd,
12078 GOT_TMPDIR_STR "/got-logmsg", "");
12079 if (err)
12080 goto done;
12082 if (write(fd, logmsg, logmsg_len) == -1) {
12083 err = got_error_from_errno2("write", logmsg_path);
12084 goto done;
12086 if (close(fd) == -1) {
12087 err = got_error_from_errno2("close", logmsg_path);
12088 goto done;
12090 fd = -1;
12092 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12093 logmsg_len, 0);
12094 if (err) {
12095 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12096 goto done;
12097 err = NULL;
12098 hle->logmsg = strdup(new_msg);
12099 if (hle->logmsg == NULL)
12100 err = got_error_from_errno("strdup");
12102 done:
12103 if (fd != -1 && close(fd) == -1 && err == NULL)
12104 err = got_error_from_errno2("close", logmsg_path);
12105 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12106 err = got_error_from_errno2("unlink", logmsg_path);
12107 free(logmsg_path);
12108 free(logmsg);
12109 free(orig_logmsg);
12110 if (commit)
12111 got_object_commit_close(commit);
12112 return err;
12115 static const struct got_error *
12116 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12117 FILE *f, struct got_repository *repo)
12119 const struct got_error *err = NULL;
12120 char *line = NULL, *p, *end;
12121 size_t i, linesize = 0;
12122 ssize_t linelen;
12123 int lineno = 0;
12124 const struct got_histedit_cmd *cmd;
12125 struct got_object_id *commit_id = NULL;
12126 struct got_histedit_list_entry *hle = NULL;
12128 for (;;) {
12129 linelen = getline(&line, &linesize, f);
12130 if (linelen == -1) {
12131 const struct got_error *getline_err;
12132 if (feof(f))
12133 break;
12134 getline_err = got_error_from_errno("getline");
12135 err = got_ferror(f, getline_err->code);
12136 break;
12138 lineno++;
12139 p = line;
12140 while (isspace((unsigned char)p[0]))
12141 p++;
12142 if (p[0] == '#' || p[0] == '\0')
12143 continue;
12144 cmd = NULL;
12145 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12146 cmd = &got_histedit_cmds[i];
12147 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12148 isspace((unsigned char)p[strlen(cmd->name)])) {
12149 p += strlen(cmd->name);
12150 break;
12152 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12153 p++;
12154 break;
12157 if (i == nitems(got_histedit_cmds)) {
12158 err = histedit_syntax_error(lineno);
12159 break;
12161 while (isspace((unsigned char)p[0]))
12162 p++;
12163 end = p;
12164 while (end[0] && !isspace((unsigned char)end[0]))
12165 end++;
12166 *end = '\0';
12167 err = got_object_resolve_id_str(&commit_id, repo, p);
12168 if (err) {
12169 /* override error code */
12170 err = histedit_syntax_error(lineno);
12171 break;
12173 hle = malloc(sizeof(*hle));
12174 if (hle == NULL) {
12175 err = got_error_from_errno("malloc");
12176 break;
12178 hle->cmd = cmd;
12179 hle->commit_id = commit_id;
12180 hle->logmsg = NULL;
12181 commit_id = NULL;
12182 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12185 free(line);
12186 free(commit_id);
12187 return err;
12190 static const struct got_error *
12191 histedit_check_script(struct got_histedit_list *histedit_cmds,
12192 struct got_object_id_queue *commits, struct got_repository *repo)
12194 const struct got_error *err = NULL;
12195 struct got_object_qid *qid;
12196 struct got_histedit_list_entry *hle;
12197 static char msg[92];
12198 char *id_str;
12200 if (TAILQ_EMPTY(histedit_cmds))
12201 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12202 "histedit script contains no commands");
12203 if (STAILQ_EMPTY(commits))
12204 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12206 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12207 struct got_histedit_list_entry *hle2;
12208 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12209 if (hle == hle2)
12210 continue;
12211 if (got_object_id_cmp(hle->commit_id,
12212 hle2->commit_id) != 0)
12213 continue;
12214 err = got_object_id_str(&id_str, hle->commit_id);
12215 if (err)
12216 return err;
12217 snprintf(msg, sizeof(msg), "commit %s is listed "
12218 "more than once in histedit script", id_str);
12219 free(id_str);
12220 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12224 STAILQ_FOREACH(qid, commits, entry) {
12225 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12226 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12227 break;
12229 if (hle == NULL) {
12230 err = got_object_id_str(&id_str, &qid->id);
12231 if (err)
12232 return err;
12233 snprintf(msg, sizeof(msg),
12234 "commit %s missing from histedit script", id_str);
12235 free(id_str);
12236 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12240 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12241 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12242 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12243 "last commit in histedit script cannot be folded");
12245 return NULL;
12248 static const struct got_error *
12249 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12250 const char *editor, const char *path,
12251 struct got_object_id_queue *commits, struct got_repository *repo)
12253 const struct got_error *err = NULL;
12254 struct stat st, st2;
12255 struct timespec timeout;
12256 FILE *f = NULL;
12258 if (stat(path, &st) == -1) {
12259 err = got_error_from_errno2("stat", path);
12260 goto done;
12263 if (spawn_editor(editor, path) == -1) {
12264 err = got_error_from_errno("failed spawning editor");
12265 goto done;
12268 timeout.tv_sec = 0;
12269 timeout.tv_nsec = 1;
12270 nanosleep(&timeout, NULL);
12272 if (stat(path, &st2) == -1) {
12273 err = got_error_from_errno2("stat", path);
12274 goto done;
12277 if (st.st_size == st2.st_size &&
12278 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12279 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12280 "no changes made to histedit script, aborting");
12281 goto done;
12284 f = fopen(path, "re");
12285 if (f == NULL) {
12286 err = got_error_from_errno("fopen");
12287 goto done;
12289 err = histedit_parse_list(histedit_cmds, f, repo);
12290 if (err)
12291 goto done;
12293 err = histedit_check_script(histedit_cmds, commits, repo);
12294 done:
12295 if (f && fclose(f) == EOF && err == NULL)
12296 err = got_error_from_errno("fclose");
12297 return err;
12300 static const struct got_error *
12301 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12302 struct got_object_id_queue *, const char *, const char *, const char *,
12303 struct got_repository *);
12305 static const struct got_error *
12306 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12307 struct got_object_id_queue *commits, const char *branch_name,
12308 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12309 const char *editor, struct got_repository *repo)
12311 const struct got_error *err;
12312 FILE *f = NULL;
12313 char *path = NULL;
12315 err = got_opentemp_named(&path, &f, "got-histedit", "");
12316 if (err)
12317 return err;
12319 err = write_cmd_list(f, branch_name, commits);
12320 if (err)
12321 goto done;
12323 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12324 fold_only, drop_only, edit_only, repo);
12325 if (err)
12326 goto done;
12328 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12329 rewind(f);
12330 err = histedit_parse_list(histedit_cmds, f, repo);
12331 } else {
12332 if (fclose(f) == EOF) {
12333 err = got_error_from_errno("fclose");
12334 goto done;
12336 f = NULL;
12337 err = histedit_run_editor(histedit_cmds, editor, path,
12338 commits, repo);
12339 if (err) {
12340 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12341 err->code != GOT_ERR_HISTEDIT_CMD)
12342 goto done;
12343 err = histedit_edit_list_retry(histedit_cmds, err,
12344 commits, editor, path, branch_name, repo);
12347 done:
12348 if (f && fclose(f) == EOF && err == NULL)
12349 err = got_error_from_errno("fclose");
12350 if (path && unlink(path) != 0 && err == NULL)
12351 err = got_error_from_errno2("unlink", path);
12352 free(path);
12353 return err;
12356 static const struct got_error *
12357 histedit_save_list(struct got_histedit_list *histedit_cmds,
12358 struct got_worktree *worktree, struct got_repository *repo)
12360 const struct got_error *err = NULL;
12361 char *path = NULL;
12362 FILE *f = NULL;
12363 struct got_histedit_list_entry *hle;
12365 err = got_worktree_get_histedit_script_path(&path, worktree);
12366 if (err)
12367 return err;
12369 f = fopen(path, "we");
12370 if (f == NULL) {
12371 err = got_error_from_errno2("fopen", path);
12372 goto done;
12374 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12375 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12376 repo);
12377 if (err)
12378 break;
12380 done:
12381 if (f && fclose(f) == EOF && err == NULL)
12382 err = got_error_from_errno("fclose");
12383 free(path);
12384 return err;
12387 static void
12388 histedit_free_list(struct got_histedit_list *histedit_cmds)
12390 struct got_histedit_list_entry *hle;
12392 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12393 TAILQ_REMOVE(histedit_cmds, hle, entry);
12394 free(hle);
12398 static const struct got_error *
12399 histedit_load_list(struct got_histedit_list *histedit_cmds,
12400 const char *path, struct got_repository *repo)
12402 const struct got_error *err = NULL;
12403 FILE *f = NULL;
12405 f = fopen(path, "re");
12406 if (f == NULL) {
12407 err = got_error_from_errno2("fopen", path);
12408 goto done;
12411 err = histedit_parse_list(histedit_cmds, f, repo);
12412 done:
12413 if (f && fclose(f) == EOF && err == NULL)
12414 err = got_error_from_errno("fclose");
12415 return err;
12418 static const struct got_error *
12419 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12420 const struct got_error *edit_err, struct got_object_id_queue *commits,
12421 const char *editor, const char *path, const char *branch_name,
12422 struct got_repository *repo)
12424 const struct got_error *err = NULL, *prev_err = edit_err;
12425 int resp = ' ';
12427 while (resp != 'c' && resp != 'r' && resp != 'a') {
12428 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12429 "or (a)bort: ", getprogname(), prev_err->msg);
12430 resp = getchar();
12431 if (resp == '\n')
12432 resp = getchar();
12433 if (resp == 'c') {
12434 histedit_free_list(histedit_cmds);
12435 err = histedit_run_editor(histedit_cmds, editor, path,
12436 commits, repo);
12437 if (err) {
12438 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12439 err->code != GOT_ERR_HISTEDIT_CMD)
12440 break;
12441 prev_err = err;
12442 resp = ' ';
12443 continue;
12445 break;
12446 } else if (resp == 'r') {
12447 histedit_free_list(histedit_cmds);
12448 err = histedit_edit_script(histedit_cmds,
12449 commits, branch_name, 0, 0, 0, 0, editor, repo);
12450 if (err) {
12451 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12452 err->code != GOT_ERR_HISTEDIT_CMD)
12453 break;
12454 prev_err = err;
12455 resp = ' ';
12456 continue;
12458 break;
12459 } else if (resp == 'a') {
12460 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12461 break;
12462 } else
12463 printf("invalid response '%c'\n", resp);
12466 return err;
12469 static const struct got_error *
12470 histedit_complete(struct got_worktree *worktree,
12471 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12472 struct got_reference *branch, struct got_repository *repo)
12474 printf("Switching work tree to %s\n",
12475 got_ref_get_symref_target(branch));
12476 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12477 branch, repo);
12480 static const struct got_error *
12481 show_histedit_progress(struct got_commit_object *commit,
12482 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12484 const struct got_error *err;
12485 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12487 err = got_object_id_str(&old_id_str, hle->commit_id);
12488 if (err)
12489 goto done;
12491 if (new_id) {
12492 err = got_object_id_str(&new_id_str, new_id);
12493 if (err)
12494 goto done;
12497 old_id_str[12] = '\0';
12498 if (new_id_str)
12499 new_id_str[12] = '\0';
12501 if (hle->logmsg) {
12502 logmsg = strdup(hle->logmsg);
12503 if (logmsg == NULL) {
12504 err = got_error_from_errno("strdup");
12505 goto done;
12507 trim_logmsg(logmsg, 42);
12508 } else {
12509 err = get_short_logmsg(&logmsg, 42, commit);
12510 if (err)
12511 goto done;
12514 switch (hle->cmd->code) {
12515 case GOT_HISTEDIT_PICK:
12516 case GOT_HISTEDIT_EDIT:
12517 case GOT_HISTEDIT_MESG:
12518 printf("%s -> %s: %s\n", old_id_str,
12519 new_id_str ? new_id_str : "no-op change", logmsg);
12520 break;
12521 case GOT_HISTEDIT_DROP:
12522 case GOT_HISTEDIT_FOLD:
12523 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12524 logmsg);
12525 break;
12526 default:
12527 break;
12529 done:
12530 free(old_id_str);
12531 free(new_id_str);
12532 return err;
12535 static const struct got_error *
12536 histedit_commit(struct got_pathlist_head *merged_paths,
12537 struct got_worktree *worktree, struct got_fileindex *fileindex,
12538 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12539 const char *committer, int allow_conflict, const char *editor,
12540 struct got_repository *repo)
12542 const struct got_error *err;
12543 struct got_commit_object *commit;
12544 struct got_object_id *new_commit_id;
12546 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12547 && hle->logmsg == NULL) {
12548 err = histedit_edit_logmsg(hle, editor, repo);
12549 if (err)
12550 return err;
12553 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12554 if (err)
12555 return err;
12557 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12558 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12559 hle->logmsg, allow_conflict, repo);
12560 if (err) {
12561 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12562 goto done;
12563 err = show_histedit_progress(commit, hle, NULL);
12564 } else {
12565 err = show_histedit_progress(commit, hle, new_commit_id);
12566 free(new_commit_id);
12568 done:
12569 got_object_commit_close(commit);
12570 return err;
12573 static const struct got_error *
12574 histedit_skip_commit(struct got_histedit_list_entry *hle,
12575 struct got_worktree *worktree, struct got_repository *repo)
12577 const struct got_error *error;
12578 struct got_commit_object *commit;
12580 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12581 repo);
12582 if (error)
12583 return error;
12585 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12586 if (error)
12587 return error;
12589 error = show_histedit_progress(commit, hle, NULL);
12590 got_object_commit_close(commit);
12591 return error;
12594 static const struct got_error *
12595 check_local_changes(void *arg, unsigned char status,
12596 unsigned char staged_status, const char *path,
12597 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12598 struct got_object_id *commit_id, int dirfd, const char *de_name)
12600 int *have_local_changes = arg;
12602 switch (status) {
12603 case GOT_STATUS_ADD:
12604 case GOT_STATUS_DELETE:
12605 case GOT_STATUS_MODIFY:
12606 case GOT_STATUS_CONFLICT:
12607 *have_local_changes = 1;
12608 return got_error(GOT_ERR_CANCELLED);
12609 default:
12610 break;
12613 switch (staged_status) {
12614 case GOT_STATUS_ADD:
12615 case GOT_STATUS_DELETE:
12616 case GOT_STATUS_MODIFY:
12617 *have_local_changes = 1;
12618 return got_error(GOT_ERR_CANCELLED);
12619 default:
12620 break;
12623 return NULL;
12626 static const struct got_error *
12627 cmd_histedit(int argc, char *argv[])
12629 const struct got_error *error = NULL;
12630 struct got_worktree *worktree = NULL;
12631 struct got_fileindex *fileindex = NULL;
12632 struct got_repository *repo = NULL;
12633 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12634 struct got_reference *branch = NULL;
12635 struct got_reference *tmp_branch = NULL;
12636 struct got_object_id *resume_commit_id = NULL;
12637 struct got_object_id *base_commit_id = NULL;
12638 struct got_object_id *head_commit_id = NULL;
12639 struct got_commit_object *commit = NULL;
12640 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12641 struct got_update_progress_arg upa;
12642 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12643 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12644 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12645 const char *edit_script_path = NULL;
12646 char *editor = NULL;
12647 struct got_object_id_queue commits;
12648 struct got_pathlist_head merged_paths;
12649 const struct got_object_id_queue *parent_ids;
12650 struct got_object_qid *pid;
12651 struct got_histedit_list histedit_cmds;
12652 struct got_histedit_list_entry *hle;
12653 int *pack_fds = NULL;
12655 STAILQ_INIT(&commits);
12656 TAILQ_INIT(&histedit_cmds);
12657 TAILQ_INIT(&merged_paths);
12658 memset(&upa, 0, sizeof(upa));
12660 #ifndef PROFILE
12661 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12662 "unveil", NULL) == -1)
12663 err(1, "pledge");
12664 #endif
12666 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12667 switch (ch) {
12668 case 'a':
12669 abort_edit = 1;
12670 break;
12671 case 'C':
12672 allow_conflict = 1;
12673 break;
12674 case 'c':
12675 continue_edit = 1;
12676 break;
12677 case 'd':
12678 drop_only = 1;
12679 break;
12680 case 'e':
12681 edit_only = 1;
12682 break;
12683 case 'F':
12684 edit_script_path = optarg;
12685 break;
12686 case 'f':
12687 fold_only = 1;
12688 break;
12689 case 'l':
12690 list_backups = 1;
12691 break;
12692 case 'm':
12693 edit_logmsg_only = 1;
12694 break;
12695 case 'X':
12696 delete_backups = 1;
12697 break;
12698 default:
12699 usage_histedit();
12700 /* NOTREACHED */
12704 argc -= optind;
12705 argv += optind;
12707 if (abort_edit && allow_conflict)
12708 option_conflict('a', 'C');
12709 if (abort_edit && continue_edit)
12710 option_conflict('a', 'c');
12711 if (edit_script_path && allow_conflict)
12712 option_conflict('F', 'C');
12713 if (edit_script_path && edit_logmsg_only)
12714 option_conflict('F', 'm');
12715 if (abort_edit && edit_logmsg_only)
12716 option_conflict('a', 'm');
12717 if (edit_logmsg_only && allow_conflict)
12718 option_conflict('m', 'C');
12719 if (continue_edit && edit_logmsg_only)
12720 option_conflict('c', 'm');
12721 if (abort_edit && fold_only)
12722 option_conflict('a', 'f');
12723 if (fold_only && allow_conflict)
12724 option_conflict('f', 'C');
12725 if (continue_edit && fold_only)
12726 option_conflict('c', 'f');
12727 if (fold_only && edit_logmsg_only)
12728 option_conflict('f', 'm');
12729 if (edit_script_path && fold_only)
12730 option_conflict('F', 'f');
12731 if (abort_edit && edit_only)
12732 option_conflict('a', 'e');
12733 if (continue_edit && edit_only)
12734 option_conflict('c', 'e');
12735 if (edit_only && edit_logmsg_only)
12736 option_conflict('e', 'm');
12737 if (edit_script_path && edit_only)
12738 option_conflict('F', 'e');
12739 if (fold_only && edit_only)
12740 option_conflict('f', 'e');
12741 if (drop_only && abort_edit)
12742 option_conflict('d', 'a');
12743 if (drop_only && allow_conflict)
12744 option_conflict('d', 'C');
12745 if (drop_only && continue_edit)
12746 option_conflict('d', 'c');
12747 if (drop_only && edit_logmsg_only)
12748 option_conflict('d', 'm');
12749 if (drop_only && edit_only)
12750 option_conflict('d', 'e');
12751 if (drop_only && edit_script_path)
12752 option_conflict('d', 'F');
12753 if (drop_only && fold_only)
12754 option_conflict('d', 'f');
12755 if (list_backups) {
12756 if (abort_edit)
12757 option_conflict('l', 'a');
12758 if (allow_conflict)
12759 option_conflict('l', 'C');
12760 if (continue_edit)
12761 option_conflict('l', 'c');
12762 if (edit_script_path)
12763 option_conflict('l', 'F');
12764 if (edit_logmsg_only)
12765 option_conflict('l', 'm');
12766 if (drop_only)
12767 option_conflict('l', 'd');
12768 if (fold_only)
12769 option_conflict('l', 'f');
12770 if (edit_only)
12771 option_conflict('l', 'e');
12772 if (delete_backups)
12773 option_conflict('l', 'X');
12774 if (argc != 0 && argc != 1)
12775 usage_histedit();
12776 } else if (delete_backups) {
12777 if (abort_edit)
12778 option_conflict('X', 'a');
12779 if (allow_conflict)
12780 option_conflict('X', 'C');
12781 if (continue_edit)
12782 option_conflict('X', 'c');
12783 if (drop_only)
12784 option_conflict('X', 'd');
12785 if (edit_script_path)
12786 option_conflict('X', 'F');
12787 if (edit_logmsg_only)
12788 option_conflict('X', 'm');
12789 if (fold_only)
12790 option_conflict('X', 'f');
12791 if (edit_only)
12792 option_conflict('X', 'e');
12793 if (list_backups)
12794 option_conflict('X', 'l');
12795 if (argc != 0 && argc != 1)
12796 usage_histedit();
12797 } else if (allow_conflict && !continue_edit)
12798 errx(1, "-C option requires -c");
12799 else if (argc != 0)
12800 usage_histedit();
12802 cwd = getcwd(NULL, 0);
12803 if (cwd == NULL) {
12804 error = got_error_from_errno("getcwd");
12805 goto done;
12808 error = got_repo_pack_fds_open(&pack_fds);
12809 if (error != NULL)
12810 goto done;
12812 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12813 if (error) {
12814 if (list_backups || delete_backups) {
12815 if (error->code != GOT_ERR_NOT_WORKTREE)
12816 goto done;
12817 } else {
12818 if (error->code == GOT_ERR_NOT_WORKTREE)
12819 error = wrap_not_worktree_error(error,
12820 "histedit", cwd);
12821 goto done;
12825 if (list_backups || delete_backups) {
12826 error = got_repo_open(&repo,
12827 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12828 NULL, pack_fds);
12829 if (error != NULL)
12830 goto done;
12831 error = apply_unveil(got_repo_get_path(repo), 0,
12832 worktree ? got_worktree_get_root_path(worktree) : NULL);
12833 if (error)
12834 goto done;
12835 error = process_backup_refs(
12836 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12837 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12838 goto done; /* nothing else to do */
12839 } else {
12840 error = get_gitconfig_path(&gitconfig_path);
12841 if (error)
12842 goto done;
12843 error = got_repo_open(&repo,
12844 got_worktree_get_repo_path(worktree), gitconfig_path,
12845 pack_fds);
12846 if (error != NULL)
12847 goto done;
12848 error = get_editor(&editor);
12849 if (error)
12850 goto done;
12851 if (unveil(editor, "x") != 0) {
12852 error = got_error_from_errno2("unveil", editor);
12853 goto done;
12855 if (edit_script_path) {
12856 if (unveil(edit_script_path, "r") != 0) {
12857 error = got_error_from_errno2("unveil",
12858 edit_script_path);
12859 goto done;
12862 error = apply_unveil(got_repo_get_path(repo), 0,
12863 got_worktree_get_root_path(worktree));
12864 if (error)
12865 goto done;
12868 if (worktree != NULL && !list_backups && !delete_backups) {
12869 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12870 if (error)
12871 goto done;
12874 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12875 if (error)
12876 goto done;
12877 if (rebase_in_progress) {
12878 error = got_error(GOT_ERR_REBASING);
12879 goto done;
12882 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12883 repo);
12884 if (error)
12885 goto done;
12886 if (merge_in_progress) {
12887 error = got_error(GOT_ERR_MERGE_BUSY);
12888 goto done;
12891 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12892 if (error)
12893 goto done;
12895 if (edit_in_progress && edit_logmsg_only) {
12896 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12897 "histedit operation is in progress in this "
12898 "work tree and must be continued or aborted "
12899 "before the -m option can be used");
12900 goto done;
12902 if (edit_in_progress && drop_only) {
12903 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12904 "histedit operation is in progress in this "
12905 "work tree and must be continued or aborted "
12906 "before the -d option can be used");
12907 goto done;
12909 if (edit_in_progress && fold_only) {
12910 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12911 "histedit operation is in progress in this "
12912 "work tree and must be continued or aborted "
12913 "before the -f option can be used");
12914 goto done;
12916 if (edit_in_progress && edit_only) {
12917 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12918 "histedit operation is in progress in this "
12919 "work tree and must be continued or aborted "
12920 "before the -e option can be used");
12921 goto done;
12924 if (edit_in_progress && abort_edit) {
12925 error = got_worktree_histedit_continue(&resume_commit_id,
12926 &tmp_branch, &branch, &base_commit_id, &fileindex,
12927 worktree, repo);
12928 if (error)
12929 goto done;
12930 printf("Switching work tree to %s\n",
12931 got_ref_get_symref_target(branch));
12932 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12933 branch, base_commit_id, abort_progress, &upa);
12934 if (error)
12935 goto done;
12936 printf("Histedit of %s aborted\n",
12937 got_ref_get_symref_target(branch));
12938 print_merge_progress_stats(&upa);
12939 goto done; /* nothing else to do */
12940 } else if (abort_edit) {
12941 error = got_error(GOT_ERR_NOT_HISTEDIT);
12942 goto done;
12945 error = get_author(&committer, repo, worktree);
12946 if (error)
12947 goto done;
12949 if (continue_edit) {
12950 char *path;
12952 if (!edit_in_progress) {
12953 error = got_error(GOT_ERR_NOT_HISTEDIT);
12954 goto done;
12957 error = got_worktree_get_histedit_script_path(&path, worktree);
12958 if (error)
12959 goto done;
12961 error = histedit_load_list(&histedit_cmds, path, repo);
12962 free(path);
12963 if (error)
12964 goto done;
12966 error = got_worktree_histedit_continue(&resume_commit_id,
12967 &tmp_branch, &branch, &base_commit_id, &fileindex,
12968 worktree, repo);
12969 if (error)
12970 goto done;
12972 error = got_ref_resolve(&head_commit_id, repo, branch);
12973 if (error)
12974 goto done;
12976 error = got_object_open_as_commit(&commit, repo,
12977 head_commit_id);
12978 if (error)
12979 goto done;
12980 parent_ids = got_object_commit_get_parent_ids(commit);
12981 pid = STAILQ_FIRST(parent_ids);
12982 if (pid == NULL) {
12983 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12984 goto done;
12986 error = collect_commits(&commits, head_commit_id, &pid->id,
12987 base_commit_id, got_worktree_get_path_prefix(worktree),
12988 GOT_ERR_HISTEDIT_PATH, repo);
12989 got_object_commit_close(commit);
12990 commit = NULL;
12991 if (error)
12992 goto done;
12993 } else {
12994 if (edit_in_progress) {
12995 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12996 goto done;
12999 error = got_ref_open(&branch, repo,
13000 got_worktree_get_head_ref_name(worktree), 0);
13001 if (error != NULL)
13002 goto done;
13004 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13005 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13006 "will not edit commit history of a branch outside "
13007 "the \"refs/heads/\" reference namespace");
13008 goto done;
13011 error = got_ref_resolve(&head_commit_id, repo, branch);
13012 got_ref_close(branch);
13013 branch = NULL;
13014 if (error)
13015 goto done;
13017 error = got_object_open_as_commit(&commit, repo,
13018 head_commit_id);
13019 if (error)
13020 goto done;
13021 parent_ids = got_object_commit_get_parent_ids(commit);
13022 pid = STAILQ_FIRST(parent_ids);
13023 if (pid == NULL) {
13024 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13025 goto done;
13027 error = collect_commits(&commits, head_commit_id, &pid->id,
13028 got_worktree_get_base_commit_id(worktree),
13029 got_worktree_get_path_prefix(worktree),
13030 GOT_ERR_HISTEDIT_PATH, repo);
13031 got_object_commit_close(commit);
13032 commit = NULL;
13033 if (error)
13034 goto done;
13036 if (STAILQ_EMPTY(&commits)) {
13037 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13038 goto done;
13041 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13042 &base_commit_id, &fileindex, worktree, repo);
13043 if (error)
13044 goto done;
13046 if (edit_script_path) {
13047 error = histedit_load_list(&histedit_cmds,
13048 edit_script_path, repo);
13049 if (error) {
13050 got_worktree_histedit_abort(worktree, fileindex,
13051 repo, branch, base_commit_id,
13052 abort_progress, &upa);
13053 print_merge_progress_stats(&upa);
13054 goto done;
13056 } else {
13057 const char *branch_name;
13058 branch_name = got_ref_get_symref_target(branch);
13059 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13060 branch_name += 11;
13061 error = histedit_edit_script(&histedit_cmds, &commits,
13062 branch_name, edit_logmsg_only, fold_only,
13063 drop_only, edit_only, editor, repo);
13064 if (error) {
13065 got_worktree_histedit_abort(worktree, fileindex,
13066 repo, branch, base_commit_id,
13067 abort_progress, &upa);
13068 print_merge_progress_stats(&upa);
13069 goto done;
13074 error = histedit_save_list(&histedit_cmds, worktree,
13075 repo);
13076 if (error) {
13077 got_worktree_histedit_abort(worktree, fileindex,
13078 repo, branch, base_commit_id,
13079 abort_progress, &upa);
13080 print_merge_progress_stats(&upa);
13081 goto done;
13086 error = histedit_check_script(&histedit_cmds, &commits, repo);
13087 if (error)
13088 goto done;
13090 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13091 if (resume_commit_id) {
13092 if (got_object_id_cmp(hle->commit_id,
13093 resume_commit_id) != 0)
13094 continue;
13096 resume_commit_id = NULL;
13097 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13098 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13099 error = histedit_skip_commit(hle, worktree,
13100 repo);
13101 if (error)
13102 goto done;
13103 } else {
13104 struct got_pathlist_head paths;
13105 int have_changes = 0;
13107 TAILQ_INIT(&paths);
13108 error = got_pathlist_append(&paths, "", NULL);
13109 if (error)
13110 goto done;
13111 error = got_worktree_status(worktree, &paths,
13112 repo, 0, check_local_changes, &have_changes,
13113 check_cancelled, NULL);
13114 got_pathlist_free(&paths,
13115 GOT_PATHLIST_FREE_NONE);
13116 if (error) {
13117 if (error->code != GOT_ERR_CANCELLED)
13118 goto done;
13119 if (sigint_received || sigpipe_received)
13120 goto done;
13122 if (have_changes) {
13123 error = histedit_commit(NULL, worktree,
13124 fileindex, tmp_branch, hle,
13125 committer, allow_conflict, editor,
13126 repo);
13127 if (error)
13128 goto done;
13129 } else {
13130 error = got_object_open_as_commit(
13131 &commit, repo, hle->commit_id);
13132 if (error)
13133 goto done;
13134 error = show_histedit_progress(commit,
13135 hle, NULL);
13136 got_object_commit_close(commit);
13137 commit = NULL;
13138 if (error)
13139 goto done;
13142 continue;
13145 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13146 error = histedit_skip_commit(hle, worktree, repo);
13147 if (error)
13148 goto done;
13149 continue;
13151 error = got_object_open_as_commit(&commit, repo,
13152 hle->commit_id);
13153 if (error)
13154 goto done;
13155 parent_ids = got_object_commit_get_parent_ids(commit);
13156 pid = STAILQ_FIRST(parent_ids);
13158 error = got_worktree_histedit_merge_files(&merged_paths,
13159 worktree, fileindex, &pid->id, hle->commit_id, repo,
13160 update_progress, &upa, check_cancelled, NULL);
13161 if (error)
13162 goto done;
13163 got_object_commit_close(commit);
13164 commit = NULL;
13166 print_merge_progress_stats(&upa);
13167 if (upa.conflicts > 0 || upa.missing > 0 ||
13168 upa.not_deleted > 0 || upa.unversioned > 0) {
13169 if (upa.conflicts > 0) {
13170 error = show_rebase_merge_conflict(
13171 hle->commit_id, repo);
13172 if (error)
13173 goto done;
13175 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13176 break;
13179 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13180 char *id_str;
13181 error = got_object_id_str(&id_str, hle->commit_id);
13182 if (error)
13183 goto done;
13184 printf("Stopping histedit for amending commit %s\n",
13185 id_str);
13186 free(id_str);
13187 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13188 error = got_worktree_histedit_postpone(worktree,
13189 fileindex);
13190 goto done;
13191 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13192 error = histedit_skip_commit(hle, worktree, repo);
13193 if (error)
13194 goto done;
13195 continue;
13196 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13197 error = histedit_edit_logmsg(hle, editor, repo);
13198 if (error)
13199 goto done;
13202 error = histedit_commit(&merged_paths, worktree, fileindex,
13203 tmp_branch, hle, committer, allow_conflict, editor, repo);
13204 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13205 if (error)
13206 goto done;
13209 if (upa.conflicts > 0 || upa.missing > 0 ||
13210 upa.not_deleted > 0 || upa.unversioned > 0) {
13211 error = got_worktree_histedit_postpone(worktree, fileindex);
13212 if (error)
13213 goto done;
13214 if (upa.conflicts > 0 && upa.missing == 0 &&
13215 upa.not_deleted == 0 && upa.unversioned == 0) {
13216 error = got_error_msg(GOT_ERR_CONFLICTS,
13217 "conflicts must be resolved before histedit "
13218 "can continue");
13219 } else if (upa.conflicts > 0) {
13220 error = got_error_msg(GOT_ERR_CONFLICTS,
13221 "conflicts must be resolved before histedit "
13222 "can continue; changes destined for some "
13223 "files were not yet merged and should be "
13224 "merged manually if required before the "
13225 "histedit operation is continued");
13226 } else {
13227 error = got_error_msg(GOT_ERR_CONFLICTS,
13228 "changes destined for some files were not "
13229 "yet merged and should be merged manually "
13230 "if required before the histedit operation "
13231 "is continued");
13233 } else
13234 error = histedit_complete(worktree, fileindex, tmp_branch,
13235 branch, repo);
13236 done:
13237 free(cwd);
13238 free(editor);
13239 free(committer);
13240 free(gitconfig_path);
13241 got_object_id_queue_free(&commits);
13242 histedit_free_list(&histedit_cmds);
13243 free(head_commit_id);
13244 free(base_commit_id);
13245 free(resume_commit_id);
13246 if (commit)
13247 got_object_commit_close(commit);
13248 if (branch)
13249 got_ref_close(branch);
13250 if (tmp_branch)
13251 got_ref_close(tmp_branch);
13252 if (worktree)
13253 got_worktree_close(worktree);
13254 if (repo) {
13255 const struct got_error *close_err = got_repo_close(repo);
13256 if (error == NULL)
13257 error = close_err;
13259 if (pack_fds) {
13260 const struct got_error *pack_err =
13261 got_repo_pack_fds_close(pack_fds);
13262 if (error == NULL)
13263 error = pack_err;
13265 return error;
13268 __dead static void
13269 usage_integrate(void)
13271 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13272 exit(1);
13275 static const struct got_error *
13276 cmd_integrate(int argc, char *argv[])
13278 const struct got_error *error = NULL;
13279 struct got_repository *repo = NULL;
13280 struct got_worktree *worktree = NULL;
13281 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13282 const char *branch_arg = NULL;
13283 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13284 struct got_fileindex *fileindex = NULL;
13285 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13286 int ch;
13287 struct got_update_progress_arg upa;
13288 int *pack_fds = NULL;
13290 #ifndef PROFILE
13291 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13292 "unveil", NULL) == -1)
13293 err(1, "pledge");
13294 #endif
13296 while ((ch = getopt(argc, argv, "")) != -1) {
13297 switch (ch) {
13298 default:
13299 usage_integrate();
13300 /* NOTREACHED */
13304 argc -= optind;
13305 argv += optind;
13307 if (argc != 1)
13308 usage_integrate();
13309 branch_arg = argv[0];
13311 cwd = getcwd(NULL, 0);
13312 if (cwd == NULL) {
13313 error = got_error_from_errno("getcwd");
13314 goto done;
13317 error = got_repo_pack_fds_open(&pack_fds);
13318 if (error != NULL)
13319 goto done;
13321 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13322 if (error) {
13323 if (error->code == GOT_ERR_NOT_WORKTREE)
13324 error = wrap_not_worktree_error(error, "integrate",
13325 cwd);
13326 goto done;
13329 error = check_rebase_or_histedit_in_progress(worktree);
13330 if (error)
13331 goto done;
13333 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13334 NULL, pack_fds);
13335 if (error != NULL)
13336 goto done;
13338 error = apply_unveil(got_repo_get_path(repo), 0,
13339 got_worktree_get_root_path(worktree));
13340 if (error)
13341 goto done;
13343 error = check_merge_in_progress(worktree, repo);
13344 if (error)
13345 goto done;
13347 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13348 error = got_error_from_errno("asprintf");
13349 goto done;
13352 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13353 &base_branch_ref, worktree, refname, repo);
13354 if (error)
13355 goto done;
13357 refname = strdup(got_ref_get_name(branch_ref));
13358 if (refname == NULL) {
13359 error = got_error_from_errno("strdup");
13360 got_worktree_integrate_abort(worktree, fileindex, repo,
13361 branch_ref, base_branch_ref);
13362 goto done;
13364 base_refname = strdup(got_ref_get_name(base_branch_ref));
13365 if (base_refname == NULL) {
13366 error = got_error_from_errno("strdup");
13367 got_worktree_integrate_abort(worktree, fileindex, repo,
13368 branch_ref, base_branch_ref);
13369 goto done;
13371 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13372 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13373 got_worktree_integrate_abort(worktree, fileindex, repo,
13374 branch_ref, base_branch_ref);
13375 goto done;
13378 error = got_ref_resolve(&commit_id, repo, branch_ref);
13379 if (error)
13380 goto done;
13382 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13383 if (error)
13384 goto done;
13386 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13387 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13388 "specified branch has already been integrated");
13389 got_worktree_integrate_abort(worktree, fileindex, repo,
13390 branch_ref, base_branch_ref);
13391 goto done;
13394 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13395 if (error) {
13396 if (error->code == GOT_ERR_ANCESTRY)
13397 error = got_error(GOT_ERR_REBASE_REQUIRED);
13398 got_worktree_integrate_abort(worktree, fileindex, repo,
13399 branch_ref, base_branch_ref);
13400 goto done;
13403 memset(&upa, 0, sizeof(upa));
13404 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13405 branch_ref, base_branch_ref, update_progress, &upa,
13406 check_cancelled, NULL);
13407 if (error)
13408 goto done;
13410 printf("Integrated %s into %s\n", refname, base_refname);
13411 print_update_progress_stats(&upa);
13412 done:
13413 if (repo) {
13414 const struct got_error *close_err = got_repo_close(repo);
13415 if (error == NULL)
13416 error = close_err;
13418 if (worktree)
13419 got_worktree_close(worktree);
13420 if (pack_fds) {
13421 const struct got_error *pack_err =
13422 got_repo_pack_fds_close(pack_fds);
13423 if (error == NULL)
13424 error = pack_err;
13426 free(cwd);
13427 free(base_commit_id);
13428 free(commit_id);
13429 free(refname);
13430 free(base_refname);
13431 return error;
13434 __dead static void
13435 usage_merge(void)
13437 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13438 exit(1);
13441 static const struct got_error *
13442 cmd_merge(int argc, char *argv[])
13444 const struct got_error *error = NULL;
13445 struct got_worktree *worktree = NULL;
13446 struct got_repository *repo = NULL;
13447 struct got_fileindex *fileindex = NULL;
13448 char *cwd = NULL, *id_str = NULL, *author = NULL;
13449 char *gitconfig_path = NULL;
13450 struct got_reference *branch = NULL, *wt_branch = NULL;
13451 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13452 struct got_object_id *wt_branch_tip = NULL;
13453 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13454 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13455 struct got_update_progress_arg upa;
13456 struct got_object_id *merge_commit_id = NULL;
13457 char *branch_name = NULL;
13458 int *pack_fds = NULL;
13460 memset(&upa, 0, sizeof(upa));
13462 #ifndef PROFILE
13463 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13464 "unveil", NULL) == -1)
13465 err(1, "pledge");
13466 #endif
13468 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13469 switch (ch) {
13470 case 'a':
13471 abort_merge = 1;
13472 break;
13473 case 'C':
13474 allow_conflict = 1;
13475 break;
13476 case 'c':
13477 continue_merge = 1;
13478 break;
13479 case 'M':
13480 prefer_fast_forward = 0;
13481 break;
13482 case 'n':
13483 interrupt_merge = 1;
13484 break;
13485 default:
13486 usage_merge();
13487 /* NOTREACHED */
13491 argc -= optind;
13492 argv += optind;
13494 if (abort_merge) {
13495 if (continue_merge)
13496 option_conflict('a', 'c');
13497 if (!prefer_fast_forward)
13498 option_conflict('a', 'M');
13499 if (interrupt_merge)
13500 option_conflict('a', 'n');
13501 } else if (continue_merge) {
13502 if (!prefer_fast_forward)
13503 option_conflict('c', 'M');
13504 if (interrupt_merge)
13505 option_conflict('c', 'n');
13507 if (allow_conflict) {
13508 if (!continue_merge)
13509 errx(1, "-C option requires -c");
13511 if (abort_merge || continue_merge) {
13512 if (argc != 0)
13513 usage_merge();
13514 } else if (argc != 1)
13515 usage_merge();
13517 cwd = getcwd(NULL, 0);
13518 if (cwd == NULL) {
13519 error = got_error_from_errno("getcwd");
13520 goto done;
13523 error = got_repo_pack_fds_open(&pack_fds);
13524 if (error != NULL)
13525 goto done;
13527 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13528 if (error) {
13529 if (error->code == GOT_ERR_NOT_WORKTREE)
13530 error = wrap_not_worktree_error(error,
13531 "merge", cwd);
13532 goto done;
13535 error = get_gitconfig_path(&gitconfig_path);
13536 if (error)
13537 goto done;
13538 error = got_repo_open(&repo,
13539 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13540 gitconfig_path, pack_fds);
13541 if (error != NULL)
13542 goto done;
13544 if (worktree != NULL) {
13545 error = worktree_has_logmsg_ref("merge", worktree, repo);
13546 if (error)
13547 goto done;
13550 error = apply_unveil(got_repo_get_path(repo), 0,
13551 worktree ? got_worktree_get_root_path(worktree) : NULL);
13552 if (error)
13553 goto done;
13555 error = check_rebase_or_histedit_in_progress(worktree);
13556 if (error)
13557 goto done;
13559 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13560 repo);
13561 if (error)
13562 goto done;
13564 if (merge_in_progress && !(abort_merge || continue_merge)) {
13565 error = got_error(GOT_ERR_MERGE_BUSY);
13566 goto done;
13569 if (!merge_in_progress && (abort_merge || continue_merge)) {
13570 error = got_error(GOT_ERR_NOT_MERGING);
13571 goto done;
13574 if (abort_merge) {
13575 error = got_worktree_merge_continue(&branch_name,
13576 &branch_tip, &fileindex, worktree, repo);
13577 if (error)
13578 goto done;
13579 error = got_worktree_merge_abort(worktree, fileindex, repo,
13580 abort_progress, &upa);
13581 if (error)
13582 goto done;
13583 printf("Merge of %s aborted\n", branch_name);
13584 goto done; /* nothing else to do */
13587 if (strncmp(got_worktree_get_head_ref_name(worktree),
13588 "refs/heads/", 11) != 0) {
13589 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13590 "work tree's current branch %s is outside the "
13591 "\"refs/heads/\" reference namespace; "
13592 "update -b required",
13593 got_worktree_get_head_ref_name(worktree));
13594 goto done;
13597 error = get_author(&author, repo, worktree);
13598 if (error)
13599 goto done;
13601 error = got_ref_open(&wt_branch, repo,
13602 got_worktree_get_head_ref_name(worktree), 0);
13603 if (error)
13604 goto done;
13605 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13606 if (error)
13607 goto done;
13609 if (continue_merge) {
13610 struct got_object_id *base_commit_id;
13611 base_commit_id = got_worktree_get_base_commit_id(worktree);
13612 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13613 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13614 goto done;
13616 error = got_worktree_merge_continue(&branch_name,
13617 &branch_tip, &fileindex, worktree, repo);
13618 if (error)
13619 goto done;
13620 } else {
13621 error = got_ref_open(&branch, repo, argv[0], 0);
13622 if (error != NULL)
13623 goto done;
13624 branch_name = strdup(got_ref_get_name(branch));
13625 if (branch_name == NULL) {
13626 error = got_error_from_errno("strdup");
13627 goto done;
13629 error = got_ref_resolve(&branch_tip, repo, branch);
13630 if (error)
13631 goto done;
13634 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13635 wt_branch_tip, branch_tip, 0, 0, repo,
13636 check_cancelled, NULL);
13637 if (error && error->code != GOT_ERR_ANCESTRY)
13638 goto done;
13640 if (!continue_merge) {
13641 error = check_path_prefix(wt_branch_tip, branch_tip,
13642 got_worktree_get_path_prefix(worktree),
13643 GOT_ERR_MERGE_PATH, repo);
13644 if (error)
13645 goto done;
13646 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13647 if (error)
13648 goto done;
13649 if (prefer_fast_forward && yca_id &&
13650 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13651 struct got_pathlist_head paths;
13652 if (interrupt_merge) {
13653 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13654 "there are no changes to merge since %s "
13655 "is already based on %s; merge cannot be "
13656 "interrupted for amending; -n",
13657 branch_name, got_ref_get_name(wt_branch));
13658 goto done;
13660 printf("Forwarding %s to %s\n",
13661 got_ref_get_name(wt_branch), branch_name);
13662 error = got_ref_change_ref(wt_branch, branch_tip);
13663 if (error)
13664 goto done;
13665 error = got_ref_write(wt_branch, repo);
13666 if (error)
13667 goto done;
13668 error = got_worktree_set_base_commit_id(worktree, repo,
13669 branch_tip);
13670 if (error)
13671 goto done;
13672 TAILQ_INIT(&paths);
13673 error = got_pathlist_append(&paths, "", NULL);
13674 if (error)
13675 goto done;
13676 error = got_worktree_checkout_files(worktree,
13677 &paths, repo, update_progress, &upa,
13678 check_cancelled, NULL);
13679 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13680 if (error)
13681 goto done;
13682 if (upa.did_something) {
13683 char *id_str;
13684 error = got_object_id_str(&id_str, branch_tip);
13685 if (error)
13686 goto done;
13687 printf("Updated to commit %s\n", id_str);
13688 free(id_str);
13689 } else
13690 printf("Already up-to-date\n");
13691 print_update_progress_stats(&upa);
13692 goto done;
13694 error = got_worktree_merge_write_refs(worktree, branch, repo);
13695 if (error)
13696 goto done;
13698 error = got_worktree_merge_branch(worktree, fileindex,
13699 yca_id, branch_tip, repo, update_progress, &upa,
13700 check_cancelled, NULL);
13701 if (error)
13702 goto done;
13703 print_merge_progress_stats(&upa);
13704 if (!upa.did_something) {
13705 error = got_worktree_merge_abort(worktree, fileindex,
13706 repo, abort_progress, &upa);
13707 if (error)
13708 goto done;
13709 printf("Already up-to-date\n");
13710 goto done;
13714 if (interrupt_merge) {
13715 error = got_worktree_merge_postpone(worktree, fileindex);
13716 if (error)
13717 goto done;
13718 printf("Merge of %s interrupted on request\n", branch_name);
13719 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13720 upa.not_deleted > 0 || upa.unversioned > 0) {
13721 error = got_worktree_merge_postpone(worktree, fileindex);
13722 if (error)
13723 goto done;
13724 if (upa.conflicts > 0 && upa.missing == 0 &&
13725 upa.not_deleted == 0 && upa.unversioned == 0) {
13726 error = got_error_msg(GOT_ERR_CONFLICTS,
13727 "conflicts must be resolved before merging "
13728 "can continue");
13729 } else if (upa.conflicts > 0) {
13730 error = got_error_msg(GOT_ERR_CONFLICTS,
13731 "conflicts must be resolved before merging "
13732 "can continue; changes destined for some "
13733 "files were not yet merged and "
13734 "should be merged manually if required before the "
13735 "merge operation is continued");
13736 } else {
13737 error = got_error_msg(GOT_ERR_CONFLICTS,
13738 "changes destined for some "
13739 "files were not yet merged and should be "
13740 "merged manually if required before the "
13741 "merge operation is continued");
13743 goto done;
13744 } else {
13745 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13746 fileindex, author, NULL, 1, branch_tip, branch_name,
13747 allow_conflict, repo, continue_merge ? print_status : NULL,
13748 NULL);
13749 if (error)
13750 goto done;
13751 error = got_worktree_merge_complete(worktree, fileindex, repo);
13752 if (error)
13753 goto done;
13754 error = got_object_id_str(&id_str, merge_commit_id);
13755 if (error)
13756 goto done;
13757 printf("Merged %s into %s: %s\n", branch_name,
13758 got_worktree_get_head_ref_name(worktree),
13759 id_str);
13762 done:
13763 free(gitconfig_path);
13764 free(id_str);
13765 free(merge_commit_id);
13766 free(author);
13767 free(branch_tip);
13768 free(branch_name);
13769 free(yca_id);
13770 if (branch)
13771 got_ref_close(branch);
13772 if (wt_branch)
13773 got_ref_close(wt_branch);
13774 if (worktree)
13775 got_worktree_close(worktree);
13776 if (repo) {
13777 const struct got_error *close_err = got_repo_close(repo);
13778 if (error == NULL)
13779 error = close_err;
13781 if (pack_fds) {
13782 const struct got_error *pack_err =
13783 got_repo_pack_fds_close(pack_fds);
13784 if (error == NULL)
13785 error = pack_err;
13787 return error;
13790 __dead static void
13791 usage_stage(void)
13793 fprintf(stderr, "usage: %s stage [-lpRS] [-F response-script] "
13794 "[path ...]\n", getprogname());
13795 exit(1);
13798 static const struct got_error *
13799 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13800 const char *path, struct got_object_id *blob_id,
13801 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13802 int dirfd, const char *de_name)
13804 const struct got_error *err = NULL;
13805 char *id_str = NULL;
13807 if (staged_status != GOT_STATUS_ADD &&
13808 staged_status != GOT_STATUS_MODIFY &&
13809 staged_status != GOT_STATUS_DELETE)
13810 return NULL;
13812 if (staged_status == GOT_STATUS_ADD ||
13813 staged_status == GOT_STATUS_MODIFY)
13814 err = got_object_id_str(&id_str, staged_blob_id);
13815 else
13816 err = got_object_id_str(&id_str, blob_id);
13817 if (err)
13818 return err;
13820 printf("%s %c %s\n", id_str, staged_status, path);
13821 free(id_str);
13822 return NULL;
13825 static const struct got_error *
13826 cmd_stage(int argc, char *argv[])
13828 const struct got_error *error = NULL;
13829 struct got_repository *repo = NULL;
13830 struct got_worktree *worktree = NULL;
13831 char *cwd = NULL;
13832 struct got_pathlist_head paths;
13833 int ch, contains_dir;
13834 int can_recurse = 0, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13835 FILE *patch_script_file = NULL;
13836 const char *patch_script_path = NULL;
13837 struct choose_patch_arg cpa;
13838 int *pack_fds = NULL;
13840 TAILQ_INIT(&paths);
13842 #ifndef PROFILE
13843 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13844 "unveil", NULL) == -1)
13845 err(1, "pledge");
13846 #endif
13848 while ((ch = getopt(argc, argv, "F:lpRS")) != -1) {
13849 switch (ch) {
13850 case 'F':
13851 patch_script_path = optarg;
13852 break;
13853 case 'l':
13854 list_stage = 1;
13855 break;
13856 case 'p':
13857 pflag = 1;
13858 break;
13859 case 'R':
13860 can_recurse = 1;
13861 break;
13862 case 'S':
13863 allow_bad_symlinks = 1;
13864 break;
13865 default:
13866 usage_stage();
13867 /* NOTREACHED */
13871 argc -= optind;
13872 argv += optind;
13874 if (list_stage && (pflag || patch_script_path))
13875 errx(1, "-l option cannot be used with other options");
13876 if (patch_script_path && !pflag)
13877 errx(1, "-F option can only be used together with -p option");
13879 cwd = getcwd(NULL, 0);
13880 if (cwd == NULL) {
13881 error = got_error_from_errno("getcwd");
13882 goto done;
13885 error = got_repo_pack_fds_open(&pack_fds);
13886 if (error != NULL)
13887 goto done;
13889 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13890 if (error) {
13891 if (error->code == GOT_ERR_NOT_WORKTREE)
13892 error = wrap_not_worktree_error(error, "stage", cwd);
13893 goto done;
13896 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13897 NULL, pack_fds);
13898 if (error != NULL)
13899 goto done;
13901 if (patch_script_path) {
13902 patch_script_file = fopen(patch_script_path, "re");
13903 if (patch_script_file == NULL) {
13904 error = got_error_from_errno2("fopen",
13905 patch_script_path);
13906 goto done;
13909 error = apply_unveil(got_repo_get_path(repo), 0,
13910 got_worktree_get_root_path(worktree));
13911 if (error)
13912 goto done;
13914 error = check_merge_in_progress(worktree, repo);
13915 if (error)
13916 goto done;
13918 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13919 if (error)
13920 goto done;
13922 if (list_stage)
13923 error = got_worktree_status(worktree, &paths, repo, 0,
13924 print_stage, NULL, check_cancelled, NULL);
13925 else {
13926 if (!can_recurse) {
13927 error = check_paths_contains_dir(&contains_dir,
13928 worktree, &paths);
13929 if (error != NULL)
13930 goto done;
13932 if (contains_dir) {
13933 error = got_error_msg(GOT_ERR_BAD_PATH,
13934 "staging directories requires -R option");
13935 goto done;
13938 cpa.patch_script_file = patch_script_file;
13939 cpa.action = "stage";
13940 error = got_worktree_stage(worktree, &paths,
13941 pflag ? NULL : print_status, NULL,
13942 pflag ? choose_patch : NULL, &cpa,
13943 allow_bad_symlinks, repo);
13945 done:
13946 if (patch_script_file && fclose(patch_script_file) == EOF &&
13947 error == NULL)
13948 error = got_error_from_errno2("fclose", patch_script_path);
13949 if (repo) {
13950 const struct got_error *close_err = got_repo_close(repo);
13951 if (error == NULL)
13952 error = close_err;
13954 if (worktree)
13955 got_worktree_close(worktree);
13956 if (pack_fds) {
13957 const struct got_error *pack_err =
13958 got_repo_pack_fds_close(pack_fds);
13959 if (error == NULL)
13960 error = pack_err;
13962 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13963 free(cwd);
13964 return error;
13967 __dead static void
13968 usage_unstage(void)
13970 fprintf(stderr, "usage: %s unstage [-pR] [-F response-script] "
13971 "[path ...]\n", getprogname());
13972 exit(1);
13976 static const struct got_error *
13977 cmd_unstage(int argc, char *argv[])
13979 const struct got_error *error = NULL;
13980 struct got_repository *repo = NULL;
13981 struct got_worktree *worktree = NULL;
13982 char *cwd = NULL;
13983 struct got_pathlist_head paths;
13984 int ch, contains_dir, can_recurse = 0, pflag = 0;
13985 struct got_update_progress_arg upa;
13986 FILE *patch_script_file = NULL;
13987 const char *patch_script_path = NULL;
13988 struct choose_patch_arg cpa;
13989 int *pack_fds = NULL;
13991 TAILQ_INIT(&paths);
13993 #ifndef PROFILE
13994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13995 "unveil", NULL) == -1)
13996 err(1, "pledge");
13997 #endif
13999 while ((ch = getopt(argc, argv, "F:Rp")) != -1) {
14000 switch (ch) {
14001 case 'F':
14002 patch_script_path = optarg;
14003 break;
14004 case 'R':
14005 can_recurse = 1;
14006 break;
14007 case 'p':
14008 pflag = 1;
14009 break;
14010 default:
14011 usage_unstage();
14012 /* NOTREACHED */
14016 argc -= optind;
14017 argv += optind;
14019 if (patch_script_path && !pflag)
14020 errx(1, "-F option can only be used together with -p option");
14022 cwd = getcwd(NULL, 0);
14023 if (cwd == NULL) {
14024 error = got_error_from_errno("getcwd");
14025 goto done;
14028 error = got_repo_pack_fds_open(&pack_fds);
14029 if (error != NULL)
14030 goto done;
14032 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14033 if (error) {
14034 if (error->code == GOT_ERR_NOT_WORKTREE)
14035 error = wrap_not_worktree_error(error, "unstage", cwd);
14036 goto done;
14039 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14040 NULL, pack_fds);
14041 if (error != NULL)
14042 goto done;
14044 if (patch_script_path) {
14045 patch_script_file = fopen(patch_script_path, "re");
14046 if (patch_script_file == NULL) {
14047 error = got_error_from_errno2("fopen",
14048 patch_script_path);
14049 goto done;
14053 error = apply_unveil(got_repo_get_path(repo), 0,
14054 got_worktree_get_root_path(worktree));
14055 if (error)
14056 goto done;
14058 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14059 if (error)
14060 goto done;
14062 if (!can_recurse) {
14063 error = check_paths_contains_dir(&contains_dir,
14064 worktree, &paths);
14065 if (error != NULL)
14066 goto done;
14068 if (contains_dir) {
14069 error = got_error_msg(GOT_ERR_BAD_PATH,
14070 "unstaging directories requires -R option");
14071 goto done;
14075 cpa.patch_script_file = patch_script_file;
14076 cpa.action = "unstage";
14077 memset(&upa, 0, sizeof(upa));
14078 error = got_worktree_unstage(worktree, &paths, update_progress,
14079 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14080 if (!error)
14081 print_merge_progress_stats(&upa);
14082 done:
14083 if (patch_script_file && fclose(patch_script_file) == EOF &&
14084 error == NULL)
14085 error = got_error_from_errno2("fclose", patch_script_path);
14086 if (repo) {
14087 const struct got_error *close_err = got_repo_close(repo);
14088 if (error == NULL)
14089 error = close_err;
14091 if (worktree)
14092 got_worktree_close(worktree);
14093 if (pack_fds) {
14094 const struct got_error *pack_err =
14095 got_repo_pack_fds_close(pack_fds);
14096 if (error == NULL)
14097 error = pack_err;
14099 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14100 free(cwd);
14101 return error;
14104 __dead static void
14105 usage_cat(void)
14107 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14108 "arg ...\n", getprogname());
14109 exit(1);
14112 static const struct got_error *
14113 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14115 const struct got_error *err;
14116 struct got_blob_object *blob;
14117 int fd = -1;
14119 fd = got_opentempfd();
14120 if (fd == -1)
14121 return got_error_from_errno("got_opentempfd");
14123 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14124 if (err)
14125 goto done;
14127 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14128 done:
14129 if (fd != -1 && close(fd) == -1 && err == NULL)
14130 err = got_error_from_errno("close");
14131 if (blob)
14132 got_object_blob_close(blob);
14133 return err;
14136 static const struct got_error *
14137 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14139 const struct got_error *err;
14140 struct got_tree_object *tree;
14141 int nentries, i;
14143 err = got_object_open_as_tree(&tree, repo, id);
14144 if (err)
14145 return err;
14147 nentries = got_object_tree_get_nentries(tree);
14148 for (i = 0; i < nentries; i++) {
14149 struct got_tree_entry *te;
14150 char *id_str;
14151 if (sigint_received || sigpipe_received)
14152 break;
14153 te = got_object_tree_get_entry(tree, i);
14154 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14155 if (err)
14156 break;
14157 fprintf(outfile, "%s %.7o %s\n", id_str,
14158 got_tree_entry_get_mode(te),
14159 got_tree_entry_get_name(te));
14160 free(id_str);
14163 got_object_tree_close(tree);
14164 return err;
14167 static const struct got_error *
14168 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14170 const struct got_error *err;
14171 struct got_commit_object *commit;
14172 const struct got_object_id_queue *parent_ids;
14173 struct got_object_qid *pid;
14174 char *id_str = NULL;
14175 const char *logmsg = NULL;
14176 char gmtoff[6];
14178 err = got_object_open_as_commit(&commit, repo, id);
14179 if (err)
14180 return err;
14182 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14183 if (err)
14184 goto done;
14186 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14187 parent_ids = got_object_commit_get_parent_ids(commit);
14188 fprintf(outfile, "numparents %d\n",
14189 got_object_commit_get_nparents(commit));
14190 STAILQ_FOREACH(pid, parent_ids, entry) {
14191 char *pid_str;
14192 err = got_object_id_str(&pid_str, &pid->id);
14193 if (err)
14194 goto done;
14195 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14196 free(pid_str);
14198 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14199 got_object_commit_get_author_gmtoff(commit));
14200 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14201 got_object_commit_get_author(commit),
14202 (long long)got_object_commit_get_author_time(commit),
14203 gmtoff);
14205 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14206 got_object_commit_get_committer_gmtoff(commit));
14207 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14208 got_object_commit_get_committer(commit),
14209 (long long)got_object_commit_get_committer_time(commit),
14210 gmtoff);
14212 logmsg = got_object_commit_get_logmsg_raw(commit);
14213 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14214 fprintf(outfile, "%s", logmsg);
14215 done:
14216 free(id_str);
14217 got_object_commit_close(commit);
14218 return err;
14221 static const struct got_error *
14222 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14224 const struct got_error *err;
14225 struct got_tag_object *tag;
14226 char *id_str = NULL;
14227 const char *tagmsg = NULL;
14228 char gmtoff[6];
14230 err = got_object_open_as_tag(&tag, repo, id);
14231 if (err)
14232 return err;
14234 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14235 if (err)
14236 goto done;
14238 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14240 switch (got_object_tag_get_object_type(tag)) {
14241 case GOT_OBJ_TYPE_BLOB:
14242 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14243 GOT_OBJ_LABEL_BLOB);
14244 break;
14245 case GOT_OBJ_TYPE_TREE:
14246 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14247 GOT_OBJ_LABEL_TREE);
14248 break;
14249 case GOT_OBJ_TYPE_COMMIT:
14250 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14251 GOT_OBJ_LABEL_COMMIT);
14252 break;
14253 case GOT_OBJ_TYPE_TAG:
14254 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14255 GOT_OBJ_LABEL_TAG);
14256 break;
14257 default:
14258 break;
14261 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14262 got_object_tag_get_name(tag));
14264 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14265 got_object_tag_get_tagger_gmtoff(tag));
14266 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14267 got_object_tag_get_tagger(tag),
14268 (long long)got_object_tag_get_tagger_time(tag),
14269 gmtoff);
14271 tagmsg = got_object_tag_get_message(tag);
14272 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14273 fprintf(outfile, "%s", tagmsg);
14274 done:
14275 free(id_str);
14276 got_object_tag_close(tag);
14277 return err;
14280 static const struct got_error *
14281 cmd_cat(int argc, char *argv[])
14283 const struct got_error *error;
14284 struct got_repository *repo = NULL;
14285 struct got_worktree *worktree = NULL;
14286 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14287 char *keyword_idstr = NULL;
14288 const char *commit_id_str = NULL;
14289 struct got_object_id *id = NULL, *commit_id = NULL;
14290 struct got_commit_object *commit = NULL;
14291 int ch, obj_type, i, force_path = 0;
14292 struct got_reflist_head refs;
14293 int *pack_fds = NULL;
14295 TAILQ_INIT(&refs);
14297 #ifndef PROFILE
14298 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14299 NULL) == -1)
14300 err(1, "pledge");
14301 #endif
14303 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14304 switch (ch) {
14305 case 'c':
14306 commit_id_str = optarg;
14307 break;
14308 case 'P':
14309 force_path = 1;
14310 break;
14311 case 'r':
14312 repo_path = realpath(optarg, NULL);
14313 if (repo_path == NULL)
14314 return got_error_from_errno2("realpath",
14315 optarg);
14316 got_path_strip_trailing_slashes(repo_path);
14317 break;
14318 default:
14319 usage_cat();
14320 /* NOTREACHED */
14324 argc -= optind;
14325 argv += optind;
14327 cwd = getcwd(NULL, 0);
14328 if (cwd == NULL) {
14329 error = got_error_from_errno("getcwd");
14330 goto done;
14333 error = got_repo_pack_fds_open(&pack_fds);
14334 if (error != NULL)
14335 goto done;
14337 if (repo_path == NULL) {
14338 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14339 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14340 goto done;
14341 if (worktree) {
14342 repo_path = strdup(
14343 got_worktree_get_repo_path(worktree));
14344 if (repo_path == NULL) {
14345 error = got_error_from_errno("strdup");
14346 goto done;
14349 if (commit_id_str == NULL) {
14350 /* Release work tree lock. */
14351 got_worktree_close(worktree);
14352 worktree = NULL;
14357 if (repo_path == NULL) {
14358 repo_path = strdup(cwd);
14359 if (repo_path == NULL)
14360 return got_error_from_errno("strdup");
14363 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14364 free(repo_path);
14365 if (error != NULL)
14366 goto done;
14368 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14369 if (error)
14370 goto done;
14372 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14373 if (error)
14374 goto done;
14376 if (commit_id_str != NULL) {
14377 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14378 repo, worktree);
14379 if (error != NULL)
14380 goto done;
14381 if (keyword_idstr != NULL)
14382 commit_id_str = keyword_idstr;
14383 if (worktree != NULL) {
14384 got_worktree_close(worktree);
14385 worktree = NULL;
14387 } else
14388 commit_id_str = GOT_REF_HEAD;
14389 error = got_repo_match_object_id(&commit_id, NULL,
14390 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14391 if (error)
14392 goto done;
14394 error = got_object_open_as_commit(&commit, repo, commit_id);
14395 if (error)
14396 goto done;
14398 for (i = 0; i < argc; i++) {
14399 if (force_path) {
14400 error = got_object_id_by_path(&id, repo, commit,
14401 argv[i]);
14402 if (error)
14403 break;
14404 } else {
14405 error = got_repo_match_object_id(&id, &label, argv[i],
14406 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14407 repo);
14408 if (error) {
14409 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14410 error->code != GOT_ERR_NOT_REF)
14411 break;
14412 error = got_object_id_by_path(&id, repo,
14413 commit, argv[i]);
14414 if (error)
14415 break;
14419 error = got_object_get_type(&obj_type, repo, id);
14420 if (error)
14421 break;
14423 switch (obj_type) {
14424 case GOT_OBJ_TYPE_BLOB:
14425 error = cat_blob(id, repo, stdout);
14426 break;
14427 case GOT_OBJ_TYPE_TREE:
14428 error = cat_tree(id, repo, stdout);
14429 break;
14430 case GOT_OBJ_TYPE_COMMIT:
14431 error = cat_commit(id, repo, stdout);
14432 break;
14433 case GOT_OBJ_TYPE_TAG:
14434 error = cat_tag(id, repo, stdout);
14435 break;
14436 default:
14437 error = got_error(GOT_ERR_OBJ_TYPE);
14438 break;
14440 if (error)
14441 break;
14442 free(label);
14443 label = NULL;
14444 free(id);
14445 id = NULL;
14447 done:
14448 free(label);
14449 free(id);
14450 free(commit_id);
14451 free(keyword_idstr);
14452 if (commit)
14453 got_object_commit_close(commit);
14454 if (worktree)
14455 got_worktree_close(worktree);
14456 if (repo) {
14457 const struct got_error *close_err = got_repo_close(repo);
14458 if (error == NULL)
14459 error = close_err;
14461 if (pack_fds) {
14462 const struct got_error *pack_err =
14463 got_repo_pack_fds_close(pack_fds);
14464 if (error == NULL)
14465 error = pack_err;
14468 got_ref_list_free(&refs);
14469 return error;
14472 __dead static void
14473 usage_info(void)
14475 fprintf(stderr, "usage: %s info [path ...]\n",
14476 getprogname());
14477 exit(1);
14480 static const struct got_error *
14481 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14482 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14483 struct got_object_id *commit_id)
14485 const struct got_error *err = NULL;
14486 char *id_str = NULL;
14487 char datebuf[128];
14488 struct tm mytm, *tm;
14489 struct got_pathlist_head *paths = arg;
14490 struct got_pathlist_entry *pe;
14493 * Clear error indication from any of the path arguments which
14494 * would cause this file index entry to be displayed.
14496 TAILQ_FOREACH(pe, paths, entry) {
14497 if (got_path_cmp(path, pe->path, strlen(path),
14498 pe->path_len) == 0 ||
14499 got_path_is_child(path, pe->path, pe->path_len))
14500 pe->data = NULL; /* no error */
14503 printf(GOT_COMMIT_SEP_STR);
14504 if (S_ISLNK(mode))
14505 printf("symlink: %s\n", path);
14506 else if (S_ISREG(mode)) {
14507 printf("file: %s\n", path);
14508 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14509 } else if (S_ISDIR(mode))
14510 printf("directory: %s\n", path);
14511 else
14512 printf("something: %s\n", path);
14514 tm = localtime_r(&mtime, &mytm);
14515 if (tm == NULL)
14516 return NULL;
14517 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14518 return got_error(GOT_ERR_NO_SPACE);
14519 printf("timestamp: %s\n", datebuf);
14521 if (blob_id) {
14522 err = got_object_id_str(&id_str, blob_id);
14523 if (err)
14524 return err;
14525 printf("based on blob: %s\n", id_str);
14526 free(id_str);
14529 if (staged_blob_id) {
14530 err = got_object_id_str(&id_str, staged_blob_id);
14531 if (err)
14532 return err;
14533 printf("based on staged blob: %s\n", id_str);
14534 free(id_str);
14537 if (commit_id) {
14538 err = got_object_id_str(&id_str, commit_id);
14539 if (err)
14540 return err;
14541 printf("based on commit: %s\n", id_str);
14542 free(id_str);
14545 return NULL;
14548 static const struct got_error *
14549 cmd_info(int argc, char *argv[])
14551 const struct got_error *error = NULL;
14552 struct got_worktree *worktree = NULL;
14553 char *cwd = NULL, *id_str = NULL;
14554 struct got_pathlist_head paths;
14555 char *uuidstr = NULL;
14556 int ch, show_files = 0;
14558 TAILQ_INIT(&paths);
14560 #ifndef PROFILE
14561 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14562 NULL) == -1)
14563 err(1, "pledge");
14564 #endif
14566 while ((ch = getopt(argc, argv, "")) != -1) {
14567 switch (ch) {
14568 default:
14569 usage_info();
14570 /* NOTREACHED */
14574 argc -= optind;
14575 argv += optind;
14577 cwd = getcwd(NULL, 0);
14578 if (cwd == NULL) {
14579 error = got_error_from_errno("getcwd");
14580 goto done;
14583 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14584 if (error) {
14585 if (error->code == GOT_ERR_NOT_WORKTREE)
14586 error = wrap_not_worktree_error(error, "info", cwd);
14587 goto done;
14590 #ifndef PROFILE
14591 /* Remove "wpath cpath proc exec sendfd" promises. */
14592 if (pledge("stdio rpath flock unveil", NULL) == -1)
14593 err(1, "pledge");
14594 #endif
14595 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14596 if (error)
14597 goto done;
14599 if (argc >= 1) {
14600 error = get_worktree_paths_from_argv(&paths, argc, argv,
14601 worktree);
14602 if (error)
14603 goto done;
14604 show_files = 1;
14607 error = got_object_id_str(&id_str,
14608 got_worktree_get_base_commit_id(worktree));
14609 if (error)
14610 goto done;
14612 error = got_worktree_get_uuid(&uuidstr, worktree);
14613 if (error)
14614 goto done;
14616 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14617 printf("work tree base commit: %s\n", id_str);
14618 printf("work tree path prefix: %s\n",
14619 got_worktree_get_path_prefix(worktree));
14620 printf("work tree branch reference: %s\n",
14621 got_worktree_get_head_ref_name(worktree));
14622 printf("work tree UUID: %s\n", uuidstr);
14623 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14625 if (show_files) {
14626 struct got_pathlist_entry *pe;
14627 TAILQ_FOREACH(pe, &paths, entry) {
14628 if (pe->path_len == 0)
14629 continue;
14631 * Assume this path will fail. This will be corrected
14632 * in print_path_info() in case the path does suceeed.
14634 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14636 error = got_worktree_path_info(worktree, &paths,
14637 print_path_info, &paths, check_cancelled, NULL);
14638 if (error)
14639 goto done;
14640 TAILQ_FOREACH(pe, &paths, entry) {
14641 if (pe->data != NULL) {
14642 const struct got_error *perr;
14644 perr = pe->data;
14645 error = got_error_fmt(perr->code, "%s",
14646 pe->path);
14647 break;
14651 done:
14652 if (worktree)
14653 got_worktree_close(worktree);
14654 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14655 free(cwd);
14656 free(id_str);
14657 free(uuidstr);
14658 return error;