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), "%F ", &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), "%F", &tm) == 0) {
5732 err = got_error(GOT_ERR_NO_SPACE);
5733 goto done;
5735 bline->annotated = 1;
5737 /* Print lines annotated so far. */
5738 bline = &a->lines[a->lineno_cur - 1];
5739 if (!bline->annotated)
5740 goto done;
5742 offset = a->line_offsets[a->lineno_cur - 1];
5743 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5744 err = got_error_from_errno("fseeko");
5745 goto done;
5748 while (a->lineno_cur <= a->nlines && bline->annotated) {
5749 char *smallerthan, *at, *nl, *committer;
5750 size_t len;
5752 if (getline(&line, &linesize, a->f) == -1) {
5753 if (ferror(a->f))
5754 err = got_error_from_errno("getline");
5755 break;
5758 committer = bline->committer;
5759 smallerthan = strchr(committer, '<');
5760 if (smallerthan && smallerthan[1] != '\0')
5761 committer = smallerthan + 1;
5762 at = strchr(committer, '@');
5763 if (at)
5764 *at = '\0';
5765 len = strlen(committer);
5766 if (len >= 9)
5767 committer[8] = '\0';
5769 nl = strchr(line, '\n');
5770 if (nl)
5771 *nl = '\0';
5772 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5773 bline->id_str, bline->datebuf, committer, line);
5775 a->lineno_cur++;
5776 bline = &a->lines[a->lineno_cur - 1];
5778 done:
5779 free(line);
5780 return err;
5783 static const struct got_error *
5784 cmd_blame(int argc, char *argv[])
5786 const struct got_error *error;
5787 struct got_repository *repo = NULL;
5788 struct got_worktree *worktree = NULL;
5789 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5790 char *link_target = NULL;
5791 struct got_object_id *obj_id = NULL;
5792 struct got_object_id *commit_id = NULL;
5793 struct got_commit_object *commit = NULL;
5794 struct got_blob_object *blob = NULL;
5795 char *commit_id_str = NULL, *keyword_idstr = NULL;
5796 struct blame_cb_args bca;
5797 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5798 off_t filesize;
5799 int *pack_fds = NULL;
5800 FILE *f1 = NULL, *f2 = NULL;
5802 fd1 = got_opentempfd();
5803 if (fd1 == -1)
5804 return got_error_from_errno("got_opentempfd");
5806 memset(&bca, 0, sizeof(bca));
5808 #ifndef PROFILE
5809 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5810 NULL) == -1)
5811 err(1, "pledge");
5812 #endif
5814 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5815 switch (ch) {
5816 case 'c':
5817 commit_id_str = optarg;
5818 break;
5819 case 'r':
5820 repo_path = realpath(optarg, NULL);
5821 if (repo_path == NULL)
5822 return got_error_from_errno2("realpath",
5823 optarg);
5824 got_path_strip_trailing_slashes(repo_path);
5825 break;
5826 default:
5827 usage_blame();
5828 /* NOTREACHED */
5832 argc -= optind;
5833 argv += optind;
5835 if (argc == 1)
5836 path = argv[0];
5837 else
5838 usage_blame();
5840 cwd = getcwd(NULL, 0);
5841 if (cwd == NULL) {
5842 error = got_error_from_errno("getcwd");
5843 goto done;
5846 error = got_repo_pack_fds_open(&pack_fds);
5847 if (error != NULL)
5848 goto done;
5850 if (repo_path == NULL) {
5851 error = got_worktree_open(&worktree, cwd,
5852 GOT_WORKTREE_GOT_DIR);
5853 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5854 goto done;
5855 else
5856 error = NULL;
5857 if (worktree) {
5858 repo_path =
5859 strdup(got_worktree_get_repo_path(worktree));
5860 if (repo_path == NULL) {
5861 error = got_error_from_errno("strdup");
5862 if (error)
5863 goto done;
5865 } else {
5866 repo_path = strdup(cwd);
5867 if (repo_path == NULL) {
5868 error = got_error_from_errno("strdup");
5869 goto done;
5874 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5875 if (error != NULL)
5876 goto done;
5878 if (worktree) {
5879 const char *prefix = got_worktree_get_path_prefix(worktree);
5880 char *p;
5882 error = got_worktree_resolve_path(&p, worktree, path);
5883 if (error)
5884 goto done;
5885 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5886 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5887 p) == -1) {
5888 error = got_error_from_errno("asprintf");
5889 free(p);
5890 goto done;
5892 free(p);
5893 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5894 } else {
5895 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5896 if (error)
5897 goto done;
5898 error = got_repo_map_path(&in_repo_path, repo, path);
5900 if (error)
5901 goto done;
5903 if (commit_id_str == NULL) {
5904 struct got_reference *head_ref;
5905 error = got_ref_open(&head_ref, repo, worktree ?
5906 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5907 if (error != NULL)
5908 goto done;
5909 error = got_ref_resolve(&commit_id, repo, head_ref);
5910 got_ref_close(head_ref);
5911 if (error != NULL)
5912 goto done;
5913 } else {
5914 struct got_reflist_head refs;
5916 TAILQ_INIT(&refs);
5917 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5918 NULL);
5919 if (error)
5920 goto done;
5922 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5923 repo, worktree);
5924 if (error != NULL)
5925 goto done;
5926 if (keyword_idstr != NULL)
5927 commit_id_str = keyword_idstr;
5929 error = got_repo_match_object_id(&commit_id, NULL,
5930 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5931 got_ref_list_free(&refs);
5932 if (error)
5933 goto done;
5936 if (worktree) {
5937 /* Release work tree lock. */
5938 got_worktree_close(worktree);
5939 worktree = NULL;
5942 error = got_object_open_as_commit(&commit, repo, commit_id);
5943 if (error)
5944 goto done;
5946 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5947 commit, repo);
5948 if (error)
5949 goto done;
5951 error = got_object_id_by_path(&obj_id, repo, commit,
5952 link_target ? link_target : in_repo_path);
5953 if (error)
5954 goto done;
5956 error = got_object_get_type(&obj_type, repo, obj_id);
5957 if (error)
5958 goto done;
5960 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5961 error = got_error_path(link_target ? link_target : in_repo_path,
5962 GOT_ERR_OBJ_TYPE);
5963 goto done;
5966 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5967 if (error)
5968 goto done;
5969 bca.f = got_opentemp();
5970 if (bca.f == NULL) {
5971 error = got_error_from_errno("got_opentemp");
5972 goto done;
5974 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5975 &bca.line_offsets, bca.f, blob);
5976 if (error || bca.nlines == 0)
5977 goto done;
5979 /* Don't include \n at EOF in the blame line count. */
5980 if (bca.line_offsets[bca.nlines - 1] == filesize)
5981 bca.nlines--;
5983 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5984 if (bca.lines == NULL) {
5985 error = got_error_from_errno("calloc");
5986 goto done;
5988 bca.lineno_cur = 1;
5989 bca.nlines_prec = 0;
5990 i = bca.nlines;
5991 while (i > 0) {
5992 i /= 10;
5993 bca.nlines_prec++;
5995 bca.repo = repo;
5997 fd2 = got_opentempfd();
5998 if (fd2 == -1) {
5999 error = got_error_from_errno("got_opentempfd");
6000 goto done;
6002 fd3 = got_opentempfd();
6003 if (fd3 == -1) {
6004 error = got_error_from_errno("got_opentempfd");
6005 goto done;
6007 f1 = got_opentemp();
6008 if (f1 == NULL) {
6009 error = got_error_from_errno("got_opentemp");
6010 goto done;
6012 f2 = got_opentemp();
6013 if (f2 == NULL) {
6014 error = got_error_from_errno("got_opentemp");
6015 goto done;
6017 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6018 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6019 check_cancelled, NULL, fd2, fd3, f1, f2);
6020 done:
6021 free(keyword_idstr);
6022 free(in_repo_path);
6023 free(link_target);
6024 free(repo_path);
6025 free(cwd);
6026 free(commit_id);
6027 free(obj_id);
6028 if (commit)
6029 got_object_commit_close(commit);
6031 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6032 error = got_error_from_errno("close");
6033 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6034 error = got_error_from_errno("close");
6035 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6036 error = got_error_from_errno("close");
6037 if (f1 && fclose(f1) == EOF && error == NULL)
6038 error = got_error_from_errno("fclose");
6039 if (f2 && fclose(f2) == EOF && error == NULL)
6040 error = got_error_from_errno("fclose");
6042 if (blob)
6043 got_object_blob_close(blob);
6044 if (worktree)
6045 got_worktree_close(worktree);
6046 if (repo) {
6047 const struct got_error *close_err = got_repo_close(repo);
6048 if (error == NULL)
6049 error = close_err;
6051 if (pack_fds) {
6052 const struct got_error *pack_err =
6053 got_repo_pack_fds_close(pack_fds);
6054 if (error == NULL)
6055 error = pack_err;
6057 if (bca.lines) {
6058 for (i = 0; i < bca.nlines; i++) {
6059 struct blame_line *bline = &bca.lines[i];
6060 free(bline->id_str);
6061 free(bline->committer);
6063 free(bca.lines);
6065 free(bca.line_offsets);
6066 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6067 error = got_error_from_errno("fclose");
6068 return error;
6071 __dead static void
6072 usage_tree(void)
6074 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6075 "[path]\n", getprogname());
6076 exit(1);
6079 static const struct got_error *
6080 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6081 const char *root_path, struct got_repository *repo)
6083 const struct got_error *err = NULL;
6084 int is_root_path = (strcmp(path, root_path) == 0);
6085 const char *modestr = "";
6086 mode_t mode = got_tree_entry_get_mode(te);
6087 char *link_target = NULL;
6089 path += strlen(root_path);
6090 while (path[0] == '/')
6091 path++;
6093 if (got_object_tree_entry_is_submodule(te))
6094 modestr = "$";
6095 else if (S_ISLNK(mode)) {
6096 int i;
6098 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6099 if (err)
6100 return err;
6101 for (i = 0; link_target[i] != '\0'; i++) {
6102 if (!isprint((unsigned char)link_target[i]))
6103 link_target[i] = '?';
6106 modestr = "@";
6108 else if (S_ISDIR(mode))
6109 modestr = "/";
6110 else if (mode & S_IXUSR)
6111 modestr = "*";
6113 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6114 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6115 link_target ? " -> ": "", link_target ? link_target : "");
6117 free(link_target);
6118 return NULL;
6121 static const struct got_error *
6122 print_tree(const char *path, struct got_commit_object *commit,
6123 int show_ids, int recurse, const char *root_path,
6124 struct got_repository *repo)
6126 const struct got_error *err = NULL;
6127 struct got_object_id *tree_id = NULL;
6128 struct got_tree_object *tree = NULL;
6129 int nentries, i;
6131 err = got_object_id_by_path(&tree_id, repo, commit, path);
6132 if (err)
6133 goto done;
6135 err = got_object_open_as_tree(&tree, repo, tree_id);
6136 if (err)
6137 goto done;
6138 nentries = got_object_tree_get_nentries(tree);
6139 for (i = 0; i < nentries; i++) {
6140 struct got_tree_entry *te;
6141 char *id = NULL;
6143 if (sigint_received || sigpipe_received)
6144 break;
6146 te = got_object_tree_get_entry(tree, i);
6147 if (show_ids) {
6148 char *id_str;
6149 err = got_object_id_str(&id_str,
6150 got_tree_entry_get_id(te));
6151 if (err)
6152 goto done;
6153 if (asprintf(&id, "%s ", id_str) == -1) {
6154 err = got_error_from_errno("asprintf");
6155 free(id_str);
6156 goto done;
6158 free(id_str);
6160 err = print_entry(te, id, path, root_path, repo);
6161 free(id);
6162 if (err)
6163 goto done;
6165 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6166 char *child_path;
6167 if (asprintf(&child_path, "%s%s%s", path,
6168 path[0] == '/' && path[1] == '\0' ? "" : "/",
6169 got_tree_entry_get_name(te)) == -1) {
6170 err = got_error_from_errno("asprintf");
6171 goto done;
6173 err = print_tree(child_path, commit, show_ids, 1,
6174 root_path, repo);
6175 free(child_path);
6176 if (err)
6177 goto done;
6180 done:
6181 if (tree)
6182 got_object_tree_close(tree);
6183 free(tree_id);
6184 return err;
6187 static const struct got_error *
6188 cmd_tree(int argc, char *argv[])
6190 const struct got_error *error;
6191 struct got_repository *repo = NULL;
6192 struct got_worktree *worktree = NULL;
6193 const char *path, *refname = NULL;
6194 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6195 struct got_object_id *commit_id = NULL;
6196 struct got_commit_object *commit = NULL;
6197 char *commit_id_str = NULL, *keyword_idstr = NULL;
6198 int show_ids = 0, recurse = 0;
6199 int ch;
6200 int *pack_fds = NULL;
6202 #ifndef PROFILE
6203 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6204 NULL) == -1)
6205 err(1, "pledge");
6206 #endif
6208 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6209 switch (ch) {
6210 case 'c':
6211 commit_id_str = optarg;
6212 break;
6213 case 'i':
6214 show_ids = 1;
6215 break;
6216 case 'R':
6217 recurse = 1;
6218 break;
6219 case 'r':
6220 repo_path = realpath(optarg, NULL);
6221 if (repo_path == NULL)
6222 return got_error_from_errno2("realpath",
6223 optarg);
6224 got_path_strip_trailing_slashes(repo_path);
6225 break;
6226 default:
6227 usage_tree();
6228 /* NOTREACHED */
6232 argc -= optind;
6233 argv += optind;
6235 if (argc == 1)
6236 path = argv[0];
6237 else if (argc > 1)
6238 usage_tree();
6239 else
6240 path = NULL;
6242 cwd = getcwd(NULL, 0);
6243 if (cwd == NULL) {
6244 error = got_error_from_errno("getcwd");
6245 goto done;
6248 error = got_repo_pack_fds_open(&pack_fds);
6249 if (error != NULL)
6250 goto done;
6252 if (repo_path == NULL) {
6253 error = got_worktree_open(&worktree, cwd,
6254 GOT_WORKTREE_GOT_DIR);
6255 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6256 goto done;
6257 else
6258 error = NULL;
6259 if (worktree) {
6260 repo_path =
6261 strdup(got_worktree_get_repo_path(worktree));
6262 if (repo_path == NULL)
6263 error = got_error_from_errno("strdup");
6264 if (error)
6265 goto done;
6266 } else {
6267 repo_path = strdup(cwd);
6268 if (repo_path == NULL) {
6269 error = got_error_from_errno("strdup");
6270 goto done;
6275 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6276 if (error != NULL)
6277 goto done;
6279 if (worktree) {
6280 const char *prefix = got_worktree_get_path_prefix(worktree);
6281 char *p;
6283 if (path == NULL || got_path_is_root_dir(path))
6284 path = "";
6285 error = got_worktree_resolve_path(&p, worktree, path);
6286 if (error)
6287 goto done;
6288 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6289 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6290 p) == -1) {
6291 error = got_error_from_errno("asprintf");
6292 free(p);
6293 goto done;
6295 free(p);
6296 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6297 if (error)
6298 goto done;
6299 } else {
6300 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6301 if (error)
6302 goto done;
6303 if (path == NULL)
6304 path = "/";
6305 error = got_repo_map_path(&in_repo_path, repo, path);
6306 if (error != NULL)
6307 goto done;
6310 if (commit_id_str == NULL) {
6311 struct got_reference *head_ref;
6312 if (worktree)
6313 refname = got_worktree_get_head_ref_name(worktree);
6314 else
6315 refname = GOT_REF_HEAD;
6316 error = got_ref_open(&head_ref, repo, refname, 0);
6317 if (error != NULL)
6318 goto done;
6319 error = got_ref_resolve(&commit_id, repo, head_ref);
6320 got_ref_close(head_ref);
6321 if (error != NULL)
6322 goto done;
6323 } else {
6324 struct got_reflist_head refs;
6326 TAILQ_INIT(&refs);
6327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6328 NULL);
6329 if (error)
6330 goto done;
6332 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6333 repo, worktree);
6334 if (error != NULL)
6335 goto done;
6336 if (keyword_idstr != NULL)
6337 commit_id_str = keyword_idstr;
6339 error = got_repo_match_object_id(&commit_id, NULL,
6340 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6341 got_ref_list_free(&refs);
6342 if (error)
6343 goto done;
6346 if (worktree) {
6347 /* Release work tree lock. */
6348 got_worktree_close(worktree);
6349 worktree = NULL;
6352 error = got_object_open_as_commit(&commit, repo, commit_id);
6353 if (error)
6354 goto done;
6356 error = print_tree(in_repo_path, commit, show_ids, recurse,
6357 in_repo_path, repo);
6358 done:
6359 free(keyword_idstr);
6360 free(in_repo_path);
6361 free(repo_path);
6362 free(cwd);
6363 free(commit_id);
6364 if (commit)
6365 got_object_commit_close(commit);
6366 if (worktree)
6367 got_worktree_close(worktree);
6368 if (repo) {
6369 const struct got_error *close_err = got_repo_close(repo);
6370 if (error == NULL)
6371 error = close_err;
6373 if (pack_fds) {
6374 const struct got_error *pack_err =
6375 got_repo_pack_fds_close(pack_fds);
6376 if (error == NULL)
6377 error = pack_err;
6379 return error;
6382 __dead static void
6383 usage_status(void)
6385 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6386 "[-s status-codes] [path ...]\n", getprogname());
6387 exit(1);
6390 struct got_status_arg {
6391 char *status_codes;
6392 int suppress;
6395 static const struct got_error *
6396 print_status(void *arg, unsigned char status, unsigned char staged_status,
6397 const char *path, struct got_object_id *blob_id,
6398 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6399 int dirfd, const char *de_name)
6401 struct got_status_arg *st = arg;
6403 if (status == staged_status && (status == GOT_STATUS_DELETE))
6404 status = GOT_STATUS_NO_CHANGE;
6405 if (st != NULL && st->status_codes) {
6406 size_t ncodes = strlen(st->status_codes);
6407 int i, j = 0;
6409 for (i = 0; i < ncodes ; i++) {
6410 if (st->suppress) {
6411 if (status == st->status_codes[i] ||
6412 staged_status == st->status_codes[i]) {
6413 j++;
6414 continue;
6416 } else {
6417 if (status == st->status_codes[i] ||
6418 staged_status == st->status_codes[i])
6419 break;
6423 if (st->suppress && j == 0)
6424 goto print;
6426 if (i == ncodes)
6427 return NULL;
6429 print:
6430 printf("%c%c %s\n", status, staged_status, path);
6431 return NULL;
6434 static const struct got_error *
6435 show_operation_in_progress(struct got_worktree *worktree,
6436 struct got_repository *repo)
6438 const struct got_error *err;
6439 char *new_base_branch_name = NULL;
6440 char *branch_name = NULL;
6441 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6443 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6444 if (err)
6445 return err;
6446 if (rebase_in_progress) {
6447 err = got_worktree_rebase_info(&new_base_branch_name,
6448 &branch_name, worktree, repo);
6449 if (err)
6450 return err;
6451 printf("Work tree is rebasing %s onto %s\n",
6452 branch_name, new_base_branch_name);
6455 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6456 worktree);
6457 if (err)
6458 return err;
6459 if (histedit_in_progress) {
6460 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6461 if (err)
6462 return err;
6463 printf("Work tree is editing the history of %s\n", branch_name);
6466 err = got_worktree_merge_in_progress(&merge_in_progress,
6467 worktree, repo);
6468 if (err)
6469 return err;
6470 if (merge_in_progress) {
6471 err = got_worktree_merge_info(&branch_name, worktree,
6472 repo);
6473 if (err)
6474 return err;
6475 printf("Work tree is merging %s into %s\n", branch_name,
6476 got_worktree_get_head_ref_name(worktree));
6479 free(new_base_branch_name);
6480 free(branch_name);
6481 return NULL;
6484 static const struct got_error *
6485 cmd_status(int argc, char *argv[])
6487 const struct got_error *close_err, *error = NULL;
6488 struct got_repository *repo = NULL;
6489 struct got_worktree *worktree = NULL;
6490 struct got_status_arg st;
6491 char *cwd = NULL;
6492 struct got_pathlist_head paths;
6493 int ch, i, no_ignores = 0;
6494 int *pack_fds = NULL;
6496 TAILQ_INIT(&paths);
6498 memset(&st, 0, sizeof(st));
6499 st.status_codes = NULL;
6500 st.suppress = 0;
6502 #ifndef PROFILE
6503 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6504 NULL) == -1)
6505 err(1, "pledge");
6506 #endif
6508 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6509 switch (ch) {
6510 case 'I':
6511 no_ignores = 1;
6512 break;
6513 case 'S':
6514 if (st.status_codes != NULL && st.suppress == 0)
6515 option_conflict('S', 's');
6516 st.suppress = 1;
6517 /* fallthrough */
6518 case 's':
6519 for (i = 0; optarg[i] != '\0'; i++) {
6520 switch (optarg[i]) {
6521 case GOT_STATUS_MODIFY:
6522 case GOT_STATUS_ADD:
6523 case GOT_STATUS_DELETE:
6524 case GOT_STATUS_CONFLICT:
6525 case GOT_STATUS_MISSING:
6526 case GOT_STATUS_OBSTRUCTED:
6527 case GOT_STATUS_UNVERSIONED:
6528 case GOT_STATUS_MODE_CHANGE:
6529 case GOT_STATUS_NONEXISTENT:
6530 break;
6531 default:
6532 errx(1, "invalid status code '%c'",
6533 optarg[i]);
6536 if (ch == 's' && st.suppress)
6537 option_conflict('s', 'S');
6538 st.status_codes = optarg;
6539 break;
6540 default:
6541 usage_status();
6542 /* NOTREACHED */
6546 argc -= optind;
6547 argv += optind;
6549 cwd = getcwd(NULL, 0);
6550 if (cwd == NULL) {
6551 error = got_error_from_errno("getcwd");
6552 goto done;
6555 error = got_repo_pack_fds_open(&pack_fds);
6556 if (error != NULL)
6557 goto done;
6559 error = got_worktree_open(&worktree, cwd,
6560 GOT_WORKTREE_GOT_DIR);
6561 if (error) {
6562 if (error->code == GOT_ERR_NOT_WORKTREE)
6563 error = wrap_not_worktree_error(error, "status", cwd);
6564 goto done;
6567 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6568 NULL, pack_fds);
6569 if (error != NULL)
6570 goto done;
6572 error = apply_unveil(got_repo_get_path(repo), 1,
6573 got_worktree_get_root_path(worktree));
6574 if (error)
6575 goto done;
6577 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6578 if (error)
6579 goto done;
6581 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6582 print_status, &st, check_cancelled, NULL);
6583 if (error)
6584 goto done;
6586 error = show_operation_in_progress(worktree, repo);
6587 done:
6588 if (pack_fds) {
6589 const struct got_error *pack_err =
6590 got_repo_pack_fds_close(pack_fds);
6591 if (error == NULL)
6592 error = pack_err;
6594 if (repo) {
6595 close_err = got_repo_close(repo);
6596 if (error == NULL)
6597 error = close_err;
6599 if (worktree != NULL) {
6600 close_err = got_worktree_close(worktree);
6601 if (error == NULL)
6602 error = close_err;
6605 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6606 free(cwd);
6607 return error;
6610 __dead static void
6611 usage_ref(void)
6613 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6614 "[-s reference] [name]\n", getprogname());
6615 exit(1);
6618 static const struct got_error *
6619 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6621 static const struct got_error *err = NULL;
6622 struct got_reflist_head refs;
6623 struct got_reflist_entry *re;
6625 TAILQ_INIT(&refs);
6626 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6627 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6628 repo);
6629 if (err)
6630 return err;
6632 TAILQ_FOREACH(re, &refs, entry) {
6633 char *refstr;
6634 refstr = got_ref_to_str(re->ref);
6635 if (refstr == NULL) {
6636 err = got_error_from_errno("got_ref_to_str");
6637 break;
6639 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6640 free(refstr);
6643 got_ref_list_free(&refs);
6644 return err;
6647 static const struct got_error *
6648 delete_ref_by_name(struct got_repository *repo, const char *refname)
6650 const struct got_error *err;
6651 struct got_reference *ref;
6653 err = got_ref_open(&ref, repo, refname, 0);
6654 if (err)
6655 return err;
6657 err = delete_ref(repo, ref);
6658 got_ref_close(ref);
6659 return err;
6662 static const struct got_error *
6663 add_ref(struct got_repository *repo, const char *refname, const char *target)
6665 const struct got_error *err = NULL;
6666 struct got_object_id *id = NULL;
6667 struct got_reference *ref = NULL;
6668 struct got_reflist_head refs;
6671 * Don't let the user create a reference name with a leading '-'.
6672 * While technically a valid reference name, this case is usually
6673 * an unintended typo.
6675 if (refname[0] == '-')
6676 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6678 TAILQ_INIT(&refs);
6679 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6680 if (err)
6681 goto done;
6682 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6683 &refs, repo);
6684 got_ref_list_free(&refs);
6685 if (err)
6686 goto done;
6688 err = got_ref_alloc(&ref, refname, id);
6689 if (err)
6690 goto done;
6692 err = got_ref_write(ref, repo);
6693 done:
6694 if (ref)
6695 got_ref_close(ref);
6696 free(id);
6697 return err;
6700 static const struct got_error *
6701 add_symref(struct got_repository *repo, const char *refname, const char *target)
6703 const struct got_error *err = NULL;
6704 struct got_reference *ref = NULL;
6705 struct got_reference *target_ref = NULL;
6708 * Don't let the user create a reference name with a leading '-'.
6709 * While technically a valid reference name, this case is usually
6710 * an unintended typo.
6712 if (refname[0] == '-')
6713 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6715 err = got_ref_open(&target_ref, repo, target, 0);
6716 if (err)
6717 return err;
6719 err = got_ref_alloc_symref(&ref, refname, target_ref);
6720 if (err)
6721 goto done;
6723 err = got_ref_write(ref, repo);
6724 done:
6725 if (target_ref)
6726 got_ref_close(target_ref);
6727 if (ref)
6728 got_ref_close(ref);
6729 return err;
6732 static const struct got_error *
6733 cmd_ref(int argc, char *argv[])
6735 const struct got_error *error = NULL;
6736 struct got_repository *repo = NULL;
6737 struct got_worktree *worktree = NULL;
6738 char *cwd = NULL, *repo_path = NULL;
6739 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6740 const char *obj_arg = NULL, *symref_target= NULL;
6741 char *refname = NULL, *keyword_idstr = NULL;
6742 int *pack_fds = NULL;
6744 #ifndef PROFILE
6745 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6746 "sendfd unveil", NULL) == -1)
6747 err(1, "pledge");
6748 #endif
6750 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6751 switch (ch) {
6752 case 'c':
6753 obj_arg = optarg;
6754 break;
6755 case 'd':
6756 do_delete = 1;
6757 break;
6758 case 'l':
6759 do_list = 1;
6760 break;
6761 case 'r':
6762 repo_path = realpath(optarg, NULL);
6763 if (repo_path == NULL)
6764 return got_error_from_errno2("realpath",
6765 optarg);
6766 got_path_strip_trailing_slashes(repo_path);
6767 break;
6768 case 's':
6769 symref_target = optarg;
6770 break;
6771 case 't':
6772 sort_by_time = 1;
6773 break;
6774 default:
6775 usage_ref();
6776 /* NOTREACHED */
6780 if (obj_arg && do_list)
6781 option_conflict('c', 'l');
6782 if (obj_arg && do_delete)
6783 option_conflict('c', 'd');
6784 if (obj_arg && symref_target)
6785 option_conflict('c', 's');
6786 if (symref_target && do_delete)
6787 option_conflict('s', 'd');
6788 if (symref_target && do_list)
6789 option_conflict('s', 'l');
6790 if (do_delete && do_list)
6791 option_conflict('d', 'l');
6792 if (sort_by_time && !do_list)
6793 errx(1, "-t option requires -l option");
6795 argc -= optind;
6796 argv += optind;
6798 if (do_list) {
6799 if (argc != 0 && argc != 1)
6800 usage_ref();
6801 if (argc == 1) {
6802 refname = strdup(argv[0]);
6803 if (refname == NULL) {
6804 error = got_error_from_errno("strdup");
6805 goto done;
6808 } else {
6809 if (argc != 1)
6810 usage_ref();
6811 refname = strdup(argv[0]);
6812 if (refname == NULL) {
6813 error = got_error_from_errno("strdup");
6814 goto done;
6818 if (refname)
6819 got_path_strip_trailing_slashes(refname);
6821 cwd = getcwd(NULL, 0);
6822 if (cwd == NULL) {
6823 error = got_error_from_errno("getcwd");
6824 goto done;
6827 error = got_repo_pack_fds_open(&pack_fds);
6828 if (error != NULL)
6829 goto done;
6831 if (repo_path == NULL) {
6832 error = got_worktree_open(&worktree, cwd,
6833 GOT_WORKTREE_GOT_DIR);
6834 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6835 goto done;
6836 else
6837 error = NULL;
6838 if (worktree) {
6839 repo_path =
6840 strdup(got_worktree_get_repo_path(worktree));
6841 if (repo_path == NULL)
6842 error = got_error_from_errno("strdup");
6843 if (error)
6844 goto done;
6845 } else {
6846 repo_path = strdup(cwd);
6847 if (repo_path == NULL) {
6848 error = got_error_from_errno("strdup");
6849 goto done;
6854 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6855 if (error != NULL)
6856 goto done;
6858 #ifndef PROFILE
6859 if (do_list) {
6860 /* Remove "cpath" promise. */
6861 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6862 NULL) == -1)
6863 err(1, "pledge");
6865 #endif
6867 error = apply_unveil(got_repo_get_path(repo), do_list,
6868 worktree ? got_worktree_get_root_path(worktree) : NULL);
6869 if (error)
6870 goto done;
6872 if (do_list)
6873 error = list_refs(repo, refname, sort_by_time);
6874 else if (do_delete)
6875 error = delete_ref_by_name(repo, refname);
6876 else if (symref_target)
6877 error = add_symref(repo, refname, symref_target);
6878 else {
6879 if (obj_arg == NULL)
6880 usage_ref();
6882 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6883 repo, worktree);
6884 if (error != NULL)
6885 goto done;
6886 if (keyword_idstr != NULL)
6887 obj_arg = keyword_idstr;
6889 error = add_ref(repo, refname, obj_arg);
6891 done:
6892 free(refname);
6893 if (repo) {
6894 const struct got_error *close_err = got_repo_close(repo);
6895 if (error == NULL)
6896 error = close_err;
6898 if (worktree)
6899 got_worktree_close(worktree);
6900 if (pack_fds) {
6901 const struct got_error *pack_err =
6902 got_repo_pack_fds_close(pack_fds);
6903 if (error == NULL)
6904 error = pack_err;
6906 free(cwd);
6907 free(repo_path);
6908 free(keyword_idstr);
6909 return error;
6912 __dead static void
6913 usage_branch(void)
6915 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6916 "[-r repository-path] [name]\n", getprogname());
6917 exit(1);
6920 static const struct got_error *
6921 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6922 struct got_reference *ref)
6924 const struct got_error *err = NULL;
6925 const char *refname;
6926 char *refstr;
6927 char marker = ' ';
6929 refname = got_ref_get_name(ref);
6930 if (worktree && strcmp(refname,
6931 got_worktree_get_head_ref_name(worktree)) == 0) {
6932 err = got_worktree_get_state(&marker, repo, worktree,
6933 check_cancelled, NULL);
6934 if (err != NULL)
6935 return err;
6938 if (strncmp(refname, "refs/heads/", 11) == 0)
6939 refname += 11;
6940 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6941 refname += 18;
6942 if (strncmp(refname, "refs/remotes/", 13) == 0)
6943 refname += 13;
6945 refstr = got_ref_to_str(ref);
6946 if (refstr == NULL)
6947 return got_error_from_errno("got_ref_to_str");
6949 printf("%c %s: %s\n", marker, refname, refstr);
6950 free(refstr);
6951 return NULL;
6954 static const struct got_error *
6955 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6957 const char *refname;
6959 if (worktree == NULL)
6960 return got_error(GOT_ERR_NOT_WORKTREE);
6962 refname = got_worktree_get_head_ref_name(worktree);
6964 if (strncmp(refname, "refs/heads/", 11) == 0)
6965 refname += 11;
6966 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6967 refname += 18;
6969 printf("%s\n", refname);
6971 return NULL;
6974 static const struct got_error *
6975 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6976 int sort_by_time)
6978 static const struct got_error *err = NULL;
6979 struct got_reflist_head refs;
6980 struct got_reflist_entry *re;
6981 struct got_reference *temp_ref = NULL;
6982 int rebase_in_progress, histedit_in_progress;
6984 TAILQ_INIT(&refs);
6986 if (worktree) {
6987 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6988 worktree);
6989 if (err)
6990 return err;
6992 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6993 worktree);
6994 if (err)
6995 return err;
6997 if (rebase_in_progress || histedit_in_progress) {
6998 err = got_ref_open(&temp_ref, repo,
6999 got_worktree_get_head_ref_name(worktree), 0);
7000 if (err)
7001 return err;
7002 list_branch(repo, worktree, temp_ref);
7003 got_ref_close(temp_ref);
7007 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7008 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7009 repo);
7010 if (err)
7011 return err;
7013 TAILQ_FOREACH(re, &refs, entry)
7014 list_branch(repo, worktree, re->ref);
7016 got_ref_list_free(&refs);
7018 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7019 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7020 repo);
7021 if (err)
7022 return err;
7024 TAILQ_FOREACH(re, &refs, entry)
7025 list_branch(repo, worktree, re->ref);
7027 got_ref_list_free(&refs);
7029 return NULL;
7032 static const struct got_error *
7033 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7034 const char *branch_name)
7036 const struct got_error *err = NULL;
7037 struct got_reference *ref = NULL;
7038 char *refname, *remote_refname = NULL;
7040 if (strncmp(branch_name, "refs/", 5) == 0)
7041 branch_name += 5;
7042 if (strncmp(branch_name, "heads/", 6) == 0)
7043 branch_name += 6;
7044 else if (strncmp(branch_name, "remotes/", 8) == 0)
7045 branch_name += 8;
7047 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7048 return got_error_from_errno("asprintf");
7050 if (asprintf(&remote_refname, "refs/remotes/%s",
7051 branch_name) == -1) {
7052 err = got_error_from_errno("asprintf");
7053 goto done;
7056 err = got_ref_open(&ref, repo, refname, 0);
7057 if (err) {
7058 const struct got_error *err2;
7059 if (err->code != GOT_ERR_NOT_REF)
7060 goto done;
7062 * Keep 'err' intact such that if neither branch exists
7063 * we report "refs/heads" rather than "refs/remotes" in
7064 * our error message.
7066 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7067 if (err2)
7068 goto done;
7069 err = NULL;
7072 if (worktree &&
7073 strcmp(got_worktree_get_head_ref_name(worktree),
7074 got_ref_get_name(ref)) == 0) {
7075 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7076 "will not delete this work tree's current branch");
7077 goto done;
7080 err = delete_ref(repo, ref);
7081 done:
7082 if (ref)
7083 got_ref_close(ref);
7084 free(refname);
7085 free(remote_refname);
7086 return err;
7089 static const struct got_error *
7090 add_branch(struct got_repository *repo, const char *branch_name,
7091 struct got_object_id *base_commit_id)
7093 const struct got_error *err = NULL;
7094 struct got_reference *ref = NULL;
7095 char *refname = NULL;
7098 * Don't let the user create a branch name with a leading '-'.
7099 * While technically a valid reference name, this case is usually
7100 * an unintended typo.
7102 if (branch_name[0] == '-')
7103 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7105 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7106 branch_name += 11;
7108 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7109 err = got_error_from_errno("asprintf");
7110 goto done;
7113 err = got_ref_open(&ref, repo, refname, 0);
7114 if (err == NULL) {
7115 err = got_error(GOT_ERR_BRANCH_EXISTS);
7116 goto done;
7117 } else if (err->code != GOT_ERR_NOT_REF)
7118 goto done;
7120 err = got_ref_alloc(&ref, refname, base_commit_id);
7121 if (err)
7122 goto done;
7124 err = got_ref_write(ref, repo);
7125 done:
7126 if (ref)
7127 got_ref_close(ref);
7128 free(refname);
7129 return err;
7132 static const struct got_error *
7133 cmd_branch(int argc, char *argv[])
7135 const struct got_error *error = NULL;
7136 struct got_repository *repo = NULL;
7137 struct got_worktree *worktree = NULL;
7138 char *cwd = NULL, *repo_path = NULL;
7139 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7140 const char *delref = NULL, *commit_id_arg = NULL;
7141 struct got_reference *ref = NULL;
7142 struct got_pathlist_head paths;
7143 struct got_object_id *commit_id = NULL;
7144 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7145 int *pack_fds = NULL;
7147 TAILQ_INIT(&paths);
7149 #ifndef PROFILE
7150 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7151 "sendfd unveil", NULL) == -1)
7152 err(1, "pledge");
7153 #endif
7155 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7156 switch (ch) {
7157 case 'c':
7158 commit_id_arg = optarg;
7159 break;
7160 case 'd':
7161 delref = optarg;
7162 break;
7163 case 'l':
7164 do_list = 1;
7165 break;
7166 case 'n':
7167 do_update = 0;
7168 break;
7169 case 'r':
7170 repo_path = realpath(optarg, NULL);
7171 if (repo_path == NULL)
7172 return got_error_from_errno2("realpath",
7173 optarg);
7174 got_path_strip_trailing_slashes(repo_path);
7175 break;
7176 case 't':
7177 sort_by_time = 1;
7178 break;
7179 default:
7180 usage_branch();
7181 /* NOTREACHED */
7185 if (do_list && delref)
7186 option_conflict('l', 'd');
7187 if (sort_by_time && !do_list)
7188 errx(1, "-t option requires -l option");
7190 argc -= optind;
7191 argv += optind;
7193 if (!do_list && !delref && argc == 0)
7194 do_show = 1;
7196 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7197 errx(1, "-c option can only be used when creating a branch");
7199 if (do_list || delref) {
7200 if (argc > 0)
7201 usage_branch();
7202 } else if (!do_show && argc != 1)
7203 usage_branch();
7205 cwd = getcwd(NULL, 0);
7206 if (cwd == NULL) {
7207 error = got_error_from_errno("getcwd");
7208 goto done;
7211 error = got_repo_pack_fds_open(&pack_fds);
7212 if (error != NULL)
7213 goto done;
7215 if (repo_path == NULL) {
7216 error = got_worktree_open(&worktree, cwd,
7217 GOT_WORKTREE_GOT_DIR);
7218 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7219 goto done;
7220 else
7221 error = NULL;
7222 if (worktree) {
7223 repo_path =
7224 strdup(got_worktree_get_repo_path(worktree));
7225 if (repo_path == NULL)
7226 error = got_error_from_errno("strdup");
7227 if (error)
7228 goto done;
7229 } else {
7230 repo_path = strdup(cwd);
7231 if (repo_path == NULL) {
7232 error = got_error_from_errno("strdup");
7233 goto done;
7238 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7239 if (error != NULL)
7240 goto done;
7242 #ifndef PROFILE
7243 if (do_list || do_show) {
7244 /* Remove "cpath" promise. */
7245 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7246 NULL) == -1)
7247 err(1, "pledge");
7249 #endif
7251 error = apply_unveil(got_repo_get_path(repo), do_list,
7252 worktree ? got_worktree_get_root_path(worktree) : NULL);
7253 if (error)
7254 goto done;
7256 if (do_show)
7257 error = show_current_branch(repo, worktree);
7258 else if (do_list)
7259 error = list_branches(repo, worktree, sort_by_time);
7260 else if (delref)
7261 error = delete_branch(repo, worktree, delref);
7262 else {
7263 struct got_reflist_head refs;
7264 TAILQ_INIT(&refs);
7265 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7266 NULL);
7267 if (error)
7268 goto done;
7269 if (commit_id_arg == NULL)
7270 commit_id_arg = worktree ?
7271 got_worktree_get_head_ref_name(worktree) :
7272 GOT_REF_HEAD;
7273 else {
7274 error = got_keyword_to_idstr(&keyword_idstr,
7275 commit_id_arg, repo, worktree);
7276 if (error != NULL)
7277 goto done;
7278 if (keyword_idstr != NULL)
7279 commit_id_arg = keyword_idstr;
7281 error = got_repo_match_object_id(&commit_id, NULL,
7282 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7283 got_ref_list_free(&refs);
7284 if (error)
7285 goto done;
7286 error = add_branch(repo, argv[0], commit_id);
7287 if (error)
7288 goto done;
7289 if (worktree && do_update) {
7290 struct got_update_progress_arg upa;
7291 char *branch_refname = NULL;
7293 error = got_object_id_str(&commit_id_str, commit_id);
7294 if (error)
7295 goto done;
7296 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7297 worktree);
7298 if (error)
7299 goto done;
7300 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7301 == -1) {
7302 error = got_error_from_errno("asprintf");
7303 goto done;
7305 error = got_ref_open(&ref, repo, branch_refname, 0);
7306 free(branch_refname);
7307 if (error)
7308 goto done;
7309 error = switch_head_ref(ref, commit_id, worktree,
7310 repo);
7311 if (error)
7312 goto done;
7313 error = got_worktree_set_base_commit_id(worktree, repo,
7314 commit_id);
7315 if (error)
7316 goto done;
7317 memset(&upa, 0, sizeof(upa));
7318 error = got_worktree_checkout_files(worktree, &paths,
7319 repo, update_progress, &upa, check_cancelled,
7320 NULL);
7321 if (error)
7322 goto done;
7323 if (upa.did_something) {
7324 printf("Updated to %s: %s\n",
7325 got_worktree_get_head_ref_name(worktree),
7326 commit_id_str);
7328 print_update_progress_stats(&upa);
7331 done:
7332 free(keyword_idstr);
7333 if (ref)
7334 got_ref_close(ref);
7335 if (repo) {
7336 const struct got_error *close_err = got_repo_close(repo);
7337 if (error == NULL)
7338 error = close_err;
7340 if (worktree)
7341 got_worktree_close(worktree);
7342 if (pack_fds) {
7343 const struct got_error *pack_err =
7344 got_repo_pack_fds_close(pack_fds);
7345 if (error == NULL)
7346 error = pack_err;
7348 free(cwd);
7349 free(repo_path);
7350 free(commit_id);
7351 free(commit_id_str);
7352 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7353 return error;
7357 __dead static void
7358 usage_tag(void)
7360 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7361 "[-r repository-path] [-s signer-id] name\n", getprogname());
7362 exit(1);
7365 #if 0
7366 static const struct got_error *
7367 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7369 const struct got_error *err = NULL;
7370 struct got_reflist_entry *re, *se, *new;
7371 struct got_object_id *re_id, *se_id;
7372 struct got_tag_object *re_tag, *se_tag;
7373 time_t re_time, se_time;
7375 STAILQ_FOREACH(re, tags, entry) {
7376 se = STAILQ_FIRST(sorted);
7377 if (se == NULL) {
7378 err = got_reflist_entry_dup(&new, re);
7379 if (err)
7380 return err;
7381 STAILQ_INSERT_HEAD(sorted, new, entry);
7382 continue;
7383 } else {
7384 err = got_ref_resolve(&re_id, repo, re->ref);
7385 if (err)
7386 break;
7387 err = got_object_open_as_tag(&re_tag, repo, re_id);
7388 free(re_id);
7389 if (err)
7390 break;
7391 re_time = got_object_tag_get_tagger_time(re_tag);
7392 got_object_tag_close(re_tag);
7395 while (se) {
7396 err = got_ref_resolve(&se_id, repo, re->ref);
7397 if (err)
7398 break;
7399 err = got_object_open_as_tag(&se_tag, repo, se_id);
7400 free(se_id);
7401 if (err)
7402 break;
7403 se_time = got_object_tag_get_tagger_time(se_tag);
7404 got_object_tag_close(se_tag);
7406 if (se_time > re_time) {
7407 err = got_reflist_entry_dup(&new, re);
7408 if (err)
7409 return err;
7410 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7411 break;
7413 se = STAILQ_NEXT(se, entry);
7414 continue;
7417 done:
7418 return err;
7420 #endif
7422 static const struct got_error *
7423 get_tag_refname(char **refname, const char *tag_name)
7425 const struct got_error *err;
7427 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7428 *refname = strdup(tag_name);
7429 if (*refname == NULL)
7430 return got_error_from_errno("strdup");
7431 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7432 err = got_error_from_errno("asprintf");
7433 *refname = NULL;
7434 return err;
7437 return NULL;
7440 static const struct got_error *
7441 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7442 const char *allowed_signers, const char *revoked_signers, int verbosity)
7444 static const struct got_error *err = NULL;
7445 struct got_reflist_head refs;
7446 struct got_reflist_entry *re;
7447 char *wanted_refname = NULL;
7448 int bad_sigs = 0;
7450 TAILQ_INIT(&refs);
7452 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7453 if (err)
7454 return err;
7456 if (tag_name) {
7457 struct got_reference *ref;
7458 err = get_tag_refname(&wanted_refname, tag_name);
7459 if (err)
7460 goto done;
7461 /* Wanted tag reference should exist. */
7462 err = got_ref_open(&ref, repo, wanted_refname, 0);
7463 if (err)
7464 goto done;
7465 got_ref_close(ref);
7468 TAILQ_FOREACH(re, &refs, entry) {
7469 const char *refname;
7470 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7471 char datebuf[26];
7472 const char *tagger, *ssh_sig = NULL;
7473 char *sig_msg = NULL;
7474 time_t tagger_time;
7475 struct got_object_id *id;
7476 struct got_tag_object *tag;
7477 struct got_commit_object *commit = NULL;
7479 refname = got_ref_get_name(re->ref);
7480 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7481 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7482 continue;
7483 refname += 10;
7484 refstr = got_ref_to_str(re->ref);
7485 if (refstr == NULL) {
7486 err = got_error_from_errno("got_ref_to_str");
7487 break;
7490 err = got_ref_resolve(&id, repo, re->ref);
7491 if (err)
7492 break;
7493 err = got_object_open_as_tag(&tag, repo, id);
7494 if (err) {
7495 if (err->code != GOT_ERR_OBJ_TYPE) {
7496 free(id);
7497 break;
7499 /* "lightweight" tag */
7500 err = got_object_open_as_commit(&commit, repo, id);
7501 if (err) {
7502 free(id);
7503 break;
7505 tagger = got_object_commit_get_committer(commit);
7506 tagger_time =
7507 got_object_commit_get_committer_time(commit);
7508 err = got_object_id_str(&id_str, id);
7509 free(id);
7510 if (err)
7511 break;
7512 } else {
7513 free(id);
7514 tagger = got_object_tag_get_tagger(tag);
7515 tagger_time = got_object_tag_get_tagger_time(tag);
7516 err = got_object_id_str(&id_str,
7517 got_object_tag_get_object_id(tag));
7518 if (err)
7519 break;
7522 if (tag && verify_tags) {
7523 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7524 got_object_tag_get_message(tag));
7525 if (ssh_sig && allowed_signers == NULL) {
7526 err = got_error_msg(
7527 GOT_ERR_VERIFY_TAG_SIGNATURE,
7528 "SSH signature verification requires "
7529 "setting allowed_signers in "
7530 "got.conf(5)");
7531 break;
7535 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7536 free(refstr);
7537 printf("from: %s\n", tagger);
7538 datestr = get_datestr(&tagger_time, datebuf);
7539 if (datestr)
7540 printf("date: %s UTC\n", datestr);
7541 if (commit)
7542 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7543 else {
7544 switch (got_object_tag_get_object_type(tag)) {
7545 case GOT_OBJ_TYPE_BLOB:
7546 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7547 id_str);
7548 break;
7549 case GOT_OBJ_TYPE_TREE:
7550 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7551 id_str);
7552 break;
7553 case GOT_OBJ_TYPE_COMMIT:
7554 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7555 id_str);
7556 break;
7557 case GOT_OBJ_TYPE_TAG:
7558 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7559 id_str);
7560 break;
7561 default:
7562 break;
7565 free(id_str);
7567 if (ssh_sig) {
7568 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7569 allowed_signers, revoked_signers, verbosity);
7570 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7571 bad_sigs = 1;
7572 else if (err)
7573 break;
7574 printf("signature: %s", sig_msg);
7575 free(sig_msg);
7576 sig_msg = NULL;
7579 if (commit) {
7580 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7581 if (err)
7582 break;
7583 got_object_commit_close(commit);
7584 } else {
7585 tagmsg0 = strdup(got_object_tag_get_message(tag));
7586 got_object_tag_close(tag);
7587 if (tagmsg0 == NULL) {
7588 err = got_error_from_errno("strdup");
7589 break;
7593 tagmsg = tagmsg0;
7594 do {
7595 line = strsep(&tagmsg, "\n");
7596 if (line)
7597 printf(" %s\n", line);
7598 } while (line);
7599 free(tagmsg0);
7601 done:
7602 got_ref_list_free(&refs);
7603 free(wanted_refname);
7605 if (err == NULL && bad_sigs)
7606 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7607 return err;
7610 static const struct got_error *
7611 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7612 const char *tag_name, const char *editor, const char *repo_path)
7614 const struct got_error *err = NULL;
7615 char *template = NULL, *initial_content = NULL;
7616 int initial_content_len;
7617 int fd = -1;
7619 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7620 err = got_error_from_errno("asprintf");
7621 goto done;
7624 initial_content_len = asprintf(&initial_content,
7625 "\n# tagging commit %s as %s\n",
7626 commit_id_str, tag_name);
7627 if (initial_content_len == -1) {
7628 err = got_error_from_errno("asprintf");
7629 goto done;
7632 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7633 if (err)
7634 goto done;
7636 if (write(fd, initial_content, initial_content_len) == -1) {
7637 err = got_error_from_errno2("write", *tagmsg_path);
7638 goto done;
7640 if (close(fd) == -1) {
7641 err = got_error_from_errno2("close", *tagmsg_path);
7642 goto done;
7644 fd = -1;
7646 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7647 initial_content_len, 1);
7648 done:
7649 free(initial_content);
7650 free(template);
7652 if (fd != -1 && close(fd) == -1 && err == NULL)
7653 err = got_error_from_errno2("close", *tagmsg_path);
7655 if (err) {
7656 free(*tagmsg);
7657 *tagmsg = NULL;
7659 return err;
7662 static const struct got_error *
7663 add_tag(struct got_repository *repo, const char *tagger,
7664 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7665 const char *signer_id, const char *editor, int verbosity)
7667 const struct got_error *err = NULL;
7668 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7669 char *label = NULL, *commit_id_str = NULL;
7670 struct got_reference *ref = NULL;
7671 char *refname = NULL, *tagmsg = NULL;
7672 char *tagmsg_path = NULL, *tag_id_str = NULL;
7673 int preserve_tagmsg = 0;
7674 struct got_reflist_head refs;
7676 TAILQ_INIT(&refs);
7679 * Don't let the user create a tag name with a leading '-'.
7680 * While technically a valid reference name, this case is usually
7681 * an unintended typo.
7683 if (tag_name[0] == '-')
7684 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7686 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7687 if (err)
7688 goto done;
7690 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7691 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7692 if (err)
7693 goto done;
7695 err = got_object_id_str(&commit_id_str, commit_id);
7696 if (err)
7697 goto done;
7699 err = get_tag_refname(&refname, tag_name);
7700 if (err)
7701 goto done;
7702 if (strncmp("refs/tags/", tag_name, 10) == 0)
7703 tag_name += 10;
7705 err = got_ref_open(&ref, repo, refname, 0);
7706 if (err == NULL) {
7707 err = got_error(GOT_ERR_TAG_EXISTS);
7708 goto done;
7709 } else if (err->code != GOT_ERR_NOT_REF)
7710 goto done;
7712 if (tagmsg_arg == NULL) {
7713 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7714 tag_name, editor, got_repo_get_path(repo));
7715 if (err) {
7716 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7717 tagmsg_path != NULL)
7718 preserve_tagmsg = 1;
7719 goto done;
7723 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7724 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7725 verbosity);
7726 if (err) {
7727 if (tagmsg_path)
7728 preserve_tagmsg = 1;
7729 goto done;
7732 err = got_ref_alloc(&ref, refname, tag_id);
7733 if (err) {
7734 if (tagmsg_path)
7735 preserve_tagmsg = 1;
7736 goto done;
7739 err = got_ref_write(ref, repo);
7740 if (err) {
7741 if (tagmsg_path)
7742 preserve_tagmsg = 1;
7743 goto done;
7746 err = got_object_id_str(&tag_id_str, tag_id);
7747 if (err) {
7748 if (tagmsg_path)
7749 preserve_tagmsg = 1;
7750 goto done;
7752 printf("Created tag %s\n", tag_id_str);
7753 done:
7754 if (preserve_tagmsg) {
7755 fprintf(stderr, "%s: tag message preserved in %s\n",
7756 getprogname(), tagmsg_path);
7757 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7758 err = got_error_from_errno2("unlink", tagmsg_path);
7759 free(tag_id_str);
7760 if (ref)
7761 got_ref_close(ref);
7762 free(commit_id);
7763 free(commit_id_str);
7764 free(refname);
7765 free(tagmsg);
7766 free(tagmsg_path);
7767 got_ref_list_free(&refs);
7768 return err;
7771 static const struct got_error *
7772 cmd_tag(int argc, char *argv[])
7774 const struct got_error *error = NULL;
7775 struct got_repository *repo = NULL;
7776 struct got_worktree *worktree = NULL;
7777 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7778 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7779 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7780 const char *signer_id = NULL;
7781 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7782 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7783 int *pack_fds = NULL;
7785 #ifndef PROFILE
7786 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7787 "sendfd unveil", NULL) == -1)
7788 err(1, "pledge");
7789 #endif
7791 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7792 switch (ch) {
7793 case 'c':
7794 commit_id_arg = optarg;
7795 break;
7796 case 'l':
7797 do_list = 1;
7798 break;
7799 case 'm':
7800 tagmsg = optarg;
7801 break;
7802 case 'r':
7803 repo_path = realpath(optarg, NULL);
7804 if (repo_path == NULL) {
7805 error = got_error_from_errno2("realpath",
7806 optarg);
7807 goto done;
7809 got_path_strip_trailing_slashes(repo_path);
7810 break;
7811 case 's':
7812 signer_id = optarg;
7813 break;
7814 case 'V':
7815 verify_tags = 1;
7816 break;
7817 case 'v':
7818 if (verbosity < 0)
7819 verbosity = 0;
7820 else if (verbosity < 3)
7821 verbosity++;
7822 break;
7823 default:
7824 usage_tag();
7825 /* NOTREACHED */
7829 argc -= optind;
7830 argv += optind;
7832 if (do_list || verify_tags) {
7833 if (commit_id_arg != NULL)
7834 errx(1,
7835 "-c option can only be used when creating a tag");
7836 if (tagmsg) {
7837 if (do_list)
7838 option_conflict('l', 'm');
7839 else
7840 option_conflict('V', 'm');
7842 if (signer_id) {
7843 if (do_list)
7844 option_conflict('l', 's');
7845 else
7846 option_conflict('V', 's');
7848 if (argc > 1)
7849 usage_tag();
7850 } else if (argc != 1)
7851 usage_tag();
7853 if (argc == 1)
7854 tag_name = argv[0];
7856 cwd = getcwd(NULL, 0);
7857 if (cwd == NULL) {
7858 error = got_error_from_errno("getcwd");
7859 goto done;
7862 error = got_repo_pack_fds_open(&pack_fds);
7863 if (error != NULL)
7864 goto done;
7866 if (repo_path == NULL) {
7867 error = got_worktree_open(&worktree, cwd,
7868 GOT_WORKTREE_GOT_DIR);
7869 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7870 goto done;
7871 else
7872 error = NULL;
7873 if (worktree) {
7874 repo_path =
7875 strdup(got_worktree_get_repo_path(worktree));
7876 if (repo_path == NULL)
7877 error = got_error_from_errno("strdup");
7878 if (error)
7879 goto done;
7880 } else {
7881 repo_path = strdup(cwd);
7882 if (repo_path == NULL) {
7883 error = got_error_from_errno("strdup");
7884 goto done;
7889 if (do_list || verify_tags) {
7890 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7891 if (error != NULL)
7892 goto done;
7893 error = get_allowed_signers(&allowed_signers, repo, worktree);
7894 if (error)
7895 goto done;
7896 error = get_revoked_signers(&revoked_signers, repo, worktree);
7897 if (error)
7898 goto done;
7899 if (worktree) {
7900 /* Release work tree lock. */
7901 got_worktree_close(worktree);
7902 worktree = NULL;
7906 * Remove "cpath" promise unless needed for signature tmpfile
7907 * creation.
7909 if (verify_tags)
7910 got_sigs_apply_unveil();
7911 else {
7912 #ifndef PROFILE
7913 if (pledge("stdio rpath wpath flock proc exec sendfd "
7914 "unveil", NULL) == -1)
7915 err(1, "pledge");
7916 #endif
7918 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7919 if (error)
7920 goto done;
7921 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7922 revoked_signers, verbosity);
7923 } else {
7924 error = get_gitconfig_path(&gitconfig_path);
7925 if (error)
7926 goto done;
7927 error = got_repo_open(&repo, repo_path, gitconfig_path,
7928 pack_fds);
7929 if (error != NULL)
7930 goto done;
7932 error = get_author(&tagger, repo, worktree);
7933 if (error)
7934 goto done;
7935 if (signer_id == NULL)
7936 signer_id = get_signer_id(repo, worktree);
7938 if (tagmsg == NULL) {
7939 error = get_editor(&editor);
7940 if (error)
7941 goto done;
7942 if (unveil(editor, "x") != 0) {
7943 error = got_error_from_errno2("unveil", editor);
7944 goto done;
7947 if (signer_id) {
7948 error = got_sigs_apply_unveil();
7949 if (error)
7950 goto done;
7952 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7953 if (error)
7954 goto done;
7956 if (commit_id_arg == NULL) {
7957 struct got_reference *head_ref;
7958 struct got_object_id *commit_id;
7959 error = got_ref_open(&head_ref, repo,
7960 worktree ? got_worktree_get_head_ref_name(worktree)
7961 : GOT_REF_HEAD, 0);
7962 if (error)
7963 goto done;
7964 error = got_ref_resolve(&commit_id, repo, head_ref);
7965 got_ref_close(head_ref);
7966 if (error)
7967 goto done;
7968 error = got_object_id_str(&commit_id_str, commit_id);
7969 free(commit_id);
7970 if (error)
7971 goto done;
7972 } else {
7973 error = got_keyword_to_idstr(&keyword_idstr,
7974 commit_id_arg, repo, worktree);
7975 if (error != NULL)
7976 goto done;
7977 commit_id_str = keyword_idstr;
7980 if (worktree) {
7981 /* Release work tree lock. */
7982 got_worktree_close(worktree);
7983 worktree = NULL;
7986 error = add_tag(repo, tagger, tag_name,
7987 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7988 signer_id, editor, verbosity);
7990 done:
7991 if (repo) {
7992 const struct got_error *close_err = got_repo_close(repo);
7993 if (error == NULL)
7994 error = close_err;
7996 if (worktree)
7997 got_worktree_close(worktree);
7998 if (pack_fds) {
7999 const struct got_error *pack_err =
8000 got_repo_pack_fds_close(pack_fds);
8001 if (error == NULL)
8002 error = pack_err;
8004 free(cwd);
8005 free(editor);
8006 free(repo_path);
8007 free(gitconfig_path);
8008 free(commit_id_str);
8009 free(tagger);
8010 free(allowed_signers);
8011 free(revoked_signers);
8012 return error;
8015 __dead static void
8016 usage_add(void)
8018 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8019 exit(1);
8022 static const struct got_error *
8023 add_progress(void *arg, unsigned char status, const char *path)
8025 while (path[0] == '/')
8026 path++;
8027 printf("%c %s\n", status, path);
8028 return NULL;
8031 static const struct got_error *
8032 pathlist_contains_directory(int *contains_dir, struct got_worktree *worktree,
8033 struct got_pathlist_head *paths)
8035 const struct got_error *error = NULL;
8036 struct got_pathlist_entry *pe;
8037 struct stat sb;
8038 char *ondisk_path;
8040 *contains_dir = 0;
8042 TAILQ_FOREACH(pe, paths, entry) {
8043 if (asprintf(&ondisk_path, "%s/%s",
8044 got_worktree_get_root_path(worktree),
8045 pe->path) == -1) {
8046 return got_error_from_errno("asprintf");
8048 if (lstat(ondisk_path, &sb) == -1) {
8049 if (errno == ENOENT) {
8050 free(ondisk_path);
8051 continue;
8053 error = got_error_from_errno2("lstat",
8054 ondisk_path);
8055 free(ondisk_path);
8056 return error;
8058 free(ondisk_path);
8059 if (S_ISDIR(sb.st_mode)) {
8060 *contains_dir = 1;
8061 return NULL;
8064 return NULL;
8067 static const struct got_error *
8068 cmd_add(int argc, char *argv[])
8070 const struct got_error *error = NULL;
8071 struct got_repository *repo = NULL;
8072 struct got_worktree *worktree = NULL;
8073 char *cwd = NULL;
8074 struct got_pathlist_head paths;
8075 int ch, contains_dir, can_recurse = 0, no_ignores = 0;
8076 int *pack_fds = NULL;
8078 TAILQ_INIT(&paths);
8080 #ifndef PROFILE
8081 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8082 NULL) == -1)
8083 err(1, "pledge");
8084 #endif
8086 while ((ch = getopt(argc, argv, "IR")) != -1) {
8087 switch (ch) {
8088 case 'I':
8089 no_ignores = 1;
8090 break;
8091 case 'R':
8092 can_recurse = 1;
8093 break;
8094 default:
8095 usage_add();
8096 /* NOTREACHED */
8100 argc -= optind;
8101 argv += optind;
8103 if (argc < 1)
8104 usage_add();
8106 cwd = getcwd(NULL, 0);
8107 if (cwd == NULL) {
8108 error = got_error_from_errno("getcwd");
8109 goto done;
8112 error = got_repo_pack_fds_open(&pack_fds);
8113 if (error != NULL)
8114 goto done;
8116 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8117 if (error) {
8118 if (error->code == GOT_ERR_NOT_WORKTREE)
8119 error = wrap_not_worktree_error(error, "add", cwd);
8120 goto done;
8123 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8124 NULL, pack_fds);
8125 if (error != NULL)
8126 goto done;
8128 error = apply_unveil(got_repo_get_path(repo), 1,
8129 got_worktree_get_root_path(worktree));
8130 if (error)
8131 goto done;
8133 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8134 if (error)
8135 goto done;
8137 if (!can_recurse) {
8138 error = pathlist_contains_directory(&contains_dir, worktree,
8139 &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 = pathlist_contains_directory(&contains_dir, worktree,
8287 &paths);
8288 if (error != NULL)
8289 goto done;
8291 if (contains_dir) {
8292 error = got_error_msg(GOT_ERR_BAD_PATH,
8293 "removing directories requires -R option");
8294 goto done;
8298 error = got_worktree_schedule_delete(worktree, &paths,
8299 delete_local_mods, status_codes, print_remove_status, NULL,
8300 repo, keep_on_disk, ignore_missing_paths);
8301 done:
8302 if (repo) {
8303 const struct got_error *close_err = got_repo_close(repo);
8304 if (error == NULL)
8305 error = close_err;
8307 if (worktree)
8308 got_worktree_close(worktree);
8309 if (pack_fds) {
8310 const struct got_error *pack_err =
8311 got_repo_pack_fds_close(pack_fds);
8312 if (error == NULL)
8313 error = pack_err;
8315 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8316 free(cwd);
8317 return error;
8320 __dead static void
8321 usage_patch(void)
8323 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8324 "[patchfile]\n", getprogname());
8325 exit(1);
8328 static const struct got_error *
8329 patch_from_stdin(int *patchfd)
8331 const struct got_error *err = NULL;
8332 ssize_t r;
8333 char buf[BUFSIZ];
8334 sig_t sighup, sigint, sigquit;
8336 *patchfd = got_opentempfd();
8337 if (*patchfd == -1)
8338 return got_error_from_errno("got_opentempfd");
8340 sighup = signal(SIGHUP, SIG_DFL);
8341 sigint = signal(SIGINT, SIG_DFL);
8342 sigquit = signal(SIGQUIT, SIG_DFL);
8344 for (;;) {
8345 r = read(0, buf, sizeof(buf));
8346 if (r == -1) {
8347 err = got_error_from_errno("read");
8348 break;
8350 if (r == 0)
8351 break;
8352 if (write(*patchfd, buf, r) == -1) {
8353 err = got_error_from_errno("write");
8354 break;
8358 signal(SIGHUP, sighup);
8359 signal(SIGINT, sigint);
8360 signal(SIGQUIT, sigquit);
8362 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8363 err = got_error_from_errno("lseek");
8365 if (err != NULL) {
8366 close(*patchfd);
8367 *patchfd = -1;
8370 return err;
8373 struct got_patch_progress_arg {
8374 int did_something;
8375 int conflicts;
8376 int rejects;
8379 static const struct got_error *
8380 patch_progress(void *arg, const char *old, const char *new,
8381 unsigned char status, const struct got_error *error, int old_from,
8382 int old_lines, int new_from, int new_lines, int offset,
8383 int ws_mangled, const struct got_error *hunk_err)
8385 const char *path = new == NULL ? old : new;
8386 struct got_patch_progress_arg *a = arg;
8388 while (*path == '/')
8389 path++;
8391 if (status != GOT_STATUS_NO_CHANGE &&
8392 status != 0 /* per-hunk progress */) {
8393 printf("%c %s\n", status, path);
8394 a->did_something = 1;
8397 if (hunk_err == NULL) {
8398 if (status == GOT_STATUS_CANNOT_UPDATE)
8399 a->rejects++;
8400 else if (status == GOT_STATUS_CONFLICT)
8401 a->conflicts++;
8404 if (error != NULL)
8405 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8407 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8408 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8409 old_lines, new_from, new_lines);
8410 if (hunk_err != NULL)
8411 printf("%s\n", hunk_err->msg);
8412 else if (offset != 0)
8413 printf("applied with offset %d\n", offset);
8414 else
8415 printf("hunk contains mangled whitespace\n");
8418 return NULL;
8421 static void
8422 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8424 if (!ppa->did_something)
8425 return;
8427 if (ppa->conflicts > 0)
8428 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8430 if (ppa->rejects > 0) {
8431 printf("Files where patch failed to apply: %d\n",
8432 ppa->rejects);
8436 static const struct got_error *
8437 cmd_patch(int argc, char *argv[])
8439 const struct got_error *error = NULL, *close_error = NULL;
8440 struct got_worktree *worktree = NULL;
8441 struct got_repository *repo = NULL;
8442 struct got_reflist_head refs;
8443 struct got_object_id *commit_id = NULL;
8444 const char *commit_id_str = NULL;
8445 struct stat sb;
8446 const char *errstr;
8447 char *cwd = NULL, *keyword_idstr = NULL;
8448 int ch, nop = 0, strip = -1, reverse = 0;
8449 int patchfd;
8450 int *pack_fds = NULL;
8451 struct got_patch_progress_arg ppa;
8453 TAILQ_INIT(&refs);
8455 #ifndef PROFILE
8456 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8457 "unveil", NULL) == -1)
8458 err(1, "pledge");
8459 #endif
8461 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8462 switch (ch) {
8463 case 'c':
8464 commit_id_str = optarg;
8465 break;
8466 case 'n':
8467 nop = 1;
8468 break;
8469 case 'p':
8470 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8471 if (errstr != NULL)
8472 errx(1, "pathname strip count is %s: %s",
8473 errstr, optarg);
8474 break;
8475 case 'R':
8476 reverse = 1;
8477 break;
8478 default:
8479 usage_patch();
8480 /* NOTREACHED */
8484 argc -= optind;
8485 argv += optind;
8487 if (argc == 0) {
8488 error = patch_from_stdin(&patchfd);
8489 if (error)
8490 return error;
8491 } else if (argc == 1) {
8492 patchfd = open(argv[0], O_RDONLY);
8493 if (patchfd == -1) {
8494 error = got_error_from_errno2("open", argv[0]);
8495 return error;
8497 if (fstat(patchfd, &sb) == -1) {
8498 error = got_error_from_errno2("fstat", argv[0]);
8499 goto done;
8501 if (!S_ISREG(sb.st_mode)) {
8502 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8503 goto done;
8505 } else
8506 usage_patch();
8508 if ((cwd = getcwd(NULL, 0)) == NULL) {
8509 error = got_error_from_errno("getcwd");
8510 goto done;
8513 error = got_repo_pack_fds_open(&pack_fds);
8514 if (error != NULL)
8515 goto done;
8517 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8518 if (error != NULL)
8519 goto done;
8521 const char *repo_path = got_worktree_get_repo_path(worktree);
8522 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8523 if (error != NULL)
8524 goto done;
8526 error = apply_unveil(got_repo_get_path(repo), 0,
8527 got_worktree_get_root_path(worktree));
8528 if (error != NULL)
8529 goto done;
8531 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8532 if (error)
8533 goto done;
8535 if (commit_id_str != NULL) {
8536 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8537 repo, worktree);
8538 if (error != NULL)
8539 goto done;
8541 error = got_repo_match_object_id(&commit_id, NULL,
8542 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8543 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8544 if (error)
8545 goto done;
8548 memset(&ppa, 0, sizeof(ppa));
8549 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8550 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8551 print_patch_progress_stats(&ppa);
8552 done:
8553 got_ref_list_free(&refs);
8554 free(keyword_idstr);
8555 free(commit_id);
8556 if (repo) {
8557 close_error = got_repo_close(repo);
8558 if (error == NULL)
8559 error = close_error;
8561 if (worktree != NULL) {
8562 close_error = got_worktree_close(worktree);
8563 if (error == NULL)
8564 error = close_error;
8566 if (pack_fds) {
8567 const struct got_error *pack_err =
8568 got_repo_pack_fds_close(pack_fds);
8569 if (error == NULL)
8570 error = pack_err;
8572 free(cwd);
8573 return error;
8576 __dead static void
8577 usage_revert(void)
8579 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8580 getprogname());
8581 exit(1);
8584 static const struct got_error *
8585 revert_progress(void *arg, unsigned char status, const char *path)
8587 if (status == GOT_STATUS_UNVERSIONED)
8588 return NULL;
8590 while (path[0] == '/')
8591 path++;
8592 printf("%c %s\n", status, path);
8593 return NULL;
8596 struct choose_patch_arg {
8597 FILE *patch_script_file;
8598 const char *action;
8601 static const struct got_error *
8602 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8603 int nchanges, const char *action)
8605 const struct got_error *err;
8606 char *line = NULL;
8607 size_t linesize = 0;
8608 ssize_t linelen;
8610 switch (status) {
8611 case GOT_STATUS_ADD:
8612 printf("A %s\n%s this addition? [y/n] ", path, action);
8613 break;
8614 case GOT_STATUS_DELETE:
8615 printf("D %s\n%s this deletion? [y/n] ", path, action);
8616 break;
8617 case GOT_STATUS_MODIFY:
8618 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8619 return got_error_from_errno("fseek");
8620 printf(GOT_COMMIT_SEP_STR);
8621 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8622 printf("%s", line);
8623 if (linelen == -1 && ferror(patch_file)) {
8624 err = got_error_from_errno("getline");
8625 free(line);
8626 return err;
8628 free(line);
8629 printf(GOT_COMMIT_SEP_STR);
8630 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8631 path, n, nchanges, action);
8632 break;
8633 default:
8634 return got_error_path(path, GOT_ERR_FILE_STATUS);
8637 fflush(stdout);
8638 return NULL;
8641 static const struct got_error *
8642 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8643 FILE *patch_file, int n, int nchanges)
8645 const struct got_error *err = NULL;
8646 char *line = NULL;
8647 size_t linesize = 0;
8648 ssize_t linelen;
8649 int resp = ' ';
8650 struct choose_patch_arg *a = arg;
8652 *choice = GOT_PATCH_CHOICE_NONE;
8654 if (a->patch_script_file) {
8655 char *nl;
8656 err = show_change(status, path, patch_file, n, nchanges,
8657 a->action);
8658 if (err)
8659 return err;
8660 linelen = getline(&line, &linesize, a->patch_script_file);
8661 if (linelen == -1) {
8662 if (ferror(a->patch_script_file))
8663 return got_error_from_errno("getline");
8664 return NULL;
8666 nl = strchr(line, '\n');
8667 if (nl)
8668 *nl = '\0';
8669 if (strcmp(line, "y") == 0) {
8670 *choice = GOT_PATCH_CHOICE_YES;
8671 printf("y\n");
8672 } else if (strcmp(line, "n") == 0) {
8673 *choice = GOT_PATCH_CHOICE_NO;
8674 printf("n\n");
8675 } else if (strcmp(line, "q") == 0 &&
8676 status == GOT_STATUS_MODIFY) {
8677 *choice = GOT_PATCH_CHOICE_QUIT;
8678 printf("q\n");
8679 } else
8680 printf("invalid response '%s'\n", line);
8681 free(line);
8682 return NULL;
8685 while (resp != 'y' && resp != 'n' && resp != 'q') {
8686 err = show_change(status, path, patch_file, n, nchanges,
8687 a->action);
8688 if (err)
8689 return err;
8690 resp = getchar();
8691 if (resp == '\n')
8692 resp = getchar();
8693 if (status == GOT_STATUS_MODIFY) {
8694 if (resp != 'y' && resp != 'n' && resp != 'q') {
8695 printf("invalid response '%c'\n", resp);
8696 resp = ' ';
8698 } else if (resp != 'y' && resp != 'n') {
8699 printf("invalid response '%c'\n", resp);
8700 resp = ' ';
8704 if (resp == 'y')
8705 *choice = GOT_PATCH_CHOICE_YES;
8706 else if (resp == 'n')
8707 *choice = GOT_PATCH_CHOICE_NO;
8708 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8709 *choice = GOT_PATCH_CHOICE_QUIT;
8711 return NULL;
8714 struct wt_commitable_path_arg {
8715 struct got_pathlist_head *commit_paths;
8716 int *has_changes;
8720 * Shortcut work tree status callback to determine if the set of paths scanned
8721 * has at least one versioned path that is being modified and, if not NULL, is
8722 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8723 * soon as a path is passed with a status that satisfies this criteria.
8725 static const struct got_error *
8726 worktree_has_commitable_path(void *arg, unsigned char status,
8727 unsigned char staged_status, const char *path,
8728 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8729 struct got_object_id *commit_id, int dirfd, const char *de_name)
8731 struct wt_commitable_path_arg *a = arg;
8733 if (status == staged_status && (status == GOT_STATUS_DELETE))
8734 status = GOT_STATUS_NO_CHANGE;
8736 if (!(status == GOT_STATUS_NO_CHANGE ||
8737 status == GOT_STATUS_UNVERSIONED) ||
8738 staged_status != GOT_STATUS_NO_CHANGE) {
8739 if (a->commit_paths != NULL) {
8740 struct got_pathlist_entry *pe;
8742 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8743 if (strncmp(path, pe->path,
8744 pe->path_len) == 0) {
8745 *a->has_changes = 1;
8746 break;
8749 } else
8750 *a->has_changes = 1;
8752 if (*a->has_changes)
8753 return got_error(GOT_ERR_FILE_MODIFIED);
8756 return NULL;
8760 * Check that the changeset of the commit identified by id is
8761 * comprised of at least one modified path that is being committed.
8763 static const struct got_error *
8764 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8765 struct got_object_id *id, struct got_worktree *worktree,
8766 struct got_repository *repo)
8768 const struct got_error *err;
8769 struct got_pathlist_head paths;
8770 struct got_commit_object *commit = NULL, *pcommit = NULL;
8771 struct got_tree_object *tree = NULL, *ptree = NULL;
8772 struct got_object_qid *pid;
8774 TAILQ_INIT(&paths);
8776 err = got_object_open_as_commit(&commit, repo, id);
8777 if (err)
8778 goto done;
8780 err = got_object_open_as_tree(&tree, repo,
8781 got_object_commit_get_tree_id(commit));
8782 if (err)
8783 goto done;
8785 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8786 if (pid != NULL) {
8787 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8788 if (err)
8789 goto done;
8791 err = got_object_open_as_tree(&ptree, repo,
8792 got_object_commit_get_tree_id(pcommit));
8793 if (err)
8794 goto done;
8797 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8798 got_diff_tree_collect_changed_paths, &paths, 0);
8799 if (err)
8800 goto done;
8802 err = got_worktree_status(worktree, &paths, repo, 0,
8803 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8804 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8806 * At least one changed path in the referenced commit is
8807 * modified in the work tree, that's all we need to know!
8809 err = NULL;
8812 done:
8813 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8814 if (commit)
8815 got_object_commit_close(commit);
8816 if (pcommit)
8817 got_object_commit_close(pcommit);
8818 if (tree)
8819 got_object_tree_close(tree);
8820 if (ptree)
8821 got_object_tree_close(ptree);
8822 return err;
8826 * Remove any "logmsg" reference comprised entirely of paths that have
8827 * been reverted in this work tree. If any path in the logmsg ref changeset
8828 * remains in a changed state in the worktree, do not remove the reference.
8830 static const struct got_error *
8831 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8833 const struct got_error *err;
8834 struct got_reflist_head refs;
8835 struct got_reflist_entry *re;
8836 struct got_commit_object *commit = NULL;
8837 struct got_object_id *commit_id = NULL;
8838 struct wt_commitable_path_arg wcpa;
8839 char *uuidstr = NULL;
8841 TAILQ_INIT(&refs);
8843 err = got_worktree_get_uuid(&uuidstr, worktree);
8844 if (err)
8845 goto done;
8847 err = got_ref_list(&refs, repo, "refs/got/worktree",
8848 got_ref_cmp_by_name, repo);
8849 if (err)
8850 goto done;
8852 TAILQ_FOREACH(re, &refs, entry) {
8853 const char *refname;
8854 int has_changes = 0;
8856 refname = got_ref_get_name(re->ref);
8858 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8859 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8860 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8861 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8862 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8863 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8864 else
8865 continue;
8867 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8868 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8869 else
8870 continue;
8872 err = got_repo_match_object_id(&commit_id, NULL, refname,
8873 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8874 if (err)
8875 goto done;
8877 err = got_object_open_as_commit(&commit, repo, commit_id);
8878 if (err)
8879 goto done;
8881 wcpa.commit_paths = NULL;
8882 wcpa.has_changes = &has_changes;
8884 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8885 worktree, repo);
8886 if (err)
8887 goto done;
8889 if (!has_changes) {
8890 err = got_ref_delete(re->ref, repo);
8891 if (err)
8892 goto done;
8895 got_object_commit_close(commit);
8896 commit = NULL;
8897 free(commit_id);
8898 commit_id = NULL;
8901 done:
8902 free(uuidstr);
8903 free(commit_id);
8904 got_ref_list_free(&refs);
8905 if (commit)
8906 got_object_commit_close(commit);
8907 return err;
8910 static const struct got_error *
8911 cmd_revert(int argc, char *argv[])
8913 const struct got_error *error = NULL;
8914 struct got_worktree *worktree = NULL;
8915 struct got_repository *repo = NULL;
8916 char *cwd = NULL, *path = NULL;
8917 struct got_pathlist_head paths;
8918 int ch, contains_dir, can_recurse = 0, pflag = 0;
8919 FILE *patch_script_file = NULL;
8920 const char *patch_script_path = NULL;
8921 struct choose_patch_arg cpa;
8922 int *pack_fds = NULL;
8924 TAILQ_INIT(&paths);
8926 #ifndef PROFILE
8927 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8928 "unveil", NULL) == -1)
8929 err(1, "pledge");
8930 #endif
8932 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8933 switch (ch) {
8934 case 'F':
8935 patch_script_path = optarg;
8936 break;
8937 case 'p':
8938 pflag = 1;
8939 break;
8940 case 'R':
8941 can_recurse = 1;
8942 break;
8943 default:
8944 usage_revert();
8945 /* NOTREACHED */
8949 argc -= optind;
8950 argv += optind;
8952 if (argc < 1)
8953 usage_revert();
8954 if (patch_script_path && !pflag)
8955 errx(1, "-F option can only be used together with -p option");
8957 cwd = getcwd(NULL, 0);
8958 if (cwd == NULL) {
8959 error = got_error_from_errno("getcwd");
8960 goto done;
8963 error = got_repo_pack_fds_open(&pack_fds);
8964 if (error != NULL)
8965 goto done;
8967 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8968 if (error) {
8969 if (error->code == GOT_ERR_NOT_WORKTREE)
8970 error = wrap_not_worktree_error(error, "revert", cwd);
8971 goto done;
8974 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8975 NULL, pack_fds);
8976 if (error != NULL)
8977 goto done;
8979 if (patch_script_path) {
8980 patch_script_file = fopen(patch_script_path, "re");
8981 if (patch_script_file == NULL) {
8982 error = got_error_from_errno2("fopen",
8983 patch_script_path);
8984 goto done;
8989 * XXX "c" perm needed on repo dir to delete merge references.
8991 error = apply_unveil(got_repo_get_path(repo), 0,
8992 got_worktree_get_root_path(worktree));
8993 if (error)
8994 goto done;
8996 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8997 if (error)
8998 goto done;
9000 if (!can_recurse) {
9001 error = pathlist_contains_directory(&contains_dir, worktree,
9002 &paths);
9003 if (error != NULL)
9004 goto done;
9006 if (contains_dir) {
9007 error = got_error_msg(GOT_ERR_BAD_PATH,
9008 "reverting directories requires -R option");
9009 goto done;
9013 cpa.patch_script_file = patch_script_file;
9014 cpa.action = "revert";
9015 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9016 pflag ? choose_patch : NULL, &cpa, repo);
9018 error = rm_logmsg_ref(worktree, repo);
9019 done:
9020 if (patch_script_file && fclose(patch_script_file) == EOF &&
9021 error == NULL)
9022 error = got_error_from_errno2("fclose", patch_script_path);
9023 if (repo) {
9024 const struct got_error *close_err = got_repo_close(repo);
9025 if (error == NULL)
9026 error = close_err;
9028 if (worktree)
9029 got_worktree_close(worktree);
9030 if (pack_fds) {
9031 const struct got_error *pack_err =
9032 got_repo_pack_fds_close(pack_fds);
9033 if (error == NULL)
9034 error = pack_err;
9036 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9037 free(path);
9038 free(cwd);
9039 return error;
9042 __dead static void
9043 usage_commit(void)
9045 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9046 "[-m message] [path ...]\n", getprogname());
9047 exit(1);
9050 struct collect_commit_logmsg_arg {
9051 const char *cmdline_log;
9052 const char *prepared_log;
9053 const char *merged_log;
9054 int non_interactive;
9055 const char *editor;
9056 const char *worktree_path;
9057 const char *branch_name;
9058 const char *repo_path;
9059 char *logmsg_path;
9063 static const struct got_error *
9064 read_prepared_logmsg(char **logmsg, const char *path)
9066 const struct got_error *err = NULL;
9067 FILE *f = NULL;
9068 struct stat sb;
9069 size_t r;
9071 *logmsg = NULL;
9072 memset(&sb, 0, sizeof(sb));
9074 f = fopen(path, "re");
9075 if (f == NULL)
9076 return got_error_from_errno2("fopen", path);
9078 if (fstat(fileno(f), &sb) == -1) {
9079 err = got_error_from_errno2("fstat", path);
9080 goto done;
9082 if (sb.st_size == 0) {
9083 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9084 goto done;
9087 *logmsg = malloc(sb.st_size + 1);
9088 if (*logmsg == NULL) {
9089 err = got_error_from_errno("malloc");
9090 goto done;
9093 r = fread(*logmsg, 1, sb.st_size, f);
9094 if (r != sb.st_size) {
9095 if (ferror(f))
9096 err = got_error_from_errno2("fread", path);
9097 else
9098 err = got_error(GOT_ERR_IO);
9099 goto done;
9101 (*logmsg)[sb.st_size] = '\0';
9102 done:
9103 if (fclose(f) == EOF && err == NULL)
9104 err = got_error_from_errno2("fclose", path);
9105 if (err) {
9106 free(*logmsg);
9107 *logmsg = NULL;
9109 return err;
9112 static const struct got_error *
9113 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9114 const char *diff_path, char **logmsg, void *arg)
9116 char *initial_content = NULL;
9117 struct got_pathlist_entry *pe;
9118 const struct got_error *err = NULL;
9119 char *template = NULL;
9120 char *prepared_msg = NULL, *merged_msg = NULL;
9121 struct collect_commit_logmsg_arg *a = arg;
9122 int initial_content_len;
9123 int fd = -1;
9124 size_t len;
9126 /* if a message was specified on the command line, just use it */
9127 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9128 len = strlen(a->cmdline_log) + 1;
9129 *logmsg = malloc(len + 1);
9130 if (*logmsg == NULL)
9131 return got_error_from_errno("malloc");
9132 strlcpy(*logmsg, a->cmdline_log, len);
9133 return NULL;
9134 } else if (a->prepared_log != NULL && a->non_interactive)
9135 return read_prepared_logmsg(logmsg, a->prepared_log);
9137 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9138 return got_error_from_errno("asprintf");
9140 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9141 if (err)
9142 goto done;
9144 if (a->prepared_log) {
9145 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9146 if (err)
9147 goto done;
9148 } else if (a->merged_log) {
9149 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9150 if (err)
9151 goto done;
9154 initial_content_len = asprintf(&initial_content,
9155 "%s%s\n# changes to be committed on branch %s:\n",
9156 prepared_msg ? prepared_msg : "",
9157 merged_msg ? merged_msg : "", a->branch_name);
9158 if (initial_content_len == -1) {
9159 err = got_error_from_errno("asprintf");
9160 goto done;
9163 if (write(fd, initial_content, initial_content_len) == -1) {
9164 err = got_error_from_errno2("write", a->logmsg_path);
9165 goto done;
9168 TAILQ_FOREACH(pe, commitable_paths, entry) {
9169 struct got_commitable *ct = pe->data;
9170 dprintf(fd, "# %c %s\n",
9171 got_commitable_get_status(ct),
9172 got_commitable_get_path(ct));
9175 if (diff_path) {
9176 dprintf(fd, "# detailed changes can be viewed in %s\n",
9177 diff_path);
9180 if (close(fd) == -1) {
9181 err = got_error_from_errno2("close", a->logmsg_path);
9182 goto done;
9184 fd = -1;
9186 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9187 initial_content_len, a->prepared_log ? 0 : 1);
9188 done:
9189 free(initial_content);
9190 free(template);
9191 free(prepared_msg);
9192 free(merged_msg);
9194 if (fd != -1 && close(fd) == -1 && err == NULL)
9195 err = got_error_from_errno2("close", a->logmsg_path);
9196 if (err) {
9197 free(*logmsg);
9198 *logmsg = NULL;
9200 return err;
9203 static const struct got_error *
9204 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9205 const char *type, int has_content)
9207 const struct got_error *err = NULL;
9208 char *logmsg = NULL;
9210 err = got_object_commit_get_logmsg(&logmsg, commit);
9211 if (err)
9212 return err;
9214 if (fprintf(f, "%s# log message of %s commit %s:%s",
9215 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9216 err = got_ferror(f, GOT_ERR_IO);
9218 free(logmsg);
9219 return err;
9223 * Lookup "logmsg" references of backed-out and cherrypicked commits
9224 * belonging to the current work tree. If found, and the worktree has
9225 * at least one modified file that was changed in the referenced commit,
9226 * add its log message to a new temporary file at *logmsg_path.
9227 * Add all refs found to matched_refs to be scheduled for removal on
9228 * successful commit.
9230 static const struct got_error *
9231 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9232 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9233 struct got_repository *repo)
9235 const struct got_error *err;
9236 struct got_commit_object *commit = NULL;
9237 struct got_object_id *id = NULL;
9238 struct got_reflist_head refs;
9239 struct got_reflist_entry *re, *re_match;
9240 FILE *f = NULL;
9241 char *uuidstr = NULL;
9242 int added_logmsg = 0;
9244 TAILQ_INIT(&refs);
9246 *logmsg_path = NULL;
9248 err = got_worktree_get_uuid(&uuidstr, worktree);
9249 if (err)
9250 goto done;
9252 err = got_ref_list(&refs, repo, "refs/got/worktree",
9253 got_ref_cmp_by_name, repo);
9254 if (err)
9255 goto done;
9257 TAILQ_FOREACH(re, &refs, entry) {
9258 const char *refname, *type;
9259 struct wt_commitable_path_arg wcpa;
9260 int add_logmsg = 0;
9262 refname = got_ref_get_name(re->ref);
9264 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9265 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9266 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9267 type = "cherrypicked";
9268 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9269 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9270 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9271 type = "backed-out";
9272 } else
9273 continue;
9275 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9276 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9277 else
9278 continue;
9280 err = got_repo_match_object_id(&id, NULL, refname,
9281 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9282 if (err)
9283 goto done;
9285 err = got_object_open_as_commit(&commit, repo, id);
9286 if (err)
9287 goto done;
9289 wcpa.commit_paths = paths;
9290 wcpa.has_changes = &add_logmsg;
9292 err = commit_path_changed_in_worktree(&wcpa, id,
9293 worktree, repo);
9294 if (err)
9295 goto done;
9297 if (add_logmsg) {
9298 if (f == NULL) {
9299 err = got_opentemp_named(logmsg_path, &f,
9300 "got-commit-logmsg", "");
9301 if (err)
9302 goto done;
9304 err = cat_logmsg(f, commit, refname, type,
9305 added_logmsg);
9306 if (err)
9307 goto done;
9308 if (!added_logmsg)
9309 ++added_logmsg;
9311 err = got_reflist_entry_dup(&re_match, re);
9312 if (err)
9313 goto done;
9314 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9317 got_object_commit_close(commit);
9318 commit = NULL;
9319 free(id);
9320 id = NULL;
9323 done:
9324 free(id);
9325 free(uuidstr);
9326 got_ref_list_free(&refs);
9327 if (commit)
9328 got_object_commit_close(commit);
9329 if (f && fclose(f) == EOF && err == NULL)
9330 err = got_error_from_errno("fclose");
9331 if (!added_logmsg) {
9332 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9333 err = got_error_from_errno2("unlink", *logmsg_path);
9334 *logmsg_path = NULL;
9336 return err;
9339 static const struct got_error *
9340 cmd_commit(int argc, char *argv[])
9342 const struct got_error *error = NULL;
9343 struct got_worktree *worktree = NULL;
9344 struct got_repository *repo = NULL;
9345 char *cwd = NULL, *id_str = NULL;
9346 struct got_object_id *id = NULL;
9347 const char *logmsg = NULL;
9348 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9349 struct collect_commit_logmsg_arg cl_arg;
9350 const char *author = NULL;
9351 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9352 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9353 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9354 int show_diff = 1, commit_conflicts = 0;
9355 struct got_pathlist_head paths;
9356 struct got_reflist_head refs;
9357 struct got_reflist_entry *re;
9358 int *pack_fds = NULL;
9360 TAILQ_INIT(&refs);
9361 TAILQ_INIT(&paths);
9362 cl_arg.logmsg_path = NULL;
9364 #ifndef PROFILE
9365 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9366 "unveil", NULL) == -1)
9367 err(1, "pledge");
9368 #endif
9370 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9371 switch (ch) {
9372 case 'A':
9373 author = optarg;
9374 error = valid_author(author);
9375 if (error)
9376 return error;
9377 break;
9378 case 'C':
9379 commit_conflicts = 1;
9380 break;
9381 case 'F':
9382 if (logmsg != NULL)
9383 option_conflict('F', 'm');
9384 prepared_logmsg = realpath(optarg, NULL);
9385 if (prepared_logmsg == NULL)
9386 return got_error_from_errno2("realpath",
9387 optarg);
9388 break;
9389 case 'm':
9390 if (prepared_logmsg)
9391 option_conflict('m', 'F');
9392 logmsg = optarg;
9393 break;
9394 case 'N':
9395 non_interactive = 1;
9396 break;
9397 case 'n':
9398 show_diff = 0;
9399 break;
9400 case 'S':
9401 allow_bad_symlinks = 1;
9402 break;
9403 default:
9404 usage_commit();
9405 /* NOTREACHED */
9409 argc -= optind;
9410 argv += optind;
9412 cwd = getcwd(NULL, 0);
9413 if (cwd == NULL) {
9414 error = got_error_from_errno("getcwd");
9415 goto done;
9418 error = got_repo_pack_fds_open(&pack_fds);
9419 if (error != NULL)
9420 goto done;
9422 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9423 if (error) {
9424 if (error->code == GOT_ERR_NOT_WORKTREE)
9425 error = wrap_not_worktree_error(error, "commit", cwd);
9426 goto done;
9429 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9430 if (error)
9431 goto done;
9432 if (rebase_in_progress) {
9433 error = got_error(GOT_ERR_REBASING);
9434 goto done;
9437 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9438 worktree);
9439 if (error)
9440 goto done;
9442 error = get_gitconfig_path(&gitconfig_path);
9443 if (error)
9444 goto done;
9445 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9446 gitconfig_path, pack_fds);
9447 if (error != NULL)
9448 goto done;
9450 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9451 if (error)
9452 goto done;
9453 if (merge_in_progress) {
9454 error = got_error(GOT_ERR_MERGE_BUSY);
9455 goto done;
9458 error = get_author(&committer, repo, worktree);
9459 if (error)
9460 goto done;
9462 if (author == NULL)
9463 author = committer;
9465 if (logmsg == NULL || strlen(logmsg) == 0) {
9466 error = get_editor(&editor);
9467 if (error)
9468 goto done;
9469 if (unveil(editor, "x") != 0) {
9470 error = got_error_from_errno2("unveil", editor);
9471 goto done;
9474 if (prepared_logmsg) {
9475 if (unveil(prepared_logmsg, "r") != 0) {
9476 error = got_error_from_errno2("unveil",
9477 prepared_logmsg);
9478 goto done;
9482 error = apply_unveil(got_repo_get_path(repo), 0,
9483 got_worktree_get_root_path(worktree));
9484 if (error)
9485 goto done;
9487 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9488 if (error)
9489 goto done;
9491 if (prepared_logmsg == NULL) {
9492 error = lookup_logmsg_ref(&merged_logmsg,
9493 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9494 if (error)
9495 goto done;
9498 cl_arg.editor = editor;
9499 cl_arg.cmdline_log = logmsg;
9500 cl_arg.prepared_log = prepared_logmsg;
9501 cl_arg.merged_log = merged_logmsg;
9502 cl_arg.non_interactive = non_interactive;
9503 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9504 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9505 if (!histedit_in_progress) {
9506 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9507 error = got_error(GOT_ERR_COMMIT_BRANCH);
9508 goto done;
9510 cl_arg.branch_name += 11;
9512 cl_arg.repo_path = got_repo_get_path(repo);
9513 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9514 allow_bad_symlinks, show_diff, commit_conflicts,
9515 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9516 if (error) {
9517 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9518 cl_arg.logmsg_path != NULL)
9519 preserve_logmsg = 1;
9520 goto done;
9523 error = got_object_id_str(&id_str, id);
9524 if (error)
9525 goto done;
9526 printf("Created commit %s\n", id_str);
9528 TAILQ_FOREACH(re, &refs, entry) {
9529 error = got_ref_delete(re->ref, repo);
9530 if (error)
9531 goto done;
9534 done:
9535 if (preserve_logmsg) {
9536 fprintf(stderr, "%s: log message preserved in %s\n",
9537 getprogname(), cl_arg.logmsg_path);
9538 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9539 error == NULL)
9540 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9541 free(cl_arg.logmsg_path);
9542 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9543 error = got_error_from_errno2("unlink", merged_logmsg);
9544 free(merged_logmsg);
9545 if (repo) {
9546 const struct got_error *close_err = got_repo_close(repo);
9547 if (error == NULL)
9548 error = close_err;
9550 if (worktree)
9551 got_worktree_close(worktree);
9552 if (pack_fds) {
9553 const struct got_error *pack_err =
9554 got_repo_pack_fds_close(pack_fds);
9555 if (error == NULL)
9556 error = pack_err;
9558 got_ref_list_free(&refs);
9559 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9560 free(cwd);
9561 free(id_str);
9562 free(gitconfig_path);
9563 free(editor);
9564 free(committer);
9565 free(prepared_logmsg);
9566 return error;
9569 __dead static void
9570 usage_send(void)
9572 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9573 "[-r repository-path] [-t tag] [remote-repository]\n",
9574 getprogname());
9575 exit(1);
9578 static void
9579 print_load_info(int print_colored, int print_found, int print_trees,
9580 int ncolored, int nfound, int ntrees)
9582 if (print_colored) {
9583 printf("%d commit%s colored", ncolored,
9584 ncolored == 1 ? "" : "s");
9586 if (print_found) {
9587 printf("%s%d object%s found",
9588 ncolored > 0 ? "; " : "",
9589 nfound, nfound == 1 ? "" : "s");
9591 if (print_trees) {
9592 printf("; %d tree%s scanned", ntrees,
9593 ntrees == 1 ? "" : "s");
9597 struct got_send_progress_arg {
9598 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9599 int verbosity;
9600 int last_ncolored;
9601 int last_nfound;
9602 int last_ntrees;
9603 int loading_done;
9604 int last_ncommits;
9605 int last_nobj_total;
9606 int last_p_deltify;
9607 int last_p_written;
9608 int last_p_sent;
9609 int printed_something;
9610 int sent_something;
9611 struct got_pathlist_head *delete_branches;
9614 static const struct got_error *
9615 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9616 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9617 int nobj_written, off_t bytes_sent, const char *refname,
9618 const char *errmsg, int success)
9620 struct got_send_progress_arg *a = arg;
9621 char scaled_packsize[FMT_SCALED_STRSIZE];
9622 char scaled_sent[FMT_SCALED_STRSIZE];
9623 int p_deltify = 0, p_written = 0, p_sent = 0;
9624 int print_colored = 0, print_found = 0, print_trees = 0;
9625 int print_searching = 0, print_total = 0;
9626 int print_deltify = 0, print_written = 0, print_sent = 0;
9628 if (a->verbosity < 0)
9629 return NULL;
9631 if (refname) {
9632 const char *status = success ? "accepted" : "rejected";
9634 if (success) {
9635 struct got_pathlist_entry *pe;
9636 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9637 const char *branchname = pe->path;
9638 if (got_path_cmp(branchname, refname,
9639 strlen(branchname), strlen(refname)) == 0) {
9640 status = "deleted";
9641 a->sent_something = 1;
9642 break;
9647 if (a->printed_something)
9648 putchar('\n');
9649 printf("Server has %s %s", status, refname);
9650 if (errmsg)
9651 printf(": %s", errmsg);
9652 a->printed_something = 1;
9653 return NULL;
9656 if (a->last_ncolored != ncolored) {
9657 print_colored = 1;
9658 a->last_ncolored = ncolored;
9661 if (a->last_nfound != nfound) {
9662 print_colored = 1;
9663 print_found = 1;
9664 a->last_nfound = nfound;
9667 if (a->last_ntrees != ntrees) {
9668 print_colored = 1;
9669 print_found = 1;
9670 print_trees = 1;
9671 a->last_ntrees = ntrees;
9674 if ((print_colored || print_found || print_trees) &&
9675 !a->loading_done) {
9676 printf("\r");
9677 print_load_info(print_colored, print_found, print_trees,
9678 ncolored, nfound, ntrees);
9679 a->printed_something = 1;
9680 fflush(stdout);
9681 return NULL;
9682 } else if (!a->loading_done) {
9683 printf("\r");
9684 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9685 printf("\n");
9686 a->loading_done = 1;
9689 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9690 return got_error_from_errno("fmt_scaled");
9691 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9692 return got_error_from_errno("fmt_scaled");
9694 if (a->last_ncommits != ncommits) {
9695 print_searching = 1;
9696 a->last_ncommits = ncommits;
9699 if (a->last_nobj_total != nobj_total) {
9700 print_searching = 1;
9701 print_total = 1;
9702 a->last_nobj_total = nobj_total;
9705 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9706 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9707 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9708 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9709 return got_error(GOT_ERR_NO_SPACE);
9712 if (nobj_deltify > 0 || nobj_written > 0) {
9713 if (nobj_deltify > 0) {
9714 p_deltify = (nobj_deltify * 100) / nobj_total;
9715 if (p_deltify != a->last_p_deltify) {
9716 a->last_p_deltify = p_deltify;
9717 print_searching = 1;
9718 print_total = 1;
9719 print_deltify = 1;
9722 if (nobj_written > 0) {
9723 p_written = (nobj_written * 100) / nobj_total;
9724 if (p_written != a->last_p_written) {
9725 a->last_p_written = p_written;
9726 print_searching = 1;
9727 print_total = 1;
9728 print_deltify = 1;
9729 print_written = 1;
9734 if (bytes_sent > 0) {
9735 p_sent = (bytes_sent * 100) / packfile_size;
9736 if (p_sent != a->last_p_sent) {
9737 a->last_p_sent = p_sent;
9738 print_searching = 1;
9739 print_total = 1;
9740 print_deltify = 1;
9741 print_written = 1;
9742 print_sent = 1;
9744 a->sent_something = 1;
9747 if (print_searching || print_total || print_deltify || print_written ||
9748 print_sent)
9749 printf("\r");
9750 if (print_searching)
9751 printf("packing %d reference%s", ncommits,
9752 ncommits == 1 ? "" : "s");
9753 if (print_total)
9754 printf("; %d object%s", nobj_total,
9755 nobj_total == 1 ? "" : "s");
9756 if (print_deltify)
9757 printf("; deltify: %d%%", p_deltify);
9758 if (print_sent)
9759 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9760 scaled_packsize, p_sent);
9761 else if (print_written)
9762 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9763 scaled_packsize, p_written);
9764 if (print_searching || print_total || print_deltify ||
9765 print_written || print_sent) {
9766 a->printed_something = 1;
9767 fflush(stdout);
9769 return NULL;
9772 static const struct got_error *
9773 cmd_send(int argc, char *argv[])
9775 const struct got_error *error = NULL;
9776 char *cwd = NULL, *repo_path = NULL;
9777 const char *remote_name;
9778 char *proto = NULL, *host = NULL, *port = NULL;
9779 char *repo_name = NULL, *server_path = NULL;
9780 const struct got_remote_repo *remotes;
9781 struct got_remote_repo *remote = NULL;
9782 int nremotes, nbranches = 0, ndelete_branches = 0;
9783 struct got_repository *repo = NULL;
9784 struct got_worktree *worktree = NULL;
9785 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9786 struct got_pathlist_head branches;
9787 struct got_pathlist_head tags;
9788 struct got_reflist_head all_branches;
9789 struct got_reflist_head all_tags;
9790 struct got_pathlist_head delete_args;
9791 struct got_pathlist_head delete_branches;
9792 struct got_reflist_entry *re;
9793 struct got_pathlist_entry *pe;
9794 int i, ch, sendfd = -1, sendstatus;
9795 pid_t sendpid = -1;
9796 struct got_send_progress_arg spa;
9797 int verbosity = 0, overwrite_refs = 0;
9798 int send_all_branches = 0, send_all_tags = 0;
9799 struct got_reference *ref = NULL;
9800 int *pack_fds = NULL;
9802 TAILQ_INIT(&branches);
9803 TAILQ_INIT(&tags);
9804 TAILQ_INIT(&all_branches);
9805 TAILQ_INIT(&all_tags);
9806 TAILQ_INIT(&delete_args);
9807 TAILQ_INIT(&delete_branches);
9809 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9810 switch (ch) {
9811 case 'a':
9812 send_all_branches = 1;
9813 break;
9814 case 'b':
9815 error = got_pathlist_append(&branches, optarg, NULL);
9816 if (error)
9817 return error;
9818 nbranches++;
9819 break;
9820 case 'd':
9821 error = got_pathlist_append(&delete_args, optarg, NULL);
9822 if (error)
9823 return error;
9824 break;
9825 case 'f':
9826 overwrite_refs = 1;
9827 break;
9828 case 'q':
9829 verbosity = -1;
9830 break;
9831 case 'r':
9832 repo_path = realpath(optarg, NULL);
9833 if (repo_path == NULL)
9834 return got_error_from_errno2("realpath",
9835 optarg);
9836 got_path_strip_trailing_slashes(repo_path);
9837 break;
9838 case 'T':
9839 send_all_tags = 1;
9840 break;
9841 case 't':
9842 error = got_pathlist_append(&tags, optarg, NULL);
9843 if (error)
9844 return error;
9845 break;
9846 case 'v':
9847 if (verbosity < 0)
9848 verbosity = 0;
9849 else if (verbosity < 3)
9850 verbosity++;
9851 break;
9852 default:
9853 usage_send();
9854 /* NOTREACHED */
9857 argc -= optind;
9858 argv += optind;
9860 if (send_all_branches && !TAILQ_EMPTY(&branches))
9861 option_conflict('a', 'b');
9862 if (send_all_tags && !TAILQ_EMPTY(&tags))
9863 option_conflict('T', 't');
9866 if (argc == 0)
9867 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9868 else if (argc == 1)
9869 remote_name = argv[0];
9870 else
9871 usage_send();
9873 cwd = getcwd(NULL, 0);
9874 if (cwd == NULL) {
9875 error = got_error_from_errno("getcwd");
9876 goto done;
9879 error = got_repo_pack_fds_open(&pack_fds);
9880 if (error != NULL)
9881 goto done;
9883 if (repo_path == NULL) {
9884 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9885 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9886 goto done;
9887 else
9888 error = NULL;
9889 if (worktree) {
9890 repo_path =
9891 strdup(got_worktree_get_repo_path(worktree));
9892 if (repo_path == NULL)
9893 error = got_error_from_errno("strdup");
9894 if (error)
9895 goto done;
9896 } else {
9897 repo_path = strdup(cwd);
9898 if (repo_path == NULL) {
9899 error = got_error_from_errno("strdup");
9900 goto done;
9905 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9906 if (error)
9907 goto done;
9909 if (worktree) {
9910 worktree_conf = got_worktree_get_gotconfig(worktree);
9911 if (worktree_conf) {
9912 got_gotconfig_get_remotes(&nremotes, &remotes,
9913 worktree_conf);
9914 for (i = 0; i < nremotes; i++) {
9915 if (strcmp(remotes[i].name, remote_name) == 0) {
9916 error = got_repo_remote_repo_dup(&remote,
9917 &remotes[i]);
9918 if (error)
9919 goto done;
9920 break;
9925 if (remote == NULL) {
9926 repo_conf = got_repo_get_gotconfig(repo);
9927 if (repo_conf) {
9928 got_gotconfig_get_remotes(&nremotes, &remotes,
9929 repo_conf);
9930 for (i = 0; i < nremotes; i++) {
9931 if (strcmp(remotes[i].name, remote_name) == 0) {
9932 error = got_repo_remote_repo_dup(&remote,
9933 &remotes[i]);
9934 if (error)
9935 goto done;
9936 break;
9941 if (remote == NULL) {
9942 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9943 for (i = 0; i < nremotes; i++) {
9944 if (strcmp(remotes[i].name, remote_name) == 0) {
9945 error = got_repo_remote_repo_dup(&remote,
9946 &remotes[i]);
9947 if (error)
9948 goto done;
9949 break;
9953 if (remote == NULL) {
9954 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9955 goto done;
9958 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9959 &repo_name, remote->send_url);
9960 if (error)
9961 goto done;
9963 if (strcmp(proto, "git") == 0) {
9964 #ifndef PROFILE
9965 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9966 "sendfd dns inet unveil", NULL) == -1)
9967 err(1, "pledge");
9968 #endif
9969 } else if (strcmp(proto, "git+ssh") == 0 ||
9970 strcmp(proto, "ssh") == 0) {
9971 #ifndef PROFILE
9972 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9973 "sendfd unveil", NULL) == -1)
9974 err(1, "pledge");
9975 #endif
9976 } else if (strcmp(proto, "http") == 0 ||
9977 strcmp(proto, "git+http") == 0) {
9978 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9979 goto done;
9980 } else {
9981 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9982 goto done;
9985 error = got_dial_apply_unveil(proto);
9986 if (error)
9987 goto done;
9989 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9990 if (error)
9991 goto done;
9993 if (send_all_branches) {
9994 error = got_ref_list(&all_branches, repo, "refs/heads",
9995 got_ref_cmp_by_name, NULL);
9996 if (error)
9997 goto done;
9998 TAILQ_FOREACH(re, &all_branches, entry) {
9999 const char *branchname = got_ref_get_name(re->ref);
10000 error = got_pathlist_append(&branches,
10001 branchname, NULL);
10002 if (error)
10003 goto done;
10004 nbranches++;
10006 } else if (nbranches == 0) {
10007 for (i = 0; i < remote->nsend_branches; i++) {
10008 error = got_pathlist_append(&branches,
10009 remote->send_branches[i], NULL);
10010 if (error)
10011 goto done;
10015 if (send_all_tags) {
10016 error = got_ref_list(&all_tags, repo, "refs/tags",
10017 got_ref_cmp_by_name, NULL);
10018 if (error)
10019 goto done;
10020 TAILQ_FOREACH(re, &all_tags, entry) {
10021 const char *tagname = got_ref_get_name(re->ref);
10022 error = got_pathlist_append(&tags,
10023 tagname, NULL);
10024 if (error)
10025 goto done;
10030 * To prevent accidents only branches in refs/heads/ can be deleted
10031 * with 'got send -d'.
10032 * Deleting anything else requires local repository access or Git.
10034 TAILQ_FOREACH(pe, &delete_args, entry) {
10035 const char *branchname = pe->path;
10036 char *s;
10037 struct got_pathlist_entry *new;
10038 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10039 s = strdup(branchname);
10040 if (s == NULL) {
10041 error = got_error_from_errno("strdup");
10042 goto done;
10044 } else {
10045 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10046 error = got_error_from_errno("asprintf");
10047 goto done;
10050 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10051 if (error || new == NULL /* duplicate */)
10052 free(s);
10053 if (error)
10054 goto done;
10055 ndelete_branches++;
10058 if (nbranches == 0 && ndelete_branches == 0) {
10059 struct got_reference *head_ref;
10060 if (worktree)
10061 error = got_ref_open(&head_ref, repo,
10062 got_worktree_get_head_ref_name(worktree), 0);
10063 else
10064 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10065 if (error)
10066 goto done;
10067 if (got_ref_is_symbolic(head_ref)) {
10068 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10069 got_ref_close(head_ref);
10070 if (error)
10071 goto done;
10072 } else
10073 ref = head_ref;
10074 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10075 NULL);
10076 if (error)
10077 goto done;
10078 nbranches++;
10081 if (worktree) {
10082 /* Release work tree lock. */
10083 got_worktree_close(worktree);
10084 worktree = NULL;
10087 if (verbosity >= 0) {
10088 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10089 remote->name, proto, host,
10090 port ? ":" : "", port ? port : "",
10091 *server_path == '/' ? "" : "/", server_path);
10094 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10095 server_path, verbosity);
10096 if (error)
10097 goto done;
10099 memset(&spa, 0, sizeof(spa));
10100 spa.last_scaled_packsize[0] = '\0';
10101 spa.last_p_deltify = -1;
10102 spa.last_p_written = -1;
10103 spa.verbosity = verbosity;
10104 spa.delete_branches = &delete_branches;
10105 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10106 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10107 check_cancelled, NULL);
10108 if (spa.printed_something)
10109 putchar('\n');
10110 if (error)
10111 goto done;
10112 if (!spa.sent_something && verbosity >= 0)
10113 printf("Already up-to-date\n");
10114 done:
10115 if (sendpid > 0) {
10116 if (kill(sendpid, SIGTERM) == -1)
10117 error = got_error_from_errno("kill");
10118 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10119 error = got_error_from_errno("waitpid");
10121 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10122 error = got_error_from_errno("close");
10123 if (repo) {
10124 const struct got_error *close_err = got_repo_close(repo);
10125 if (error == NULL)
10126 error = close_err;
10128 if (worktree)
10129 got_worktree_close(worktree);
10130 if (pack_fds) {
10131 const struct got_error *pack_err =
10132 got_repo_pack_fds_close(pack_fds);
10133 if (error == NULL)
10134 error = pack_err;
10136 if (ref)
10137 got_ref_close(ref);
10138 got_repo_free_remote_repo_data(remote);
10139 free(remote);
10140 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10141 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10142 got_ref_list_free(&all_branches);
10143 got_ref_list_free(&all_tags);
10144 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10145 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10146 free(cwd);
10147 free(repo_path);
10148 free(proto);
10149 free(host);
10150 free(port);
10151 free(server_path);
10152 free(repo_name);
10153 return error;
10157 * Print and if delete is set delete all ref_prefix references.
10158 * If wanted_ref is not NULL, only print or delete this reference.
10160 static const struct got_error *
10161 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10162 const char *wanted_ref, int delete, struct got_worktree *worktree,
10163 struct got_repository *repo)
10165 const struct got_error *err;
10166 struct got_pathlist_head paths;
10167 struct got_reflist_head refs;
10168 struct got_reflist_entry *re;
10169 struct got_reflist_object_id_map *refs_idmap = NULL;
10170 struct got_commit_object *commit = NULL;
10171 struct got_object_id *id = NULL;
10172 const char *header_prefix;
10173 char *uuidstr = NULL;
10174 int found = 0;
10176 TAILQ_INIT(&refs);
10177 TAILQ_INIT(&paths);
10179 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10180 if (err)
10181 goto done;
10183 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10184 if (err)
10185 goto done;
10187 if (worktree != NULL) {
10188 err = got_worktree_get_uuid(&uuidstr, worktree);
10189 if (err)
10190 goto done;
10193 if (wanted_ref) {
10194 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10195 wanted_ref += 11;
10198 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10199 header_prefix = "backout";
10200 else
10201 header_prefix = "cherrypick";
10203 TAILQ_FOREACH(re, &refs, entry) {
10204 const char *refname, *wt;
10206 refname = got_ref_get_name(re->ref);
10208 err = check_cancelled(NULL);
10209 if (err)
10210 goto done;
10212 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10213 refname += prefix_len + 1; /* skip '-' delimiter */
10214 else
10215 continue;
10217 wt = refname;
10219 if (worktree == NULL || strncmp(refname, uuidstr,
10220 GOT_WORKTREE_UUID_STRLEN) == 0)
10221 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10222 else
10223 continue;
10225 err = got_repo_match_object_id(&id, NULL, refname,
10226 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10227 if (err)
10228 goto done;
10230 err = got_object_open_as_commit(&commit, repo, id);
10231 if (err)
10232 goto done;
10234 if (wanted_ref)
10235 found = strncmp(wanted_ref, refname,
10236 strlen(wanted_ref)) == 0;
10237 if (wanted_ref && !found) {
10238 struct got_reflist_head *ci_refs;
10240 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10241 id);
10243 if (ci_refs) {
10244 char *refs_str = NULL;
10245 char const *r = NULL;
10247 err = build_refs_str(&refs_str, ci_refs, id,
10248 repo, 1);
10249 if (err)
10250 goto done;
10252 r = refs_str;
10253 while (r) {
10254 if (strncmp(r, wanted_ref,
10255 strlen(wanted_ref)) == 0) {
10256 found = 1;
10257 break;
10259 r = strchr(r, ' ');
10260 if (r)
10261 ++r;
10263 free(refs_str);
10267 if (wanted_ref == NULL || found) {
10268 if (delete) {
10269 err = got_ref_delete(re->ref, repo);
10270 if (err)
10271 goto done;
10272 printf("Deleted: ");
10273 err = print_commit_oneline(commit, id, repo,
10274 refs_idmap);
10275 } else {
10277 * Print paths modified by commit to help
10278 * associate commits with worktree changes.
10280 err = get_changed_paths(&paths, commit,
10281 repo, NULL);
10282 if (err)
10283 goto done;
10285 err = print_commit(commit, id, repo, NULL,
10286 &paths, NULL, 0, 0, refs_idmap, NULL,
10287 header_prefix);
10288 got_pathlist_free(&paths,
10289 GOT_PATHLIST_FREE_ALL);
10291 if (worktree == NULL)
10292 printf("work tree: %.*s\n\n",
10293 GOT_WORKTREE_UUID_STRLEN, wt);
10295 if (err || found)
10296 goto done;
10299 got_object_commit_close(commit);
10300 commit = NULL;
10301 free(id);
10302 id = NULL;
10305 if (wanted_ref != NULL && !found)
10306 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10308 done:
10309 free(id);
10310 free(uuidstr);
10311 got_ref_list_free(&refs);
10312 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10313 if (refs_idmap)
10314 got_reflist_object_id_map_free(refs_idmap);
10315 if (commit)
10316 got_object_commit_close(commit);
10317 return err;
10321 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10322 * identified by id for log messages to prepopulate the editor on commit.
10324 static const struct got_error *
10325 logmsg_ref(struct got_object_id *id, const char *prefix,
10326 struct got_worktree *worktree, struct got_repository *repo)
10328 const struct got_error *err = NULL;
10329 char *idstr, *ref = NULL, *refname = NULL;
10330 int histedit_in_progress;
10331 int rebase_in_progress, merge_in_progress;
10334 * Silenty refuse to create merge reference if any histedit, merge,
10335 * or rebase operation is in progress.
10337 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10338 worktree);
10339 if (err)
10340 return err;
10341 if (histedit_in_progress)
10342 return NULL;
10344 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10345 if (err)
10346 return err;
10347 if (rebase_in_progress)
10348 return NULL;
10350 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10351 repo);
10352 if (err)
10353 return err;
10354 if (merge_in_progress)
10355 return NULL;
10357 err = got_object_id_str(&idstr, id);
10358 if (err)
10359 return err;
10361 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10362 if (err)
10363 goto done;
10365 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10366 err = got_error_from_errno("asprintf");
10367 goto done;
10370 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10371 -1, repo);
10372 done:
10373 free(ref);
10374 free(idstr);
10375 free(refname);
10376 return err;
10379 __dead static void
10380 usage_cherrypick(void)
10382 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10383 getprogname());
10384 exit(1);
10387 static const struct got_error *
10388 cmd_cherrypick(int argc, char *argv[])
10390 const struct got_error *error = NULL;
10391 struct got_worktree *worktree = NULL;
10392 struct got_repository *repo = NULL;
10393 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10394 struct got_object_id *commit_id = NULL;
10395 struct got_commit_object *commit = NULL;
10396 struct got_object_qid *pid;
10397 int ch, list_refs = 0, remove_refs = 0;
10398 struct got_update_progress_arg upa;
10399 int *pack_fds = NULL;
10401 #ifndef PROFILE
10402 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10403 "unveil", NULL) == -1)
10404 err(1, "pledge");
10405 #endif
10407 while ((ch = getopt(argc, argv, "lX")) != -1) {
10408 switch (ch) {
10409 case 'l':
10410 list_refs = 1;
10411 break;
10412 case 'X':
10413 remove_refs = 1;
10414 break;
10415 default:
10416 usage_cherrypick();
10417 /* NOTREACHED */
10421 argc -= optind;
10422 argv += optind;
10424 if (list_refs || remove_refs) {
10425 if (argc != 0 && argc != 1)
10426 usage_cherrypick();
10427 } else if (argc != 1)
10428 usage_cherrypick();
10429 if (list_refs && remove_refs)
10430 option_conflict('l', 'X');
10432 cwd = getcwd(NULL, 0);
10433 if (cwd == NULL) {
10434 error = got_error_from_errno("getcwd");
10435 goto done;
10438 error = got_repo_pack_fds_open(&pack_fds);
10439 if (error != NULL)
10440 goto done;
10442 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10443 if (error) {
10444 if (list_refs || remove_refs) {
10445 if (error->code != GOT_ERR_NOT_WORKTREE)
10446 goto done;
10447 } else {
10448 if (error->code == GOT_ERR_NOT_WORKTREE)
10449 error = wrap_not_worktree_error(error,
10450 "cherrypick", cwd);
10451 goto done;
10455 error = got_repo_open(&repo,
10456 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10457 NULL, pack_fds);
10458 if (error != NULL)
10459 goto done;
10461 error = apply_unveil(got_repo_get_path(repo), 0,
10462 worktree ? got_worktree_get_root_path(worktree) : NULL);
10463 if (error)
10464 goto done;
10466 if (list_refs || remove_refs) {
10467 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10468 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10469 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10470 goto done;
10473 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10474 if (error != NULL)
10475 goto done;
10477 error = got_repo_match_object_id(&commit_id, NULL,
10478 keyword_idstr != NULL ? keyword_idstr : argv[0],
10479 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10480 if (error)
10481 goto done;
10482 error = got_object_id_str(&commit_id_str, commit_id);
10483 if (error)
10484 goto done;
10486 error = got_object_open_as_commit(&commit, repo, commit_id);
10487 if (error)
10488 goto done;
10489 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10490 memset(&upa, 0, sizeof(upa));
10491 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10492 commit_id, repo, update_progress, &upa, check_cancelled,
10493 NULL);
10494 if (error != NULL)
10495 goto done;
10497 if (upa.did_something) {
10498 error = logmsg_ref(commit_id,
10499 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10500 if (error)
10501 goto done;
10502 printf("Merged commit %s\n", commit_id_str);
10504 print_merge_progress_stats(&upa);
10505 done:
10506 free(cwd);
10507 free(keyword_idstr);
10508 if (commit)
10509 got_object_commit_close(commit);
10510 free(commit_id_str);
10511 if (worktree)
10512 got_worktree_close(worktree);
10513 if (repo) {
10514 const struct got_error *close_err = got_repo_close(repo);
10515 if (error == NULL)
10516 error = close_err;
10518 if (pack_fds) {
10519 const struct got_error *pack_err =
10520 got_repo_pack_fds_close(pack_fds);
10521 if (error == NULL)
10522 error = pack_err;
10525 return error;
10528 __dead static void
10529 usage_backout(void)
10531 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10532 exit(1);
10535 static const struct got_error *
10536 cmd_backout(int argc, char *argv[])
10538 const struct got_error *error = NULL;
10539 struct got_worktree *worktree = NULL;
10540 struct got_repository *repo = NULL;
10541 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10542 struct got_object_id *commit_id = NULL;
10543 struct got_commit_object *commit = NULL;
10544 struct got_object_qid *pid;
10545 int ch, list_refs = 0, remove_refs = 0;
10546 struct got_update_progress_arg upa;
10547 int *pack_fds = NULL;
10549 #ifndef PROFILE
10550 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10551 "unveil", NULL) == -1)
10552 err(1, "pledge");
10553 #endif
10555 while ((ch = getopt(argc, argv, "lX")) != -1) {
10556 switch (ch) {
10557 case 'l':
10558 list_refs = 1;
10559 break;
10560 case 'X':
10561 remove_refs = 1;
10562 break;
10563 default:
10564 usage_backout();
10565 /* NOTREACHED */
10569 argc -= optind;
10570 argv += optind;
10572 if (list_refs || remove_refs) {
10573 if (argc != 0 && argc != 1)
10574 usage_backout();
10575 } else if (argc != 1)
10576 usage_backout();
10577 if (list_refs && remove_refs)
10578 option_conflict('l', 'X');
10580 cwd = getcwd(NULL, 0);
10581 if (cwd == NULL) {
10582 error = got_error_from_errno("getcwd");
10583 goto done;
10586 error = got_repo_pack_fds_open(&pack_fds);
10587 if (error != NULL)
10588 goto done;
10590 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10591 if (error) {
10592 if (list_refs || remove_refs) {
10593 if (error->code != GOT_ERR_NOT_WORKTREE)
10594 goto done;
10595 } else {
10596 if (error->code == GOT_ERR_NOT_WORKTREE)
10597 error = wrap_not_worktree_error(error,
10598 "backout", cwd);
10599 goto done;
10603 error = got_repo_open(&repo,
10604 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10605 NULL, pack_fds);
10606 if (error != NULL)
10607 goto done;
10609 error = apply_unveil(got_repo_get_path(repo), 0,
10610 worktree ? got_worktree_get_root_path(worktree) : NULL);
10611 if (error)
10612 goto done;
10614 if (list_refs || remove_refs) {
10615 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10616 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10617 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10618 goto done;
10621 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10622 if (error != NULL)
10623 goto done;
10625 error = got_repo_match_object_id(&commit_id, NULL,
10626 keyword_idstr != NULL ? keyword_idstr : argv[0],
10627 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10628 if (error)
10629 goto done;
10630 error = got_object_id_str(&commit_id_str, commit_id);
10631 if (error)
10632 goto done;
10634 error = got_object_open_as_commit(&commit, repo, commit_id);
10635 if (error)
10636 goto done;
10637 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10638 if (pid == NULL) {
10639 error = got_error(GOT_ERR_ROOT_COMMIT);
10640 goto done;
10643 memset(&upa, 0, sizeof(upa));
10644 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10645 repo, update_progress, &upa, check_cancelled, NULL);
10646 if (error != NULL)
10647 goto done;
10649 if (upa.did_something) {
10650 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10651 worktree, repo);
10652 if (error)
10653 goto done;
10654 printf("Backed out commit %s\n", commit_id_str);
10656 print_merge_progress_stats(&upa);
10657 done:
10658 free(cwd);
10659 free(keyword_idstr);
10660 if (commit)
10661 got_object_commit_close(commit);
10662 free(commit_id_str);
10663 if (worktree)
10664 got_worktree_close(worktree);
10665 if (repo) {
10666 const struct got_error *close_err = got_repo_close(repo);
10667 if (error == NULL)
10668 error = close_err;
10670 if (pack_fds) {
10671 const struct got_error *pack_err =
10672 got_repo_pack_fds_close(pack_fds);
10673 if (error == NULL)
10674 error = pack_err;
10676 return error;
10679 __dead static void
10680 usage_rebase(void)
10682 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10683 exit(1);
10686 static void
10687 trim_logmsg(char *logmsg, int limit)
10689 char *nl;
10690 size_t len;
10692 len = strlen(logmsg);
10693 if (len > limit)
10694 len = limit;
10695 logmsg[len] = '\0';
10696 nl = strchr(logmsg, '\n');
10697 if (nl)
10698 *nl = '\0';
10701 static const struct got_error *
10702 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10704 const struct got_error *err;
10705 char *logmsg0 = NULL;
10706 const char *s;
10708 err = got_object_commit_get_logmsg(&logmsg0, commit);
10709 if (err)
10710 return err;
10712 s = logmsg0;
10713 while (isspace((unsigned char)s[0]))
10714 s++;
10716 *logmsg = strdup(s);
10717 if (*logmsg == NULL) {
10718 err = got_error_from_errno("strdup");
10719 goto done;
10722 trim_logmsg(*logmsg, limit);
10723 done:
10724 free(logmsg0);
10725 return err;
10728 static const struct got_error *
10729 show_rebase_merge_conflict(struct got_object_id *id,
10730 struct got_repository *repo)
10732 const struct got_error *err;
10733 struct got_commit_object *commit = NULL;
10734 char *id_str = NULL, *logmsg = NULL;
10736 err = got_object_open_as_commit(&commit, repo, id);
10737 if (err)
10738 return err;
10740 err = got_object_id_str(&id_str, id);
10741 if (err)
10742 goto done;
10744 id_str[12] = '\0';
10746 err = get_short_logmsg(&logmsg, 42, commit);
10747 if (err)
10748 goto done;
10750 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10751 done:
10752 free(id_str);
10753 got_object_commit_close(commit);
10754 free(logmsg);
10755 return err;
10758 static const struct got_error *
10759 show_rebase_progress(struct got_commit_object *commit,
10760 struct got_object_id *old_id, struct got_object_id *new_id)
10762 const struct got_error *err;
10763 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10765 err = got_object_id_str(&old_id_str, old_id);
10766 if (err)
10767 goto done;
10769 if (new_id) {
10770 err = got_object_id_str(&new_id_str, new_id);
10771 if (err)
10772 goto done;
10775 old_id_str[12] = '\0';
10776 if (new_id_str)
10777 new_id_str[12] = '\0';
10779 err = get_short_logmsg(&logmsg, 42, commit);
10780 if (err)
10781 goto done;
10783 printf("%s -> %s: %s\n", old_id_str,
10784 new_id_str ? new_id_str : "no-op change", logmsg);
10785 done:
10786 free(old_id_str);
10787 free(new_id_str);
10788 free(logmsg);
10789 return err;
10792 static const struct got_error *
10793 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10794 struct got_reference *branch, struct got_reference *tmp_branch,
10795 struct got_repository *repo, int create_backup)
10797 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10798 return got_worktree_rebase_complete(worktree, fileindex,
10799 tmp_branch, branch, repo, create_backup);
10802 static const struct got_error *
10803 rebase_commit(struct got_pathlist_head *merged_paths,
10804 struct got_worktree *worktree, struct got_fileindex *fileindex,
10805 struct got_reference *tmp_branch, const char *committer,
10806 struct got_object_id *commit_id, int allow_conflict,
10807 struct got_repository *repo)
10809 const struct got_error *error;
10810 struct got_commit_object *commit;
10811 struct got_object_id *new_commit_id;
10813 error = got_object_open_as_commit(&commit, repo, commit_id);
10814 if (error)
10815 return error;
10817 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10818 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10819 allow_conflict, repo);
10820 if (error) {
10821 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10822 goto done;
10823 error = show_rebase_progress(commit, commit_id, NULL);
10824 } else {
10825 error = show_rebase_progress(commit, commit_id, new_commit_id);
10826 free(new_commit_id);
10828 done:
10829 got_object_commit_close(commit);
10830 return error;
10833 struct check_path_prefix_arg {
10834 const char *path_prefix;
10835 size_t len;
10836 int errcode;
10839 static const struct got_error *
10840 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10841 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10842 struct got_object_id *id1, struct got_object_id *id2,
10843 const char *path1, const char *path2,
10844 mode_t mode1, mode_t mode2, struct got_repository *repo)
10846 struct check_path_prefix_arg *a = arg;
10848 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10849 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10850 return got_error(a->errcode);
10852 return NULL;
10855 static const struct got_error *
10856 check_path_prefix(struct got_object_id *parent_id,
10857 struct got_object_id *commit_id, const char *path_prefix,
10858 int errcode, struct got_repository *repo)
10860 const struct got_error *err;
10861 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10862 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10863 struct check_path_prefix_arg cpp_arg;
10865 if (got_path_is_root_dir(path_prefix))
10866 return NULL;
10868 err = got_object_open_as_commit(&commit, repo, commit_id);
10869 if (err)
10870 goto done;
10872 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10873 if (err)
10874 goto done;
10876 err = got_object_open_as_tree(&tree1, repo,
10877 got_object_commit_get_tree_id(parent_commit));
10878 if (err)
10879 goto done;
10881 err = got_object_open_as_tree(&tree2, repo,
10882 got_object_commit_get_tree_id(commit));
10883 if (err)
10884 goto done;
10886 cpp_arg.path_prefix = path_prefix;
10887 while (cpp_arg.path_prefix[0] == '/')
10888 cpp_arg.path_prefix++;
10889 cpp_arg.len = strlen(cpp_arg.path_prefix);
10890 cpp_arg.errcode = errcode;
10891 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10892 check_path_prefix_in_diff, &cpp_arg, 0);
10893 done:
10894 if (tree1)
10895 got_object_tree_close(tree1);
10896 if (tree2)
10897 got_object_tree_close(tree2);
10898 if (commit)
10899 got_object_commit_close(commit);
10900 if (parent_commit)
10901 got_object_commit_close(parent_commit);
10902 return err;
10905 static const struct got_error *
10906 collect_commits(struct got_object_id_queue *commits,
10907 struct got_object_id *initial_commit_id,
10908 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10909 const char *path_prefix, int path_prefix_errcode,
10910 struct got_repository *repo)
10912 const struct got_error *err = NULL;
10913 struct got_commit_graph *graph = NULL;
10914 struct got_object_id parent_id, commit_id;
10915 struct got_object_qid *qid;
10917 err = got_commit_graph_open(&graph, "/", 1);
10918 if (err)
10919 return err;
10921 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10922 check_cancelled, NULL);
10923 if (err)
10924 goto done;
10926 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10927 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10928 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10929 check_cancelled, NULL);
10930 if (err) {
10931 if (err->code == GOT_ERR_ITER_COMPLETED) {
10932 err = got_error_msg(GOT_ERR_ANCESTRY,
10933 "ran out of commits to rebase before "
10934 "youngest common ancestor commit has "
10935 "been reached?!?");
10937 goto done;
10938 } else {
10939 err = check_path_prefix(&parent_id, &commit_id,
10940 path_prefix, path_prefix_errcode, repo);
10941 if (err)
10942 goto done;
10944 err = got_object_qid_alloc(&qid, &commit_id);
10945 if (err)
10946 goto done;
10947 STAILQ_INSERT_HEAD(commits, qid, entry);
10949 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10952 done:
10953 got_commit_graph_close(graph);
10954 return err;
10957 static const struct got_error *
10958 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10960 const struct got_error *err = NULL;
10961 time_t committer_time;
10962 struct tm tm;
10963 char datebuf[11]; /* YYYY-MM-DD + NUL */
10964 char *author0 = NULL, *author, *smallerthan;
10965 char *logmsg0 = NULL, *logmsg, *newline;
10967 committer_time = got_object_commit_get_committer_time(commit);
10968 if (gmtime_r(&committer_time, &tm) == NULL)
10969 return got_error_from_errno("gmtime_r");
10970 if (strftime(datebuf, sizeof(datebuf), "%F", &tm) == 0)
10971 return got_error(GOT_ERR_NO_SPACE);
10973 author0 = strdup(got_object_commit_get_author(commit));
10974 if (author0 == NULL)
10975 return got_error_from_errno("strdup");
10976 author = author0;
10977 smallerthan = strchr(author, '<');
10978 if (smallerthan && smallerthan[1] != '\0')
10979 author = smallerthan + 1;
10980 author[strcspn(author, "@>")] = '\0';
10982 err = got_object_commit_get_logmsg(&logmsg0, commit);
10983 if (err)
10984 goto done;
10985 logmsg = logmsg0;
10986 while (*logmsg == '\n')
10987 logmsg++;
10988 newline = strchr(logmsg, '\n');
10989 if (newline)
10990 *newline = '\0';
10992 if (asprintf(brief_str, "%s %s %s",
10993 datebuf, author, logmsg) == -1)
10994 err = got_error_from_errno("asprintf");
10995 done:
10996 free(author0);
10997 free(logmsg0);
10998 return err;
11001 static const struct got_error *
11002 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11003 struct got_repository *repo)
11005 const struct got_error *err;
11006 char *id_str;
11008 err = got_object_id_str(&id_str, id);
11009 if (err)
11010 return err;
11012 err = got_ref_delete(ref, repo);
11013 if (err)
11014 goto done;
11016 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11017 done:
11018 free(id_str);
11019 return err;
11022 static const struct got_error *
11023 print_backup_ref(const char *branch_name, const char *new_id_str,
11024 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11025 struct got_reflist_object_id_map *refs_idmap,
11026 struct got_repository *repo)
11028 const struct got_error *err = NULL;
11029 struct got_reflist_head *refs;
11030 char *refs_str = NULL;
11031 struct got_object_id *new_commit_id = NULL;
11032 struct got_commit_object *new_commit = NULL;
11033 char *new_commit_brief_str = NULL;
11034 struct got_object_id *yca_id = NULL;
11035 struct got_commit_object *yca_commit = NULL;
11036 char *yca_id_str = NULL, *yca_brief_str = NULL;
11037 char *custom_refs_str;
11039 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11040 return got_error_from_errno("asprintf");
11042 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11043 0, 0, refs_idmap, custom_refs_str, NULL);
11044 if (err)
11045 goto done;
11047 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11048 if (err)
11049 goto done;
11051 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11052 if (refs) {
11053 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11054 if (err)
11055 goto done;
11058 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11059 if (err)
11060 goto done;
11062 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11063 if (err)
11064 goto done;
11066 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11067 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11068 if (err)
11069 goto done;
11071 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11072 refs_str ? " (" : "", refs_str ? refs_str : "",
11073 refs_str ? ")" : "", new_commit_brief_str);
11074 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11075 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11076 free(refs_str);
11077 refs_str = NULL;
11079 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11080 if (err)
11081 goto done;
11083 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11084 if (err)
11085 goto done;
11087 err = got_object_id_str(&yca_id_str, yca_id);
11088 if (err)
11089 goto done;
11091 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11092 if (refs) {
11093 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11094 if (err)
11095 goto done;
11097 printf("history forked at %s%s%s%s\n %s\n",
11098 yca_id_str,
11099 refs_str ? " (" : "", refs_str ? refs_str : "",
11100 refs_str ? ")" : "", yca_brief_str);
11102 done:
11103 free(custom_refs_str);
11104 free(new_commit_id);
11105 free(refs_str);
11106 free(yca_id);
11107 free(yca_id_str);
11108 free(yca_brief_str);
11109 if (new_commit)
11110 got_object_commit_close(new_commit);
11111 if (yca_commit)
11112 got_object_commit_close(yca_commit);
11114 return err;
11117 static const struct got_error *
11118 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11119 struct got_repository *repo)
11121 const struct got_error *err;
11122 struct got_reflist_head refs;
11123 struct got_reflist_entry *re;
11124 char *uuidstr = NULL;
11125 static char msg[160];
11127 TAILQ_INIT(&refs);
11129 err = got_worktree_get_uuid(&uuidstr, worktree);
11130 if (err)
11131 goto done;
11133 err = got_ref_list(&refs, repo, "refs/got/worktree",
11134 got_ref_cmp_by_name, repo);
11135 if (err)
11136 goto done;
11138 TAILQ_FOREACH(re, &refs, entry) {
11139 const char *cmd, *refname, *type;
11141 refname = got_ref_get_name(re->ref);
11143 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11144 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11145 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11146 cmd = "cherrypick";
11147 type = "cherrypicked";
11148 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11149 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11150 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11151 cmd = "backout";
11152 type = "backed-out";
11153 } else
11154 continue;
11156 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11157 continue;
11159 snprintf(msg, sizeof(msg),
11160 "work tree has references created by %s commits which "
11161 "must be removed with 'got %s -X' before running the %s "
11162 "command", type, cmd, caller);
11163 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11164 goto done;
11167 done:
11168 free(uuidstr);
11169 got_ref_list_free(&refs);
11170 return err;
11173 static const struct got_error *
11174 process_backup_refs(const char *backup_ref_prefix,
11175 const char *wanted_branch_name,
11176 int delete, struct got_repository *repo)
11178 const struct got_error *err;
11179 struct got_reflist_head refs, backup_refs;
11180 struct got_reflist_entry *re;
11181 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11182 struct got_object_id *old_commit_id = NULL;
11183 char *branch_name = NULL;
11184 struct got_commit_object *old_commit = NULL;
11185 struct got_reflist_object_id_map *refs_idmap = NULL;
11186 int wanted_branch_found = 0;
11188 TAILQ_INIT(&refs);
11189 TAILQ_INIT(&backup_refs);
11191 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11192 if (err)
11193 return err;
11195 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11196 if (err)
11197 goto done;
11199 if (wanted_branch_name) {
11200 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11201 wanted_branch_name += 11;
11204 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11205 got_ref_cmp_by_commit_timestamp_descending, repo);
11206 if (err)
11207 goto done;
11209 TAILQ_FOREACH(re, &backup_refs, entry) {
11210 const char *refname = got_ref_get_name(re->ref);
11211 char *slash;
11213 err = check_cancelled(NULL);
11214 if (err)
11215 break;
11217 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11218 if (err)
11219 break;
11221 err = got_object_open_as_commit(&old_commit, repo,
11222 old_commit_id);
11223 if (err)
11224 break;
11226 if (strncmp(backup_ref_prefix, refname,
11227 backup_ref_prefix_len) == 0)
11228 refname += backup_ref_prefix_len;
11230 while (refname[0] == '/')
11231 refname++;
11233 branch_name = strdup(refname);
11234 if (branch_name == NULL) {
11235 err = got_error_from_errno("strdup");
11236 break;
11238 slash = strrchr(branch_name, '/');
11239 if (slash) {
11240 *slash = '\0';
11241 refname += strlen(branch_name) + 1;
11244 if (wanted_branch_name == NULL ||
11245 strcmp(wanted_branch_name, branch_name) == 0) {
11246 wanted_branch_found = 1;
11247 if (delete) {
11248 err = delete_backup_ref(re->ref,
11249 old_commit_id, repo);
11250 } else {
11251 err = print_backup_ref(branch_name, refname,
11252 old_commit_id, old_commit, refs_idmap,
11253 repo);
11255 if (err)
11256 break;
11259 free(old_commit_id);
11260 old_commit_id = NULL;
11261 free(branch_name);
11262 branch_name = NULL;
11263 got_object_commit_close(old_commit);
11264 old_commit = NULL;
11267 if (wanted_branch_name && !wanted_branch_found) {
11268 err = got_error_fmt(GOT_ERR_NOT_REF,
11269 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11271 done:
11272 if (refs_idmap)
11273 got_reflist_object_id_map_free(refs_idmap);
11274 got_ref_list_free(&refs);
11275 got_ref_list_free(&backup_refs);
11276 free(old_commit_id);
11277 free(branch_name);
11278 if (old_commit)
11279 got_object_commit_close(old_commit);
11280 return err;
11283 static const struct got_error *
11284 abort_progress(void *arg, unsigned char status, const char *path)
11287 * Unversioned files should not clutter progress output when
11288 * an operation is aborted.
11290 if (status == GOT_STATUS_UNVERSIONED)
11291 return NULL;
11293 return update_progress(arg, status, path);
11296 static const struct got_error *
11297 find_merge_commit_yca(struct got_object_id **new_yca_id,
11298 struct got_object_id *branch_head_commit_id,
11299 struct got_object_id *yca_id,
11300 struct got_object_id *base_commit_id,
11301 struct got_repository *repo)
11303 const struct got_error *err = NULL;
11304 struct got_commit_graph *graph = NULL;
11305 struct got_commit_object *commit = NULL;
11307 *new_yca_id = NULL;
11309 err = got_commit_graph_open(&graph, "/", 1);
11310 if (err)
11311 return err;
11313 err = got_commit_graph_bfsort(graph, base_commit_id,
11314 repo, check_cancelled, NULL);
11315 if (err)
11316 goto done;
11318 for (;;) {
11319 struct got_object_id id;
11321 err = got_commit_graph_iter_next(&id, graph, repo,
11322 check_cancelled, NULL);
11323 if (err) {
11324 if (err->code == GOT_ERR_ITER_COMPLETED)
11325 err = NULL;
11326 break;
11329 err = got_object_open_as_commit(&commit, repo, &id);
11330 if (err)
11331 break;
11333 if (got_object_commit_get_nparents(commit) > 1) {
11334 /* Search for a better YCA using toposort. */
11335 err = got_commit_graph_find_youngest_common_ancestor(
11336 new_yca_id, base_commit_id, branch_head_commit_id,
11337 0, 1, repo, check_cancelled, NULL);
11338 break;
11341 if (got_object_id_cmp(&id, yca_id) == 0)
11342 break;
11343 got_object_commit_close(commit);
11344 commit = NULL;
11346 done:
11347 got_commit_graph_close(graph);
11348 if (commit)
11349 got_object_commit_close(commit);
11350 return err;
11353 static const struct got_error *
11354 cmd_rebase(int argc, char *argv[])
11356 const struct got_error *error = NULL;
11357 struct got_worktree *worktree = NULL;
11358 struct got_repository *repo = NULL;
11359 struct got_fileindex *fileindex = NULL;
11360 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11361 struct got_reference *branch = NULL;
11362 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11363 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11364 struct got_object_id *resume_commit_id = NULL;
11365 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11366 struct got_object_id *head_commit_id = NULL;
11367 struct got_reference *head_ref = NULL;
11368 struct got_commit_object *commit = NULL;
11369 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11370 int histedit_in_progress = 0, merge_in_progress = 0;
11371 int create_backup = 1, list_backups = 0, delete_backups = 0;
11372 int allow_conflict = 0;
11373 struct got_object_id_queue commits;
11374 struct got_pathlist_head merged_paths;
11375 const struct got_object_id_queue *parent_ids;
11376 struct got_object_qid *qid, *pid;
11377 struct got_update_progress_arg upa;
11378 int *pack_fds = NULL;
11380 STAILQ_INIT(&commits);
11381 TAILQ_INIT(&merged_paths);
11382 memset(&upa, 0, sizeof(upa));
11384 #ifndef PROFILE
11385 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11386 "unveil", NULL) == -1)
11387 err(1, "pledge");
11388 #endif
11390 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11391 switch (ch) {
11392 case 'a':
11393 abort_rebase = 1;
11394 break;
11395 case 'C':
11396 allow_conflict = 1;
11397 break;
11398 case 'c':
11399 continue_rebase = 1;
11400 break;
11401 case 'l':
11402 list_backups = 1;
11403 break;
11404 case 'X':
11405 delete_backups = 1;
11406 break;
11407 default:
11408 usage_rebase();
11409 /* NOTREACHED */
11413 argc -= optind;
11414 argv += optind;
11416 if (list_backups) {
11417 if (abort_rebase)
11418 option_conflict('l', 'a');
11419 if (allow_conflict)
11420 option_conflict('l', 'C');
11421 if (continue_rebase)
11422 option_conflict('l', 'c');
11423 if (delete_backups)
11424 option_conflict('l', 'X');
11425 if (argc != 0 && argc != 1)
11426 usage_rebase();
11427 } else if (delete_backups) {
11428 if (abort_rebase)
11429 option_conflict('X', 'a');
11430 if (allow_conflict)
11431 option_conflict('X', 'C');
11432 if (continue_rebase)
11433 option_conflict('X', 'c');
11434 if (list_backups)
11435 option_conflict('l', 'X');
11436 if (argc != 0 && argc != 1)
11437 usage_rebase();
11438 } else if (allow_conflict) {
11439 if (abort_rebase)
11440 option_conflict('C', 'a');
11441 if (!continue_rebase)
11442 errx(1, "-C option requires -c");
11443 } else {
11444 if (abort_rebase && continue_rebase)
11445 usage_rebase();
11446 else if (abort_rebase || continue_rebase) {
11447 if (argc != 0)
11448 usage_rebase();
11449 } else if (argc != 1)
11450 usage_rebase();
11453 cwd = getcwd(NULL, 0);
11454 if (cwd == NULL) {
11455 error = got_error_from_errno("getcwd");
11456 goto done;
11459 error = got_repo_pack_fds_open(&pack_fds);
11460 if (error != NULL)
11461 goto done;
11463 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11464 if (error) {
11465 if (list_backups || delete_backups) {
11466 if (error->code != GOT_ERR_NOT_WORKTREE)
11467 goto done;
11468 } else {
11469 if (error->code == GOT_ERR_NOT_WORKTREE)
11470 error = wrap_not_worktree_error(error,
11471 "rebase", cwd);
11472 goto done;
11476 error = get_gitconfig_path(&gitconfig_path);
11477 if (error)
11478 goto done;
11479 error = got_repo_open(&repo,
11480 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11481 gitconfig_path, pack_fds);
11482 if (error != NULL)
11483 goto done;
11485 if (worktree != NULL && !list_backups && !delete_backups) {
11486 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11487 if (error)
11488 goto done;
11491 error = get_author(&committer, repo, worktree);
11492 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11493 goto done;
11495 error = apply_unveil(got_repo_get_path(repo), 0,
11496 worktree ? got_worktree_get_root_path(worktree) : NULL);
11497 if (error)
11498 goto done;
11500 if (list_backups || delete_backups) {
11501 error = process_backup_refs(
11502 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11503 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11504 goto done; /* nothing else to do */
11507 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11508 worktree);
11509 if (error)
11510 goto done;
11511 if (histedit_in_progress) {
11512 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11513 goto done;
11516 error = got_worktree_merge_in_progress(&merge_in_progress,
11517 worktree, repo);
11518 if (error)
11519 goto done;
11520 if (merge_in_progress) {
11521 error = got_error(GOT_ERR_MERGE_BUSY);
11522 goto done;
11525 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11526 if (error)
11527 goto done;
11529 if (abort_rebase) {
11530 if (!rebase_in_progress) {
11531 error = got_error(GOT_ERR_NOT_REBASING);
11532 goto done;
11534 error = got_worktree_rebase_continue(&resume_commit_id,
11535 &new_base_branch, &tmp_branch, &branch, &fileindex,
11536 worktree, repo);
11537 if (error)
11538 goto done;
11539 printf("Switching work tree to %s\n",
11540 got_ref_get_symref_target(new_base_branch));
11541 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11542 new_base_branch, abort_progress, &upa);
11543 if (error)
11544 goto done;
11545 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11546 print_merge_progress_stats(&upa);
11547 goto done; /* nothing else to do */
11550 if (continue_rebase) {
11551 if (!rebase_in_progress) {
11552 error = got_error(GOT_ERR_NOT_REBASING);
11553 goto done;
11555 error = got_worktree_rebase_continue(&resume_commit_id,
11556 &new_base_branch, &tmp_branch, &branch, &fileindex,
11557 worktree, repo);
11558 if (error)
11559 goto done;
11561 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11562 committer, resume_commit_id, allow_conflict, repo);
11563 if (error)
11564 goto done;
11566 yca_id = got_object_id_dup(resume_commit_id);
11567 if (yca_id == NULL) {
11568 error = got_error_from_errno("got_object_id_dup");
11569 goto done;
11571 } else {
11572 error = got_ref_open(&branch, repo, argv[0], 0);
11573 if (error != NULL)
11574 goto done;
11575 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11576 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11577 "will not rebase a branch which lives outside "
11578 "the \"refs/heads/\" reference namespace");
11579 goto done;
11583 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11584 if (error)
11585 goto done;
11587 if (!continue_rebase) {
11588 struct got_object_id *base_commit_id;
11590 error = got_ref_open(&head_ref, repo,
11591 got_worktree_get_head_ref_name(worktree), 0);
11592 if (error)
11593 goto done;
11594 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11595 if (error)
11596 goto done;
11597 base_commit_id = got_worktree_get_base_commit_id(worktree);
11598 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11599 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11600 goto done;
11603 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11604 base_commit_id, branch_head_commit_id, 1, 0,
11605 repo, check_cancelled, NULL);
11606 if (error) {
11607 if (error->code == GOT_ERR_ANCESTRY) {
11608 error = got_error_msg(GOT_ERR_ANCESTRY,
11609 "specified branch shares no common "
11610 "ancestry with work tree's branch");
11612 goto done;
11616 * If a merge commit appears between the new base branch tip
11617 * and a YCA found via first-parent traversal then we might
11618 * find a better YCA using topologically sorted commits.
11620 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11621 struct got_object_id *better_yca_id;
11622 error = find_merge_commit_yca(&better_yca_id,
11623 branch_head_commit_id, yca_id,
11624 base_commit_id, repo);
11625 if (error)
11626 goto done;
11627 if (better_yca_id) {
11628 free(yca_id);
11629 yca_id = better_yca_id;
11633 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11634 struct got_pathlist_head paths;
11635 printf("%s is already based on %s\n",
11636 got_ref_get_name(branch),
11637 got_worktree_get_head_ref_name(worktree));
11638 error = switch_head_ref(branch, branch_head_commit_id,
11639 worktree, repo);
11640 if (error)
11641 goto done;
11642 error = got_worktree_set_base_commit_id(worktree, repo,
11643 branch_head_commit_id);
11644 if (error)
11645 goto done;
11646 TAILQ_INIT(&paths);
11647 error = got_pathlist_append(&paths, "", NULL);
11648 if (error)
11649 goto done;
11650 error = got_worktree_checkout_files(worktree,
11651 &paths, repo, update_progress, &upa,
11652 check_cancelled, NULL);
11653 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11654 if (error)
11655 goto done;
11656 if (upa.did_something) {
11657 char *id_str;
11658 error = got_object_id_str(&id_str,
11659 branch_head_commit_id);
11660 if (error)
11661 goto done;
11662 printf("Updated to %s: %s\n",
11663 got_worktree_get_head_ref_name(worktree),
11664 id_str);
11665 free(id_str);
11666 } else
11667 printf("Already up-to-date\n");
11668 print_update_progress_stats(&upa);
11669 goto done;
11673 commit_id = branch_head_commit_id;
11674 error = got_object_open_as_commit(&commit, repo, commit_id);
11675 if (error)
11676 goto done;
11678 parent_ids = got_object_commit_get_parent_ids(commit);
11679 pid = STAILQ_FIRST(parent_ids);
11680 if (pid) {
11681 error = collect_commits(&commits, commit_id, &pid->id,
11682 yca_id, got_worktree_get_path_prefix(worktree),
11683 GOT_ERR_REBASE_PATH, repo);
11684 if (error)
11685 goto done;
11688 got_object_commit_close(commit);
11689 commit = NULL;
11691 if (!continue_rebase) {
11692 error = got_worktree_rebase_prepare(&new_base_branch,
11693 &tmp_branch, &fileindex, worktree, branch, repo);
11694 if (error)
11695 goto done;
11698 if (STAILQ_EMPTY(&commits)) {
11699 if (continue_rebase) {
11700 error = rebase_complete(worktree, fileindex,
11701 branch, tmp_branch, repo, create_backup);
11702 goto done;
11703 } else {
11704 /* Fast-forward the reference of the branch. */
11705 struct got_object_id *new_head_commit_id;
11706 char *id_str;
11707 error = got_ref_resolve(&new_head_commit_id, repo,
11708 new_base_branch);
11709 if (error)
11710 goto done;
11711 error = got_object_id_str(&id_str, new_head_commit_id);
11712 if (error)
11713 goto done;
11714 printf("Forwarding %s to commit %s\n",
11715 got_ref_get_name(branch), id_str);
11716 free(id_str);
11717 error = got_ref_change_ref(branch,
11718 new_head_commit_id);
11719 if (error)
11720 goto done;
11721 /* No backup needed since objects did not change. */
11722 create_backup = 0;
11726 pid = NULL;
11727 STAILQ_FOREACH(qid, &commits, entry) {
11729 commit_id = &qid->id;
11730 parent_id = pid ? &pid->id : yca_id;
11731 pid = qid;
11733 memset(&upa, 0, sizeof(upa));
11734 error = got_worktree_rebase_merge_files(&merged_paths,
11735 worktree, fileindex, parent_id, commit_id, repo,
11736 update_progress, &upa, check_cancelled, NULL);
11737 if (error)
11738 goto done;
11740 print_merge_progress_stats(&upa);
11741 if (upa.conflicts > 0 || upa.missing > 0 ||
11742 upa.not_deleted > 0 || upa.unversioned > 0) {
11743 if (upa.conflicts > 0) {
11744 error = show_rebase_merge_conflict(&qid->id,
11745 repo);
11746 if (error)
11747 goto done;
11749 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11750 break;
11753 error = rebase_commit(&merged_paths, worktree, fileindex,
11754 tmp_branch, committer, commit_id, 0, repo);
11755 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11756 if (error)
11757 goto done;
11760 if (upa.conflicts > 0 || upa.missing > 0 ||
11761 upa.not_deleted > 0 || upa.unversioned > 0) {
11762 error = got_worktree_rebase_postpone(worktree, fileindex);
11763 if (error)
11764 goto done;
11765 if (upa.conflicts > 0 && upa.missing == 0 &&
11766 upa.not_deleted == 0 && upa.unversioned == 0) {
11767 error = got_error_msg(GOT_ERR_CONFLICTS,
11768 "conflicts must be resolved before rebasing "
11769 "can continue");
11770 } else if (upa.conflicts > 0) {
11771 error = got_error_msg(GOT_ERR_CONFLICTS,
11772 "conflicts must be resolved before rebasing "
11773 "can continue; changes destined for some "
11774 "files were not yet merged and should be "
11775 "merged manually if required before the "
11776 "rebase operation is continued");
11777 } else {
11778 error = got_error_msg(GOT_ERR_CONFLICTS,
11779 "changes destined for some files were not "
11780 "yet merged and should be merged manually "
11781 "if required before the rebase operation "
11782 "is continued");
11784 } else
11785 error = rebase_complete(worktree, fileindex, branch,
11786 tmp_branch, repo, create_backup);
11787 done:
11788 free(cwd);
11789 free(committer);
11790 free(gitconfig_path);
11791 got_object_id_queue_free(&commits);
11792 free(branch_head_commit_id);
11793 free(resume_commit_id);
11794 free(head_commit_id);
11795 free(yca_id);
11796 if (commit)
11797 got_object_commit_close(commit);
11798 if (branch)
11799 got_ref_close(branch);
11800 if (new_base_branch)
11801 got_ref_close(new_base_branch);
11802 if (tmp_branch)
11803 got_ref_close(tmp_branch);
11804 if (head_ref)
11805 got_ref_close(head_ref);
11806 if (worktree)
11807 got_worktree_close(worktree);
11808 if (repo) {
11809 const struct got_error *close_err = got_repo_close(repo);
11810 if (error == NULL)
11811 error = close_err;
11813 if (pack_fds) {
11814 const struct got_error *pack_err =
11815 got_repo_pack_fds_close(pack_fds);
11816 if (error == NULL)
11817 error = pack_err;
11819 return error;
11822 __dead static void
11823 usage_histedit(void)
11825 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11826 "[branch]\n", getprogname());
11827 exit(1);
11830 #define GOT_HISTEDIT_PICK 'p'
11831 #define GOT_HISTEDIT_EDIT 'e'
11832 #define GOT_HISTEDIT_FOLD 'f'
11833 #define GOT_HISTEDIT_DROP 'd'
11834 #define GOT_HISTEDIT_MESG 'm'
11836 static const struct got_histedit_cmd {
11837 unsigned char code;
11838 const char *name;
11839 const char *desc;
11840 } got_histedit_cmds[] = {
11841 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11842 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11843 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11844 "be used" },
11845 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11846 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11849 struct got_histedit_list_entry {
11850 TAILQ_ENTRY(got_histedit_list_entry) entry;
11851 struct got_object_id *commit_id;
11852 const struct got_histedit_cmd *cmd;
11853 char *logmsg;
11855 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11857 static const struct got_error *
11858 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11859 FILE *f, struct got_repository *repo)
11861 const struct got_error *err = NULL;
11862 char *logmsg = NULL, *id_str = NULL;
11863 struct got_commit_object *commit = NULL;
11864 int n;
11866 err = got_object_open_as_commit(&commit, repo, commit_id);
11867 if (err)
11868 goto done;
11870 err = get_short_logmsg(&logmsg, 34, commit);
11871 if (err)
11872 goto done;
11874 err = got_object_id_str(&id_str, commit_id);
11875 if (err)
11876 goto done;
11878 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11879 if (n < 0)
11880 err = got_ferror(f, GOT_ERR_IO);
11881 done:
11882 if (commit)
11883 got_object_commit_close(commit);
11884 free(id_str);
11885 free(logmsg);
11886 return err;
11889 static const struct got_error *
11890 histedit_write_commit_list(struct got_object_id_queue *commits,
11891 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11892 int edit_only, struct got_repository *repo)
11894 const struct got_error *err = NULL;
11895 struct got_object_qid *qid;
11896 const char *histedit_cmd = NULL;
11898 if (STAILQ_EMPTY(commits))
11899 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11901 STAILQ_FOREACH(qid, commits, entry) {
11902 histedit_cmd = got_histedit_cmds[0].name;
11903 if (drop_only)
11904 histedit_cmd = "drop";
11905 else if (edit_only)
11906 histedit_cmd = "edit";
11907 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11908 histedit_cmd = "fold";
11909 else if (edit_logmsg_only)
11910 histedit_cmd = "mesg";
11911 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11912 if (err)
11913 break;
11916 return err;
11919 static const struct got_error *
11920 write_cmd_list(FILE *f, const char *branch_name,
11921 struct got_object_id_queue *commits)
11923 const struct got_error *err = NULL;
11924 size_t i;
11925 int n;
11926 char *id_str;
11927 struct got_object_qid *qid;
11929 qid = STAILQ_FIRST(commits);
11930 err = got_object_id_str(&id_str, &qid->id);
11931 if (err)
11932 return err;
11934 n = fprintf(f,
11935 "# Editing the history of branch '%s' starting at\n"
11936 "# commit %s\n"
11937 "# Commits will be processed in order from top to "
11938 "bottom of this file.\n", branch_name, id_str);
11939 if (n < 0) {
11940 err = got_ferror(f, GOT_ERR_IO);
11941 goto done;
11944 n = fprintf(f, "# Available histedit commands:\n");
11945 if (n < 0) {
11946 err = got_ferror(f, GOT_ERR_IO);
11947 goto done;
11950 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11951 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11952 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11953 cmd->desc);
11954 if (n < 0) {
11955 err = got_ferror(f, GOT_ERR_IO);
11956 break;
11959 done:
11960 free(id_str);
11961 return err;
11964 static const struct got_error *
11965 histedit_syntax_error(int lineno)
11967 static char msg[42];
11968 int ret;
11970 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11971 lineno);
11972 if (ret < 0 || (size_t)ret >= sizeof(msg))
11973 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11975 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11978 static const struct got_error *
11979 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11980 char *logmsg, struct got_repository *repo)
11982 const struct got_error *err;
11983 struct got_commit_object *folded_commit = NULL;
11984 char *id_str, *folded_logmsg = NULL;
11986 err = got_object_id_str(&id_str, hle->commit_id);
11987 if (err)
11988 return err;
11990 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11991 if (err)
11992 goto done;
11994 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11995 if (err)
11996 goto done;
11997 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11998 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11999 folded_logmsg) == -1) {
12000 err = got_error_from_errno("asprintf");
12002 done:
12003 if (folded_commit)
12004 got_object_commit_close(folded_commit);
12005 free(id_str);
12006 free(folded_logmsg);
12007 return err;
12010 static struct got_histedit_list_entry *
12011 get_folded_commits(struct got_histedit_list_entry *hle)
12013 struct got_histedit_list_entry *prev, *folded = NULL;
12015 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12016 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12017 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12018 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12019 folded = prev;
12020 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12023 return folded;
12026 static const struct got_error *
12027 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12028 const char *editor, struct got_repository *repo)
12030 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12031 char *logmsg = NULL, *new_msg = NULL;
12032 const struct got_error *err = NULL;
12033 struct got_commit_object *commit = NULL;
12034 int logmsg_len;
12035 int fd = -1;
12036 struct got_histedit_list_entry *folded = NULL;
12038 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12039 if (err)
12040 return err;
12042 folded = get_folded_commits(hle);
12043 if (folded) {
12044 while (folded != hle) {
12045 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12046 folded = TAILQ_NEXT(folded, entry);
12047 continue;
12049 err = append_folded_commit_msg(&new_msg, folded,
12050 logmsg, repo);
12051 if (err)
12052 goto done;
12053 free(logmsg);
12054 logmsg = new_msg;
12055 folded = TAILQ_NEXT(folded, entry);
12059 err = got_object_id_str(&id_str, hle->commit_id);
12060 if (err)
12061 goto done;
12062 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12063 if (err)
12064 goto done;
12065 logmsg_len = asprintf(&new_msg,
12066 "%s\n# original log message of commit %s: %s",
12067 logmsg ? logmsg : "", id_str, orig_logmsg);
12068 if (logmsg_len == -1) {
12069 err = got_error_from_errno("asprintf");
12070 goto done;
12072 free(logmsg);
12073 logmsg = new_msg;
12075 err = got_object_id_str(&id_str, hle->commit_id);
12076 if (err)
12077 goto done;
12079 err = got_opentemp_named_fd(&logmsg_path, &fd,
12080 GOT_TMPDIR_STR "/got-logmsg", "");
12081 if (err)
12082 goto done;
12084 if (write(fd, logmsg, logmsg_len) == -1) {
12085 err = got_error_from_errno2("write", logmsg_path);
12086 goto done;
12088 if (close(fd) == -1) {
12089 err = got_error_from_errno2("close", logmsg_path);
12090 goto done;
12092 fd = -1;
12094 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12095 logmsg_len, 0);
12096 if (err) {
12097 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12098 goto done;
12099 err = NULL;
12100 hle->logmsg = strdup(new_msg);
12101 if (hle->logmsg == NULL)
12102 err = got_error_from_errno("strdup");
12104 done:
12105 if (fd != -1 && close(fd) == -1 && err == NULL)
12106 err = got_error_from_errno2("close", logmsg_path);
12107 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12108 err = got_error_from_errno2("unlink", logmsg_path);
12109 free(logmsg_path);
12110 free(logmsg);
12111 free(orig_logmsg);
12112 if (commit)
12113 got_object_commit_close(commit);
12114 return err;
12117 static const struct got_error *
12118 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12119 FILE *f, struct got_repository *repo)
12121 const struct got_error *err = NULL;
12122 char *line = NULL, *p, *end;
12123 size_t i, linesize = 0;
12124 ssize_t linelen;
12125 int lineno = 0;
12126 const struct got_histedit_cmd *cmd;
12127 struct got_object_id *commit_id = NULL;
12128 struct got_histedit_list_entry *hle = NULL;
12130 for (;;) {
12131 linelen = getline(&line, &linesize, f);
12132 if (linelen == -1) {
12133 const struct got_error *getline_err;
12134 if (feof(f))
12135 break;
12136 getline_err = got_error_from_errno("getline");
12137 err = got_ferror(f, getline_err->code);
12138 break;
12140 lineno++;
12141 p = line;
12142 while (isspace((unsigned char)p[0]))
12143 p++;
12144 if (p[0] == '#' || p[0] == '\0')
12145 continue;
12146 cmd = NULL;
12147 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12148 cmd = &got_histedit_cmds[i];
12149 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12150 isspace((unsigned char)p[strlen(cmd->name)])) {
12151 p += strlen(cmd->name);
12152 break;
12154 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12155 p++;
12156 break;
12159 if (i == nitems(got_histedit_cmds)) {
12160 err = histedit_syntax_error(lineno);
12161 break;
12163 while (isspace((unsigned char)p[0]))
12164 p++;
12165 end = p;
12166 while (end[0] && !isspace((unsigned char)end[0]))
12167 end++;
12168 *end = '\0';
12169 err = got_object_resolve_id_str(&commit_id, repo, p);
12170 if (err) {
12171 /* override error code */
12172 err = histedit_syntax_error(lineno);
12173 break;
12175 hle = malloc(sizeof(*hle));
12176 if (hle == NULL) {
12177 err = got_error_from_errno("malloc");
12178 break;
12180 hle->cmd = cmd;
12181 hle->commit_id = commit_id;
12182 hle->logmsg = NULL;
12183 commit_id = NULL;
12184 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12187 free(line);
12188 free(commit_id);
12189 return err;
12192 static const struct got_error *
12193 histedit_check_script(struct got_histedit_list *histedit_cmds,
12194 struct got_object_id_queue *commits, struct got_repository *repo)
12196 const struct got_error *err = NULL;
12197 struct got_object_qid *qid;
12198 struct got_histedit_list_entry *hle;
12199 static char msg[92];
12200 char *id_str;
12202 if (TAILQ_EMPTY(histedit_cmds))
12203 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12204 "histedit script contains no commands");
12205 if (STAILQ_EMPTY(commits))
12206 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12208 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12209 struct got_histedit_list_entry *hle2;
12210 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12211 if (hle == hle2)
12212 continue;
12213 if (got_object_id_cmp(hle->commit_id,
12214 hle2->commit_id) != 0)
12215 continue;
12216 err = got_object_id_str(&id_str, hle->commit_id);
12217 if (err)
12218 return err;
12219 snprintf(msg, sizeof(msg), "commit %s is listed "
12220 "more than once in histedit script", id_str);
12221 free(id_str);
12222 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12226 STAILQ_FOREACH(qid, commits, entry) {
12227 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12228 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12229 break;
12231 if (hle == NULL) {
12232 err = got_object_id_str(&id_str, &qid->id);
12233 if (err)
12234 return err;
12235 snprintf(msg, sizeof(msg),
12236 "commit %s missing from histedit script", id_str);
12237 free(id_str);
12238 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12242 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12243 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12244 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12245 "last commit in histedit script cannot be folded");
12247 return NULL;
12250 static const struct got_error *
12251 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12252 const char *editor, const char *path,
12253 struct got_object_id_queue *commits, struct got_repository *repo)
12255 const struct got_error *err = NULL;
12256 struct stat st, st2;
12257 struct timespec timeout;
12258 FILE *f = NULL;
12260 if (stat(path, &st) == -1) {
12261 err = got_error_from_errno2("stat", path);
12262 goto done;
12265 if (spawn_editor(editor, path) == -1) {
12266 err = got_error_from_errno("failed spawning editor");
12267 goto done;
12270 timeout.tv_sec = 0;
12271 timeout.tv_nsec = 1;
12272 nanosleep(&timeout, NULL);
12274 if (stat(path, &st2) == -1) {
12275 err = got_error_from_errno2("stat", path);
12276 goto done;
12279 if (st.st_size == st2.st_size &&
12280 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12281 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12282 "no changes made to histedit script, aborting");
12283 goto done;
12286 f = fopen(path, "re");
12287 if (f == NULL) {
12288 err = got_error_from_errno("fopen");
12289 goto done;
12291 err = histedit_parse_list(histedit_cmds, f, repo);
12292 if (err)
12293 goto done;
12295 err = histedit_check_script(histedit_cmds, commits, repo);
12296 done:
12297 if (f && fclose(f) == EOF && err == NULL)
12298 err = got_error_from_errno("fclose");
12299 return err;
12302 static const struct got_error *
12303 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12304 struct got_object_id_queue *, const char *, const char *, const char *,
12305 struct got_repository *);
12307 static const struct got_error *
12308 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12309 struct got_object_id_queue *commits, const char *branch_name,
12310 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12311 const char *editor, struct got_repository *repo)
12313 const struct got_error *err;
12314 FILE *f = NULL;
12315 char *path = NULL;
12317 err = got_opentemp_named(&path, &f, "got-histedit", "");
12318 if (err)
12319 return err;
12321 err = write_cmd_list(f, branch_name, commits);
12322 if (err)
12323 goto done;
12325 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12326 fold_only, drop_only, edit_only, repo);
12327 if (err)
12328 goto done;
12330 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12331 rewind(f);
12332 err = histedit_parse_list(histedit_cmds, f, repo);
12333 } else {
12334 if (fclose(f) == EOF) {
12335 err = got_error_from_errno("fclose");
12336 goto done;
12338 f = NULL;
12339 err = histedit_run_editor(histedit_cmds, editor, path,
12340 commits, repo);
12341 if (err) {
12342 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12343 err->code != GOT_ERR_HISTEDIT_CMD)
12344 goto done;
12345 err = histedit_edit_list_retry(histedit_cmds, err,
12346 commits, editor, path, branch_name, repo);
12349 done:
12350 if (f && fclose(f) == EOF && err == NULL)
12351 err = got_error_from_errno("fclose");
12352 if (path && unlink(path) != 0 && err == NULL)
12353 err = got_error_from_errno2("unlink", path);
12354 free(path);
12355 return err;
12358 static const struct got_error *
12359 histedit_save_list(struct got_histedit_list *histedit_cmds,
12360 struct got_worktree *worktree, struct got_repository *repo)
12362 const struct got_error *err = NULL;
12363 char *path = NULL;
12364 FILE *f = NULL;
12365 struct got_histedit_list_entry *hle;
12367 err = got_worktree_get_histedit_script_path(&path, worktree);
12368 if (err)
12369 return err;
12371 f = fopen(path, "we");
12372 if (f == NULL) {
12373 err = got_error_from_errno2("fopen", path);
12374 goto done;
12376 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12377 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12378 repo);
12379 if (err)
12380 break;
12382 done:
12383 if (f && fclose(f) == EOF && err == NULL)
12384 err = got_error_from_errno("fclose");
12385 free(path);
12386 return err;
12389 static void
12390 histedit_free_list(struct got_histedit_list *histedit_cmds)
12392 struct got_histedit_list_entry *hle;
12394 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12395 TAILQ_REMOVE(histedit_cmds, hle, entry);
12396 free(hle);
12400 static const struct got_error *
12401 histedit_load_list(struct got_histedit_list *histedit_cmds,
12402 const char *path, struct got_repository *repo)
12404 const struct got_error *err = NULL;
12405 FILE *f = NULL;
12407 f = fopen(path, "re");
12408 if (f == NULL) {
12409 err = got_error_from_errno2("fopen", path);
12410 goto done;
12413 err = histedit_parse_list(histedit_cmds, f, repo);
12414 done:
12415 if (f && fclose(f) == EOF && err == NULL)
12416 err = got_error_from_errno("fclose");
12417 return err;
12420 static const struct got_error *
12421 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12422 const struct got_error *edit_err, struct got_object_id_queue *commits,
12423 const char *editor, const char *path, const char *branch_name,
12424 struct got_repository *repo)
12426 const struct got_error *err = NULL, *prev_err = edit_err;
12427 int resp = ' ';
12429 while (resp != 'c' && resp != 'r' && resp != 'a') {
12430 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12431 "or (a)bort: ", getprogname(), prev_err->msg);
12432 resp = getchar();
12433 if (resp == '\n')
12434 resp = getchar();
12435 if (resp == 'c') {
12436 histedit_free_list(histedit_cmds);
12437 err = histedit_run_editor(histedit_cmds, editor, path,
12438 commits, repo);
12439 if (err) {
12440 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12441 err->code != GOT_ERR_HISTEDIT_CMD)
12442 break;
12443 prev_err = err;
12444 resp = ' ';
12445 continue;
12447 break;
12448 } else if (resp == 'r') {
12449 histedit_free_list(histedit_cmds);
12450 err = histedit_edit_script(histedit_cmds,
12451 commits, branch_name, 0, 0, 0, 0, editor, repo);
12452 if (err) {
12453 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12454 err->code != GOT_ERR_HISTEDIT_CMD)
12455 break;
12456 prev_err = err;
12457 resp = ' ';
12458 continue;
12460 break;
12461 } else if (resp == 'a') {
12462 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12463 break;
12464 } else
12465 printf("invalid response '%c'\n", resp);
12468 return err;
12471 static const struct got_error *
12472 histedit_complete(struct got_worktree *worktree,
12473 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12474 struct got_reference *branch, struct got_repository *repo)
12476 printf("Switching work tree to %s\n",
12477 got_ref_get_symref_target(branch));
12478 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12479 branch, repo);
12482 static const struct got_error *
12483 show_histedit_progress(struct got_commit_object *commit,
12484 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12486 const struct got_error *err;
12487 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12489 err = got_object_id_str(&old_id_str, hle->commit_id);
12490 if (err)
12491 goto done;
12493 if (new_id) {
12494 err = got_object_id_str(&new_id_str, new_id);
12495 if (err)
12496 goto done;
12499 old_id_str[12] = '\0';
12500 if (new_id_str)
12501 new_id_str[12] = '\0';
12503 if (hle->logmsg) {
12504 logmsg = strdup(hle->logmsg);
12505 if (logmsg == NULL) {
12506 err = got_error_from_errno("strdup");
12507 goto done;
12509 trim_logmsg(logmsg, 42);
12510 } else {
12511 err = get_short_logmsg(&logmsg, 42, commit);
12512 if (err)
12513 goto done;
12516 switch (hle->cmd->code) {
12517 case GOT_HISTEDIT_PICK:
12518 case GOT_HISTEDIT_EDIT:
12519 case GOT_HISTEDIT_MESG:
12520 printf("%s -> %s: %s\n", old_id_str,
12521 new_id_str ? new_id_str : "no-op change", logmsg);
12522 break;
12523 case GOT_HISTEDIT_DROP:
12524 case GOT_HISTEDIT_FOLD:
12525 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12526 logmsg);
12527 break;
12528 default:
12529 break;
12531 done:
12532 free(old_id_str);
12533 free(new_id_str);
12534 return err;
12537 static const struct got_error *
12538 histedit_commit(struct got_pathlist_head *merged_paths,
12539 struct got_worktree *worktree, struct got_fileindex *fileindex,
12540 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12541 const char *committer, int allow_conflict, const char *editor,
12542 struct got_repository *repo)
12544 const struct got_error *err;
12545 struct got_commit_object *commit;
12546 struct got_object_id *new_commit_id;
12548 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12549 && hle->logmsg == NULL) {
12550 err = histedit_edit_logmsg(hle, editor, repo);
12551 if (err)
12552 return err;
12555 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12556 if (err)
12557 return err;
12559 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12560 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12561 hle->logmsg, allow_conflict, repo);
12562 if (err) {
12563 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12564 goto done;
12565 err = show_histedit_progress(commit, hle, NULL);
12566 } else {
12567 err = show_histedit_progress(commit, hle, new_commit_id);
12568 free(new_commit_id);
12570 done:
12571 got_object_commit_close(commit);
12572 return err;
12575 static const struct got_error *
12576 histedit_skip_commit(struct got_histedit_list_entry *hle,
12577 struct got_worktree *worktree, struct got_repository *repo)
12579 const struct got_error *error;
12580 struct got_commit_object *commit;
12582 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12583 repo);
12584 if (error)
12585 return error;
12587 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12588 if (error)
12589 return error;
12591 error = show_histedit_progress(commit, hle, NULL);
12592 got_object_commit_close(commit);
12593 return error;
12596 static const struct got_error *
12597 check_local_changes(void *arg, unsigned char status,
12598 unsigned char staged_status, const char *path,
12599 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12600 struct got_object_id *commit_id, int dirfd, const char *de_name)
12602 int *have_local_changes = arg;
12604 switch (status) {
12605 case GOT_STATUS_ADD:
12606 case GOT_STATUS_DELETE:
12607 case GOT_STATUS_MODIFY:
12608 case GOT_STATUS_CONFLICT:
12609 *have_local_changes = 1;
12610 return got_error(GOT_ERR_CANCELLED);
12611 default:
12612 break;
12615 switch (staged_status) {
12616 case GOT_STATUS_ADD:
12617 case GOT_STATUS_DELETE:
12618 case GOT_STATUS_MODIFY:
12619 *have_local_changes = 1;
12620 return got_error(GOT_ERR_CANCELLED);
12621 default:
12622 break;
12625 return NULL;
12628 static const struct got_error *
12629 cmd_histedit(int argc, char *argv[])
12631 const struct got_error *error = NULL;
12632 struct got_worktree *worktree = NULL;
12633 struct got_fileindex *fileindex = NULL;
12634 struct got_repository *repo = NULL;
12635 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12636 struct got_reference *branch = NULL;
12637 struct got_reference *tmp_branch = NULL;
12638 struct got_object_id *resume_commit_id = NULL;
12639 struct got_object_id *base_commit_id = NULL;
12640 struct got_object_id *head_commit_id = NULL;
12641 struct got_commit_object *commit = NULL;
12642 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12643 struct got_update_progress_arg upa;
12644 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12645 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12646 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12647 const char *edit_script_path = NULL;
12648 char *editor = NULL;
12649 struct got_object_id_queue commits;
12650 struct got_pathlist_head merged_paths;
12651 const struct got_object_id_queue *parent_ids;
12652 struct got_object_qid *pid;
12653 struct got_histedit_list histedit_cmds;
12654 struct got_histedit_list_entry *hle;
12655 int *pack_fds = NULL;
12657 STAILQ_INIT(&commits);
12658 TAILQ_INIT(&histedit_cmds);
12659 TAILQ_INIT(&merged_paths);
12660 memset(&upa, 0, sizeof(upa));
12662 #ifndef PROFILE
12663 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12664 "unveil", NULL) == -1)
12665 err(1, "pledge");
12666 #endif
12668 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12669 switch (ch) {
12670 case 'a':
12671 abort_edit = 1;
12672 break;
12673 case 'C':
12674 allow_conflict = 1;
12675 break;
12676 case 'c':
12677 continue_edit = 1;
12678 break;
12679 case 'd':
12680 drop_only = 1;
12681 break;
12682 case 'e':
12683 edit_only = 1;
12684 break;
12685 case 'F':
12686 edit_script_path = optarg;
12687 break;
12688 case 'f':
12689 fold_only = 1;
12690 break;
12691 case 'l':
12692 list_backups = 1;
12693 break;
12694 case 'm':
12695 edit_logmsg_only = 1;
12696 break;
12697 case 'X':
12698 delete_backups = 1;
12699 break;
12700 default:
12701 usage_histedit();
12702 /* NOTREACHED */
12706 argc -= optind;
12707 argv += optind;
12709 if (abort_edit && allow_conflict)
12710 option_conflict('a', 'C');
12711 if (abort_edit && continue_edit)
12712 option_conflict('a', 'c');
12713 if (edit_script_path && allow_conflict)
12714 option_conflict('F', 'C');
12715 if (edit_script_path && edit_logmsg_only)
12716 option_conflict('F', 'm');
12717 if (abort_edit && edit_logmsg_only)
12718 option_conflict('a', 'm');
12719 if (edit_logmsg_only && allow_conflict)
12720 option_conflict('m', 'C');
12721 if (continue_edit && edit_logmsg_only)
12722 option_conflict('c', 'm');
12723 if (abort_edit && fold_only)
12724 option_conflict('a', 'f');
12725 if (fold_only && allow_conflict)
12726 option_conflict('f', 'C');
12727 if (continue_edit && fold_only)
12728 option_conflict('c', 'f');
12729 if (fold_only && edit_logmsg_only)
12730 option_conflict('f', 'm');
12731 if (edit_script_path && fold_only)
12732 option_conflict('F', 'f');
12733 if (abort_edit && edit_only)
12734 option_conflict('a', 'e');
12735 if (continue_edit && edit_only)
12736 option_conflict('c', 'e');
12737 if (edit_only && edit_logmsg_only)
12738 option_conflict('e', 'm');
12739 if (edit_script_path && edit_only)
12740 option_conflict('F', 'e');
12741 if (fold_only && edit_only)
12742 option_conflict('f', 'e');
12743 if (drop_only && abort_edit)
12744 option_conflict('d', 'a');
12745 if (drop_only && allow_conflict)
12746 option_conflict('d', 'C');
12747 if (drop_only && continue_edit)
12748 option_conflict('d', 'c');
12749 if (drop_only && edit_logmsg_only)
12750 option_conflict('d', 'm');
12751 if (drop_only && edit_only)
12752 option_conflict('d', 'e');
12753 if (drop_only && edit_script_path)
12754 option_conflict('d', 'F');
12755 if (drop_only && fold_only)
12756 option_conflict('d', 'f');
12757 if (list_backups) {
12758 if (abort_edit)
12759 option_conflict('l', 'a');
12760 if (allow_conflict)
12761 option_conflict('l', 'C');
12762 if (continue_edit)
12763 option_conflict('l', 'c');
12764 if (edit_script_path)
12765 option_conflict('l', 'F');
12766 if (edit_logmsg_only)
12767 option_conflict('l', 'm');
12768 if (drop_only)
12769 option_conflict('l', 'd');
12770 if (fold_only)
12771 option_conflict('l', 'f');
12772 if (edit_only)
12773 option_conflict('l', 'e');
12774 if (delete_backups)
12775 option_conflict('l', 'X');
12776 if (argc != 0 && argc != 1)
12777 usage_histedit();
12778 } else if (delete_backups) {
12779 if (abort_edit)
12780 option_conflict('X', 'a');
12781 if (allow_conflict)
12782 option_conflict('X', 'C');
12783 if (continue_edit)
12784 option_conflict('X', 'c');
12785 if (drop_only)
12786 option_conflict('X', 'd');
12787 if (edit_script_path)
12788 option_conflict('X', 'F');
12789 if (edit_logmsg_only)
12790 option_conflict('X', 'm');
12791 if (fold_only)
12792 option_conflict('X', 'f');
12793 if (edit_only)
12794 option_conflict('X', 'e');
12795 if (list_backups)
12796 option_conflict('X', 'l');
12797 if (argc != 0 && argc != 1)
12798 usage_histedit();
12799 } else if (allow_conflict && !continue_edit)
12800 errx(1, "-C option requires -c");
12801 else if (argc != 0)
12802 usage_histedit();
12804 cwd = getcwd(NULL, 0);
12805 if (cwd == NULL) {
12806 error = got_error_from_errno("getcwd");
12807 goto done;
12810 error = got_repo_pack_fds_open(&pack_fds);
12811 if (error != NULL)
12812 goto done;
12814 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12815 if (error) {
12816 if (list_backups || delete_backups) {
12817 if (error->code != GOT_ERR_NOT_WORKTREE)
12818 goto done;
12819 } else {
12820 if (error->code == GOT_ERR_NOT_WORKTREE)
12821 error = wrap_not_worktree_error(error,
12822 "histedit", cwd);
12823 goto done;
12827 if (list_backups || delete_backups) {
12828 error = got_repo_open(&repo,
12829 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12830 NULL, pack_fds);
12831 if (error != NULL)
12832 goto done;
12833 error = apply_unveil(got_repo_get_path(repo), 0,
12834 worktree ? got_worktree_get_root_path(worktree) : NULL);
12835 if (error)
12836 goto done;
12837 error = process_backup_refs(
12838 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12839 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12840 goto done; /* nothing else to do */
12841 } else {
12842 error = get_gitconfig_path(&gitconfig_path);
12843 if (error)
12844 goto done;
12845 error = got_repo_open(&repo,
12846 got_worktree_get_repo_path(worktree), gitconfig_path,
12847 pack_fds);
12848 if (error != NULL)
12849 goto done;
12850 error = get_editor(&editor);
12851 if (error)
12852 goto done;
12853 if (unveil(editor, "x") != 0) {
12854 error = got_error_from_errno2("unveil", editor);
12855 goto done;
12857 if (edit_script_path) {
12858 if (unveil(edit_script_path, "r") != 0) {
12859 error = got_error_from_errno2("unveil",
12860 edit_script_path);
12861 goto done;
12864 error = apply_unveil(got_repo_get_path(repo), 0,
12865 got_worktree_get_root_path(worktree));
12866 if (error)
12867 goto done;
12870 if (worktree != NULL && !list_backups && !delete_backups) {
12871 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12872 if (error)
12873 goto done;
12876 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12877 if (error)
12878 goto done;
12879 if (rebase_in_progress) {
12880 error = got_error(GOT_ERR_REBASING);
12881 goto done;
12884 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12885 repo);
12886 if (error)
12887 goto done;
12888 if (merge_in_progress) {
12889 error = got_error(GOT_ERR_MERGE_BUSY);
12890 goto done;
12893 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12894 if (error)
12895 goto done;
12897 if (edit_in_progress && edit_logmsg_only) {
12898 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12899 "histedit operation is in progress in this "
12900 "work tree and must be continued or aborted "
12901 "before the -m option can be used");
12902 goto done;
12904 if (edit_in_progress && drop_only) {
12905 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12906 "histedit operation is in progress in this "
12907 "work tree and must be continued or aborted "
12908 "before the -d option can be used");
12909 goto done;
12911 if (edit_in_progress && fold_only) {
12912 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12913 "histedit operation is in progress in this "
12914 "work tree and must be continued or aborted "
12915 "before the -f option can be used");
12916 goto done;
12918 if (edit_in_progress && edit_only) {
12919 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12920 "histedit operation is in progress in this "
12921 "work tree and must be continued or aborted "
12922 "before the -e option can be used");
12923 goto done;
12926 if (edit_in_progress && abort_edit) {
12927 error = got_worktree_histedit_continue(&resume_commit_id,
12928 &tmp_branch, &branch, &base_commit_id, &fileindex,
12929 worktree, repo);
12930 if (error)
12931 goto done;
12932 printf("Switching work tree to %s\n",
12933 got_ref_get_symref_target(branch));
12934 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12935 branch, base_commit_id, abort_progress, &upa);
12936 if (error)
12937 goto done;
12938 printf("Histedit of %s aborted\n",
12939 got_ref_get_symref_target(branch));
12940 print_merge_progress_stats(&upa);
12941 goto done; /* nothing else to do */
12942 } else if (abort_edit) {
12943 error = got_error(GOT_ERR_NOT_HISTEDIT);
12944 goto done;
12947 error = get_author(&committer, repo, worktree);
12948 if (error)
12949 goto done;
12951 if (continue_edit) {
12952 char *path;
12954 if (!edit_in_progress) {
12955 error = got_error(GOT_ERR_NOT_HISTEDIT);
12956 goto done;
12959 error = got_worktree_get_histedit_script_path(&path, worktree);
12960 if (error)
12961 goto done;
12963 error = histedit_load_list(&histedit_cmds, path, repo);
12964 free(path);
12965 if (error)
12966 goto done;
12968 error = got_worktree_histedit_continue(&resume_commit_id,
12969 &tmp_branch, &branch, &base_commit_id, &fileindex,
12970 worktree, repo);
12971 if (error)
12972 goto done;
12974 error = got_ref_resolve(&head_commit_id, repo, branch);
12975 if (error)
12976 goto done;
12978 error = got_object_open_as_commit(&commit, repo,
12979 head_commit_id);
12980 if (error)
12981 goto done;
12982 parent_ids = got_object_commit_get_parent_ids(commit);
12983 pid = STAILQ_FIRST(parent_ids);
12984 if (pid == NULL) {
12985 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12986 goto done;
12988 error = collect_commits(&commits, head_commit_id, &pid->id,
12989 base_commit_id, got_worktree_get_path_prefix(worktree),
12990 GOT_ERR_HISTEDIT_PATH, repo);
12991 got_object_commit_close(commit);
12992 commit = NULL;
12993 if (error)
12994 goto done;
12995 } else {
12996 if (edit_in_progress) {
12997 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12998 goto done;
13001 error = got_ref_open(&branch, repo,
13002 got_worktree_get_head_ref_name(worktree), 0);
13003 if (error != NULL)
13004 goto done;
13006 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13007 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13008 "will not edit commit history of a branch outside "
13009 "the \"refs/heads/\" reference namespace");
13010 goto done;
13013 error = got_ref_resolve(&head_commit_id, repo, branch);
13014 got_ref_close(branch);
13015 branch = NULL;
13016 if (error)
13017 goto done;
13019 error = got_object_open_as_commit(&commit, repo,
13020 head_commit_id);
13021 if (error)
13022 goto done;
13023 parent_ids = got_object_commit_get_parent_ids(commit);
13024 pid = STAILQ_FIRST(parent_ids);
13025 if (pid == NULL) {
13026 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13027 goto done;
13029 error = collect_commits(&commits, head_commit_id, &pid->id,
13030 got_worktree_get_base_commit_id(worktree),
13031 got_worktree_get_path_prefix(worktree),
13032 GOT_ERR_HISTEDIT_PATH, repo);
13033 got_object_commit_close(commit);
13034 commit = NULL;
13035 if (error)
13036 goto done;
13038 if (STAILQ_EMPTY(&commits)) {
13039 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13040 goto done;
13043 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13044 &base_commit_id, &fileindex, worktree, repo);
13045 if (error)
13046 goto done;
13048 if (edit_script_path) {
13049 error = histedit_load_list(&histedit_cmds,
13050 edit_script_path, repo);
13051 if (error) {
13052 got_worktree_histedit_abort(worktree, fileindex,
13053 repo, branch, base_commit_id,
13054 abort_progress, &upa);
13055 print_merge_progress_stats(&upa);
13056 goto done;
13058 } else {
13059 const char *branch_name;
13060 branch_name = got_ref_get_symref_target(branch);
13061 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13062 branch_name += 11;
13063 error = histedit_edit_script(&histedit_cmds, &commits,
13064 branch_name, edit_logmsg_only, fold_only,
13065 drop_only, edit_only, editor, repo);
13066 if (error) {
13067 got_worktree_histedit_abort(worktree, fileindex,
13068 repo, branch, base_commit_id,
13069 abort_progress, &upa);
13070 print_merge_progress_stats(&upa);
13071 goto done;
13076 error = histedit_save_list(&histedit_cmds, worktree,
13077 repo);
13078 if (error) {
13079 got_worktree_histedit_abort(worktree, fileindex,
13080 repo, branch, base_commit_id,
13081 abort_progress, &upa);
13082 print_merge_progress_stats(&upa);
13083 goto done;
13088 error = histedit_check_script(&histedit_cmds, &commits, repo);
13089 if (error)
13090 goto done;
13092 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13093 if (resume_commit_id) {
13094 if (got_object_id_cmp(hle->commit_id,
13095 resume_commit_id) != 0)
13096 continue;
13098 resume_commit_id = NULL;
13099 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13100 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13101 error = histedit_skip_commit(hle, worktree,
13102 repo);
13103 if (error)
13104 goto done;
13105 } else {
13106 struct got_pathlist_head paths;
13107 int have_changes = 0;
13109 TAILQ_INIT(&paths);
13110 error = got_pathlist_append(&paths, "", NULL);
13111 if (error)
13112 goto done;
13113 error = got_worktree_status(worktree, &paths,
13114 repo, 0, check_local_changes, &have_changes,
13115 check_cancelled, NULL);
13116 got_pathlist_free(&paths,
13117 GOT_PATHLIST_FREE_NONE);
13118 if (error) {
13119 if (error->code != GOT_ERR_CANCELLED)
13120 goto done;
13121 if (sigint_received || sigpipe_received)
13122 goto done;
13124 if (have_changes) {
13125 error = histedit_commit(NULL, worktree,
13126 fileindex, tmp_branch, hle,
13127 committer, allow_conflict, editor,
13128 repo);
13129 if (error)
13130 goto done;
13131 } else {
13132 error = got_object_open_as_commit(
13133 &commit, repo, hle->commit_id);
13134 if (error)
13135 goto done;
13136 error = show_histedit_progress(commit,
13137 hle, NULL);
13138 got_object_commit_close(commit);
13139 commit = NULL;
13140 if (error)
13141 goto done;
13144 continue;
13147 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13148 error = histedit_skip_commit(hle, worktree, repo);
13149 if (error)
13150 goto done;
13151 continue;
13153 error = got_object_open_as_commit(&commit, repo,
13154 hle->commit_id);
13155 if (error)
13156 goto done;
13157 parent_ids = got_object_commit_get_parent_ids(commit);
13158 pid = STAILQ_FIRST(parent_ids);
13160 error = got_worktree_histedit_merge_files(&merged_paths,
13161 worktree, fileindex, &pid->id, hle->commit_id, repo,
13162 update_progress, &upa, check_cancelled, NULL);
13163 if (error)
13164 goto done;
13165 got_object_commit_close(commit);
13166 commit = NULL;
13168 print_merge_progress_stats(&upa);
13169 if (upa.conflicts > 0 || upa.missing > 0 ||
13170 upa.not_deleted > 0 || upa.unversioned > 0) {
13171 if (upa.conflicts > 0) {
13172 error = show_rebase_merge_conflict(
13173 hle->commit_id, repo);
13174 if (error)
13175 goto done;
13177 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13178 break;
13181 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13182 char *id_str;
13183 error = got_object_id_str(&id_str, hle->commit_id);
13184 if (error)
13185 goto done;
13186 printf("Stopping histedit for amending commit %s\n",
13187 id_str);
13188 free(id_str);
13189 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13190 error = got_worktree_histedit_postpone(worktree,
13191 fileindex);
13192 goto done;
13193 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13194 error = histedit_skip_commit(hle, worktree, repo);
13195 if (error)
13196 goto done;
13197 continue;
13198 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13199 error = histedit_edit_logmsg(hle, editor, repo);
13200 if (error)
13201 goto done;
13204 error = histedit_commit(&merged_paths, worktree, fileindex,
13205 tmp_branch, hle, committer, allow_conflict, editor, repo);
13206 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13207 if (error)
13208 goto done;
13211 if (upa.conflicts > 0 || upa.missing > 0 ||
13212 upa.not_deleted > 0 || upa.unversioned > 0) {
13213 error = got_worktree_histedit_postpone(worktree, fileindex);
13214 if (error)
13215 goto done;
13216 if (upa.conflicts > 0 && upa.missing == 0 &&
13217 upa.not_deleted == 0 && upa.unversioned == 0) {
13218 error = got_error_msg(GOT_ERR_CONFLICTS,
13219 "conflicts must be resolved before histedit "
13220 "can continue");
13221 } else if (upa.conflicts > 0) {
13222 error = got_error_msg(GOT_ERR_CONFLICTS,
13223 "conflicts must be resolved before histedit "
13224 "can continue; changes destined for some "
13225 "files were not yet merged and should be "
13226 "merged manually if required before the "
13227 "histedit operation is continued");
13228 } else {
13229 error = got_error_msg(GOT_ERR_CONFLICTS,
13230 "changes destined for some files were not "
13231 "yet merged and should be merged manually "
13232 "if required before the histedit operation "
13233 "is continued");
13235 } else
13236 error = histedit_complete(worktree, fileindex, tmp_branch,
13237 branch, repo);
13238 done:
13239 free(cwd);
13240 free(editor);
13241 free(committer);
13242 free(gitconfig_path);
13243 got_object_id_queue_free(&commits);
13244 histedit_free_list(&histedit_cmds);
13245 free(head_commit_id);
13246 free(base_commit_id);
13247 free(resume_commit_id);
13248 if (commit)
13249 got_object_commit_close(commit);
13250 if (branch)
13251 got_ref_close(branch);
13252 if (tmp_branch)
13253 got_ref_close(tmp_branch);
13254 if (worktree)
13255 got_worktree_close(worktree);
13256 if (repo) {
13257 const struct got_error *close_err = got_repo_close(repo);
13258 if (error == NULL)
13259 error = close_err;
13261 if (pack_fds) {
13262 const struct got_error *pack_err =
13263 got_repo_pack_fds_close(pack_fds);
13264 if (error == NULL)
13265 error = pack_err;
13267 return error;
13270 __dead static void
13271 usage_integrate(void)
13273 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13274 exit(1);
13277 static const struct got_error *
13278 cmd_integrate(int argc, char *argv[])
13280 const struct got_error *error = NULL;
13281 struct got_repository *repo = NULL;
13282 struct got_worktree *worktree = NULL;
13283 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13284 const char *branch_arg = NULL;
13285 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13286 struct got_fileindex *fileindex = NULL;
13287 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13288 int ch;
13289 struct got_update_progress_arg upa;
13290 int *pack_fds = NULL;
13292 #ifndef PROFILE
13293 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13294 "unveil", NULL) == -1)
13295 err(1, "pledge");
13296 #endif
13298 while ((ch = getopt(argc, argv, "")) != -1) {
13299 switch (ch) {
13300 default:
13301 usage_integrate();
13302 /* NOTREACHED */
13306 argc -= optind;
13307 argv += optind;
13309 if (argc != 1)
13310 usage_integrate();
13311 branch_arg = argv[0];
13313 cwd = getcwd(NULL, 0);
13314 if (cwd == NULL) {
13315 error = got_error_from_errno("getcwd");
13316 goto done;
13319 error = got_repo_pack_fds_open(&pack_fds);
13320 if (error != NULL)
13321 goto done;
13323 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13324 if (error) {
13325 if (error->code == GOT_ERR_NOT_WORKTREE)
13326 error = wrap_not_worktree_error(error, "integrate",
13327 cwd);
13328 goto done;
13331 error = check_rebase_or_histedit_in_progress(worktree);
13332 if (error)
13333 goto done;
13335 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13336 NULL, pack_fds);
13337 if (error != NULL)
13338 goto done;
13340 error = apply_unveil(got_repo_get_path(repo), 0,
13341 got_worktree_get_root_path(worktree));
13342 if (error)
13343 goto done;
13345 error = check_merge_in_progress(worktree, repo);
13346 if (error)
13347 goto done;
13349 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13350 error = got_error_from_errno("asprintf");
13351 goto done;
13354 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13355 &base_branch_ref, worktree, refname, repo);
13356 if (error)
13357 goto done;
13359 refname = strdup(got_ref_get_name(branch_ref));
13360 if (refname == NULL) {
13361 error = got_error_from_errno("strdup");
13362 got_worktree_integrate_abort(worktree, fileindex, repo,
13363 branch_ref, base_branch_ref);
13364 goto done;
13366 base_refname = strdup(got_ref_get_name(base_branch_ref));
13367 if (base_refname == NULL) {
13368 error = got_error_from_errno("strdup");
13369 got_worktree_integrate_abort(worktree, fileindex, repo,
13370 branch_ref, base_branch_ref);
13371 goto done;
13373 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13374 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13375 got_worktree_integrate_abort(worktree, fileindex, repo,
13376 branch_ref, base_branch_ref);
13377 goto done;
13380 error = got_ref_resolve(&commit_id, repo, branch_ref);
13381 if (error)
13382 goto done;
13384 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13385 if (error)
13386 goto done;
13388 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13389 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13390 "specified branch has already been integrated");
13391 got_worktree_integrate_abort(worktree, fileindex, repo,
13392 branch_ref, base_branch_ref);
13393 goto done;
13396 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13397 if (error) {
13398 if (error->code == GOT_ERR_ANCESTRY)
13399 error = got_error(GOT_ERR_REBASE_REQUIRED);
13400 got_worktree_integrate_abort(worktree, fileindex, repo,
13401 branch_ref, base_branch_ref);
13402 goto done;
13405 memset(&upa, 0, sizeof(upa));
13406 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13407 branch_ref, base_branch_ref, update_progress, &upa,
13408 check_cancelled, NULL);
13409 if (error)
13410 goto done;
13412 printf("Integrated %s into %s\n", refname, base_refname);
13413 print_update_progress_stats(&upa);
13414 done:
13415 if (repo) {
13416 const struct got_error *close_err = got_repo_close(repo);
13417 if (error == NULL)
13418 error = close_err;
13420 if (worktree)
13421 got_worktree_close(worktree);
13422 if (pack_fds) {
13423 const struct got_error *pack_err =
13424 got_repo_pack_fds_close(pack_fds);
13425 if (error == NULL)
13426 error = pack_err;
13428 free(cwd);
13429 free(base_commit_id);
13430 free(commit_id);
13431 free(refname);
13432 free(base_refname);
13433 return error;
13436 __dead static void
13437 usage_merge(void)
13439 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13440 exit(1);
13443 static const struct got_error *
13444 cmd_merge(int argc, char *argv[])
13446 const struct got_error *error = NULL;
13447 struct got_worktree *worktree = NULL;
13448 struct got_repository *repo = NULL;
13449 struct got_fileindex *fileindex = NULL;
13450 char *cwd = NULL, *id_str = NULL, *author = NULL;
13451 char *gitconfig_path = NULL;
13452 struct got_reference *branch = NULL, *wt_branch = NULL;
13453 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13454 struct got_object_id *wt_branch_tip = NULL;
13455 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13456 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13457 struct got_update_progress_arg upa;
13458 struct got_object_id *merge_commit_id = NULL;
13459 char *branch_name = NULL;
13460 int *pack_fds = NULL;
13462 memset(&upa, 0, sizeof(upa));
13464 #ifndef PROFILE
13465 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13466 "unveil", NULL) == -1)
13467 err(1, "pledge");
13468 #endif
13470 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13471 switch (ch) {
13472 case 'a':
13473 abort_merge = 1;
13474 break;
13475 case 'C':
13476 allow_conflict = 1;
13477 break;
13478 case 'c':
13479 continue_merge = 1;
13480 break;
13481 case 'M':
13482 prefer_fast_forward = 0;
13483 break;
13484 case 'n':
13485 interrupt_merge = 1;
13486 break;
13487 default:
13488 usage_merge();
13489 /* NOTREACHED */
13493 argc -= optind;
13494 argv += optind;
13496 if (abort_merge) {
13497 if (continue_merge)
13498 option_conflict('a', 'c');
13499 if (!prefer_fast_forward)
13500 option_conflict('a', 'M');
13501 if (interrupt_merge)
13502 option_conflict('a', 'n');
13503 } else if (continue_merge) {
13504 if (!prefer_fast_forward)
13505 option_conflict('c', 'M');
13506 if (interrupt_merge)
13507 option_conflict('c', 'n');
13509 if (allow_conflict) {
13510 if (!continue_merge)
13511 errx(1, "-C option requires -c");
13513 if (abort_merge || continue_merge) {
13514 if (argc != 0)
13515 usage_merge();
13516 } else if (argc != 1)
13517 usage_merge();
13519 cwd = getcwd(NULL, 0);
13520 if (cwd == NULL) {
13521 error = got_error_from_errno("getcwd");
13522 goto done;
13525 error = got_repo_pack_fds_open(&pack_fds);
13526 if (error != NULL)
13527 goto done;
13529 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13530 if (error) {
13531 if (error->code == GOT_ERR_NOT_WORKTREE)
13532 error = wrap_not_worktree_error(error,
13533 "merge", cwd);
13534 goto done;
13537 error = get_gitconfig_path(&gitconfig_path);
13538 if (error)
13539 goto done;
13540 error = got_repo_open(&repo,
13541 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13542 gitconfig_path, pack_fds);
13543 if (error != NULL)
13544 goto done;
13546 if (worktree != NULL) {
13547 error = worktree_has_logmsg_ref("merge", worktree, repo);
13548 if (error)
13549 goto done;
13552 error = apply_unveil(got_repo_get_path(repo), 0,
13553 worktree ? got_worktree_get_root_path(worktree) : NULL);
13554 if (error)
13555 goto done;
13557 error = check_rebase_or_histedit_in_progress(worktree);
13558 if (error)
13559 goto done;
13561 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13562 repo);
13563 if (error)
13564 goto done;
13566 if (merge_in_progress && !(abort_merge || continue_merge)) {
13567 error = got_error(GOT_ERR_MERGE_BUSY);
13568 goto done;
13571 if (!merge_in_progress && (abort_merge || continue_merge)) {
13572 error = got_error(GOT_ERR_NOT_MERGING);
13573 goto done;
13576 if (abort_merge) {
13577 error = got_worktree_merge_continue(&branch_name,
13578 &branch_tip, &fileindex, worktree, repo);
13579 if (error)
13580 goto done;
13581 error = got_worktree_merge_abort(worktree, fileindex, repo,
13582 abort_progress, &upa);
13583 if (error)
13584 goto done;
13585 printf("Merge of %s aborted\n", branch_name);
13586 goto done; /* nothing else to do */
13589 if (strncmp(got_worktree_get_head_ref_name(worktree),
13590 "refs/heads/", 11) != 0) {
13591 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13592 "work tree's current branch %s is outside the "
13593 "\"refs/heads/\" reference namespace; "
13594 "update -b required",
13595 got_worktree_get_head_ref_name(worktree));
13596 goto done;
13599 error = get_author(&author, repo, worktree);
13600 if (error)
13601 goto done;
13603 error = got_ref_open(&wt_branch, repo,
13604 got_worktree_get_head_ref_name(worktree), 0);
13605 if (error)
13606 goto done;
13607 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13608 if (error)
13609 goto done;
13611 if (continue_merge) {
13612 struct got_object_id *base_commit_id;
13613 base_commit_id = got_worktree_get_base_commit_id(worktree);
13614 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13615 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13616 goto done;
13618 error = got_worktree_merge_continue(&branch_name,
13619 &branch_tip, &fileindex, worktree, repo);
13620 if (error)
13621 goto done;
13622 } else {
13623 error = got_ref_open(&branch, repo, argv[0], 0);
13624 if (error != NULL)
13625 goto done;
13626 branch_name = strdup(got_ref_get_name(branch));
13627 if (branch_name == NULL) {
13628 error = got_error_from_errno("strdup");
13629 goto done;
13631 error = got_ref_resolve(&branch_tip, repo, branch);
13632 if (error)
13633 goto done;
13636 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13637 wt_branch_tip, branch_tip, 0, 0, repo,
13638 check_cancelled, NULL);
13639 if (error && error->code != GOT_ERR_ANCESTRY)
13640 goto done;
13642 if (!continue_merge) {
13643 error = check_path_prefix(wt_branch_tip, branch_tip,
13644 got_worktree_get_path_prefix(worktree),
13645 GOT_ERR_MERGE_PATH, repo);
13646 if (error)
13647 goto done;
13648 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13649 if (error)
13650 goto done;
13651 if (prefer_fast_forward && yca_id &&
13652 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13653 struct got_pathlist_head paths;
13654 if (interrupt_merge) {
13655 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13656 "there are no changes to merge since %s "
13657 "is already based on %s; merge cannot be "
13658 "interrupted for amending; -n",
13659 branch_name, got_ref_get_name(wt_branch));
13660 goto done;
13662 printf("Forwarding %s to %s\n",
13663 got_ref_get_name(wt_branch), branch_name);
13664 error = got_ref_change_ref(wt_branch, branch_tip);
13665 if (error)
13666 goto done;
13667 error = got_ref_write(wt_branch, repo);
13668 if (error)
13669 goto done;
13670 error = got_worktree_set_base_commit_id(worktree, repo,
13671 branch_tip);
13672 if (error)
13673 goto done;
13674 TAILQ_INIT(&paths);
13675 error = got_pathlist_append(&paths, "", NULL);
13676 if (error)
13677 goto done;
13678 error = got_worktree_checkout_files(worktree,
13679 &paths, repo, update_progress, &upa,
13680 check_cancelled, NULL);
13681 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13682 if (error)
13683 goto done;
13684 if (upa.did_something) {
13685 char *id_str;
13686 error = got_object_id_str(&id_str, branch_tip);
13687 if (error)
13688 goto done;
13689 printf("Updated to commit %s\n", id_str);
13690 free(id_str);
13691 } else
13692 printf("Already up-to-date\n");
13693 print_update_progress_stats(&upa);
13694 goto done;
13696 error = got_worktree_merge_write_refs(worktree, branch, repo);
13697 if (error)
13698 goto done;
13700 error = got_worktree_merge_branch(worktree, fileindex,
13701 yca_id, branch_tip, repo, update_progress, &upa,
13702 check_cancelled, NULL);
13703 if (error)
13704 goto done;
13705 print_merge_progress_stats(&upa);
13706 if (!upa.did_something) {
13707 error = got_worktree_merge_abort(worktree, fileindex,
13708 repo, abort_progress, &upa);
13709 if (error)
13710 goto done;
13711 printf("Already up-to-date\n");
13712 goto done;
13716 if (interrupt_merge) {
13717 error = got_worktree_merge_postpone(worktree, fileindex);
13718 if (error)
13719 goto done;
13720 printf("Merge of %s interrupted on request\n", branch_name);
13721 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13722 upa.not_deleted > 0 || upa.unversioned > 0) {
13723 error = got_worktree_merge_postpone(worktree, fileindex);
13724 if (error)
13725 goto done;
13726 if (upa.conflicts > 0 && upa.missing == 0 &&
13727 upa.not_deleted == 0 && upa.unversioned == 0) {
13728 error = got_error_msg(GOT_ERR_CONFLICTS,
13729 "conflicts must be resolved before merging "
13730 "can continue");
13731 } else if (upa.conflicts > 0) {
13732 error = got_error_msg(GOT_ERR_CONFLICTS,
13733 "conflicts must be resolved before merging "
13734 "can continue; changes destined for some "
13735 "files were not yet merged and "
13736 "should be merged manually if required before the "
13737 "merge operation is continued");
13738 } else {
13739 error = got_error_msg(GOT_ERR_CONFLICTS,
13740 "changes destined for some "
13741 "files were not yet merged and should be "
13742 "merged manually if required before the "
13743 "merge operation is continued");
13745 goto done;
13746 } else {
13747 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13748 fileindex, author, NULL, 1, branch_tip, branch_name,
13749 allow_conflict, repo, continue_merge ? print_status : NULL,
13750 NULL);
13751 if (error)
13752 goto done;
13753 error = got_worktree_merge_complete(worktree, fileindex, repo);
13754 if (error)
13755 goto done;
13756 error = got_object_id_str(&id_str, merge_commit_id);
13757 if (error)
13758 goto done;
13759 printf("Merged %s into %s: %s\n", branch_name,
13760 got_worktree_get_head_ref_name(worktree),
13761 id_str);
13764 done:
13765 free(gitconfig_path);
13766 free(id_str);
13767 free(merge_commit_id);
13768 free(author);
13769 free(branch_tip);
13770 free(branch_name);
13771 free(yca_id);
13772 if (branch)
13773 got_ref_close(branch);
13774 if (wt_branch)
13775 got_ref_close(wt_branch);
13776 if (worktree)
13777 got_worktree_close(worktree);
13778 if (repo) {
13779 const struct got_error *close_err = got_repo_close(repo);
13780 if (error == NULL)
13781 error = close_err;
13783 if (pack_fds) {
13784 const struct got_error *pack_err =
13785 got_repo_pack_fds_close(pack_fds);
13786 if (error == NULL)
13787 error = pack_err;
13789 return error;
13792 __dead static void
13793 usage_stage(void)
13795 fprintf(stderr, "usage: %s stage [-lpRS] [-F response-script] "
13796 "[path ...]\n", getprogname());
13797 exit(1);
13800 static const struct got_error *
13801 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13802 const char *path, struct got_object_id *blob_id,
13803 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13804 int dirfd, const char *de_name)
13806 const struct got_error *err = NULL;
13807 char *id_str = NULL;
13809 if (staged_status != GOT_STATUS_ADD &&
13810 staged_status != GOT_STATUS_MODIFY &&
13811 staged_status != GOT_STATUS_DELETE)
13812 return NULL;
13814 if (staged_status == GOT_STATUS_ADD ||
13815 staged_status == GOT_STATUS_MODIFY)
13816 err = got_object_id_str(&id_str, staged_blob_id);
13817 else
13818 err = got_object_id_str(&id_str, blob_id);
13819 if (err)
13820 return err;
13822 printf("%s %c %s\n", id_str, staged_status, path);
13823 free(id_str);
13824 return NULL;
13827 static const struct got_error *
13828 cmd_stage(int argc, char *argv[])
13830 const struct got_error *error = NULL;
13831 struct got_repository *repo = NULL;
13832 struct got_worktree *worktree = NULL;
13833 char *cwd = NULL;
13834 struct got_pathlist_head paths;
13835 int ch, contains_dir;
13836 int can_recurse = 0, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13837 FILE *patch_script_file = NULL;
13838 const char *patch_script_path = NULL;
13839 struct choose_patch_arg cpa;
13840 int *pack_fds = NULL;
13842 TAILQ_INIT(&paths);
13844 #ifndef PROFILE
13845 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13846 "unveil", NULL) == -1)
13847 err(1, "pledge");
13848 #endif
13850 while ((ch = getopt(argc, argv, "F:lpRS")) != -1) {
13851 switch (ch) {
13852 case 'F':
13853 patch_script_path = optarg;
13854 break;
13855 case 'l':
13856 list_stage = 1;
13857 break;
13858 case 'p':
13859 pflag = 1;
13860 break;
13861 case 'R':
13862 can_recurse = 1;
13863 break;
13864 case 'S':
13865 allow_bad_symlinks = 1;
13866 break;
13867 default:
13868 usage_stage();
13869 /* NOTREACHED */
13873 argc -= optind;
13874 argv += optind;
13876 if (list_stage && (pflag || patch_script_path))
13877 errx(1, "-l option cannot be used with other options");
13878 if (patch_script_path && !pflag)
13879 errx(1, "-F option can only be used together with -p option");
13881 cwd = getcwd(NULL, 0);
13882 if (cwd == NULL) {
13883 error = got_error_from_errno("getcwd");
13884 goto done;
13887 error = got_repo_pack_fds_open(&pack_fds);
13888 if (error != NULL)
13889 goto done;
13891 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13892 if (error) {
13893 if (error->code == GOT_ERR_NOT_WORKTREE)
13894 error = wrap_not_worktree_error(error, "stage", cwd);
13895 goto done;
13898 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13899 NULL, pack_fds);
13900 if (error != NULL)
13901 goto done;
13903 if (patch_script_path) {
13904 patch_script_file = fopen(patch_script_path, "re");
13905 if (patch_script_file == NULL) {
13906 error = got_error_from_errno2("fopen",
13907 patch_script_path);
13908 goto done;
13911 error = apply_unveil(got_repo_get_path(repo), 0,
13912 got_worktree_get_root_path(worktree));
13913 if (error)
13914 goto done;
13916 error = check_merge_in_progress(worktree, repo);
13917 if (error)
13918 goto done;
13920 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13921 if (error)
13922 goto done;
13924 if (list_stage)
13925 error = got_worktree_status(worktree, &paths, repo, 0,
13926 print_stage, NULL, check_cancelled, NULL);
13927 else {
13928 if (!can_recurse) {
13929 error = pathlist_contains_directory(&contains_dir,
13930 worktree, &paths);
13931 if (error != NULL)
13932 goto done;
13934 if (contains_dir) {
13935 error = got_error_msg(GOT_ERR_BAD_PATH,
13936 "staging directories requires -R option");
13937 goto done;
13940 cpa.patch_script_file = patch_script_file;
13941 cpa.action = "stage";
13942 error = got_worktree_stage(worktree, &paths,
13943 pflag ? NULL : print_status, NULL,
13944 pflag ? choose_patch : NULL, &cpa,
13945 allow_bad_symlinks, repo);
13947 done:
13948 if (patch_script_file && fclose(patch_script_file) == EOF &&
13949 error == NULL)
13950 error = got_error_from_errno2("fclose", patch_script_path);
13951 if (repo) {
13952 const struct got_error *close_err = got_repo_close(repo);
13953 if (error == NULL)
13954 error = close_err;
13956 if (worktree)
13957 got_worktree_close(worktree);
13958 if (pack_fds) {
13959 const struct got_error *pack_err =
13960 got_repo_pack_fds_close(pack_fds);
13961 if (error == NULL)
13962 error = pack_err;
13964 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13965 free(cwd);
13966 return error;
13969 __dead static void
13970 usage_unstage(void)
13972 fprintf(stderr, "usage: %s unstage [-pR] [-F response-script] "
13973 "[path ...]\n", getprogname());
13974 exit(1);
13978 static const struct got_error *
13979 cmd_unstage(int argc, char *argv[])
13981 const struct got_error *error = NULL;
13982 struct got_repository *repo = NULL;
13983 struct got_worktree *worktree = NULL;
13984 char *cwd = NULL;
13985 struct got_pathlist_head paths;
13986 int ch, contains_dir, can_recurse = 0, pflag = 0;
13987 struct got_update_progress_arg upa;
13988 FILE *patch_script_file = NULL;
13989 const char *patch_script_path = NULL;
13990 struct choose_patch_arg cpa;
13991 int *pack_fds = NULL;
13993 TAILQ_INIT(&paths);
13995 #ifndef PROFILE
13996 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13997 "unveil", NULL) == -1)
13998 err(1, "pledge");
13999 #endif
14001 while ((ch = getopt(argc, argv, "F:Rp")) != -1) {
14002 switch (ch) {
14003 case 'F':
14004 patch_script_path = optarg;
14005 break;
14006 case 'R':
14007 can_recurse = 1;
14008 break;
14009 case 'p':
14010 pflag = 1;
14011 break;
14012 default:
14013 usage_unstage();
14014 /* NOTREACHED */
14018 argc -= optind;
14019 argv += optind;
14021 if (patch_script_path && !pflag)
14022 errx(1, "-F option can only be used together with -p option");
14024 cwd = getcwd(NULL, 0);
14025 if (cwd == NULL) {
14026 error = got_error_from_errno("getcwd");
14027 goto done;
14030 error = got_repo_pack_fds_open(&pack_fds);
14031 if (error != NULL)
14032 goto done;
14034 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14035 if (error) {
14036 if (error->code == GOT_ERR_NOT_WORKTREE)
14037 error = wrap_not_worktree_error(error, "unstage", cwd);
14038 goto done;
14041 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14042 NULL, pack_fds);
14043 if (error != NULL)
14044 goto done;
14046 if (patch_script_path) {
14047 patch_script_file = fopen(patch_script_path, "re");
14048 if (patch_script_file == NULL) {
14049 error = got_error_from_errno2("fopen",
14050 patch_script_path);
14051 goto done;
14055 error = apply_unveil(got_repo_get_path(repo), 0,
14056 got_worktree_get_root_path(worktree));
14057 if (error)
14058 goto done;
14060 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14061 if (error)
14062 goto done;
14064 if (!can_recurse) {
14065 error = pathlist_contains_directory(&contains_dir,
14066 worktree, &paths);
14067 if (error != NULL)
14068 goto done;
14070 if (contains_dir) {
14071 error = got_error_msg(GOT_ERR_BAD_PATH,
14072 "unstaging directories requires -R option");
14073 goto done;
14077 cpa.patch_script_file = patch_script_file;
14078 cpa.action = "unstage";
14079 memset(&upa, 0, sizeof(upa));
14080 error = got_worktree_unstage(worktree, &paths, update_progress,
14081 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14082 if (!error)
14083 print_merge_progress_stats(&upa);
14084 done:
14085 if (patch_script_file && fclose(patch_script_file) == EOF &&
14086 error == NULL)
14087 error = got_error_from_errno2("fclose", patch_script_path);
14088 if (repo) {
14089 const struct got_error *close_err = got_repo_close(repo);
14090 if (error == NULL)
14091 error = close_err;
14093 if (worktree)
14094 got_worktree_close(worktree);
14095 if (pack_fds) {
14096 const struct got_error *pack_err =
14097 got_repo_pack_fds_close(pack_fds);
14098 if (error == NULL)
14099 error = pack_err;
14101 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14102 free(cwd);
14103 return error;
14106 __dead static void
14107 usage_cat(void)
14109 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14110 "arg ...\n", getprogname());
14111 exit(1);
14114 static const struct got_error *
14115 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14117 const struct got_error *err;
14118 struct got_blob_object *blob;
14119 int fd = -1;
14121 fd = got_opentempfd();
14122 if (fd == -1)
14123 return got_error_from_errno("got_opentempfd");
14125 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14126 if (err)
14127 goto done;
14129 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14130 done:
14131 if (fd != -1 && close(fd) == -1 && err == NULL)
14132 err = got_error_from_errno("close");
14133 if (blob)
14134 got_object_blob_close(blob);
14135 return err;
14138 static const struct got_error *
14139 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14141 const struct got_error *err;
14142 struct got_tree_object *tree;
14143 int nentries, i;
14145 err = got_object_open_as_tree(&tree, repo, id);
14146 if (err)
14147 return err;
14149 nentries = got_object_tree_get_nentries(tree);
14150 for (i = 0; i < nentries; i++) {
14151 struct got_tree_entry *te;
14152 char *id_str;
14153 if (sigint_received || sigpipe_received)
14154 break;
14155 te = got_object_tree_get_entry(tree, i);
14156 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14157 if (err)
14158 break;
14159 fprintf(outfile, "%s %.7o %s\n", id_str,
14160 got_tree_entry_get_mode(te),
14161 got_tree_entry_get_name(te));
14162 free(id_str);
14165 got_object_tree_close(tree);
14166 return err;
14169 static const struct got_error *
14170 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14172 const struct got_error *err;
14173 struct got_commit_object *commit;
14174 const struct got_object_id_queue *parent_ids;
14175 struct got_object_qid *pid;
14176 char *id_str = NULL;
14177 const char *logmsg = NULL;
14178 char gmtoff[6];
14180 err = got_object_open_as_commit(&commit, repo, id);
14181 if (err)
14182 return err;
14184 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14185 if (err)
14186 goto done;
14188 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14189 parent_ids = got_object_commit_get_parent_ids(commit);
14190 fprintf(outfile, "numparents %d\n",
14191 got_object_commit_get_nparents(commit));
14192 STAILQ_FOREACH(pid, parent_ids, entry) {
14193 char *pid_str;
14194 err = got_object_id_str(&pid_str, &pid->id);
14195 if (err)
14196 goto done;
14197 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14198 free(pid_str);
14200 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14201 got_object_commit_get_author_gmtoff(commit));
14202 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14203 got_object_commit_get_author(commit),
14204 (long long)got_object_commit_get_author_time(commit),
14205 gmtoff);
14207 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14208 got_object_commit_get_committer_gmtoff(commit));
14209 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14210 got_object_commit_get_committer(commit),
14211 (long long)got_object_commit_get_committer_time(commit),
14212 gmtoff);
14214 logmsg = got_object_commit_get_logmsg_raw(commit);
14215 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14216 fprintf(outfile, "%s", logmsg);
14217 done:
14218 free(id_str);
14219 got_object_commit_close(commit);
14220 return err;
14223 static const struct got_error *
14224 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14226 const struct got_error *err;
14227 struct got_tag_object *tag;
14228 char *id_str = NULL;
14229 const char *tagmsg = NULL;
14230 char gmtoff[6];
14232 err = got_object_open_as_tag(&tag, repo, id);
14233 if (err)
14234 return err;
14236 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14237 if (err)
14238 goto done;
14240 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14242 switch (got_object_tag_get_object_type(tag)) {
14243 case GOT_OBJ_TYPE_BLOB:
14244 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14245 GOT_OBJ_LABEL_BLOB);
14246 break;
14247 case GOT_OBJ_TYPE_TREE:
14248 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14249 GOT_OBJ_LABEL_TREE);
14250 break;
14251 case GOT_OBJ_TYPE_COMMIT:
14252 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14253 GOT_OBJ_LABEL_COMMIT);
14254 break;
14255 case GOT_OBJ_TYPE_TAG:
14256 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14257 GOT_OBJ_LABEL_TAG);
14258 break;
14259 default:
14260 break;
14263 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14264 got_object_tag_get_name(tag));
14266 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14267 got_object_tag_get_tagger_gmtoff(tag));
14268 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14269 got_object_tag_get_tagger(tag),
14270 (long long)got_object_tag_get_tagger_time(tag),
14271 gmtoff);
14273 tagmsg = got_object_tag_get_message(tag);
14274 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14275 fprintf(outfile, "%s", tagmsg);
14276 done:
14277 free(id_str);
14278 got_object_tag_close(tag);
14279 return err;
14282 static const struct got_error *
14283 cmd_cat(int argc, char *argv[])
14285 const struct got_error *error;
14286 struct got_repository *repo = NULL;
14287 struct got_worktree *worktree = NULL;
14288 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14289 char *keyword_idstr = NULL;
14290 const char *commit_id_str = NULL;
14291 struct got_object_id *id = NULL, *commit_id = NULL;
14292 struct got_commit_object *commit = NULL;
14293 int ch, obj_type, i, force_path = 0;
14294 struct got_reflist_head refs;
14295 int *pack_fds = NULL;
14297 TAILQ_INIT(&refs);
14299 #ifndef PROFILE
14300 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14301 NULL) == -1)
14302 err(1, "pledge");
14303 #endif
14305 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14306 switch (ch) {
14307 case 'c':
14308 commit_id_str = optarg;
14309 break;
14310 case 'P':
14311 force_path = 1;
14312 break;
14313 case 'r':
14314 repo_path = realpath(optarg, NULL);
14315 if (repo_path == NULL)
14316 return got_error_from_errno2("realpath",
14317 optarg);
14318 got_path_strip_trailing_slashes(repo_path);
14319 break;
14320 default:
14321 usage_cat();
14322 /* NOTREACHED */
14326 argc -= optind;
14327 argv += optind;
14329 cwd = getcwd(NULL, 0);
14330 if (cwd == NULL) {
14331 error = got_error_from_errno("getcwd");
14332 goto done;
14335 error = got_repo_pack_fds_open(&pack_fds);
14336 if (error != NULL)
14337 goto done;
14339 if (repo_path == NULL) {
14340 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14342 goto done;
14343 if (worktree) {
14344 repo_path = strdup(
14345 got_worktree_get_repo_path(worktree));
14346 if (repo_path == NULL) {
14347 error = got_error_from_errno("strdup");
14348 goto done;
14351 if (commit_id_str == NULL) {
14352 /* Release work tree lock. */
14353 got_worktree_close(worktree);
14354 worktree = NULL;
14359 if (repo_path == NULL) {
14360 repo_path = strdup(cwd);
14361 if (repo_path == NULL)
14362 return got_error_from_errno("strdup");
14365 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14366 free(repo_path);
14367 if (error != NULL)
14368 goto done;
14370 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14371 if (error)
14372 goto done;
14374 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14375 if (error)
14376 goto done;
14378 if (commit_id_str != NULL) {
14379 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14380 repo, worktree);
14381 if (error != NULL)
14382 goto done;
14383 if (keyword_idstr != NULL)
14384 commit_id_str = keyword_idstr;
14385 if (worktree != NULL) {
14386 got_worktree_close(worktree);
14387 worktree = NULL;
14389 } else
14390 commit_id_str = GOT_REF_HEAD;
14391 error = got_repo_match_object_id(&commit_id, NULL,
14392 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14393 if (error)
14394 goto done;
14396 error = got_object_open_as_commit(&commit, repo, commit_id);
14397 if (error)
14398 goto done;
14400 for (i = 0; i < argc; i++) {
14401 if (force_path) {
14402 error = got_object_id_by_path(&id, repo, commit,
14403 argv[i]);
14404 if (error)
14405 break;
14406 } else {
14407 error = got_repo_match_object_id(&id, &label, argv[i],
14408 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14409 repo);
14410 if (error) {
14411 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14412 error->code != GOT_ERR_NOT_REF)
14413 break;
14414 error = got_object_id_by_path(&id, repo,
14415 commit, argv[i]);
14416 if (error)
14417 break;
14421 error = got_object_get_type(&obj_type, repo, id);
14422 if (error)
14423 break;
14425 switch (obj_type) {
14426 case GOT_OBJ_TYPE_BLOB:
14427 error = cat_blob(id, repo, stdout);
14428 break;
14429 case GOT_OBJ_TYPE_TREE:
14430 error = cat_tree(id, repo, stdout);
14431 break;
14432 case GOT_OBJ_TYPE_COMMIT:
14433 error = cat_commit(id, repo, stdout);
14434 break;
14435 case GOT_OBJ_TYPE_TAG:
14436 error = cat_tag(id, repo, stdout);
14437 break;
14438 default:
14439 error = got_error(GOT_ERR_OBJ_TYPE);
14440 break;
14442 if (error)
14443 break;
14444 free(label);
14445 label = NULL;
14446 free(id);
14447 id = NULL;
14449 done:
14450 free(label);
14451 free(id);
14452 free(commit_id);
14453 free(keyword_idstr);
14454 if (commit)
14455 got_object_commit_close(commit);
14456 if (worktree)
14457 got_worktree_close(worktree);
14458 if (repo) {
14459 const struct got_error *close_err = got_repo_close(repo);
14460 if (error == NULL)
14461 error = close_err;
14463 if (pack_fds) {
14464 const struct got_error *pack_err =
14465 got_repo_pack_fds_close(pack_fds);
14466 if (error == NULL)
14467 error = pack_err;
14470 got_ref_list_free(&refs);
14471 return error;
14474 __dead static void
14475 usage_info(void)
14477 fprintf(stderr, "usage: %s info [path ...]\n",
14478 getprogname());
14479 exit(1);
14482 static const struct got_error *
14483 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14484 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14485 struct got_object_id *commit_id)
14487 const struct got_error *err = NULL;
14488 char *id_str = NULL;
14489 char datebuf[128];
14490 struct tm mytm, *tm;
14491 struct got_pathlist_head *paths = arg;
14492 struct got_pathlist_entry *pe;
14495 * Clear error indication from any of the path arguments which
14496 * would cause this file index entry to be displayed.
14498 TAILQ_FOREACH(pe, paths, entry) {
14499 if (got_path_cmp(path, pe->path, strlen(path),
14500 pe->path_len) == 0 ||
14501 got_path_is_child(path, pe->path, pe->path_len))
14502 pe->data = NULL; /* no error */
14505 printf(GOT_COMMIT_SEP_STR);
14506 if (S_ISLNK(mode))
14507 printf("symlink: %s\n", path);
14508 else if (S_ISREG(mode)) {
14509 printf("file: %s\n", path);
14510 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14511 } else if (S_ISDIR(mode))
14512 printf("directory: %s\n", path);
14513 else
14514 printf("something: %s\n", path);
14516 tm = localtime_r(&mtime, &mytm);
14517 if (tm == NULL)
14518 return NULL;
14519 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14520 return got_error(GOT_ERR_NO_SPACE);
14521 printf("timestamp: %s\n", datebuf);
14523 if (blob_id) {
14524 err = got_object_id_str(&id_str, blob_id);
14525 if (err)
14526 return err;
14527 printf("based on blob: %s\n", id_str);
14528 free(id_str);
14531 if (staged_blob_id) {
14532 err = got_object_id_str(&id_str, staged_blob_id);
14533 if (err)
14534 return err;
14535 printf("based on staged blob: %s\n", id_str);
14536 free(id_str);
14539 if (commit_id) {
14540 err = got_object_id_str(&id_str, commit_id);
14541 if (err)
14542 return err;
14543 printf("based on commit: %s\n", id_str);
14544 free(id_str);
14547 return NULL;
14550 static const struct got_error *
14551 cmd_info(int argc, char *argv[])
14553 const struct got_error *error = NULL;
14554 struct got_worktree *worktree = NULL;
14555 char *cwd = NULL, *id_str = NULL;
14556 struct got_pathlist_head paths;
14557 char *uuidstr = NULL;
14558 int ch, show_files = 0;
14560 TAILQ_INIT(&paths);
14562 #ifndef PROFILE
14563 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14564 NULL) == -1)
14565 err(1, "pledge");
14566 #endif
14568 while ((ch = getopt(argc, argv, "")) != -1) {
14569 switch (ch) {
14570 default:
14571 usage_info();
14572 /* NOTREACHED */
14576 argc -= optind;
14577 argv += optind;
14579 cwd = getcwd(NULL, 0);
14580 if (cwd == NULL) {
14581 error = got_error_from_errno("getcwd");
14582 goto done;
14585 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14586 if (error) {
14587 if (error->code == GOT_ERR_NOT_WORKTREE)
14588 error = wrap_not_worktree_error(error, "info", cwd);
14589 goto done;
14592 #ifndef PROFILE
14593 /* Remove "wpath cpath proc exec sendfd" promises. */
14594 if (pledge("stdio rpath flock unveil", NULL) == -1)
14595 err(1, "pledge");
14596 #endif
14597 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14598 if (error)
14599 goto done;
14601 if (argc >= 1) {
14602 error = get_worktree_paths_from_argv(&paths, argc, argv,
14603 worktree);
14604 if (error)
14605 goto done;
14606 show_files = 1;
14609 error = got_object_id_str(&id_str,
14610 got_worktree_get_base_commit_id(worktree));
14611 if (error)
14612 goto done;
14614 error = got_worktree_get_uuid(&uuidstr, worktree);
14615 if (error)
14616 goto done;
14618 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14619 printf("work tree base commit: %s\n", id_str);
14620 printf("work tree path prefix: %s\n",
14621 got_worktree_get_path_prefix(worktree));
14622 printf("work tree branch reference: %s\n",
14623 got_worktree_get_head_ref_name(worktree));
14624 printf("work tree UUID: %s\n", uuidstr);
14625 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14627 if (show_files) {
14628 struct got_pathlist_entry *pe;
14629 TAILQ_FOREACH(pe, &paths, entry) {
14630 if (pe->path_len == 0)
14631 continue;
14633 * Assume this path will fail. This will be corrected
14634 * in print_path_info() in case the path does suceeed.
14636 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14638 error = got_worktree_path_info(worktree, &paths,
14639 print_path_info, &paths, check_cancelled, NULL);
14640 if (error)
14641 goto done;
14642 TAILQ_FOREACH(pe, &paths, entry) {
14643 if (pe->data != NULL) {
14644 const struct got_error *perr;
14646 perr = pe->data;
14647 error = got_error_fmt(perr->code, "%s",
14648 pe->path);
14649 break;
14653 done:
14654 if (worktree)
14655 got_worktree_close(worktree);
14656 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14657 free(cwd);
14658 free(id_str);
14659 free(uuidstr);
14660 return error;