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 "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.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>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 static volatile sig_atomic_t sigint_received;
71 static volatile sig_atomic_t sigpipe_received;
73 static void
74 catch_sigint(int signo)
75 {
76 sigint_received = 1;
77 }
79 static void
80 catch_sigpipe(int signo)
81 {
82 sigpipe_received = 1;
83 }
86 struct got_cmd {
87 const char *cmd_name;
88 const struct got_error *(*cmd_main)(int, char *[]);
89 void (*cmd_usage)(void);
90 const char *cmd_alias;
91 };
93 __dead static void usage(int, int);
94 __dead static void usage_import(void);
95 __dead static void usage_clone(void);
96 __dead static void usage_fetch(void);
97 __dead static void usage_checkout(void);
98 __dead static void usage_update(void);
99 __dead static void usage_log(void);
100 __dead static void usage_diff(void);
101 __dead static void usage_blame(void);
102 __dead static void usage_tree(void);
103 __dead static void usage_status(void);
104 __dead static void usage_ref(void);
105 __dead static void usage_branch(void);
106 __dead static void usage_tag(void);
107 __dead static void usage_add(void);
108 __dead static void usage_remove(void);
109 __dead static void usage_patch(void);
110 __dead static void usage_revert(void);
111 __dead static void usage_commit(void);
112 __dead static void usage_send(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_rebase(void);
116 __dead static void usage_histedit(void);
117 __dead static void usage_integrate(void);
118 __dead static void usage_merge(void);
119 __dead static void usage_stage(void);
120 __dead static void usage_unstage(void);
121 __dead static void usage_cat(void);
122 __dead static void usage_info(void);
124 static const struct got_error* cmd_import(int, char *[]);
125 static const struct got_error* cmd_clone(int, char *[]);
126 static const struct got_error* cmd_fetch(int, char *[]);
127 static const struct got_error* cmd_checkout(int, char *[]);
128 static const struct got_error* cmd_update(int, char *[]);
129 static const struct got_error* cmd_log(int, char *[]);
130 static const struct got_error* cmd_diff(int, char *[]);
131 static const struct got_error* cmd_blame(int, char *[]);
132 static const struct got_error* cmd_tree(int, char *[]);
133 static const struct got_error* cmd_status(int, char *[]);
134 static const struct got_error* cmd_ref(int, char *[]);
135 static const struct got_error* cmd_branch(int, char *[]);
136 static const struct got_error* cmd_tag(int, char *[]);
137 static const struct got_error* cmd_add(int, char *[]);
138 static const struct got_error* cmd_remove(int, char *[]);
139 static const struct got_error* cmd_patch(int, char *[]);
140 static const struct got_error* cmd_revert(int, char *[]);
141 static const struct got_error* cmd_commit(int, char *[]);
142 static const struct got_error* cmd_send(int, char *[]);
143 static const struct got_error* cmd_cherrypick(int, char *[]);
144 static const struct got_error* cmd_backout(int, char *[]);
145 static const struct got_error* cmd_rebase(int, char *[]);
146 static const struct got_error* cmd_histedit(int, char *[]);
147 static const struct got_error* cmd_integrate(int, char *[]);
148 static const struct got_error* cmd_merge(int, char *[]);
149 static const struct got_error* cmd_stage(int, char *[]);
150 static const struct got_error* cmd_unstage(int, char *[]);
151 static const struct got_error* cmd_cat(int, char *[]);
152 static const struct got_error* cmd_info(int, char *[]);
154 static const struct got_cmd got_commands[] = {
155 { "import", cmd_import, usage_import, "im" },
156 { "clone", cmd_clone, usage_clone, "cl" },
157 { "fetch", cmd_fetch, usage_fetch, "fe" },
158 { "checkout", cmd_checkout, usage_checkout, "co" },
159 { "update", cmd_update, usage_update, "up" },
160 { "log", cmd_log, usage_log, "" },
161 { "diff", cmd_diff, usage_diff, "di" },
162 { "blame", cmd_blame, usage_blame, "bl" },
163 { "tree", cmd_tree, usage_tree, "tr" },
164 { "status", cmd_status, usage_status, "st" },
165 { "ref", cmd_ref, usage_ref, "" },
166 { "branch", cmd_branch, usage_branch, "br" },
167 { "tag", cmd_tag, usage_tag, "" },
168 { "add", cmd_add, usage_add, "" },
169 { "remove", cmd_remove, usage_remove, "rm" },
170 { "patch", cmd_patch, usage_patch, "pa" },
171 { "revert", cmd_revert, usage_revert, "rv" },
172 { "commit", cmd_commit, usage_commit, "ci" },
173 { "send", cmd_send, usage_send, "se" },
174 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
175 { "backout", cmd_backout, usage_backout, "bo" },
176 { "rebase", cmd_rebase, usage_rebase, "rb" },
177 { "histedit", cmd_histedit, usage_histedit, "he" },
178 { "integrate", cmd_integrate, usage_integrate,"ig" },
179 { "merge", cmd_merge, usage_merge, "mg" },
180 { "stage", cmd_stage, usage_stage, "sg" },
181 { "unstage", cmd_unstage, usage_unstage, "ug" },
182 { "cat", cmd_cat, usage_cat, "" },
183 { "info", cmd_info, usage_info, "" },
184 };
186 static void
187 list_commands(FILE *fp)
189 size_t i;
191 fprintf(fp, "commands:");
192 for (i = 0; i < nitems(got_commands); i++) {
193 const struct got_cmd *cmd = &got_commands[i];
194 fprintf(fp, " %s", cmd->cmd_name);
196 fputc('\n', fp);
199 __dead static void
200 option_conflict(char a, char b)
202 errx(1, "-%c and -%c options are mutually exclusive", a, b);
205 int
206 main(int argc, char *argv[])
208 const struct got_cmd *cmd;
209 size_t i;
210 int ch;
211 int hflag = 0, Vflag = 0;
212 static const struct option longopts[] = {
213 { "version", no_argument, NULL, 'V' },
214 { NULL, 0, NULL, 0 }
215 };
217 setlocale(LC_CTYPE, "");
219 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
220 switch (ch) {
221 case 'h':
222 hflag = 1;
223 break;
224 case 'V':
225 Vflag = 1;
226 break;
227 default:
228 usage(hflag, 1);
229 /* NOTREACHED */
233 argc -= optind;
234 argv += optind;
235 optind = 1;
236 optreset = 1;
238 if (Vflag) {
239 got_version_print_str();
240 return 0;
243 if (argc <= 0)
244 usage(hflag, hflag ? 0 : 1);
246 signal(SIGINT, catch_sigint);
247 signal(SIGPIPE, catch_sigpipe);
249 for (i = 0; i < nitems(got_commands); i++) {
250 const struct got_error *error;
252 cmd = &got_commands[i];
254 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
255 strcmp(cmd->cmd_alias, argv[0]) != 0)
256 continue;
258 if (hflag)
259 cmd->cmd_usage();
261 error = cmd->cmd_main(argc, argv);
262 if (error && error->code != GOT_ERR_CANCELLED &&
263 error->code != GOT_ERR_PRIVSEP_EXIT &&
264 !(sigpipe_received &&
265 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
266 !(sigint_received &&
267 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
268 fflush(stdout);
269 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
270 return 1;
273 return 0;
276 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
277 list_commands(stderr);
278 return 1;
281 __dead static void
282 usage(int hflag, int status)
284 FILE *fp = (status == 0) ? stdout : stderr;
286 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
287 getprogname());
288 if (hflag)
289 list_commands(fp);
290 exit(status);
293 static const struct got_error *
294 get_editor(char **abspath)
296 const struct got_error *err = NULL;
297 const char *editor;
299 *abspath = NULL;
301 editor = getenv("VISUAL");
302 if (editor == NULL)
303 editor = getenv("EDITOR");
305 if (editor) {
306 err = got_path_find_prog(abspath, editor);
307 if (err)
308 return err;
311 if (*abspath == NULL) {
312 *abspath = strdup("/usr/bin/vi");
313 if (*abspath == NULL)
314 return got_error_from_errno("strdup");
317 return NULL;
320 static const struct got_error *
321 apply_unveil(const char *repo_path, int repo_read_only,
322 const char *worktree_path)
324 const struct got_error *err;
326 #ifdef PROFILE
327 if (unveil("gmon.out", "rwc") != 0)
328 return got_error_from_errno2("unveil", "gmon.out");
329 #endif
330 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
331 return got_error_from_errno2("unveil", repo_path);
333 if (worktree_path && unveil(worktree_path, "rwc") != 0)
334 return got_error_from_errno2("unveil", worktree_path);
336 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
337 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
339 err = got_privsep_unveil_exec_helpers();
340 if (err != NULL)
341 return err;
343 if (unveil(NULL, NULL) != 0)
344 return got_error_from_errno("unveil");
346 return NULL;
349 __dead static void
350 usage_import(void)
352 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
353 "[-r repository-path] directory\n", getprogname());
354 exit(1);
357 static int
358 spawn_editor(const char *editor, const char *file)
360 pid_t pid;
361 sig_t sighup, sigint, sigquit;
362 int st = -1;
364 sighup = signal(SIGHUP, SIG_IGN);
365 sigint = signal(SIGINT, SIG_IGN);
366 sigquit = signal(SIGQUIT, SIG_IGN);
368 switch (pid = fork()) {
369 case -1:
370 goto doneediting;
371 case 0:
372 execl(editor, editor, file, (char *)NULL);
373 _exit(127);
376 while (waitpid(pid, &st, 0) == -1)
377 if (errno != EINTR)
378 break;
380 doneediting:
381 (void)signal(SIGHUP, sighup);
382 (void)signal(SIGINT, sigint);
383 (void)signal(SIGQUIT, sigquit);
385 if (!WIFEXITED(st)) {
386 errno = EINTR;
387 return -1;
390 return WEXITSTATUS(st);
393 static const struct got_error *
394 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
400 *logmsg = NULL;
401 *len = 0;
403 if (fseeko(fp, 0L, SEEK_SET) == -1)
404 return got_error_from_errno("fseeko");
406 *logmsg = malloc(filesize + 1);
407 if (*logmsg == NULL)
408 return got_error_from_errno("malloc");
409 (*logmsg)[0] = '\0';
411 while (getline(&line, &linesize, fp) != -1) {
412 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t logmsg_len;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (require_modification) {
458 struct timespec timeout;
460 timeout.tv_sec = 0;
461 timeout.tv_nsec = 1;
462 nanosleep(&timeout, NULL);
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno2("stat", logmsg_path);
468 if (require_modification && st.st_size == st2.st_size &&
469 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 fp = fopen(logmsg_path, "re");
474 if (fp == NULL) {
475 err = got_error_from_errno("fopen");
476 goto done;
479 /* strip comments and leading/trailing newlines */
480 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
481 if (err)
482 goto done;
483 if (logmsg_len == 0) {
484 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
485 "commit message cannot be empty, aborting");
486 goto done;
488 done:
489 if (fp && fclose(fp) == EOF && err == NULL)
490 err = got_error_from_errno("fclose");
491 if (err) {
492 free(*logmsg);
493 *logmsg = NULL;
495 return err;
498 static const struct got_error *
499 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
500 const char *path_dir, const char *branch_name)
502 char *initial_content = NULL;
503 const struct got_error *err = NULL;
504 int initial_content_len;
505 int fd = -1;
507 initial_content_len = asprintf(&initial_content,
508 "\n# %s to be imported to branch %s\n", path_dir,
509 branch_name);
510 if (initial_content_len == -1)
511 return got_error_from_errno("asprintf");
513 err = got_opentemp_named_fd(logmsg_path, &fd,
514 GOT_TMPDIR_STR "/got-importmsg", "");
515 if (err)
516 goto done;
518 if (write(fd, initial_content, initial_content_len) == -1) {
519 err = got_error_from_errno2("write", *logmsg_path);
520 goto done;
522 if (close(fd) == -1) {
523 err = got_error_from_errno2("close", *logmsg_path);
524 goto done;
526 fd = -1;
528 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
529 initial_content_len, 1);
530 done:
531 if (fd != -1 && close(fd) == -1 && err == NULL)
532 err = got_error_from_errno2("close", *logmsg_path);
533 free(initial_content);
534 if (err) {
535 free(*logmsg_path);
536 *logmsg_path = NULL;
538 return err;
541 static const struct got_error *
542 import_progress(void *arg, const char *path)
544 printf("A %s\n", path);
545 return NULL;
548 static const struct got_error *
549 valid_author(const char *author)
551 const char *email = author;
553 /*
554 * Git' expects the author (or committer) to be in the form
555 * "name <email>", which are mostly free form (see the
556 * "committer" description in git-fast-import(1)). We're only
557 * doing this to avoid git's object parser breaking on commits
558 * we create.
559 */
561 while (*author && *author != '\n' && *author != '<' && *author != '>')
562 author++;
563 if (author != email && *author == '<' && *(author - 1) != ' ')
564 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
565 "between author name and email required", email);
566 if (*author++ != '<')
567 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
568 while (*author && *author != '\n' && *author != '<' && *author != '>')
569 author++;
570 if (strcmp(author, ">") != 0)
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 return NULL;
575 static const struct got_error *
576 get_author(char **author, struct got_repository *repo,
577 struct got_worktree *worktree)
579 const struct got_error *err = NULL;
580 const char *got_author = NULL, *name, *email;
581 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
583 *author = NULL;
585 if (worktree)
586 worktree_conf = got_worktree_get_gotconfig(worktree);
587 repo_conf = got_repo_get_gotconfig(repo);
589 /*
590 * Priority of potential author information sources, from most
591 * significant to least significant:
592 * 1) work tree's .got/got.conf file
593 * 2) repository's got.conf file
594 * 3) repository's git config file
595 * 4) environment variables
596 * 5) global git config files (in user's home directory or /etc)
597 */
599 if (worktree_conf)
600 got_author = got_gotconfig_get_author(worktree_conf);
601 if (got_author == NULL)
602 got_author = got_gotconfig_get_author(repo_conf);
603 if (got_author == NULL) {
604 name = got_repo_get_gitconfig_author_name(repo);
605 email = got_repo_get_gitconfig_author_email(repo);
606 if (name && email) {
607 if (asprintf(author, "%s <%s>", name, email) == -1)
608 return got_error_from_errno("asprintf");
609 return NULL;
612 got_author = getenv("GOT_AUTHOR");
613 if (got_author == NULL) {
614 name = got_repo_get_global_gitconfig_author_name(repo);
615 email = got_repo_get_global_gitconfig_author_email(
616 repo);
617 if (name && email) {
618 if (asprintf(author, "%s <%s>", name, email)
619 == -1)
620 return got_error_from_errno("asprintf");
621 return NULL;
623 /* TODO: Look up user in password database? */
624 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
628 *author = strdup(got_author);
629 if (*author == NULL)
630 return got_error_from_errno("strdup");
632 err = valid_author(*author);
633 if (err) {
634 free(*author);
635 *author = NULL;
637 return err;
640 static const struct got_error *
641 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const char *got_allowed_signers = NULL;
645 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
647 *allowed_signers = NULL;
649 if (worktree)
650 worktree_conf = got_worktree_get_gotconfig(worktree);
651 repo_conf = got_repo_get_gotconfig(repo);
653 /*
654 * Priority of potential author information sources, from most
655 * significant to least significant:
656 * 1) work tree's .got/got.conf file
657 * 2) repository's got.conf file
658 */
660 if (worktree_conf)
661 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
662 worktree_conf);
663 if (got_allowed_signers == NULL)
664 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
665 repo_conf);
667 if (got_allowed_signers) {
668 *allowed_signers = strdup(got_allowed_signers);
669 if (*allowed_signers == NULL)
670 return got_error_from_errno("strdup");
672 return NULL;
675 static const struct got_error *
676 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
677 struct got_worktree *worktree)
679 const char *got_revoked_signers = NULL;
680 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
682 *revoked_signers = NULL;
684 if (worktree)
685 worktree_conf = got_worktree_get_gotconfig(worktree);
686 repo_conf = got_repo_get_gotconfig(repo);
688 /*
689 * Priority of potential author information sources, from most
690 * significant to least significant:
691 * 1) work tree's .got/got.conf file
692 * 2) repository's got.conf file
693 */
695 if (worktree_conf)
696 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
697 worktree_conf);
698 if (got_revoked_signers == NULL)
699 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
700 repo_conf);
702 if (got_revoked_signers) {
703 *revoked_signers = strdup(got_revoked_signers);
704 if (*revoked_signers == NULL)
705 return got_error_from_errno("strdup");
707 return NULL;
710 static const char *
711 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
713 const char *got_signer_id = NULL;
714 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
716 if (worktree)
717 worktree_conf = got_worktree_get_gotconfig(worktree);
718 repo_conf = got_repo_get_gotconfig(repo);
720 /*
721 * Priority of potential author information sources, from most
722 * significant to least significant:
723 * 1) work tree's .got/got.conf file
724 * 2) repository's got.conf file
725 */
727 if (worktree_conf)
728 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
729 if (got_signer_id == NULL)
730 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
732 return got_signer_id;
735 static const struct got_error *
736 get_gitconfig_path(char **gitconfig_path)
738 const char *homedir = getenv("HOME");
740 *gitconfig_path = NULL;
741 if (homedir) {
742 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
743 return got_error_from_errno("asprintf");
746 return NULL;
749 static const struct got_error *
750 cmd_import(int argc, char *argv[])
752 const struct got_error *error = NULL;
753 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
754 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
755 const char *branch_name = NULL;
756 char *id_str = NULL, *logmsg_path = NULL;
757 char refname[PATH_MAX] = "refs/heads/";
758 struct got_repository *repo = NULL;
759 struct got_reference *branch_ref = NULL, *head_ref = NULL;
760 struct got_object_id *new_commit_id = NULL;
761 int ch, n = 0;
762 struct got_pathlist_head ignores;
763 struct got_pathlist_entry *pe;
764 int preserve_logmsg = 0;
765 int *pack_fds = NULL;
767 TAILQ_INIT(&ignores);
769 #ifndef PROFILE
770 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
771 "unveil",
772 NULL) == -1)
773 err(1, "pledge");
774 #endif
776 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
777 switch (ch) {
778 case 'b':
779 branch_name = optarg;
780 break;
781 case 'I':
782 if (optarg[0] == '\0')
783 break;
784 error = got_pathlist_insert(&pe, &ignores, optarg,
785 NULL);
786 if (error)
787 goto done;
788 break;
789 case 'm':
790 logmsg = strdup(optarg);
791 if (logmsg == NULL) {
792 error = got_error_from_errno("strdup");
793 goto done;
795 break;
796 case 'r':
797 repo_path = realpath(optarg, NULL);
798 if (repo_path == NULL) {
799 error = got_error_from_errno2("realpath",
800 optarg);
801 goto done;
803 break;
804 default:
805 usage_import();
806 /* NOTREACHED */
810 argc -= optind;
811 argv += optind;
813 if (argc != 1)
814 usage_import();
816 if (repo_path == NULL) {
817 repo_path = getcwd(NULL, 0);
818 if (repo_path == NULL)
819 return got_error_from_errno("getcwd");
821 got_path_strip_trailing_slashes(repo_path);
822 error = get_gitconfig_path(&gitconfig_path);
823 if (error)
824 goto done;
825 error = got_repo_pack_fds_open(&pack_fds);
826 if (error != NULL)
827 goto done;
828 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
829 if (error)
830 goto done;
832 error = get_author(&author, repo, NULL);
833 if (error)
834 return error;
836 /*
837 * Don't let the user create a branch name with a leading '-'.
838 * While technically a valid reference name, this case is usually
839 * an unintended typo.
840 */
841 if (branch_name && branch_name[0] == '-')
842 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
844 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
845 if (error && error->code != GOT_ERR_NOT_REF)
846 goto done;
848 if (branch_name)
849 n = strlcat(refname, branch_name, sizeof(refname));
850 else if (head_ref && got_ref_is_symbolic(head_ref))
851 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
852 sizeof(refname));
853 else
854 n = strlcat(refname, "main", sizeof(refname));
855 if (n >= sizeof(refname)) {
856 error = got_error(GOT_ERR_NO_SPACE);
857 goto done;
860 error = got_ref_open(&branch_ref, repo, refname, 0);
861 if (error) {
862 if (error->code != GOT_ERR_NOT_REF)
863 goto done;
864 } else {
865 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
866 "import target branch already exists");
867 goto done;
870 path_dir = realpath(argv[0], NULL);
871 if (path_dir == NULL) {
872 error = got_error_from_errno2("realpath", argv[0]);
873 goto done;
875 got_path_strip_trailing_slashes(path_dir);
877 /*
878 * unveil(2) traverses exec(2); if an editor is used we have
879 * to apply unveil after the log message has been written.
880 */
881 if (logmsg == NULL || *logmsg == '\0') {
882 error = get_editor(&editor);
883 if (error)
884 goto done;
885 free(logmsg);
886 error = collect_import_msg(&logmsg, &logmsg_path, editor,
887 path_dir, refname);
888 if (error) {
889 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
890 logmsg_path != NULL)
891 preserve_logmsg = 1;
892 goto done;
896 if (unveil(path_dir, "r") != 0) {
897 error = got_error_from_errno2("unveil", path_dir);
898 if (logmsg_path)
899 preserve_logmsg = 1;
900 goto done;
903 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
904 if (error) {
905 if (logmsg_path)
906 preserve_logmsg = 1;
907 goto done;
910 error = got_repo_import(&new_commit_id, path_dir, logmsg,
911 author, &ignores, repo, import_progress, NULL);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
919 if (error) {
920 if (logmsg_path)
921 preserve_logmsg = 1;
922 goto done;
925 error = got_ref_write(branch_ref, repo);
926 if (error) {
927 if (logmsg_path)
928 preserve_logmsg = 1;
929 goto done;
932 error = got_object_id_str(&id_str, new_commit_id);
933 if (error) {
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
940 if (error) {
941 if (error->code != GOT_ERR_NOT_REF) {
942 if (logmsg_path)
943 preserve_logmsg = 1;
944 goto done;
947 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
948 branch_ref);
949 if (error) {
950 if (logmsg_path)
951 preserve_logmsg = 1;
952 goto done;
955 error = got_ref_write(head_ref, repo);
956 if (error) {
957 if (logmsg_path)
958 preserve_logmsg = 1;
959 goto done;
963 printf("Created branch %s with commit %s\n",
964 got_ref_get_name(branch_ref), id_str);
965 done:
966 if (pack_fds) {
967 const struct got_error *pack_err =
968 got_repo_pack_fds_close(pack_fds);
969 if (error == NULL)
970 error = pack_err;
972 if (repo) {
973 const struct got_error *close_err = got_repo_close(repo);
974 if (error == NULL)
975 error = close_err;
977 if (preserve_logmsg) {
978 fprintf(stderr, "%s: log message preserved in %s\n",
979 getprogname(), logmsg_path);
980 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
981 error = got_error_from_errno2("unlink", logmsg_path);
982 free(logmsg);
983 free(logmsg_path);
984 free(repo_path);
985 free(editor);
986 free(new_commit_id);
987 free(id_str);
988 free(author);
989 free(gitconfig_path);
990 if (branch_ref)
991 got_ref_close(branch_ref);
992 if (head_ref)
993 got_ref_close(head_ref);
994 return error;
997 __dead static void
998 usage_clone(void)
1000 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1001 "repository-URL [directory]\n", getprogname());
1002 exit(1);
1005 struct got_fetch_progress_arg {
1006 char last_scaled_size[FMT_SCALED_STRSIZE];
1007 int last_p_indexed;
1008 int last_p_resolved;
1009 int verbosity;
1011 struct got_repository *repo;
1013 int create_configs;
1014 int configs_created;
1015 struct {
1016 struct got_pathlist_head *symrefs;
1017 struct got_pathlist_head *wanted_branches;
1018 struct got_pathlist_head *wanted_refs;
1019 const char *proto;
1020 const char *host;
1021 const char *port;
1022 const char *remote_repo_path;
1023 const char *git_url;
1024 int fetch_all_branches;
1025 int mirror_references;
1026 } config_info;
1029 /* XXX forward declaration */
1030 static const struct got_error *
1031 create_config_files(const char *proto, const char *host, const char *port,
1032 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1033 int mirror_references, struct got_pathlist_head *symrefs,
1034 struct got_pathlist_head *wanted_branches,
1035 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1037 static const struct got_error *
1038 fetch_progress(void *arg, const char *message, off_t packfile_size,
1039 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1041 const struct got_error *err = NULL;
1042 struct got_fetch_progress_arg *a = arg;
1043 char scaled_size[FMT_SCALED_STRSIZE];
1044 int p_indexed, p_resolved;
1045 int print_size = 0, print_indexed = 0, print_resolved = 0;
1048 * In order to allow a failed clone to be resumed with 'got fetch'
1049 * we try to create configuration files as soon as possible.
1050 * Once the server has sent information about its default branch
1051 * we have all required information.
1053 if (a->create_configs && !a->configs_created &&
1054 !TAILQ_EMPTY(a->config_info.symrefs)) {
1055 err = create_config_files(a->config_info.proto,
1056 a->config_info.host, a->config_info.port,
1057 a->config_info.remote_repo_path,
1058 a->config_info.git_url,
1059 a->config_info.fetch_all_branches,
1060 a->config_info.mirror_references,
1061 a->config_info.symrefs,
1062 a->config_info.wanted_branches,
1063 a->config_info.wanted_refs, a->repo);
1064 if (err)
1065 return err;
1066 a->configs_created = 1;
1069 if (a->verbosity < 0)
1070 return NULL;
1072 if (message && message[0] != '\0') {
1073 printf("\rserver: %s", message);
1074 fflush(stdout);
1075 return NULL;
1078 if (packfile_size > 0 || nobj_indexed > 0) {
1079 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1080 (a->last_scaled_size[0] == '\0' ||
1081 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1082 print_size = 1;
1083 if (strlcpy(a->last_scaled_size, scaled_size,
1084 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1085 return got_error(GOT_ERR_NO_SPACE);
1087 if (nobj_indexed > 0) {
1088 p_indexed = (nobj_indexed * 100) / nobj_total;
1089 if (p_indexed != a->last_p_indexed) {
1090 a->last_p_indexed = p_indexed;
1091 print_indexed = 1;
1092 print_size = 1;
1095 if (nobj_resolved > 0) {
1096 p_resolved = (nobj_resolved * 100) /
1097 (nobj_total - nobj_loose);
1098 if (p_resolved != a->last_p_resolved) {
1099 a->last_p_resolved = p_resolved;
1100 print_resolved = 1;
1101 print_indexed = 1;
1102 print_size = 1;
1107 if (print_size || print_indexed || print_resolved)
1108 printf("\r");
1109 if (print_size)
1110 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1111 if (print_indexed)
1112 printf("; indexing %d%%", p_indexed);
1113 if (print_resolved)
1114 printf("; resolving deltas %d%%", p_resolved);
1115 if (print_size || print_indexed || print_resolved)
1116 fflush(stdout);
1118 return NULL;
1121 static const struct got_error *
1122 create_symref(const char *refname, struct got_reference *target_ref,
1123 int verbosity, struct got_repository *repo)
1125 const struct got_error *err;
1126 struct got_reference *head_symref;
1128 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1129 if (err)
1130 return err;
1132 err = got_ref_write(head_symref, repo);
1133 if (err == NULL && verbosity > 0) {
1134 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1135 got_ref_get_name(target_ref));
1137 got_ref_close(head_symref);
1138 return err;
1141 static const struct got_error *
1142 list_remote_refs(struct got_pathlist_head *symrefs,
1143 struct got_pathlist_head *refs)
1145 const struct got_error *err;
1146 struct got_pathlist_entry *pe;
1148 TAILQ_FOREACH(pe, symrefs, entry) {
1149 const char *refname = pe->path;
1150 const char *targetref = pe->data;
1152 printf("%s: %s\n", refname, targetref);
1155 TAILQ_FOREACH(pe, refs, entry) {
1156 const char *refname = pe->path;
1157 struct got_object_id *id = pe->data;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1163 printf("%s: %s\n", refname, id_str);
1164 free(id_str);
1167 return NULL;
1170 static const struct got_error *
1171 create_ref(const char *refname, struct got_object_id *id,
1172 int verbosity, struct got_repository *repo)
1174 const struct got_error *err = NULL;
1175 struct got_reference *ref;
1176 char *id_str;
1178 err = got_object_id_str(&id_str, id);
1179 if (err)
1180 return err;
1182 err = got_ref_alloc(&ref, refname, id);
1183 if (err)
1184 goto done;
1186 err = got_ref_write(ref, repo);
1187 got_ref_close(ref);
1189 if (err == NULL && verbosity >= 0)
1190 printf("Created reference %s: %s\n", refname, id_str);
1191 done:
1192 free(id_str);
1193 return err;
1196 static int
1197 match_wanted_ref(const char *refname, const char *wanted_ref)
1199 if (strncmp(refname, "refs/", 5) != 0)
1200 return 0;
1201 refname += 5;
1204 * Prevent fetching of references that won't make any
1205 * sense outside of the remote repository's context.
1207 if (strncmp(refname, "got/", 4) == 0)
1208 return 0;
1209 if (strncmp(refname, "remotes/", 8) == 0)
1210 return 0;
1212 if (strncmp(wanted_ref, "refs/", 5) == 0)
1213 wanted_ref += 5;
1215 /* Allow prefix match. */
1216 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1217 return 1;
1219 /* Allow exact match. */
1220 return (strcmp(refname, wanted_ref) == 0);
1223 static int
1224 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1226 struct got_pathlist_entry *pe;
1228 TAILQ_FOREACH(pe, wanted_refs, entry) {
1229 if (match_wanted_ref(refname, pe->path))
1230 return 1;
1233 return 0;
1236 static const struct got_error *
1237 create_wanted_ref(const char *refname, struct got_object_id *id,
1238 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1240 const struct got_error *err;
1241 char *remote_refname;
1243 if (strncmp("refs/", refname, 5) == 0)
1244 refname += 5;
1246 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1247 remote_repo_name, refname) == -1)
1248 return got_error_from_errno("asprintf");
1250 err = create_ref(remote_refname, id, verbosity, repo);
1251 free(remote_refname);
1252 return err;
1255 static const struct got_error *
1256 create_gotconfig(const char *proto, const char *host, const char *port,
1257 const char *remote_repo_path, const char *default_branch,
1258 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1259 struct got_pathlist_head *wanted_refs, int mirror_references,
1260 struct got_repository *repo)
1262 const struct got_error *err = NULL;
1263 char *gotconfig_path = NULL;
1264 char *gotconfig = NULL;
1265 FILE *gotconfig_file = NULL;
1266 const char *branchname = NULL;
1267 char *branches = NULL, *refs = NULL;
1268 ssize_t n;
1270 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_branches, entry) {
1273 char *s;
1274 branchname = pe->path;
1275 if (strncmp(branchname, "refs/heads/", 11) == 0)
1276 branchname += 11;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 branches ? branches : "", branchname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(branches);
1283 branches = s;
1285 } else if (!fetch_all_branches && default_branch) {
1286 branchname = default_branch;
1287 if (strncmp(branchname, "refs/heads/", 11) == 0)
1288 branchname += 11;
1289 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1290 err = got_error_from_errno("asprintf");
1291 goto done;
1294 if (!TAILQ_EMPTY(wanted_refs)) {
1295 struct got_pathlist_entry *pe;
1296 TAILQ_FOREACH(pe, wanted_refs, entry) {
1297 char *s;
1298 const char *refname = pe->path;
1299 if (strncmp(refname, "refs/", 5) == 0)
1300 branchname += 5;
1301 if (asprintf(&s, "%s\"%s\" ",
1302 refs ? refs : "", refname) == -1) {
1303 err = got_error_from_errno("asprintf");
1304 goto done;
1306 free(refs);
1307 refs = s;
1311 /* Create got.conf(5). */
1312 gotconfig_path = got_repo_get_path_gotconfig(repo);
1313 if (gotconfig_path == NULL) {
1314 err = got_error_from_errno("got_repo_get_path_gotconfig");
1315 goto done;
1317 gotconfig_file = fopen(gotconfig_path, "ae");
1318 if (gotconfig_file == NULL) {
1319 err = got_error_from_errno2("fopen", gotconfig_path);
1320 goto done;
1322 if (asprintf(&gotconfig,
1323 "remote \"%s\" {\n"
1324 "\tserver %s\n"
1325 "\tprotocol %s\n"
1326 "%s%s%s"
1327 "\trepository \"%s\"\n"
1328 "%s%s%s"
1329 "%s%s%s"
1330 "%s"
1331 "%s"
1332 "}\n",
1333 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1334 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1335 remote_repo_path, branches ? "\tbranch { " : "",
1336 branches ? branches : "", branches ? "}\n" : "",
1337 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1338 mirror_references ? "\tmirror_references yes\n" : "",
1339 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1344 if (n != strlen(gotconfig)) {
1345 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1346 goto done;
1349 done:
1350 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1351 err = got_error_from_errno2("fclose", gotconfig_path);
1352 free(gotconfig_path);
1353 free(branches);
1354 return err;
1357 static const struct got_error *
1358 create_gitconfig(const char *git_url, const char *default_branch,
1359 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1360 struct got_pathlist_head *wanted_refs, int mirror_references,
1361 struct got_repository *repo)
1363 const struct got_error *err = NULL;
1364 char *gitconfig_path = NULL;
1365 char *gitconfig = NULL;
1366 FILE *gitconfig_file = NULL;
1367 char *branches = NULL, *refs = NULL;
1368 const char *branchname;
1369 ssize_t n;
1371 /* Create a config file Git can understand. */
1372 gitconfig_path = got_repo_get_path_gitconfig(repo);
1373 if (gitconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gitconfig");
1375 goto done;
1377 gitconfig_file = fopen(gitconfig_path, "ae");
1378 if (gitconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gitconfig_path);
1380 goto done;
1382 if (fetch_all_branches) {
1383 if (mirror_references) {
1384 if (asprintf(&branches,
1385 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1386 err = got_error_from_errno("asprintf");
1387 goto done;
1389 } else if (asprintf(&branches,
1390 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1391 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 } else if (!TAILQ_EMPTY(wanted_branches)) {
1396 struct got_pathlist_entry *pe;
1397 TAILQ_FOREACH(pe, wanted_branches, entry) {
1398 char *s;
1399 branchname = pe->path;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 if (mirror_references) {
1403 if (asprintf(&s,
1404 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1405 branches ? branches : "",
1406 branchname, branchname) == -1) {
1407 err = got_error_from_errno("asprintf");
1408 goto done;
1410 } else if (asprintf(&s,
1411 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1412 branches ? branches : "",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1418 free(branches);
1419 branches = s;
1421 } else {
1423 * If the server specified a default branch, use just that one.
1424 * Otherwise fall back to fetching all branches on next fetch.
1426 if (default_branch) {
1427 branchname = default_branch;
1428 if (strncmp(branchname, "refs/heads/", 11) == 0)
1429 branchname += 11;
1430 } else
1431 branchname = "*"; /* fall back to all branches */
1432 if (mirror_references) {
1433 if (asprintf(&branches,
1434 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1435 branchname, branchname) == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 } else if (asprintf(&branches,
1440 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1441 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1442 branchname) == -1) {
1443 err = got_error_from_errno("asprintf");
1444 goto done;
1447 if (!TAILQ_EMPTY(wanted_refs)) {
1448 struct got_pathlist_entry *pe;
1449 TAILQ_FOREACH(pe, wanted_refs, entry) {
1450 char *s;
1451 const char *refname = pe->path;
1452 if (strncmp(refname, "refs/", 5) == 0)
1453 refname += 5;
1454 if (mirror_references) {
1455 if (asprintf(&s,
1456 "%s\tfetch = refs/%s:refs/%s\n",
1457 refs ? refs : "", refname, refname) == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 } else if (asprintf(&s,
1462 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1463 refs ? refs : "",
1464 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1465 refname) == -1) {
1466 err = got_error_from_errno("asprintf");
1467 goto done;
1469 free(refs);
1470 refs = s;
1474 if (asprintf(&gitconfig,
1475 "[remote \"%s\"]\n"
1476 "\turl = %s\n"
1477 "%s"
1478 "%s"
1479 "\tfetch = refs/tags/*:refs/tags/*\n",
1480 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1481 refs ? refs : "") == -1) {
1482 err = got_error_from_errno("asprintf");
1483 goto done;
1485 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1486 if (n != strlen(gitconfig)) {
1487 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1488 goto done;
1490 done:
1491 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1492 err = got_error_from_errno2("fclose", gitconfig_path);
1493 free(gitconfig_path);
1494 free(branches);
1495 return err;
1498 static const struct got_error *
1499 create_config_files(const char *proto, const char *host, const char *port,
1500 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1501 int mirror_references, struct got_pathlist_head *symrefs,
1502 struct got_pathlist_head *wanted_branches,
1503 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1505 const struct got_error *err = NULL;
1506 const char *default_branch = NULL;
1507 struct got_pathlist_entry *pe;
1510 * If we asked for a set of wanted branches then use the first
1511 * one of those.
1513 if (!TAILQ_EMPTY(wanted_branches)) {
1514 pe = TAILQ_FIRST(wanted_branches);
1515 default_branch = pe->path;
1516 } else {
1517 /* First HEAD ref listed by server is the default branch. */
1518 TAILQ_FOREACH(pe, symrefs, entry) {
1519 const char *refname = pe->path;
1520 const char *target = pe->data;
1522 if (strcmp(refname, GOT_REF_HEAD) != 0)
1523 continue;
1525 default_branch = target;
1526 break;
1530 /* Create got.conf(5). */
1531 err = create_gotconfig(proto, host, port, remote_repo_path,
1532 default_branch, fetch_all_branches, wanted_branches,
1533 wanted_refs, mirror_references, repo);
1534 if (err)
1535 return err;
1537 /* Create a config file Git can understand. */
1538 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1539 wanted_branches, wanted_refs, mirror_references, repo);
1542 static const struct got_error *
1543 cmd_clone(int argc, char *argv[])
1545 const struct got_error *error = NULL;
1546 const char *uri, *dirname;
1547 char *proto, *host, *port, *repo_name, *server_path;
1548 char *default_destdir = NULL, *id_str = NULL;
1549 const char *repo_path;
1550 struct got_repository *repo = NULL;
1551 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1552 struct got_pathlist_entry *pe;
1553 struct got_object_id *pack_hash = NULL;
1554 int ch, fetchfd = -1, fetchstatus;
1555 pid_t fetchpid = -1;
1556 struct got_fetch_progress_arg fpa;
1557 char *git_url = NULL;
1558 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1559 int bflag = 0, list_refs_only = 0;
1560 int *pack_fds = NULL;
1562 TAILQ_INIT(&refs);
1563 TAILQ_INIT(&symrefs);
1564 TAILQ_INIT(&wanted_branches);
1565 TAILQ_INIT(&wanted_refs);
1567 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1568 switch (ch) {
1569 case 'a':
1570 fetch_all_branches = 1;
1571 break;
1572 case 'b':
1573 error = got_pathlist_append(&wanted_branches,
1574 optarg, NULL);
1575 if (error)
1576 return error;
1577 bflag = 1;
1578 break;
1579 case 'l':
1580 list_refs_only = 1;
1581 break;
1582 case 'm':
1583 mirror_references = 1;
1584 break;
1585 case 'q':
1586 verbosity = -1;
1587 break;
1588 case 'R':
1589 error = got_pathlist_append(&wanted_refs,
1590 optarg, NULL);
1591 if (error)
1592 return error;
1593 break;
1594 case 'v':
1595 if (verbosity < 0)
1596 verbosity = 0;
1597 else if (verbosity < 3)
1598 verbosity++;
1599 break;
1600 default:
1601 usage_clone();
1602 break;
1605 argc -= optind;
1606 argv += optind;
1608 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1609 option_conflict('a', 'b');
1610 if (list_refs_only) {
1611 if (!TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('l', 'b');
1613 if (fetch_all_branches)
1614 option_conflict('l', 'a');
1615 if (mirror_references)
1616 option_conflict('l', 'm');
1617 if (!TAILQ_EMPTY(&wanted_refs))
1618 option_conflict('l', 'R');
1621 uri = argv[0];
1623 if (argc == 1)
1624 dirname = NULL;
1625 else if (argc == 2)
1626 dirname = argv[1];
1627 else
1628 usage_clone();
1630 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1631 &repo_name, uri);
1632 if (error)
1633 goto done;
1635 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1636 host, port ? ":" : "", port ? port : "",
1637 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1638 error = got_error_from_errno("asprintf");
1639 goto done;
1642 if (strcmp(proto, "git") == 0) {
1643 #ifndef PROFILE
1644 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1645 "sendfd dns inet unveil", NULL) == -1)
1646 err(1, "pledge");
1647 #endif
1648 } else if (strcmp(proto, "git+ssh") == 0 ||
1649 strcmp(proto, "ssh") == 0) {
1650 #ifndef PROFILE
1651 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1652 "sendfd unveil", NULL) == -1)
1653 err(1, "pledge");
1654 #endif
1655 } else if (strcmp(proto, "http") == 0 ||
1656 strcmp(proto, "git+http") == 0) {
1657 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1658 goto done;
1659 } else {
1660 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1661 goto done;
1663 if (dirname == NULL) {
1664 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1665 error = got_error_from_errno("asprintf");
1666 goto done;
1668 repo_path = default_destdir;
1669 } else
1670 repo_path = dirname;
1672 if (!list_refs_only) {
1673 error = got_path_mkdir(repo_path);
1674 if (error &&
1675 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1676 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1677 goto done;
1678 if (!got_path_dir_is_empty(repo_path)) {
1679 error = got_error_path(repo_path,
1680 GOT_ERR_DIR_NOT_EMPTY);
1681 goto done;
1685 error = got_dial_apply_unveil(proto);
1686 if (error)
1687 goto done;
1689 error = apply_unveil(repo_path, 0, NULL);
1690 if (error)
1691 goto done;
1693 if (verbosity >= 0)
1694 printf("Connecting to %s\n", git_url);
1696 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1697 server_path, verbosity);
1698 if (error)
1699 goto done;
1701 if (!list_refs_only) {
1702 error = got_repo_init(repo_path, NULL);
1703 if (error)
1704 goto done;
1705 error = got_repo_pack_fds_open(&pack_fds);
1706 if (error != NULL)
1707 goto done;
1708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1709 if (error)
1710 goto done;
1713 fpa.last_scaled_size[0] = '\0';
1714 fpa.last_p_indexed = -1;
1715 fpa.last_p_resolved = -1;
1716 fpa.verbosity = verbosity;
1717 fpa.create_configs = 1;
1718 fpa.configs_created = 0;
1719 fpa.repo = repo;
1720 fpa.config_info.symrefs = &symrefs;
1721 fpa.config_info.wanted_branches = &wanted_branches;
1722 fpa.config_info.wanted_refs = &wanted_refs;
1723 fpa.config_info.proto = proto;
1724 fpa.config_info.host = host;
1725 fpa.config_info.port = port;
1726 fpa.config_info.remote_repo_path = server_path;
1727 fpa.config_info.git_url = git_url;
1728 fpa.config_info.fetch_all_branches = fetch_all_branches;
1729 fpa.config_info.mirror_references = mirror_references;
1730 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1731 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1732 fetch_all_branches, &wanted_branches, &wanted_refs,
1733 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1734 fetch_progress, &fpa);
1735 if (error)
1736 goto done;
1738 if (list_refs_only) {
1739 error = list_remote_refs(&symrefs, &refs);
1740 goto done;
1743 if (pack_hash == NULL) {
1744 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1745 "server sent an empty pack file");
1746 goto done;
1748 error = got_object_id_str(&id_str, pack_hash);
1749 if (error)
1750 goto done;
1751 if (verbosity >= 0)
1752 printf("\nFetched %s.pack\n", id_str);
1753 free(id_str);
1755 /* Set up references provided with the pack file. */
1756 TAILQ_FOREACH(pe, &refs, entry) {
1757 const char *refname = pe->path;
1758 struct got_object_id *id = pe->data;
1759 char *remote_refname;
1761 if (is_wanted_ref(&wanted_refs, refname) &&
1762 !mirror_references) {
1763 error = create_wanted_ref(refname, id,
1764 GOT_FETCH_DEFAULT_REMOTE_NAME,
1765 verbosity - 1, repo);
1766 if (error)
1767 goto done;
1768 continue;
1771 error = create_ref(refname, id, verbosity - 1, repo);
1772 if (error)
1773 goto done;
1775 if (mirror_references)
1776 continue;
1778 if (strncmp("refs/heads/", refname, 11) != 0)
1779 continue;
1781 if (asprintf(&remote_refname,
1782 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1783 refname + 11) == -1) {
1784 error = got_error_from_errno("asprintf");
1785 goto done;
1787 error = create_ref(remote_refname, id, verbosity - 1, repo);
1788 free(remote_refname);
1789 if (error)
1790 goto done;
1793 /* Set the HEAD reference if the server provided one. */
1794 TAILQ_FOREACH(pe, &symrefs, entry) {
1795 struct got_reference *target_ref;
1796 const char *refname = pe->path;
1797 const char *target = pe->data;
1798 char *remote_refname = NULL, *remote_target = NULL;
1800 if (strcmp(refname, GOT_REF_HEAD) != 0)
1801 continue;
1803 error = got_ref_open(&target_ref, repo, target, 0);
1804 if (error) {
1805 if (error->code == GOT_ERR_NOT_REF) {
1806 error = NULL;
1807 continue;
1809 goto done;
1812 error = create_symref(refname, target_ref, verbosity, repo);
1813 got_ref_close(target_ref);
1814 if (error)
1815 goto done;
1817 if (mirror_references)
1818 continue;
1820 if (strncmp("refs/heads/", target, 11) != 0)
1821 continue;
1823 if (asprintf(&remote_refname,
1824 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1825 refname) == -1) {
1826 error = got_error_from_errno("asprintf");
1827 goto done;
1829 if (asprintf(&remote_target,
1830 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 target + 11) == -1) {
1832 error = got_error_from_errno("asprintf");
1833 free(remote_refname);
1834 goto done;
1836 error = got_ref_open(&target_ref, repo, remote_target, 0);
1837 if (error) {
1838 free(remote_refname);
1839 free(remote_target);
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1846 error = create_symref(remote_refname, target_ref,
1847 verbosity - 1, repo);
1848 free(remote_refname);
1849 free(remote_target);
1850 got_ref_close(target_ref);
1851 if (error)
1852 goto done;
1854 if (pe == NULL) {
1856 * We failed to set the HEAD reference. If we asked for
1857 * a set of wanted branches use the first of one of those
1858 * which could be fetched instead.
1860 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1861 const char *target = pe->path;
1862 struct got_reference *target_ref;
1864 error = got_ref_open(&target_ref, repo, target, 0);
1865 if (error) {
1866 if (error->code == GOT_ERR_NOT_REF) {
1867 error = NULL;
1868 continue;
1870 goto done;
1873 error = create_symref(GOT_REF_HEAD, target_ref,
1874 verbosity, repo);
1875 got_ref_close(target_ref);
1876 if (error)
1877 goto done;
1878 break;
1881 if (!fpa.configs_created && pe != NULL) {
1882 error = create_config_files(fpa.config_info.proto,
1883 fpa.config_info.host, fpa.config_info.port,
1884 fpa.config_info.remote_repo_path,
1885 fpa.config_info.git_url,
1886 fpa.config_info.fetch_all_branches,
1887 fpa.config_info.mirror_references,
1888 fpa.config_info.symrefs,
1889 fpa.config_info.wanted_branches,
1890 fpa.config_info.wanted_refs, fpa.repo);
1891 if (error)
1892 goto done;
1896 if (verbosity >= 0)
1897 printf("Created %s repository '%s'\n",
1898 mirror_references ? "mirrored" : "cloned", repo_path);
1899 done:
1900 if (pack_fds) {
1901 const struct got_error *pack_err =
1902 got_repo_pack_fds_close(pack_fds);
1903 if (error == NULL)
1904 error = pack_err;
1906 if (fetchpid > 0) {
1907 if (kill(fetchpid, SIGTERM) == -1)
1908 error = got_error_from_errno("kill");
1909 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1910 error = got_error_from_errno("waitpid");
1912 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1913 error = got_error_from_errno("close");
1914 if (repo) {
1915 const struct got_error *close_err = got_repo_close(repo);
1916 if (error == NULL)
1917 error = close_err;
1919 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1921 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1922 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1923 free(pack_hash);
1924 free(proto);
1925 free(host);
1926 free(port);
1927 free(server_path);
1928 free(repo_name);
1929 free(default_destdir);
1930 free(git_url);
1931 return error;
1934 static const struct got_error *
1935 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1936 int replace_tags, int verbosity, struct got_repository *repo)
1938 const struct got_error *err = NULL;
1939 char *new_id_str = NULL;
1940 struct got_object_id *old_id = NULL;
1942 err = got_object_id_str(&new_id_str, new_id);
1943 if (err)
1944 goto done;
1946 if (!replace_tags &&
1947 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1948 err = got_ref_resolve(&old_id, repo, ref);
1949 if (err)
1950 goto done;
1951 if (got_object_id_cmp(old_id, new_id) == 0)
1952 goto done;
1953 if (verbosity >= 0) {
1954 printf("Rejecting update of existing tag %s: %s\n",
1955 got_ref_get_name(ref), new_id_str);
1957 goto done;
1960 if (got_ref_is_symbolic(ref)) {
1961 if (verbosity >= 0) {
1962 printf("Replacing reference %s: %s\n",
1963 got_ref_get_name(ref),
1964 got_ref_get_symref_target(ref));
1966 err = got_ref_change_symref_to_ref(ref, new_id);
1967 if (err)
1968 goto done;
1969 err = got_ref_write(ref, repo);
1970 if (err)
1971 goto done;
1972 } else {
1973 err = got_ref_resolve(&old_id, repo, ref);
1974 if (err)
1975 goto done;
1976 if (got_object_id_cmp(old_id, new_id) == 0)
1977 goto done;
1979 err = got_ref_change_ref(ref, new_id);
1980 if (err)
1981 goto done;
1982 err = got_ref_write(ref, repo);
1983 if (err)
1984 goto done;
1987 if (verbosity >= 0)
1988 printf("Updated %s: %s\n", got_ref_get_name(ref),
1989 new_id_str);
1990 done:
1991 free(old_id);
1992 free(new_id_str);
1993 return err;
1996 static const struct got_error *
1997 update_symref(const char *refname, struct got_reference *target_ref,
1998 int verbosity, struct got_repository *repo)
2000 const struct got_error *err = NULL, *unlock_err;
2001 struct got_reference *symref;
2002 int symref_is_locked = 0;
2004 err = got_ref_open(&symref, repo, refname, 1);
2005 if (err) {
2006 if (err->code != GOT_ERR_NOT_REF)
2007 return err;
2008 err = got_ref_alloc_symref(&symref, refname, target_ref);
2009 if (err)
2010 goto done;
2012 err = got_ref_write(symref, repo);
2013 if (err)
2014 goto done;
2016 if (verbosity >= 0)
2017 printf("Created reference %s: %s\n",
2018 got_ref_get_name(symref),
2019 got_ref_get_symref_target(symref));
2020 } else {
2021 symref_is_locked = 1;
2023 if (strcmp(got_ref_get_symref_target(symref),
2024 got_ref_get_name(target_ref)) == 0)
2025 goto done;
2027 err = got_ref_change_symref(symref,
2028 got_ref_get_name(target_ref));
2029 if (err)
2030 goto done;
2032 err = got_ref_write(symref, repo);
2033 if (err)
2034 goto done;
2036 if (verbosity >= 0)
2037 printf("Updated %s: %s\n", got_ref_get_name(symref),
2038 got_ref_get_symref_target(symref));
2041 done:
2042 if (symref_is_locked) {
2043 unlock_err = got_ref_unlock(symref);
2044 if (unlock_err && err == NULL)
2045 err = unlock_err;
2047 got_ref_close(symref);
2048 return err;
2051 __dead static void
2052 usage_fetch(void)
2054 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2055 "[-R reference] [-r repository-path] [remote-repository]\n",
2056 getprogname());
2057 exit(1);
2060 static const struct got_error *
2061 delete_missing_ref(struct got_reference *ref,
2062 int verbosity, struct got_repository *repo)
2064 const struct got_error *err = NULL;
2065 struct got_object_id *id = NULL;
2066 char *id_str = NULL;
2068 if (got_ref_is_symbolic(ref)) {
2069 err = got_ref_delete(ref, repo);
2070 if (err)
2071 return err;
2072 if (verbosity >= 0) {
2073 printf("Deleted %s: %s\n",
2074 got_ref_get_name(ref),
2075 got_ref_get_symref_target(ref));
2077 } else {
2078 err = got_ref_resolve(&id, repo, ref);
2079 if (err)
2080 return err;
2081 err = got_object_id_str(&id_str, id);
2082 if (err)
2083 goto done;
2085 err = got_ref_delete(ref, repo);
2086 if (err)
2087 goto done;
2088 if (verbosity >= 0) {
2089 printf("Deleted %s: %s\n",
2090 got_ref_get_name(ref), id_str);
2093 done:
2094 free(id);
2095 free(id_str);
2096 return err;
2099 static const struct got_error *
2100 delete_missing_refs(struct got_pathlist_head *their_refs,
2101 struct got_pathlist_head *their_symrefs,
2102 const struct got_remote_repo *remote,
2103 int verbosity, struct got_repository *repo)
2105 const struct got_error *err = NULL, *unlock_err;
2106 struct got_reflist_head my_refs;
2107 struct got_reflist_entry *re;
2108 struct got_pathlist_entry *pe;
2109 char *remote_namespace = NULL;
2110 char *local_refname = NULL;
2112 TAILQ_INIT(&my_refs);
2114 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2115 == -1)
2116 return got_error_from_errno("asprintf");
2118 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2119 if (err)
2120 goto done;
2122 TAILQ_FOREACH(re, &my_refs, entry) {
2123 const char *refname = got_ref_get_name(re->ref);
2124 const char *their_refname;
2126 if (remote->mirror_references) {
2127 their_refname = refname;
2128 } else {
2129 if (strncmp(refname, remote_namespace,
2130 strlen(remote_namespace)) == 0) {
2131 if (strcmp(refname + strlen(remote_namespace),
2132 GOT_REF_HEAD) == 0)
2133 continue;
2134 if (asprintf(&local_refname, "refs/heads/%s",
2135 refname + strlen(remote_namespace)) == -1) {
2136 err = got_error_from_errno("asprintf");
2137 goto done;
2139 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2140 continue;
2142 their_refname = local_refname;
2145 TAILQ_FOREACH(pe, their_refs, entry) {
2146 if (strcmp(their_refname, pe->path) == 0)
2147 break;
2149 if (pe != NULL)
2150 continue;
2152 TAILQ_FOREACH(pe, their_symrefs, entry) {
2153 if (strcmp(their_refname, pe->path) == 0)
2154 break;
2156 if (pe != NULL)
2157 continue;
2159 err = delete_missing_ref(re->ref, verbosity, repo);
2160 if (err)
2161 break;
2163 if (local_refname) {
2164 struct got_reference *ref;
2165 err = got_ref_open(&ref, repo, local_refname, 1);
2166 if (err) {
2167 if (err->code != GOT_ERR_NOT_REF)
2168 break;
2169 free(local_refname);
2170 local_refname = NULL;
2171 continue;
2173 err = delete_missing_ref(ref, verbosity, repo);
2174 if (err)
2175 break;
2176 unlock_err = got_ref_unlock(ref);
2177 got_ref_close(ref);
2178 if (unlock_err && err == NULL) {
2179 err = unlock_err;
2180 break;
2183 free(local_refname);
2184 local_refname = NULL;
2187 done:
2188 got_ref_list_free(&my_refs);
2189 free(remote_namespace);
2190 free(local_refname);
2191 return err;
2194 static const struct got_error *
2195 update_wanted_ref(const char *refname, struct got_object_id *id,
2196 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2198 const struct got_error *err, *unlock_err;
2199 char *remote_refname;
2200 struct got_reference *ref;
2202 if (strncmp("refs/", refname, 5) == 0)
2203 refname += 5;
2205 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2206 remote_repo_name, refname) == -1)
2207 return got_error_from_errno("asprintf");
2209 err = got_ref_open(&ref, repo, remote_refname, 1);
2210 if (err) {
2211 if (err->code != GOT_ERR_NOT_REF)
2212 goto done;
2213 err = create_ref(remote_refname, id, verbosity, repo);
2214 } else {
2215 err = update_ref(ref, id, 0, verbosity, repo);
2216 unlock_err = got_ref_unlock(ref);
2217 if (unlock_err && err == NULL)
2218 err = unlock_err;
2219 got_ref_close(ref);
2221 done:
2222 free(remote_refname);
2223 return err;
2226 static const struct got_error *
2227 delete_ref(struct got_repository *repo, struct got_reference *ref)
2229 const struct got_error *err = NULL;
2230 struct got_object_id *id = NULL;
2231 char *id_str = NULL;
2232 const char *target;
2234 if (got_ref_is_symbolic(ref)) {
2235 target = got_ref_get_symref_target(ref);
2236 } else {
2237 err = got_ref_resolve(&id, repo, ref);
2238 if (err)
2239 goto done;
2240 err = got_object_id_str(&id_str, id);
2241 if (err)
2242 goto done;
2243 target = id_str;
2246 err = got_ref_delete(ref, repo);
2247 if (err)
2248 goto done;
2250 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2251 done:
2252 free(id);
2253 free(id_str);
2254 return err;
2257 static const struct got_error *
2258 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2260 const struct got_error *err = NULL;
2261 struct got_reflist_head refs;
2262 struct got_reflist_entry *re;
2263 char *prefix;
2265 TAILQ_INIT(&refs);
2267 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2268 err = got_error_from_errno("asprintf");
2269 goto done;
2271 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2272 if (err)
2273 goto done;
2275 TAILQ_FOREACH(re, &refs, entry)
2276 delete_ref(repo, re->ref);
2277 done:
2278 got_ref_list_free(&refs);
2279 return err;
2282 static const struct got_error *
2283 cmd_fetch(int argc, char *argv[])
2285 const struct got_error *error = NULL, *unlock_err;
2286 char *cwd = NULL, *repo_path = NULL;
2287 const char *remote_name;
2288 char *proto = NULL, *host = NULL, *port = NULL;
2289 char *repo_name = NULL, *server_path = NULL;
2290 const struct got_remote_repo *remotes, *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 struct got_pathlist_entry *pe;
2298 struct got_reflist_head remote_refs;
2299 struct got_reflist_entry *re;
2300 struct got_object_id *pack_hash = NULL;
2301 int i, ch, fetchfd = -1, fetchstatus;
2302 pid_t fetchpid = -1;
2303 struct got_fetch_progress_arg fpa;
2304 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2305 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2306 int *pack_fds = NULL, have_bflag = 0;
2307 const char *remote_head = NULL, *worktree_branch = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&remote_refs);
2312 TAILQ_INIT(&wanted_branches);
2313 TAILQ_INIT(&wanted_refs);
2315 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2316 switch (ch) {
2317 case 'a':
2318 fetch_all_branches = 1;
2319 break;
2320 case 'b':
2321 error = got_pathlist_append(&wanted_branches,
2322 optarg, NULL);
2323 if (error)
2324 return error;
2325 have_bflag = 1;
2326 break;
2327 case 'd':
2328 delete_refs = 1;
2329 break;
2330 case 'l':
2331 list_refs_only = 1;
2332 break;
2333 case 'q':
2334 verbosity = -1;
2335 break;
2336 case 'R':
2337 error = got_pathlist_append(&wanted_refs,
2338 optarg, NULL);
2339 if (error)
2340 return error;
2341 break;
2342 case 'r':
2343 repo_path = realpath(optarg, NULL);
2344 if (repo_path == NULL)
2345 return got_error_from_errno2("realpath",
2346 optarg);
2347 got_path_strip_trailing_slashes(repo_path);
2348 break;
2349 case 't':
2350 replace_tags = 1;
2351 break;
2352 case 'v':
2353 if (verbosity < 0)
2354 verbosity = 0;
2355 else if (verbosity < 3)
2356 verbosity++;
2357 break;
2358 case 'X':
2359 delete_remote = 1;
2360 break;
2361 default:
2362 usage_fetch();
2363 break;
2366 argc -= optind;
2367 argv += optind;
2369 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2370 option_conflict('a', 'b');
2371 if (list_refs_only) {
2372 if (!TAILQ_EMPTY(&wanted_branches))
2373 option_conflict('l', 'b');
2374 if (fetch_all_branches)
2375 option_conflict('l', 'a');
2376 if (delete_refs)
2377 option_conflict('l', 'd');
2378 if (delete_remote)
2379 option_conflict('l', 'X');
2381 if (delete_remote) {
2382 if (fetch_all_branches)
2383 option_conflict('X', 'a');
2384 if (!TAILQ_EMPTY(&wanted_branches))
2385 option_conflict('X', 'b');
2386 if (delete_refs)
2387 option_conflict('X', 'd');
2388 if (replace_tags)
2389 option_conflict('X', 't');
2390 if (!TAILQ_EMPTY(&wanted_refs))
2391 option_conflict('X', 'R');
2394 if (argc == 0) {
2395 if (delete_remote)
2396 errx(1, "-X option requires a remote name");
2397 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2398 } else if (argc == 1)
2399 remote_name = argv[0];
2400 else
2401 usage_fetch();
2403 cwd = getcwd(NULL, 0);
2404 if (cwd == NULL) {
2405 error = got_error_from_errno("getcwd");
2406 goto done;
2409 error = got_repo_pack_fds_open(&pack_fds);
2410 if (error != NULL)
2411 goto done;
2413 if (repo_path == NULL) {
2414 error = got_worktree_open(&worktree, cwd);
2415 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2416 goto done;
2417 else
2418 error = NULL;
2419 if (worktree) {
2420 repo_path =
2421 strdup(got_worktree_get_repo_path(worktree));
2422 if (repo_path == NULL)
2423 error = got_error_from_errno("strdup");
2424 if (error)
2425 goto done;
2426 } else {
2427 repo_path = strdup(cwd);
2428 if (repo_path == NULL) {
2429 error = got_error_from_errno("strdup");
2430 goto done;
2435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2436 if (error)
2437 goto done;
2439 if (delete_remote) {
2440 error = delete_refs_for_remote(repo, remote_name);
2441 goto done; /* nothing else to do */
2444 if (worktree) {
2445 worktree_conf = got_worktree_get_gotconfig(worktree);
2446 if (worktree_conf) {
2447 got_gotconfig_get_remotes(&nremotes, &remotes,
2448 worktree_conf);
2449 for (i = 0; i < nremotes; i++) {
2450 if (strcmp(remotes[i].name, remote_name) == 0) {
2451 remote = &remotes[i];
2452 break;
2457 if (remote == NULL) {
2458 repo_conf = got_repo_get_gotconfig(repo);
2459 if (repo_conf) {
2460 got_gotconfig_get_remotes(&nremotes, &remotes,
2461 repo_conf);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2470 if (remote == NULL) {
2471 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2472 for (i = 0; i < nremotes; i++) {
2473 if (strcmp(remotes[i].name, remote_name) == 0) {
2474 remote = &remotes[i];
2475 break;
2479 if (remote == NULL) {
2480 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_branches)) {
2485 if (!fetch_all_branches)
2486 fetch_all_branches = remote->fetch_all_branches;
2487 for (i = 0; i < remote->nfetch_branches; i++) {
2488 error = got_pathlist_append(&wanted_branches,
2489 remote->fetch_branches[i], NULL);
2490 if (error)
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_refs)) {
2495 for (i = 0; i < remote->nfetch_refs; i++) {
2496 error = got_pathlist_append(&wanted_refs,
2497 remote->fetch_refs[i], NULL);
2498 if (error)
2499 goto done;
2503 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2504 &repo_name, remote->fetch_url);
2505 if (error)
2506 goto done;
2508 if (strcmp(proto, "git") == 0) {
2509 #ifndef PROFILE
2510 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2511 "sendfd dns inet unveil", NULL) == -1)
2512 err(1, "pledge");
2513 #endif
2514 } else if (strcmp(proto, "git+ssh") == 0 ||
2515 strcmp(proto, "ssh") == 0) {
2516 #ifndef PROFILE
2517 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2518 "sendfd unveil", NULL) == -1)
2519 err(1, "pledge");
2520 #endif
2521 } else if (strcmp(proto, "http") == 0 ||
2522 strcmp(proto, "git+http") == 0) {
2523 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2524 goto done;
2525 } else {
2526 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2527 goto done;
2530 error = got_dial_apply_unveil(proto);
2531 if (error)
2532 goto done;
2534 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2535 if (error)
2536 goto done;
2538 if (verbosity >= 0) {
2539 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2540 remote->name, proto, host,
2541 port ? ":" : "", port ? port : "",
2542 *server_path == '/' ? "" : "/", server_path);
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 if (!have_bflag) {
2552 * If set, get this remote's HEAD ref target so
2553 * if it has changed on the server we can fetch it.
2555 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2556 got_ref_cmp_by_name, repo);
2557 if (error)
2558 goto done;
2560 TAILQ_FOREACH(re, &remote_refs, entry) {
2561 const char *remote_refname, *remote_target;
2562 size_t remote_name_len;
2564 if (!got_ref_is_symbolic(re->ref))
2565 continue;
2567 remote_name_len = strlen(remote->name);
2568 remote_refname = got_ref_get_name(re->ref);
2570 /* we only want refs/remotes/$remote->name/HEAD */
2571 if (strncmp(remote_refname + 13, remote->name,
2572 remote_name_len) != 0)
2573 continue;
2575 if (strcmp(remote_refname + remote_name_len + 14,
2576 GOT_REF_HEAD) != 0)
2577 continue;
2580 * Take the name itself because we already
2581 * only match with refs/heads/ in fetch_pack().
2583 remote_target = got_ref_get_symref_target(re->ref);
2584 remote_head = remote_target + remote_name_len + 14;
2585 break;
2588 if (worktree) {
2589 const char *refname;
2591 refname = got_worktree_get_head_ref_name(worktree);
2592 if (strncmp(refname, "refs/heads/", 11) == 0)
2593 worktree_branch = refname;
2597 fpa.last_scaled_size[0] = '\0';
2598 fpa.last_p_indexed = -1;
2599 fpa.last_p_resolved = -1;
2600 fpa.verbosity = verbosity;
2601 fpa.repo = repo;
2602 fpa.create_configs = 0;
2603 fpa.configs_created = 0;
2604 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2606 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2607 remote->mirror_references, fetch_all_branches, &wanted_branches,
2608 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2609 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2610 if (error)
2611 goto done;
2613 if (list_refs_only) {
2614 error = list_remote_refs(&symrefs, &refs);
2615 goto done;
2618 if (pack_hash == NULL) {
2619 if (verbosity >= 0)
2620 printf("Already up-to-date\n");
2621 } else if (verbosity >= 0) {
2622 error = got_object_id_str(&id_str, pack_hash);
2623 if (error)
2624 goto done;
2625 printf("\nFetched %s.pack\n", id_str);
2626 free(id_str);
2627 id_str = NULL;
2630 /* Update references provided with the pack file. */
2631 TAILQ_FOREACH(pe, &refs, entry) {
2632 const char *refname = pe->path;
2633 struct got_object_id *id = pe->data;
2634 struct got_reference *ref;
2635 char *remote_refname;
2637 if (is_wanted_ref(&wanted_refs, refname) &&
2638 !remote->mirror_references) {
2639 error = update_wanted_ref(refname, id,
2640 remote->name, verbosity, repo);
2641 if (error)
2642 goto done;
2643 continue;
2646 if (remote->mirror_references ||
2647 strncmp("refs/tags/", refname, 10) == 0) {
2648 error = got_ref_open(&ref, repo, refname, 1);
2649 if (error) {
2650 if (error->code != GOT_ERR_NOT_REF)
2651 goto done;
2652 error = create_ref(refname, id, verbosity,
2653 repo);
2654 if (error)
2655 goto done;
2656 } else {
2657 error = update_ref(ref, id, replace_tags,
2658 verbosity, repo);
2659 unlock_err = got_ref_unlock(ref);
2660 if (unlock_err && error == NULL)
2661 error = unlock_err;
2662 got_ref_close(ref);
2663 if (error)
2664 goto done;
2666 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2667 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2668 remote_name, refname + 11) == -1) {
2669 error = got_error_from_errno("asprintf");
2670 goto done;
2673 error = got_ref_open(&ref, repo, remote_refname, 1);
2674 if (error) {
2675 if (error->code != GOT_ERR_NOT_REF)
2676 goto done;
2677 error = create_ref(remote_refname, id,
2678 verbosity, repo);
2679 if (error)
2680 goto done;
2681 } else {
2682 error = update_ref(ref, id, replace_tags,
2683 verbosity, repo);
2684 unlock_err = got_ref_unlock(ref);
2685 if (unlock_err && error == NULL)
2686 error = unlock_err;
2687 got_ref_close(ref);
2688 if (error)
2689 goto done;
2692 /* Also create a local branch if none exists yet. */
2693 error = got_ref_open(&ref, repo, refname, 1);
2694 if (error) {
2695 if (error->code != GOT_ERR_NOT_REF)
2696 goto done;
2697 error = create_ref(refname, id, verbosity,
2698 repo);
2699 if (error)
2700 goto done;
2701 } else {
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2709 if (delete_refs) {
2710 error = delete_missing_refs(&refs, &symrefs, remote,
2711 verbosity, repo);
2712 if (error)
2713 goto done;
2716 if (!remote->mirror_references) {
2717 /* Update remote HEAD reference if the server provided one. */
2718 TAILQ_FOREACH(pe, &symrefs, entry) {
2719 struct got_reference *target_ref;
2720 const char *refname = pe->path;
2721 const char *target = pe->data;
2722 char *remote_refname = NULL, *remote_target = NULL;
2724 if (strcmp(refname, GOT_REF_HEAD) != 0)
2725 continue;
2727 if (strncmp("refs/heads/", target, 11) != 0)
2728 continue;
2730 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2731 remote->name, refname) == -1) {
2732 error = got_error_from_errno("asprintf");
2733 goto done;
2735 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2736 remote->name, target + 11) == -1) {
2737 error = got_error_from_errno("asprintf");
2738 free(remote_refname);
2739 goto done;
2742 error = got_ref_open(&target_ref, repo, remote_target,
2743 0);
2744 if (error) {
2745 free(remote_refname);
2746 free(remote_target);
2747 if (error->code == GOT_ERR_NOT_REF) {
2748 error = NULL;
2749 continue;
2751 goto done;
2753 error = update_symref(remote_refname, target_ref,
2754 verbosity, repo);
2755 free(remote_refname);
2756 free(remote_target);
2757 got_ref_close(target_ref);
2758 if (error)
2759 goto done;
2762 done:
2763 if (fetchpid > 0) {
2764 if (kill(fetchpid, SIGTERM) == -1)
2765 error = got_error_from_errno("kill");
2766 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2767 error = got_error_from_errno("waitpid");
2769 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2770 error = got_error_from_errno("close");
2771 if (repo) {
2772 const struct got_error *close_err = got_repo_close(repo);
2773 if (error == NULL)
2774 error = close_err;
2776 if (worktree)
2777 got_worktree_close(worktree);
2778 if (pack_fds) {
2779 const struct got_error *pack_err =
2780 got_repo_pack_fds_close(pack_fds);
2781 if (error == NULL)
2782 error = pack_err;
2784 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2786 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2787 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2788 got_ref_list_free(&remote_refs);
2789 free(id_str);
2790 free(cwd);
2791 free(repo_path);
2792 free(pack_hash);
2793 free(proto);
2794 free(host);
2795 free(port);
2796 free(server_path);
2797 free(repo_name);
2798 return error;
2802 __dead static void
2803 usage_checkout(void)
2805 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2806 "[-p path-prefix] repository-path [work-tree-path]\n",
2807 getprogname());
2808 exit(1);
2811 static void
2812 show_worktree_base_ref_warning(void)
2814 fprintf(stderr, "%s: warning: could not create a reference "
2815 "to the work tree's base commit; the commit could be "
2816 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2817 "repository writable and running 'got update' will prevent this\n",
2818 getprogname());
2821 struct got_checkout_progress_arg {
2822 const char *worktree_path;
2823 int had_base_commit_ref_error;
2824 int verbosity;
2827 static const struct got_error *
2828 checkout_progress(void *arg, unsigned char status, const char *path)
2830 struct got_checkout_progress_arg *a = arg;
2832 /* Base commit bump happens silently. */
2833 if (status == GOT_STATUS_BUMP_BASE)
2834 return NULL;
2836 if (status == GOT_STATUS_BASE_REF_ERR) {
2837 a->had_base_commit_ref_error = 1;
2838 return NULL;
2841 while (path[0] == '/')
2842 path++;
2844 if (a->verbosity >= 0)
2845 printf("%c %s/%s\n", status, a->worktree_path, path);
2847 return NULL;
2850 static const struct got_error *
2851 check_cancelled(void *arg)
2853 if (sigint_received || sigpipe_received)
2854 return got_error(GOT_ERR_CANCELLED);
2855 return NULL;
2858 static const struct got_error *
2859 check_linear_ancestry(struct got_object_id *commit_id,
2860 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2861 struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct got_object_id *yca_id;
2866 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2867 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2868 if (err)
2869 return err;
2871 if (yca_id == NULL)
2872 return got_error(GOT_ERR_ANCESTRY);
2875 * Require a straight line of history between the target commit
2876 * and the work tree's base commit.
2878 * Non-linear situations such as this require a rebase:
2880 * (commit) D F (base_commit)
2881 * \ /
2882 * C E
2883 * \ /
2884 * B (yca)
2885 * |
2886 * A
2888 * 'got update' only handles linear cases:
2889 * Update forwards in time: A (base/yca) - B - C - D (commit)
2890 * Update backwards in time: D (base) - C - B - A (commit/yca)
2892 if (allow_forwards_in_time_only) {
2893 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2894 return got_error(GOT_ERR_ANCESTRY);
2895 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2896 got_object_id_cmp(base_commit_id, yca_id) != 0)
2897 return got_error(GOT_ERR_ANCESTRY);
2899 free(yca_id);
2900 return NULL;
2903 static const struct got_error *
2904 check_same_branch(struct got_object_id *commit_id,
2905 struct got_reference *head_ref, struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2911 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2912 if (err)
2913 goto done;
2915 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2916 goto done;
2918 err = got_commit_graph_open(&graph, "/", 1);
2919 if (err)
2920 goto done;
2922 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2923 check_cancelled, NULL);
2924 if (err)
2925 goto done;
2927 for (;;) {
2928 struct got_object_id id;
2930 err = got_commit_graph_iter_next(&id, graph, repo,
2931 check_cancelled, NULL);
2932 if (err) {
2933 if (err->code == GOT_ERR_ITER_COMPLETED)
2934 err = got_error(GOT_ERR_ANCESTRY);
2935 break;
2938 if (got_object_id_cmp(&id, commit_id) == 0)
2939 break;
2941 done:
2942 if (graph)
2943 got_commit_graph_close(graph);
2944 free(head_commit_id);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL, *keyword_idstr = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 #ifndef PROFILE
2994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2995 "unveil", NULL) == -1)
2996 err(1, "pledge");
2997 #endif
2999 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3000 switch (ch) {
3001 case 'b':
3002 branch_name = optarg;
3003 break;
3004 case 'c':
3005 commit_id_str = strdup(optarg);
3006 if (commit_id_str == NULL)
3007 return got_error_from_errno("strdup");
3008 break;
3009 case 'E':
3010 allow_nonempty = 1;
3011 break;
3012 case 'p':
3013 path_prefix = optarg;
3014 break;
3015 case 'q':
3016 verbosity = -1;
3017 break;
3018 default:
3019 usage_checkout();
3020 /* NOTREACHED */
3024 argc -= optind;
3025 argv += optind;
3027 if (argc == 1) {
3028 char *base, *dotgit;
3029 const char *path;
3030 repo_path = realpath(argv[0], NULL);
3031 if (repo_path == NULL)
3032 return got_error_from_errno2("realpath", argv[0]);
3033 cwd = getcwd(NULL, 0);
3034 if (cwd == NULL) {
3035 error = got_error_from_errno("getcwd");
3036 goto done;
3038 if (path_prefix[0])
3039 path = path_prefix;
3040 else
3041 path = repo_path;
3042 error = got_path_basename(&base, path);
3043 if (error)
3044 goto done;
3045 dotgit = strstr(base, ".git");
3046 if (dotgit)
3047 *dotgit = '\0';
3048 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3049 error = got_error_from_errno("asprintf");
3050 free(base);
3051 goto done;
3053 free(base);
3054 } else if (argc == 2) {
3055 repo_path = realpath(argv[0], NULL);
3056 if (repo_path == NULL) {
3057 error = got_error_from_errno2("realpath", argv[0]);
3058 goto done;
3060 worktree_path = realpath(argv[1], NULL);
3061 if (worktree_path == NULL) {
3062 if (errno != ENOENT) {
3063 error = got_error_from_errno2("realpath",
3064 argv[1]);
3065 goto done;
3067 worktree_path = strdup(argv[1]);
3068 if (worktree_path == NULL) {
3069 error = got_error_from_errno("strdup");
3070 goto done;
3073 } else
3074 usage_checkout();
3076 got_path_strip_trailing_slashes(repo_path);
3077 got_path_strip_trailing_slashes(worktree_path);
3079 error = got_repo_pack_fds_open(&pack_fds);
3080 if (error != NULL)
3081 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 /* Pre-create work tree path for unveil(2) */
3088 error = got_path_mkdir(worktree_path);
3089 if (error) {
3090 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3091 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3092 goto done;
3093 if (!allow_nonempty &&
3094 !got_path_dir_is_empty(worktree_path)) {
3095 error = got_error_path(worktree_path,
3096 GOT_ERR_DIR_NOT_EMPTY);
3097 goto done;
3101 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3102 if (error)
3103 goto done;
3105 error = got_ref_open(&head_ref, repo, branch_name, 0);
3106 if (error != NULL)
3107 goto done;
3109 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3110 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3111 goto done;
3113 error = got_worktree_open(&worktree, worktree_path);
3114 if (error != NULL)
3115 goto done;
3117 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3118 path_prefix);
3119 if (error != NULL)
3120 goto done;
3121 if (!same_path_prefix) {
3122 error = got_error(GOT_ERR_PATH_PREFIX);
3123 goto done;
3126 if (commit_id_str) {
3127 struct got_reflist_head refs;
3128 TAILQ_INIT(&refs);
3129 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3130 NULL);
3131 if (error)
3132 goto done;
3134 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3135 repo, worktree);
3136 if (error != NULL)
3137 goto done;
3138 if (keyword_idstr != NULL) {
3139 free(commit_id_str);
3140 commit_id_str = keyword_idstr;
3143 error = got_repo_match_object_id(&commit_id, NULL,
3144 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3145 got_ref_list_free(&refs);
3146 if (error)
3147 goto done;
3148 error = check_linear_ancestry(commit_id,
3149 got_worktree_get_base_commit_id(worktree), 0, repo);
3150 if (error != NULL) {
3151 if (error->code == GOT_ERR_ANCESTRY) {
3152 error = checkout_ancestry_error(
3153 head_ref, commit_id_str);
3155 goto done;
3157 error = check_same_branch(commit_id, head_ref, repo);
3158 if (error) {
3159 if (error->code == GOT_ERR_ANCESTRY) {
3160 error = checkout_ancestry_error(
3161 head_ref, commit_id_str);
3163 goto done;
3165 error = got_worktree_set_base_commit_id(worktree, repo,
3166 commit_id);
3167 if (error)
3168 goto done;
3169 /* Expand potentially abbreviated commit ID string. */
3170 free(commit_id_str);
3171 error = got_object_id_str(&commit_id_str, commit_id);
3172 if (error)
3173 goto done;
3174 } else {
3175 commit_id = got_object_id_dup(
3176 got_worktree_get_base_commit_id(worktree));
3177 if (commit_id == NULL) {
3178 error = got_error_from_errno("got_object_id_dup");
3179 goto done;
3181 error = got_object_id_str(&commit_id_str, commit_id);
3182 if (error)
3183 goto done;
3186 error = got_pathlist_append(&paths, "", NULL);
3187 if (error)
3188 goto done;
3189 cpa.worktree_path = worktree_path;
3190 cpa.had_base_commit_ref_error = 0;
3191 cpa.verbosity = verbosity;
3192 error = got_worktree_checkout_files(worktree, &paths, repo,
3193 checkout_progress, &cpa, check_cancelled, NULL);
3194 if (error != NULL)
3195 goto done;
3197 if (got_ref_is_symbolic(head_ref)) {
3198 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3199 if (error)
3200 goto done;
3201 refname = got_ref_get_name(ref);
3202 } else
3203 refname = got_ref_get_name(head_ref);
3204 printf("Checked out %s: %s\n", refname, commit_id_str);
3205 printf("Now shut up and hack\n");
3206 if (cpa.had_base_commit_ref_error)
3207 show_worktree_base_ref_warning();
3208 done:
3209 if (pack_fds) {
3210 const struct got_error *pack_err =
3211 got_repo_pack_fds_close(pack_fds);
3212 if (error == NULL)
3213 error = pack_err;
3215 if (head_ref)
3216 got_ref_close(head_ref);
3217 if (ref)
3218 got_ref_close(ref);
3219 if (repo) {
3220 const struct got_error *close_err = got_repo_close(repo);
3221 if (error == NULL)
3222 error = close_err;
3224 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3225 free(commit_id_str);
3226 free(commit_id);
3227 free(repo_path);
3228 free(worktree_path);
3229 free(cwd);
3230 return error;
3233 struct got_update_progress_arg {
3234 int did_something;
3235 int conflicts;
3236 int obstructed;
3237 int not_updated;
3238 int missing;
3239 int not_deleted;
3240 int unversioned;
3241 int verbosity;
3244 static void
3245 print_update_progress_stats(struct got_update_progress_arg *upa)
3247 if (!upa->did_something)
3248 return;
3250 if (upa->conflicts > 0)
3251 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3252 if (upa->obstructed > 0)
3253 printf("File paths obstructed by a non-regular file: %d\n",
3254 upa->obstructed);
3255 if (upa->not_updated > 0)
3256 printf("Files not updated because of existing merge "
3257 "conflicts: %d\n", upa->not_updated);
3261 * The meaning of some status codes differs between merge-style operations and
3262 * update operations. For example, the ! status code means "file was missing"
3263 * if changes were merged into the work tree, and "missing file was restored"
3264 * if the work tree was updated. This function should be used by any operation
3265 * which merges changes into the work tree without updating the work tree.
3267 static void
3268 print_merge_progress_stats(struct got_update_progress_arg *upa)
3270 if (!upa->did_something)
3271 return;
3273 if (upa->conflicts > 0)
3274 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3275 if (upa->obstructed > 0)
3276 printf("File paths obstructed by a non-regular file: %d\n",
3277 upa->obstructed);
3278 if (upa->missing > 0)
3279 printf("Files which had incoming changes but could not be "
3280 "found in the work tree: %d\n", upa->missing);
3281 if (upa->not_deleted > 0)
3282 printf("Files not deleted due to differences in deleted "
3283 "content: %d\n", upa->not_deleted);
3284 if (upa->unversioned > 0)
3285 printf("Files not merged because an unversioned file was "
3286 "found in the work tree: %d\n", upa->unversioned);
3289 __dead static void
3290 usage_update(void)
3292 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3293 "[path ...]\n", getprogname());
3294 exit(1);
3297 static const struct got_error *
3298 update_progress(void *arg, unsigned char status, const char *path)
3300 struct got_update_progress_arg *upa = arg;
3302 if (status == GOT_STATUS_EXISTS ||
3303 status == GOT_STATUS_BASE_REF_ERR)
3304 return NULL;
3306 upa->did_something = 1;
3308 /* Base commit bump happens silently. */
3309 if (status == GOT_STATUS_BUMP_BASE)
3310 return NULL;
3312 if (status == GOT_STATUS_CONFLICT)
3313 upa->conflicts++;
3314 if (status == GOT_STATUS_OBSTRUCTED)
3315 upa->obstructed++;
3316 if (status == GOT_STATUS_CANNOT_UPDATE)
3317 upa->not_updated++;
3318 if (status == GOT_STATUS_MISSING)
3319 upa->missing++;
3320 if (status == GOT_STATUS_CANNOT_DELETE)
3321 upa->not_deleted++;
3322 if (status == GOT_STATUS_UNVERSIONED)
3323 upa->unversioned++;
3325 while (path[0] == '/')
3326 path++;
3327 if (upa->verbosity >= 0)
3328 printf("%c %s\n", status, path);
3330 return NULL;
3333 static const struct got_error *
3334 switch_head_ref(struct got_reference *head_ref,
3335 struct got_object_id *commit_id, struct got_worktree *worktree,
3336 struct got_repository *repo)
3338 const struct got_error *err = NULL;
3339 char *base_id_str;
3340 int ref_has_moved = 0;
3342 /* Trivial case: switching between two different references. */
3343 if (strcmp(got_ref_get_name(head_ref),
3344 got_worktree_get_head_ref_name(worktree)) != 0) {
3345 printf("Switching work tree from %s to %s\n",
3346 got_worktree_get_head_ref_name(worktree),
3347 got_ref_get_name(head_ref));
3348 return got_worktree_set_head_ref(worktree, head_ref);
3351 err = check_linear_ancestry(commit_id,
3352 got_worktree_get_base_commit_id(worktree), 0, repo);
3353 if (err) {
3354 if (err->code != GOT_ERR_ANCESTRY)
3355 return err;
3356 ref_has_moved = 1;
3358 if (!ref_has_moved)
3359 return NULL;
3361 /* Switching to a rebased branch with the same reference name. */
3362 err = got_object_id_str(&base_id_str,
3363 got_worktree_get_base_commit_id(worktree));
3364 if (err)
3365 return err;
3366 printf("Reference %s now points at a different branch\n",
3367 got_worktree_get_head_ref_name(worktree));
3368 printf("Switching work tree from %s to %s\n", base_id_str,
3369 got_worktree_get_head_ref_name(worktree));
3370 return NULL;
3373 static const struct got_error *
3374 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3376 const struct got_error *err;
3377 int in_progress;
3379 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3380 if (err)
3381 return err;
3382 if (in_progress)
3383 return got_error(GOT_ERR_REBASING);
3385 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3386 if (err)
3387 return err;
3388 if (in_progress)
3389 return got_error(GOT_ERR_HISTEDIT_BUSY);
3391 return NULL;
3394 static const struct got_error *
3395 check_merge_in_progress(struct got_worktree *worktree,
3396 struct got_repository *repo)
3398 const struct got_error *err;
3399 int in_progress;
3401 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3402 if (err)
3403 return err;
3404 if (in_progress)
3405 return got_error(GOT_ERR_MERGE_BUSY);
3407 return NULL;
3410 static const struct got_error *
3411 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3412 char *argv[], struct got_worktree *worktree)
3414 const struct got_error *err = NULL;
3415 char *path;
3416 struct got_pathlist_entry *new;
3417 int i;
3419 if (argc == 0) {
3420 path = strdup("");
3421 if (path == NULL)
3422 return got_error_from_errno("strdup");
3423 return got_pathlist_append(paths, path, NULL);
3426 for (i = 0; i < argc; i++) {
3427 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3428 if (err)
3429 break;
3430 err = got_pathlist_insert(&new, paths, path, NULL);
3431 if (err || new == NULL /* duplicate */) {
3432 free(path);
3433 if (err)
3434 break;
3438 return err;
3441 static const struct got_error *
3442 wrap_not_worktree_error(const struct got_error *orig_err,
3443 const char *cmdname, const char *path)
3445 const struct got_error *err;
3446 struct got_repository *repo;
3447 static char msg[512];
3448 int *pack_fds = NULL;
3450 err = got_repo_pack_fds_open(&pack_fds);
3451 if (err)
3452 return err;
3454 err = got_repo_open(&repo, path, NULL, pack_fds);
3455 if (err)
3456 return orig_err;
3458 snprintf(msg, sizeof(msg),
3459 "'got %s' needs a work tree in addition to a git repository\n"
3460 "Work trees can be checked out from this Git repository with "
3461 "'got checkout'.\n"
3462 "The got(1) manual page contains more information.", cmdname);
3463 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3464 if (repo) {
3465 const struct got_error *close_err = got_repo_close(repo);
3466 if (err == NULL)
3467 err = close_err;
3469 if (pack_fds) {
3470 const struct got_error *pack_err =
3471 got_repo_pack_fds_close(pack_fds);
3472 if (err == NULL)
3473 err = pack_err;
3475 return err;
3478 static const struct got_error *
3479 cmd_update(int argc, char *argv[])
3481 const struct got_error *error = NULL;
3482 struct got_repository *repo = NULL;
3483 struct got_worktree *worktree = NULL;
3484 char *worktree_path = NULL;
3485 struct got_object_id *commit_id = NULL;
3486 char *commit_id_str = NULL;
3487 const char *branch_name = NULL;
3488 struct got_reference *head_ref = NULL;
3489 struct got_pathlist_head paths;
3490 struct got_pathlist_entry *pe;
3491 int ch, verbosity = 0;
3492 struct got_update_progress_arg upa;
3493 int *pack_fds = NULL;
3495 TAILQ_INIT(&paths);
3497 #ifndef PROFILE
3498 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3499 "unveil", NULL) == -1)
3500 err(1, "pledge");
3501 #endif
3503 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3504 switch (ch) {
3505 case 'b':
3506 branch_name = optarg;
3507 break;
3508 case 'c':
3509 commit_id_str = strdup(optarg);
3510 if (commit_id_str == NULL)
3511 return got_error_from_errno("strdup");
3512 break;
3513 case 'q':
3514 verbosity = -1;
3515 break;
3516 default:
3517 usage_update();
3518 /* NOTREACHED */
3522 argc -= optind;
3523 argv += optind;
3525 worktree_path = getcwd(NULL, 0);
3526 if (worktree_path == NULL) {
3527 error = got_error_from_errno("getcwd");
3528 goto done;
3531 error = got_repo_pack_fds_open(&pack_fds);
3532 if (error != NULL)
3533 goto done;
3535 error = got_worktree_open(&worktree, worktree_path);
3536 if (error) {
3537 if (error->code == GOT_ERR_NOT_WORKTREE)
3538 error = wrap_not_worktree_error(error, "update",
3539 worktree_path);
3540 goto done;
3543 error = check_rebase_or_histedit_in_progress(worktree);
3544 if (error)
3545 goto done;
3547 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3548 NULL, pack_fds);
3549 if (error != NULL)
3550 goto done;
3552 error = apply_unveil(got_repo_get_path(repo), 0,
3553 got_worktree_get_root_path(worktree));
3554 if (error)
3555 goto done;
3557 error = check_merge_in_progress(worktree, repo);
3558 if (error)
3559 goto done;
3561 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3562 if (error)
3563 goto done;
3565 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3566 got_worktree_get_head_ref_name(worktree), 0);
3567 if (error != NULL)
3568 goto done;
3569 if (commit_id_str == NULL) {
3570 error = got_ref_resolve(&commit_id, repo, head_ref);
3571 if (error != NULL)
3572 goto done;
3573 error = got_object_id_str(&commit_id_str, commit_id);
3574 if (error != NULL)
3575 goto done;
3576 } else {
3577 struct got_reflist_head refs;
3578 char *keyword_idstr = NULL;
3580 TAILQ_INIT(&refs);
3582 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3583 NULL);
3584 if (error)
3585 goto done;
3587 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3588 repo, worktree);
3589 if (error != NULL)
3590 goto done;
3591 if (keyword_idstr != NULL) {
3592 free(commit_id_str);
3593 commit_id_str = keyword_idstr;
3596 error = got_repo_match_object_id(&commit_id, NULL,
3597 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3598 got_ref_list_free(&refs);
3599 free(commit_id_str);
3600 commit_id_str = NULL;
3601 if (error)
3602 goto done;
3603 error = got_object_id_str(&commit_id_str, commit_id);
3604 if (error)
3605 goto done;
3608 if (branch_name) {
3609 struct got_object_id *head_commit_id;
3610 TAILQ_FOREACH(pe, &paths, entry) {
3611 if (pe->path_len == 0)
3612 continue;
3613 error = got_error_msg(GOT_ERR_BAD_PATH,
3614 "switching between branches requires that "
3615 "the entire work tree gets updated");
3616 goto done;
3618 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3619 if (error)
3620 goto done;
3621 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3622 repo);
3623 free(head_commit_id);
3624 if (error != NULL)
3625 goto done;
3626 error = check_same_branch(commit_id, head_ref, repo);
3627 if (error)
3628 goto done;
3629 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3630 if (error)
3631 goto done;
3632 } else {
3633 error = check_linear_ancestry(commit_id,
3634 got_worktree_get_base_commit_id(worktree), 0, repo);
3635 if (error != NULL) {
3636 if (error->code == GOT_ERR_ANCESTRY)
3637 error = got_error(GOT_ERR_BRANCH_MOVED);
3638 goto done;
3640 error = check_same_branch(commit_id, head_ref, repo);
3641 if (error)
3642 goto done;
3645 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3646 commit_id) != 0) {
3647 error = got_worktree_set_base_commit_id(worktree, repo,
3648 commit_id);
3649 if (error)
3650 goto done;
3653 memset(&upa, 0, sizeof(upa));
3654 upa.verbosity = verbosity;
3655 error = got_worktree_checkout_files(worktree, &paths, repo,
3656 update_progress, &upa, check_cancelled, NULL);
3657 if (error != NULL)
3658 goto done;
3660 if (upa.did_something) {
3661 printf("Updated to %s: %s\n",
3662 got_worktree_get_head_ref_name(worktree), commit_id_str);
3663 } else
3664 printf("Already up-to-date\n");
3666 print_update_progress_stats(&upa);
3667 done:
3668 if (pack_fds) {
3669 const struct got_error *pack_err =
3670 got_repo_pack_fds_close(pack_fds);
3671 if (error == NULL)
3672 error = pack_err;
3674 if (repo) {
3675 const struct got_error *close_err = got_repo_close(repo);
3676 if (error == NULL)
3677 error = close_err;
3679 free(worktree_path);
3680 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3681 free(commit_id);
3682 free(commit_id_str);
3683 return error;
3686 static const struct got_error *
3687 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3688 const char *path, int diff_context, int ignore_whitespace,
3689 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3690 struct got_repository *repo, FILE *outfile)
3692 const struct got_error *err = NULL;
3693 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3694 FILE *f1 = NULL, *f2 = NULL;
3695 int fd1 = -1, fd2 = -1;
3697 fd1 = got_opentempfd();
3698 if (fd1 == -1)
3699 return got_error_from_errno("got_opentempfd");
3700 fd2 = got_opentempfd();
3701 if (fd2 == -1) {
3702 err = got_error_from_errno("got_opentempfd");
3703 goto done;
3706 if (blob_id1) {
3707 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3708 fd1);
3709 if (err)
3710 goto done;
3713 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3714 if (err)
3715 goto done;
3717 f1 = got_opentemp();
3718 if (f1 == NULL) {
3719 err = got_error_from_errno("got_opentemp");
3720 goto done;
3722 f2 = got_opentemp();
3723 if (f2 == NULL) {
3724 err = got_error_from_errno("got_opentemp");
3725 goto done;
3728 while (path[0] == '/')
3729 path++;
3730 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3731 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3732 force_text_diff, dsa, outfile);
3733 done:
3734 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3735 err = got_error_from_errno("close");
3736 if (blob1)
3737 got_object_blob_close(blob1);
3738 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3739 err = got_error_from_errno("close");
3740 if (blob2)
3741 got_object_blob_close(blob2);
3742 if (f1 && fclose(f1) == EOF && err == NULL)
3743 err = got_error_from_errno("fclose");
3744 if (f2 && fclose(f2) == EOF && err == NULL)
3745 err = got_error_from_errno("fclose");
3746 return err;
3749 static const struct got_error *
3750 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3751 const char *path, int diff_context, int ignore_whitespace,
3752 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3753 struct got_repository *repo, FILE *outfile)
3755 const struct got_error *err = NULL;
3756 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3757 struct got_diff_blob_output_unidiff_arg arg;
3758 FILE *f1 = NULL, *f2 = NULL;
3759 int fd1 = -1, fd2 = -1;
3761 if (tree_id1) {
3762 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3763 if (err)
3764 goto done;
3765 fd1 = got_opentempfd();
3766 if (fd1 == -1) {
3767 err = got_error_from_errno("got_opentempfd");
3768 goto done;
3772 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3773 if (err)
3774 goto done;
3776 f1 = got_opentemp();
3777 if (f1 == NULL) {
3778 err = got_error_from_errno("got_opentemp");
3779 goto done;
3782 f2 = got_opentemp();
3783 if (f2 == NULL) {
3784 err = got_error_from_errno("got_opentemp");
3785 goto done;
3787 fd2 = got_opentempfd();
3788 if (fd2 == -1) {
3789 err = got_error_from_errno("got_opentempfd");
3790 goto done;
3792 arg.diff_context = diff_context;
3793 arg.ignore_whitespace = ignore_whitespace;
3794 arg.force_text_diff = force_text_diff;
3795 arg.diffstat = dsa;
3796 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3797 arg.outfile = outfile;
3798 arg.lines = NULL;
3799 arg.nlines = 0;
3800 while (path[0] == '/')
3801 path++;
3802 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3803 got_diff_blob_output_unidiff, &arg, 1);
3804 done:
3805 if (tree1)
3806 got_object_tree_close(tree1);
3807 if (tree2)
3808 got_object_tree_close(tree2);
3809 if (f1 && fclose(f1) == EOF && err == NULL)
3810 err = got_error_from_errno("fclose");
3811 if (f2 && fclose(f2) == EOF && err == NULL)
3812 err = got_error_from_errno("fclose");
3813 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3814 err = got_error_from_errno("close");
3815 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3816 err = got_error_from_errno("close");
3817 return err;
3820 static const struct got_error *
3821 get_changed_paths(struct got_pathlist_head *paths,
3822 struct got_commit_object *commit, struct got_repository *repo,
3823 struct got_diffstat_cb_arg *dsa)
3825 const struct got_error *err = NULL;
3826 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3827 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3828 struct got_object_qid *qid;
3829 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3830 FILE *f1 = NULL, *f2 = NULL;
3831 int fd1 = -1, fd2 = -1;
3833 if (dsa) {
3834 cb = got_diff_tree_compute_diffstat;
3836 f1 = got_opentemp();
3837 if (f1 == NULL) {
3838 err = got_error_from_errno("got_opentemp");
3839 goto done;
3841 f2 = got_opentemp();
3842 if (f2 == NULL) {
3843 err = got_error_from_errno("got_opentemp");
3844 goto done;
3846 fd1 = got_opentempfd();
3847 if (fd1 == -1) {
3848 err = got_error_from_errno("got_opentempfd");
3849 goto done;
3851 fd2 = got_opentempfd();
3852 if (fd2 == -1) {
3853 err = got_error_from_errno("got_opentempfd");
3854 goto done;
3858 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3859 if (qid != NULL) {
3860 struct got_commit_object *pcommit;
3861 err = got_object_open_as_commit(&pcommit, repo,
3862 &qid->id);
3863 if (err)
3864 return err;
3866 tree_id1 = got_object_id_dup(
3867 got_object_commit_get_tree_id(pcommit));
3868 if (tree_id1 == NULL) {
3869 got_object_commit_close(pcommit);
3870 return got_error_from_errno("got_object_id_dup");
3872 got_object_commit_close(pcommit);
3876 if (tree_id1) {
3877 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3878 if (err)
3879 goto done;
3882 tree_id2 = got_object_commit_get_tree_id(commit);
3883 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3884 if (err)
3885 goto done;
3887 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3888 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3889 done:
3890 if (tree1)
3891 got_object_tree_close(tree1);
3892 if (tree2)
3893 got_object_tree_close(tree2);
3894 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3895 err = got_error_from_errno("close");
3896 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3897 err = got_error_from_errno("close");
3898 if (f1 && fclose(f1) == EOF && err == NULL)
3899 err = got_error_from_errno("fclose");
3900 if (f2 && fclose(f2) == EOF && err == NULL)
3901 err = got_error_from_errno("fclose");
3902 free(tree_id1);
3903 return err;
3906 static const struct got_error *
3907 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3908 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3909 struct got_repository *repo, FILE *outfile)
3911 const struct got_error *err = NULL;
3912 struct got_commit_object *pcommit = NULL;
3913 char *id_str1 = NULL, *id_str2 = NULL;
3914 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3915 struct got_object_qid *qid;
3917 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3918 if (qid != NULL) {
3919 err = got_object_open_as_commit(&pcommit, repo,
3920 &qid->id);
3921 if (err)
3922 return err;
3923 err = got_object_id_str(&id_str1, &qid->id);
3924 if (err)
3925 goto done;
3928 err = got_object_id_str(&id_str2, id);
3929 if (err)
3930 goto done;
3932 if (path && path[0] != '\0') {
3933 int obj_type;
3934 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3935 if (err)
3936 goto done;
3937 if (pcommit) {
3938 err = got_object_id_by_path(&obj_id1, repo,
3939 pcommit, path);
3940 if (err) {
3941 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3942 free(obj_id2);
3943 goto done;
3947 err = got_object_get_type(&obj_type, repo, obj_id2);
3948 if (err) {
3949 free(obj_id2);
3950 goto done;
3952 fprintf(outfile,
3953 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3954 fprintf(outfile, "commit - %s\n",
3955 id_str1 ? id_str1 : "/dev/null");
3956 fprintf(outfile, "commit + %s\n", id_str2);
3957 switch (obj_type) {
3958 case GOT_OBJ_TYPE_BLOB:
3959 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3960 0, 0, dsa, repo, outfile);
3961 break;
3962 case GOT_OBJ_TYPE_TREE:
3963 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3964 0, 0, dsa, repo, outfile);
3965 break;
3966 default:
3967 err = got_error(GOT_ERR_OBJ_TYPE);
3968 break;
3970 free(obj_id1);
3971 free(obj_id2);
3972 } else {
3973 obj_id2 = got_object_commit_get_tree_id(commit);
3974 if (pcommit)
3975 obj_id1 = got_object_commit_get_tree_id(pcommit);
3976 fprintf(outfile,
3977 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3978 fprintf(outfile, "commit - %s\n",
3979 id_str1 ? id_str1 : "/dev/null");
3980 fprintf(outfile, "commit + %s\n", id_str2);
3981 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3982 dsa, repo, outfile);
3984 done:
3985 free(id_str1);
3986 free(id_str2);
3987 if (pcommit)
3988 got_object_commit_close(pcommit);
3989 return err;
3992 static char *
3993 get_datestr(time_t *time, char *datebuf)
3995 struct tm mytm, *tm;
3996 char *p, *s;
3998 tm = gmtime_r(time, &mytm);
3999 if (tm == NULL)
4000 return NULL;
4001 s = asctime_r(tm, datebuf);
4002 if (s == NULL)
4003 return NULL;
4004 p = strchr(s, '\n');
4005 if (p)
4006 *p = '\0';
4007 return s;
4010 static const struct got_error *
4011 match_commit(int *have_match, struct got_object_id *id,
4012 struct got_commit_object *commit, regex_t *regex)
4014 const struct got_error *err = NULL;
4015 regmatch_t regmatch;
4016 char *id_str = NULL, *logmsg = NULL;
4018 *have_match = 0;
4020 err = got_object_id_str(&id_str, id);
4021 if (err)
4022 return err;
4024 err = got_object_commit_get_logmsg(&logmsg, commit);
4025 if (err)
4026 goto done;
4028 if (regexec(regex, got_object_commit_get_author(commit), 1,
4029 &regmatch, 0) == 0 ||
4030 regexec(regex, got_object_commit_get_committer(commit), 1,
4031 &regmatch, 0) == 0 ||
4032 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4033 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4034 *have_match = 1;
4035 done:
4036 free(id_str);
4037 free(logmsg);
4038 return err;
4041 static void
4042 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4043 regex_t *regex)
4045 regmatch_t regmatch;
4046 struct got_pathlist_entry *pe;
4048 *have_match = 0;
4050 TAILQ_FOREACH(pe, changed_paths, entry) {
4051 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4052 *have_match = 1;
4053 break;
4058 static const struct got_error *
4059 match_patch(int *have_match, struct got_commit_object *commit,
4060 struct got_object_id *id, const char *path, int diff_context,
4061 struct got_repository *repo, regex_t *regex, FILE *f)
4063 const struct got_error *err = NULL;
4064 char *line = NULL;
4065 size_t linesize = 0;
4066 regmatch_t regmatch;
4068 *have_match = 0;
4070 err = got_opentemp_truncate(f);
4071 if (err)
4072 return err;
4074 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4075 if (err)
4076 goto done;
4078 if (fseeko(f, 0L, SEEK_SET) == -1) {
4079 err = got_error_from_errno("fseeko");
4080 goto done;
4083 while (getline(&line, &linesize, f) != -1) {
4084 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4085 *have_match = 1;
4086 break;
4089 done:
4090 free(line);
4091 return err;
4094 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4096 static const struct got_error*
4097 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4098 struct got_object_id *id, struct got_repository *repo,
4099 int local_only)
4101 static const struct got_error *err = NULL;
4102 struct got_reflist_entry *re;
4103 char *s;
4104 const char *name;
4106 *refs_str = NULL;
4108 TAILQ_FOREACH(re, refs, entry) {
4109 struct got_tag_object *tag = NULL;
4110 struct got_object_id *ref_id;
4111 int cmp;
4113 name = got_ref_get_name(re->ref);
4114 if (strcmp(name, GOT_REF_HEAD) == 0)
4115 continue;
4116 if (strncmp(name, "refs/", 5) == 0)
4117 name += 5;
4118 if (strncmp(name, "got/", 4) == 0)
4119 continue;
4120 if (strncmp(name, "heads/", 6) == 0)
4121 name += 6;
4122 if (strncmp(name, "remotes/", 8) == 0) {
4123 if (local_only)
4124 continue;
4125 name += 8;
4126 s = strstr(name, "/" GOT_REF_HEAD);
4127 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4128 continue;
4130 err = got_ref_resolve(&ref_id, repo, re->ref);
4131 if (err)
4132 break;
4133 if (strncmp(name, "tags/", 5) == 0) {
4134 err = got_object_open_as_tag(&tag, repo, ref_id);
4135 if (err) {
4136 if (err->code != GOT_ERR_OBJ_TYPE) {
4137 free(ref_id);
4138 break;
4140 /* Ref points at something other than a tag. */
4141 err = NULL;
4142 tag = NULL;
4145 cmp = got_object_id_cmp(tag ?
4146 got_object_tag_get_object_id(tag) : ref_id, id);
4147 free(ref_id);
4148 if (tag)
4149 got_object_tag_close(tag);
4150 if (cmp != 0)
4151 continue;
4152 s = *refs_str;
4153 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4154 s ? ", " : "", name) == -1) {
4155 err = got_error_from_errno("asprintf");
4156 free(s);
4157 *refs_str = NULL;
4158 break;
4160 free(s);
4163 return err;
4166 static const struct got_error *
4167 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4168 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4170 const struct got_error *err = NULL;
4171 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4172 char *comma, *s, *nl;
4173 struct got_reflist_head *refs;
4174 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4175 struct tm tm;
4176 time_t committer_time;
4178 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4179 if (refs) {
4180 err = build_refs_str(&ref_str, refs, id, repo, 1);
4181 if (err)
4182 return err;
4184 /* Display the first matching ref only. */
4185 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4186 *comma = '\0';
4189 if (ref_str == NULL) {
4190 err = got_object_id_str(&id_str, id);
4191 if (err)
4192 return err;
4195 committer_time = got_object_commit_get_committer_time(commit);
4196 if (gmtime_r(&committer_time, &tm) == NULL) {
4197 err = got_error_from_errno("gmtime_r");
4198 goto done;
4200 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4201 err = got_error(GOT_ERR_NO_SPACE);
4202 goto done;
4205 err = got_object_commit_get_logmsg(&logmsg0, commit);
4206 if (err)
4207 goto done;
4209 s = logmsg0;
4210 while (isspace((unsigned char)s[0]))
4211 s++;
4213 nl = strchr(s, '\n');
4214 if (nl) {
4215 *nl = '\0';
4218 if (ref_str)
4219 printf("%s%-7s %s\n", datebuf, ref_str, s);
4220 else
4221 printf("%s%.7s %s\n", datebuf, id_str, s);
4223 if (fflush(stdout) != 0 && err == NULL)
4224 err = got_error_from_errno("fflush");
4225 done:
4226 free(id_str);
4227 free(ref_str);
4228 free(logmsg0);
4229 return err;
4232 static const struct got_error *
4233 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4235 struct got_pathlist_entry *pe;
4237 if (header != NULL)
4238 printf("%s\n", header);
4240 TAILQ_FOREACH(pe, dsa->paths, entry) {
4241 struct got_diff_changed_path *cp = pe->data;
4242 int pad = dsa->max_path_len - pe->path_len + 1;
4244 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4245 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4247 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4248 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4249 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4251 if (fflush(stdout) != 0)
4252 return got_error_from_errno("fflush");
4254 return NULL;
4257 static const struct got_error *
4258 printfile(FILE *f)
4260 char buf[8192];
4261 size_t r;
4263 if (fseeko(f, 0L, SEEK_SET) == -1)
4264 return got_error_from_errno("fseek");
4266 for (;;) {
4267 r = fread(buf, 1, sizeof(buf), f);
4268 if (r == 0) {
4269 if (ferror(f))
4270 return got_error_from_errno("fread");
4271 if (feof(f))
4272 break;
4274 if (fwrite(buf, 1, r, stdout) != r)
4275 return got_ferror(stdout, GOT_ERR_IO);
4278 return NULL;
4281 static const struct got_error *
4282 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4283 struct got_repository *repo, const char *path,
4284 struct got_pathlist_head *changed_paths,
4285 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4286 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4287 const char *prefix)
4289 const struct got_error *err = NULL;
4290 FILE *f = NULL;
4291 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4292 char datebuf[26];
4293 time_t committer_time;
4294 const char *author, *committer;
4295 char *refs_str = NULL;
4297 err = got_object_id_str(&id_str, id);
4298 if (err)
4299 return err;
4301 if (custom_refs_str == NULL) {
4302 struct got_reflist_head *refs;
4303 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4304 if (refs) {
4305 err = build_refs_str(&refs_str, refs, id, repo, 0);
4306 if (err)
4307 goto done;
4311 printf(GOT_COMMIT_SEP_STR);
4312 if (custom_refs_str)
4313 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4314 custom_refs_str);
4315 else
4316 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4317 refs_str ? " (" : "", refs_str ? refs_str : "",
4318 refs_str ? ")" : "");
4319 free(id_str);
4320 id_str = NULL;
4321 free(refs_str);
4322 refs_str = NULL;
4323 printf("from: %s\n", got_object_commit_get_author(commit));
4324 author = got_object_commit_get_author(commit);
4325 committer = got_object_commit_get_committer(commit);
4326 if (strcmp(author, committer) != 0)
4327 printf("via: %s\n", committer);
4328 committer_time = got_object_commit_get_committer_time(commit);
4329 datestr = get_datestr(&committer_time, datebuf);
4330 if (datestr)
4331 printf("date: %s UTC\n", datestr);
4332 if (got_object_commit_get_nparents(commit) > 1) {
4333 const struct got_object_id_queue *parent_ids;
4334 struct got_object_qid *qid;
4335 int n = 1;
4336 parent_ids = got_object_commit_get_parent_ids(commit);
4337 STAILQ_FOREACH(qid, parent_ids, entry) {
4338 err = got_object_id_str(&id_str, &qid->id);
4339 if (err)
4340 goto done;
4341 printf("parent %d: %s\n", n++, id_str);
4342 free(id_str);
4343 id_str = NULL;
4347 err = got_object_commit_get_logmsg(&logmsg0, commit);
4348 if (err)
4349 goto done;
4351 logmsg = logmsg0;
4352 do {
4353 line = strsep(&logmsg, "\n");
4354 if (line)
4355 printf(" %s\n", line);
4356 } while (line);
4357 free(logmsg0);
4359 if (changed_paths && diffstat == NULL) {
4360 struct got_pathlist_entry *pe;
4362 TAILQ_FOREACH(pe, changed_paths, entry) {
4363 struct got_diff_changed_path *cp = pe->data;
4365 printf(" %c %s\n", cp->status, pe->path);
4367 printf("\n");
4369 if (show_patch) {
4370 if (diffstat) {
4371 f = got_opentemp();
4372 if (f == NULL) {
4373 err = got_error_from_errno("got_opentemp");
4374 goto done;
4378 err = print_patch(commit, id, path, diff_context, diffstat,
4379 repo, diffstat == NULL ? stdout : f);
4380 if (err)
4381 goto done;
4383 if (diffstat) {
4384 err = print_diffstat(diffstat, NULL);
4385 if (err)
4386 goto done;
4387 if (show_patch) {
4388 err = printfile(f);
4389 if (err)
4390 goto done;
4393 if (show_patch)
4394 printf("\n");
4396 if (fflush(stdout) != 0 && err == NULL)
4397 err = got_error_from_errno("fflush");
4398 done:
4399 if (f && fclose(f) == EOF && err == NULL)
4400 err = got_error_from_errno("fclose");
4401 free(id_str);
4402 free(refs_str);
4403 return err;
4406 static const struct got_error *
4407 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4408 struct got_repository *repo, const char *path, int show_changed_paths,
4409 int show_diffstat, int show_patch, const char *search_pattern,
4410 int diff_context, int limit, int log_branches, int reverse_display_order,
4411 struct got_reflist_object_id_map *refs_idmap, int one_line,
4412 FILE *tmpfile)
4414 const struct got_error *err;
4415 struct got_commit_graph *graph;
4416 regex_t regex;
4417 int have_match;
4418 struct got_object_id_queue reversed_commits;
4419 struct got_object_qid *qid;
4420 struct got_commit_object *commit;
4421 struct got_pathlist_head changed_paths;
4423 STAILQ_INIT(&reversed_commits);
4424 TAILQ_INIT(&changed_paths);
4426 if (search_pattern && regcomp(&regex, search_pattern,
4427 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4428 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4430 err = got_commit_graph_open(&graph, path, !log_branches);
4431 if (err)
4432 return err;
4433 err = got_commit_graph_iter_start(graph, root_id, repo,
4434 check_cancelled, NULL);
4435 if (err)
4436 goto done;
4437 for (;;) {
4438 struct got_object_id id;
4439 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4440 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4442 if (sigint_received || sigpipe_received)
4443 break;
4445 err = got_commit_graph_iter_next(&id, graph, repo,
4446 check_cancelled, NULL);
4447 if (err) {
4448 if (err->code == GOT_ERR_ITER_COMPLETED)
4449 err = NULL;
4450 break;
4453 err = got_object_open_as_commit(&commit, repo, &id);
4454 if (err)
4455 break;
4457 if ((show_changed_paths || (show_diffstat && !show_patch))
4458 && !reverse_display_order) {
4459 err = get_changed_paths(&changed_paths, commit, repo,
4460 show_diffstat ? &dsa : NULL);
4461 if (err)
4462 break;
4465 if (search_pattern) {
4466 err = match_commit(&have_match, &id, commit, &regex);
4467 if (err) {
4468 got_object_commit_close(commit);
4469 break;
4471 if (have_match == 0 && show_changed_paths)
4472 match_changed_paths(&have_match,
4473 &changed_paths, &regex);
4474 if (have_match == 0 && show_patch) {
4475 err = match_patch(&have_match, commit, &id,
4476 path, diff_context, repo, &regex, tmpfile);
4477 if (err)
4478 break;
4480 if (have_match == 0) {
4481 got_object_commit_close(commit);
4482 got_pathlist_free(&changed_paths,
4483 GOT_PATHLIST_FREE_ALL);
4484 continue;
4488 if (reverse_display_order) {
4489 err = got_object_qid_alloc(&qid, &id);
4490 if (err)
4491 break;
4492 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4493 got_object_commit_close(commit);
4494 } else {
4495 if (one_line)
4496 err = print_commit_oneline(commit, &id,
4497 repo, refs_idmap);
4498 else
4499 err = print_commit(commit, &id, repo, path,
4500 (show_changed_paths || show_diffstat) ?
4501 &changed_paths : NULL,
4502 show_diffstat ? &dsa : NULL, show_patch,
4503 diff_context, refs_idmap, NULL, NULL);
4504 got_object_commit_close(commit);
4505 if (err)
4506 break;
4508 if ((limit && --limit == 0) ||
4509 (end_id && got_object_id_cmp(&id, end_id) == 0))
4510 break;
4512 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4514 if (reverse_display_order) {
4515 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4516 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4517 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4519 err = got_object_open_as_commit(&commit, repo,
4520 &qid->id);
4521 if (err)
4522 break;
4523 if (show_changed_paths ||
4524 (show_diffstat && !show_patch)) {
4525 err = get_changed_paths(&changed_paths, commit,
4526 repo, show_diffstat ? &dsa : NULL);
4527 if (err)
4528 break;
4530 if (one_line)
4531 err = print_commit_oneline(commit, &qid->id,
4532 repo, refs_idmap);
4533 else
4534 err = print_commit(commit, &qid->id, repo, path,
4535 (show_changed_paths || show_diffstat) ?
4536 &changed_paths : NULL,
4537 show_diffstat ? &dsa : NULL, show_patch,
4538 diff_context, refs_idmap, NULL, NULL);
4539 got_object_commit_close(commit);
4540 if (err)
4541 break;
4542 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4545 done:
4546 while (!STAILQ_EMPTY(&reversed_commits)) {
4547 qid = STAILQ_FIRST(&reversed_commits);
4548 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4549 got_object_qid_free(qid);
4551 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4552 if (search_pattern)
4553 regfree(&regex);
4554 got_commit_graph_close(graph);
4555 return err;
4558 __dead static void
4559 usage_log(void)
4561 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4562 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4563 "[path]\n", getprogname());
4564 exit(1);
4567 static int
4568 get_default_log_limit(void)
4570 const char *got_default_log_limit;
4571 long long n;
4572 const char *errstr;
4574 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4575 if (got_default_log_limit == NULL)
4576 return 0;
4577 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4578 if (errstr != NULL)
4579 return 0;
4580 return n;
4583 static const struct got_error *
4584 cmd_log(int argc, char *argv[])
4586 const struct got_error *error;
4587 struct got_repository *repo = NULL;
4588 struct got_worktree *worktree = NULL;
4589 struct got_object_id *start_id = NULL, *end_id = NULL;
4590 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4591 const char *start_commit = NULL, *end_commit = NULL;
4592 const char *search_pattern = NULL;
4593 int diff_context = -1, ch;
4594 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4595 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4596 const char *errstr;
4597 struct got_reflist_head refs;
4598 struct got_reflist_object_id_map *refs_idmap = NULL;
4599 FILE *tmpfile = NULL;
4600 int *pack_fds = NULL;
4602 TAILQ_INIT(&refs);
4604 #ifndef PROFILE
4605 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4606 NULL)
4607 == -1)
4608 err(1, "pledge");
4609 #endif
4611 limit = get_default_log_limit();
4613 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4614 switch (ch) {
4615 case 'b':
4616 log_branches = 1;
4617 break;
4618 case 'C':
4619 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4620 &errstr);
4621 if (errstr != NULL)
4622 errx(1, "number of context lines is %s: %s",
4623 errstr, optarg);
4624 break;
4625 case 'c':
4626 start_commit = optarg;
4627 break;
4628 case 'd':
4629 show_diffstat = 1;
4630 break;
4631 case 'l':
4632 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4633 if (errstr != NULL)
4634 errx(1, "number of commits is %s: %s",
4635 errstr, optarg);
4636 break;
4637 case 'P':
4638 show_changed_paths = 1;
4639 break;
4640 case 'p':
4641 show_patch = 1;
4642 break;
4643 case 'R':
4644 reverse_display_order = 1;
4645 break;
4646 case 'r':
4647 repo_path = realpath(optarg, NULL);
4648 if (repo_path == NULL)
4649 return got_error_from_errno2("realpath",
4650 optarg);
4651 got_path_strip_trailing_slashes(repo_path);
4652 break;
4653 case 'S':
4654 search_pattern = optarg;
4655 break;
4656 case 's':
4657 one_line = 1;
4658 break;
4659 case 'x':
4660 end_commit = optarg;
4661 break;
4662 default:
4663 usage_log();
4664 /* NOTREACHED */
4668 argc -= optind;
4669 argv += optind;
4671 if (diff_context == -1)
4672 diff_context = 3;
4673 else if (!show_patch)
4674 errx(1, "-C requires -p");
4676 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4677 errx(1, "cannot use -s with -d, -p or -P");
4679 cwd = getcwd(NULL, 0);
4680 if (cwd == NULL) {
4681 error = got_error_from_errno("getcwd");
4682 goto done;
4685 error = got_repo_pack_fds_open(&pack_fds);
4686 if (error != NULL)
4687 goto done;
4689 if (repo_path == NULL) {
4690 error = got_worktree_open(&worktree, cwd);
4691 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4692 goto done;
4693 error = NULL;
4696 if (argc == 1) {
4697 if (worktree) {
4698 error = got_worktree_resolve_path(&path, worktree,
4699 argv[0]);
4700 if (error)
4701 goto done;
4702 } else {
4703 path = strdup(argv[0]);
4704 if (path == NULL) {
4705 error = got_error_from_errno("strdup");
4706 goto done;
4709 } else if (argc != 0)
4710 usage_log();
4712 if (repo_path == NULL) {
4713 repo_path = worktree ?
4714 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4716 if (repo_path == NULL) {
4717 error = got_error_from_errno("strdup");
4718 goto done;
4721 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4722 if (error != NULL)
4723 goto done;
4725 error = apply_unveil(got_repo_get_path(repo), 1,
4726 worktree ? got_worktree_get_root_path(worktree) : NULL);
4727 if (error)
4728 goto done;
4730 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4731 if (error)
4732 goto done;
4734 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4735 if (error)
4736 goto done;
4738 if (start_commit == NULL) {
4739 struct got_reference *head_ref;
4740 struct got_commit_object *commit = NULL;
4741 error = got_ref_open(&head_ref, repo,
4742 worktree ? got_worktree_get_head_ref_name(worktree)
4743 : GOT_REF_HEAD, 0);
4744 if (error != NULL)
4745 goto done;
4746 error = got_ref_resolve(&start_id, repo, head_ref);
4747 got_ref_close(head_ref);
4748 if (error != NULL)
4749 goto done;
4750 error = got_object_open_as_commit(&commit, repo,
4751 start_id);
4752 if (error != NULL)
4753 goto done;
4754 got_object_commit_close(commit);
4755 } else {
4756 char *keyword_idstr = NULL;
4758 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4759 repo, worktree);
4760 if (error != NULL)
4761 goto done;
4762 if (keyword_idstr != NULL)
4763 start_commit = keyword_idstr;
4765 error = got_repo_match_object_id(&start_id, NULL,
4766 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4767 free(keyword_idstr);
4768 if (error != NULL)
4769 goto done;
4771 if (end_commit != NULL) {
4772 error = got_repo_match_object_id(&end_id, NULL,
4773 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4774 if (error != NULL)
4775 goto done;
4778 if (worktree) {
4780 * If a path was specified on the command line it was resolved
4781 * to a path in the work tree above. Prepend the work tree's
4782 * path prefix to obtain the corresponding in-repository path.
4784 if (path) {
4785 const char *prefix;
4786 prefix = got_worktree_get_path_prefix(worktree);
4787 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4788 (path[0] != '\0') ? "/" : "", path) == -1) {
4789 error = got_error_from_errno("asprintf");
4790 goto done;
4793 } else
4794 error = got_repo_map_path(&in_repo_path, repo,
4795 path ? path : "");
4796 if (error != NULL)
4797 goto done;
4798 if (in_repo_path) {
4799 free(path);
4800 path = in_repo_path;
4803 if (worktree) {
4804 /* Release work tree lock. */
4805 got_worktree_close(worktree);
4806 worktree = NULL;
4809 if (search_pattern && show_patch) {
4810 tmpfile = got_opentemp();
4811 if (tmpfile == NULL) {
4812 error = got_error_from_errno("got_opentemp");
4813 goto done;
4817 error = print_commits(start_id, end_id, repo, path ? path : "",
4818 show_changed_paths, show_diffstat, show_patch, search_pattern,
4819 diff_context, limit, log_branches, reverse_display_order,
4820 refs_idmap, one_line, tmpfile);
4821 done:
4822 free(path);
4823 free(repo_path);
4824 free(cwd);
4825 free(start_id);
4826 free(end_id);
4827 if (worktree)
4828 got_worktree_close(worktree);
4829 if (repo) {
4830 const struct got_error *close_err = got_repo_close(repo);
4831 if (error == NULL)
4832 error = close_err;
4834 if (pack_fds) {
4835 const struct got_error *pack_err =
4836 got_repo_pack_fds_close(pack_fds);
4837 if (error == NULL)
4838 error = pack_err;
4840 if (refs_idmap)
4841 got_reflist_object_id_map_free(refs_idmap);
4842 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4843 error = got_error_from_errno("fclose");
4844 got_ref_list_free(&refs);
4845 return error;
4848 __dead static void
4849 usage_diff(void)
4851 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4852 "[-r repository-path] [object1 object2 | path ...]\n",
4853 getprogname());
4854 exit(1);
4857 struct print_diff_arg {
4858 struct got_repository *repo;
4859 struct got_worktree *worktree;
4860 struct got_diffstat_cb_arg *diffstat;
4861 int diff_context;
4862 const char *id_str;
4863 int header_shown;
4864 int diff_staged;
4865 enum got_diff_algorithm diff_algo;
4866 int ignore_whitespace;
4867 int force_text_diff;
4868 FILE *f1;
4869 FILE *f2;
4870 FILE *outfile;
4874 * Create a file which contains the target path of a symlink so we can feed
4875 * it as content to the diff engine.
4877 static const struct got_error *
4878 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4879 const char *abspath)
4881 const struct got_error *err = NULL;
4882 char target_path[PATH_MAX];
4883 ssize_t target_len, outlen;
4885 *fd = -1;
4887 if (dirfd != -1) {
4888 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4889 if (target_len == -1)
4890 return got_error_from_errno2("readlinkat", abspath);
4891 } else {
4892 target_len = readlink(abspath, target_path, PATH_MAX);
4893 if (target_len == -1)
4894 return got_error_from_errno2("readlink", abspath);
4897 *fd = got_opentempfd();
4898 if (*fd == -1)
4899 return got_error_from_errno("got_opentempfd");
4901 outlen = write(*fd, target_path, target_len);
4902 if (outlen == -1) {
4903 err = got_error_from_errno("got_opentempfd");
4904 goto done;
4907 if (lseek(*fd, 0, SEEK_SET) == -1) {
4908 err = got_error_from_errno2("lseek", abspath);
4909 goto done;
4911 done:
4912 if (err) {
4913 close(*fd);
4914 *fd = -1;
4916 return err;
4919 static const struct got_error *
4920 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4921 const char *path, struct got_object_id *blob_id,
4922 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4923 int dirfd, const char *de_name)
4925 struct print_diff_arg *a = arg;
4926 const struct got_error *err = NULL;
4927 struct got_blob_object *blob1 = NULL;
4928 int fd = -1, fd1 = -1, fd2 = -1;
4929 FILE *f2 = NULL;
4930 char *abspath = NULL, *label1 = NULL;
4931 struct stat sb;
4932 off_t size1 = 0;
4933 int f2_exists = 0;
4935 memset(&sb, 0, sizeof(sb));
4937 if (a->diff_staged) {
4938 if (staged_status != GOT_STATUS_MODIFY &&
4939 staged_status != GOT_STATUS_ADD &&
4940 staged_status != GOT_STATUS_DELETE)
4941 return NULL;
4942 } else {
4943 if (staged_status == GOT_STATUS_DELETE)
4944 return NULL;
4945 if (status == GOT_STATUS_NONEXISTENT)
4946 return got_error_set_errno(ENOENT, path);
4947 if (status != GOT_STATUS_MODIFY &&
4948 status != GOT_STATUS_ADD &&
4949 status != GOT_STATUS_DELETE &&
4950 status != GOT_STATUS_CONFLICT)
4951 return NULL;
4954 err = got_opentemp_truncate(a->f1);
4955 if (err)
4956 return got_error_from_errno("got_opentemp_truncate");
4957 err = got_opentemp_truncate(a->f2);
4958 if (err)
4959 return got_error_from_errno("got_opentemp_truncate");
4961 if (!a->header_shown) {
4962 if (fprintf(a->outfile, "diff %s%s\n",
4963 a->diff_staged ? "-s " : "",
4964 got_worktree_get_root_path(a->worktree)) < 0) {
4965 err = got_error_from_errno("fprintf");
4966 goto done;
4968 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4969 err = got_error_from_errno("fprintf");
4970 goto done;
4972 if (fprintf(a->outfile, "path + %s%s\n",
4973 got_worktree_get_root_path(a->worktree),
4974 a->diff_staged ? " (staged changes)" : "") < 0) {
4975 err = got_error_from_errno("fprintf");
4976 goto done;
4978 a->header_shown = 1;
4981 if (a->diff_staged) {
4982 const char *label1 = NULL, *label2 = NULL;
4983 switch (staged_status) {
4984 case GOT_STATUS_MODIFY:
4985 label1 = path;
4986 label2 = path;
4987 break;
4988 case GOT_STATUS_ADD:
4989 label2 = path;
4990 break;
4991 case GOT_STATUS_DELETE:
4992 label1 = path;
4993 break;
4994 default:
4995 return got_error(GOT_ERR_FILE_STATUS);
4997 fd1 = got_opentempfd();
4998 if (fd1 == -1) {
4999 err = got_error_from_errno("got_opentempfd");
5000 goto done;
5002 fd2 = got_opentempfd();
5003 if (fd2 == -1) {
5004 err = got_error_from_errno("got_opentempfd");
5005 goto done;
5007 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5008 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5009 a->diff_algo, a->diff_context, a->ignore_whitespace,
5010 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5011 goto done;
5014 fd1 = got_opentempfd();
5015 if (fd1 == -1) {
5016 err = got_error_from_errno("got_opentempfd");
5017 goto done;
5020 if (staged_status == GOT_STATUS_ADD ||
5021 staged_status == GOT_STATUS_MODIFY) {
5022 char *id_str;
5023 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5024 8192, fd1);
5025 if (err)
5026 goto done;
5027 err = got_object_id_str(&id_str, staged_blob_id);
5028 if (err)
5029 goto done;
5030 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5031 err = got_error_from_errno("asprintf");
5032 free(id_str);
5033 goto done;
5035 free(id_str);
5036 } else if (status != GOT_STATUS_ADD) {
5037 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5038 fd1);
5039 if (err)
5040 goto done;
5043 if (status != GOT_STATUS_DELETE) {
5044 if (asprintf(&abspath, "%s/%s",
5045 got_worktree_get_root_path(a->worktree), path) == -1) {
5046 err = got_error_from_errno("asprintf");
5047 goto done;
5050 if (dirfd != -1) {
5051 fd = openat(dirfd, de_name,
5052 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5053 if (fd == -1) {
5054 if (!got_err_open_nofollow_on_symlink()) {
5055 err = got_error_from_errno2("openat",
5056 abspath);
5057 goto done;
5059 err = get_symlink_target_file(&fd, dirfd,
5060 de_name, abspath);
5061 if (err)
5062 goto done;
5064 } else {
5065 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5066 if (fd == -1) {
5067 if (!got_err_open_nofollow_on_symlink()) {
5068 err = got_error_from_errno2("open",
5069 abspath);
5070 goto done;
5072 err = get_symlink_target_file(&fd, dirfd,
5073 de_name, abspath);
5074 if (err)
5075 goto done;
5078 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5079 err = got_error_from_errno2("fstatat", abspath);
5080 goto done;
5082 f2 = fdopen(fd, "r");
5083 if (f2 == NULL) {
5084 err = got_error_from_errno2("fdopen", abspath);
5085 goto done;
5087 fd = -1;
5088 f2_exists = 1;
5091 if (blob1) {
5092 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5093 a->f1, blob1);
5094 if (err)
5095 goto done;
5098 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5099 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5100 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5101 done:
5102 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5103 err = got_error_from_errno("close");
5104 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5105 err = got_error_from_errno("close");
5106 if (blob1)
5107 got_object_blob_close(blob1);
5108 if (fd != -1 && close(fd) == -1 && err == NULL)
5109 err = got_error_from_errno("close");
5110 if (f2 && fclose(f2) == EOF && err == NULL)
5111 err = got_error_from_errno("fclose");
5112 free(abspath);
5113 return err;
5116 static const struct got_error *
5117 cmd_diff(int argc, char *argv[])
5119 const struct got_error *error;
5120 struct got_repository *repo = NULL;
5121 struct got_worktree *worktree = NULL;
5122 char *cwd = NULL, *repo_path = NULL;
5123 const char *commit_args[2] = { NULL, NULL };
5124 int ncommit_args = 0;
5125 struct got_object_id *ids[2] = { NULL, NULL };
5126 char *labels[2] = { NULL, NULL };
5127 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5128 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5129 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5130 const char *errstr;
5131 struct got_reflist_head refs;
5132 struct got_pathlist_head diffstat_paths, paths;
5133 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5134 int fd1 = -1, fd2 = -1;
5135 int *pack_fds = NULL;
5136 struct got_diffstat_cb_arg dsa;
5138 memset(&dsa, 0, sizeof(dsa));
5140 TAILQ_INIT(&refs);
5141 TAILQ_INIT(&paths);
5142 TAILQ_INIT(&diffstat_paths);
5144 #ifndef PROFILE
5145 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5146 NULL) == -1)
5147 err(1, "pledge");
5148 #endif
5150 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5151 switch (ch) {
5152 case 'a':
5153 force_text_diff = 1;
5154 break;
5155 case 'C':
5156 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5157 &errstr);
5158 if (errstr != NULL)
5159 errx(1, "number of context lines is %s: %s",
5160 errstr, optarg);
5161 break;
5162 case 'c':
5163 if (ncommit_args >= 2)
5164 errx(1, "too many -c options used");
5165 commit_args[ncommit_args++] = optarg;
5166 break;
5167 case 'd':
5168 show_diffstat = 1;
5169 break;
5170 case 'P':
5171 force_path = 1;
5172 break;
5173 case 'r':
5174 repo_path = realpath(optarg, NULL);
5175 if (repo_path == NULL)
5176 return got_error_from_errno2("realpath",
5177 optarg);
5178 got_path_strip_trailing_slashes(repo_path);
5179 rflag = 1;
5180 break;
5181 case 's':
5182 diff_staged = 1;
5183 break;
5184 case 'w':
5185 ignore_whitespace = 1;
5186 break;
5187 default:
5188 usage_diff();
5189 /* NOTREACHED */
5193 argc -= optind;
5194 argv += optind;
5196 cwd = getcwd(NULL, 0);
5197 if (cwd == NULL) {
5198 error = got_error_from_errno("getcwd");
5199 goto done;
5202 error = got_repo_pack_fds_open(&pack_fds);
5203 if (error != NULL)
5204 goto done;
5206 if (repo_path == NULL) {
5207 error = got_worktree_open(&worktree, cwd);
5208 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5209 goto done;
5210 else
5211 error = NULL;
5212 if (worktree) {
5213 repo_path =
5214 strdup(got_worktree_get_repo_path(worktree));
5215 if (repo_path == NULL) {
5216 error = got_error_from_errno("strdup");
5217 goto done;
5219 } else {
5220 repo_path = strdup(cwd);
5221 if (repo_path == NULL) {
5222 error = got_error_from_errno("strdup");
5223 goto done;
5228 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5229 free(repo_path);
5230 if (error != NULL)
5231 goto done;
5233 if (show_diffstat) {
5234 dsa.paths = &diffstat_paths;
5235 dsa.force_text = force_text_diff;
5236 dsa.ignore_ws = ignore_whitespace;
5237 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5240 if (rflag || worktree == NULL || ncommit_args > 0) {
5241 if (force_path) {
5242 error = got_error_msg(GOT_ERR_NOT_IMPL,
5243 "-P option can only be used when diffing "
5244 "a work tree");
5245 goto done;
5247 if (diff_staged) {
5248 error = got_error_msg(GOT_ERR_NOT_IMPL,
5249 "-s option can only be used when diffing "
5250 "a work tree");
5251 goto done;
5255 error = apply_unveil(got_repo_get_path(repo), 1,
5256 worktree ? got_worktree_get_root_path(worktree) : NULL);
5257 if (error)
5258 goto done;
5260 if ((!force_path && argc == 2) || ncommit_args > 0) {
5261 int obj_type = (ncommit_args > 0 ?
5262 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5263 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5264 NULL);
5265 if (error)
5266 goto done;
5267 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5268 const char *arg;
5269 char *keyword_idstr = NULL;
5271 if (ncommit_args > 0)
5272 arg = commit_args[i];
5273 else
5274 arg = argv[i];
5276 error = got_keyword_to_idstr(&keyword_idstr, arg,
5277 repo, worktree);
5278 if (error != NULL)
5279 goto done;
5280 if (keyword_idstr != NULL)
5281 arg = keyword_idstr;
5283 error = got_repo_match_object_id(&ids[i], &labels[i],
5284 arg, obj_type, &refs, repo);
5285 free(keyword_idstr);
5286 if (error) {
5287 if (error->code != GOT_ERR_NOT_REF &&
5288 error->code != GOT_ERR_NO_OBJ)
5289 goto done;
5290 if (ncommit_args > 0)
5291 goto done;
5292 error = NULL;
5293 break;
5298 f1 = got_opentemp();
5299 if (f1 == NULL) {
5300 error = got_error_from_errno("got_opentemp");
5301 goto done;
5304 f2 = got_opentemp();
5305 if (f2 == NULL) {
5306 error = got_error_from_errno("got_opentemp");
5307 goto done;
5310 outfile = got_opentemp();
5311 if (outfile == NULL) {
5312 error = got_error_from_errno("got_opentemp");
5313 goto done;
5316 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5317 struct print_diff_arg arg;
5318 char *id_str;
5320 if (worktree == NULL) {
5321 if (argc == 2 && ids[0] == NULL) {
5322 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5323 goto done;
5324 } else if (argc == 2 && ids[1] == NULL) {
5325 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5326 goto done;
5327 } else if (argc > 0) {
5328 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5329 "%s", "specified paths cannot be resolved");
5330 goto done;
5331 } else {
5332 error = got_error(GOT_ERR_NOT_WORKTREE);
5333 goto done;
5337 error = get_worktree_paths_from_argv(&paths, argc, argv,
5338 worktree);
5339 if (error)
5340 goto done;
5342 error = got_object_id_str(&id_str,
5343 got_worktree_get_base_commit_id(worktree));
5344 if (error)
5345 goto done;
5346 arg.repo = repo;
5347 arg.worktree = worktree;
5348 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5349 arg.diff_context = diff_context;
5350 arg.id_str = id_str;
5351 arg.header_shown = 0;
5352 arg.diff_staged = diff_staged;
5353 arg.ignore_whitespace = ignore_whitespace;
5354 arg.force_text_diff = force_text_diff;
5355 arg.diffstat = show_diffstat ? &dsa : NULL;
5356 arg.f1 = f1;
5357 arg.f2 = f2;
5358 arg.outfile = outfile;
5360 error = got_worktree_status(worktree, &paths, repo, 0,
5361 print_diff, &arg, check_cancelled, NULL);
5362 free(id_str);
5363 if (error)
5364 goto done;
5366 if (show_diffstat && dsa.nfiles > 0) {
5367 char *header;
5369 if (asprintf(&header, "diffstat %s%s",
5370 diff_staged ? "-s " : "",
5371 got_worktree_get_root_path(worktree)) == -1) {
5372 error = got_error_from_errno("asprintf");
5373 goto done;
5376 error = print_diffstat(&dsa, header);
5377 free(header);
5378 if (error)
5379 goto done;
5382 error = printfile(outfile);
5383 goto done;
5386 if (ncommit_args == 1) {
5387 struct got_commit_object *commit;
5388 error = got_object_open_as_commit(&commit, repo, ids[0]);
5389 if (error)
5390 goto done;
5392 labels[1] = labels[0];
5393 ids[1] = ids[0];
5394 if (got_object_commit_get_nparents(commit) > 0) {
5395 const struct got_object_id_queue *pids;
5396 struct got_object_qid *pid;
5397 pids = got_object_commit_get_parent_ids(commit);
5398 pid = STAILQ_FIRST(pids);
5399 ids[0] = got_object_id_dup(&pid->id);
5400 if (ids[0] == NULL) {
5401 error = got_error_from_errno(
5402 "got_object_id_dup");
5403 got_object_commit_close(commit);
5404 goto done;
5406 error = got_object_id_str(&labels[0], ids[0]);
5407 if (error) {
5408 got_object_commit_close(commit);
5409 goto done;
5411 } else {
5412 ids[0] = NULL;
5413 labels[0] = strdup("/dev/null");
5414 if (labels[0] == NULL) {
5415 error = got_error_from_errno("strdup");
5416 got_object_commit_close(commit);
5417 goto done;
5421 got_object_commit_close(commit);
5424 if (ncommit_args == 0 && argc > 2) {
5425 error = got_error_msg(GOT_ERR_BAD_PATH,
5426 "path arguments cannot be used when diffing two objects");
5427 goto done;
5430 if (ids[0]) {
5431 error = got_object_get_type(&type1, repo, ids[0]);
5432 if (error)
5433 goto done;
5436 error = got_object_get_type(&type2, repo, ids[1]);
5437 if (error)
5438 goto done;
5439 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5440 error = got_error(GOT_ERR_OBJ_TYPE);
5441 goto done;
5443 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5444 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5445 "path arguments cannot be used when diffing blobs");
5446 goto done;
5449 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5450 char *in_repo_path;
5451 struct got_pathlist_entry *new;
5452 if (worktree) {
5453 const char *prefix;
5454 char *p;
5455 error = got_worktree_resolve_path(&p, worktree,
5456 argv[i]);
5457 if (error)
5458 goto done;
5459 prefix = got_worktree_get_path_prefix(worktree);
5460 while (prefix[0] == '/')
5461 prefix++;
5462 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5463 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5464 p) == -1) {
5465 error = got_error_from_errno("asprintf");
5466 free(p);
5467 goto done;
5469 free(p);
5470 } else {
5471 char *mapped_path, *s;
5472 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5473 if (error)
5474 goto done;
5475 s = mapped_path;
5476 while (s[0] == '/')
5477 s++;
5478 in_repo_path = strdup(s);
5479 if (in_repo_path == NULL) {
5480 error = got_error_from_errno("asprintf");
5481 free(mapped_path);
5482 goto done;
5484 free(mapped_path);
5487 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5488 if (error || new == NULL /* duplicate */)
5489 free(in_repo_path);
5490 if (error)
5491 goto done;
5494 if (worktree) {
5495 /* Release work tree lock. */
5496 got_worktree_close(worktree);
5497 worktree = NULL;
5500 fd1 = got_opentempfd();
5501 if (fd1 == -1) {
5502 error = got_error_from_errno("got_opentempfd");
5503 goto done;
5506 fd2 = got_opentempfd();
5507 if (fd2 == -1) {
5508 error = got_error_from_errno("got_opentempfd");
5509 goto done;
5512 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5513 case GOT_OBJ_TYPE_BLOB:
5514 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5515 fd1, fd2, ids[0], ids[1], NULL, NULL,
5516 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5517 ignore_whitespace, force_text_diff,
5518 show_diffstat ? &dsa : NULL, repo, outfile);
5519 break;
5520 case GOT_OBJ_TYPE_TREE:
5521 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5522 ids[0], ids[1], &paths, "", "",
5523 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5524 ignore_whitespace, force_text_diff,
5525 show_diffstat ? &dsa : NULL, repo, outfile);
5526 break;
5527 case GOT_OBJ_TYPE_COMMIT:
5528 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5529 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5530 fd1, fd2, ids[0], ids[1], &paths,
5531 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5532 ignore_whitespace, force_text_diff,
5533 show_diffstat ? &dsa : NULL, repo, outfile);
5534 break;
5535 default:
5536 error = got_error(GOT_ERR_OBJ_TYPE);
5538 if (error)
5539 goto done;
5541 if (show_diffstat && dsa.nfiles > 0) {
5542 char *header = NULL;
5544 if (asprintf(&header, "diffstat %s %s",
5545 labels[0], labels[1]) == -1) {
5546 error = got_error_from_errno("asprintf");
5547 goto done;
5550 error = print_diffstat(&dsa, header);
5551 free(header);
5552 if (error)
5553 goto done;
5556 error = printfile(outfile);
5558 done:
5559 free(labels[0]);
5560 free(labels[1]);
5561 free(ids[0]);
5562 free(ids[1]);
5563 if (worktree)
5564 got_worktree_close(worktree);
5565 if (repo) {
5566 const struct got_error *close_err = got_repo_close(repo);
5567 if (error == NULL)
5568 error = close_err;
5570 if (pack_fds) {
5571 const struct got_error *pack_err =
5572 got_repo_pack_fds_close(pack_fds);
5573 if (error == NULL)
5574 error = pack_err;
5576 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5577 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5578 got_ref_list_free(&refs);
5579 if (outfile && fclose(outfile) == EOF && error == NULL)
5580 error = got_error_from_errno("fclose");
5581 if (f1 && fclose(f1) == EOF && error == NULL)
5582 error = got_error_from_errno("fclose");
5583 if (f2 && fclose(f2) == EOF && error == NULL)
5584 error = got_error_from_errno("fclose");
5585 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5586 error = got_error_from_errno("close");
5587 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5588 error = got_error_from_errno("close");
5589 return error;
5592 __dead static void
5593 usage_blame(void)
5595 fprintf(stderr,
5596 "usage: %s blame [-c commit] [-r repository-path] path\n",
5597 getprogname());
5598 exit(1);
5601 struct blame_line {
5602 int annotated;
5603 char *id_str;
5604 char *committer;
5605 char datebuf[11]; /* YYYY-MM-DD + NUL */
5608 struct blame_cb_args {
5609 struct blame_line *lines;
5610 int nlines;
5611 int nlines_prec;
5612 int lineno_cur;
5613 off_t *line_offsets;
5614 FILE *f;
5615 struct got_repository *repo;
5618 static const struct got_error *
5619 blame_cb(void *arg, int nlines, int lineno,
5620 struct got_commit_object *commit, struct got_object_id *id)
5622 const struct got_error *err = NULL;
5623 struct blame_cb_args *a = arg;
5624 struct blame_line *bline;
5625 char *line = NULL;
5626 size_t linesize = 0;
5627 off_t offset;
5628 struct tm tm;
5629 time_t committer_time;
5631 if (nlines != a->nlines ||
5632 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5633 return got_error(GOT_ERR_RANGE);
5635 if (sigint_received)
5636 return got_error(GOT_ERR_ITER_COMPLETED);
5638 if (lineno == -1)
5639 return NULL; /* no change in this commit */
5641 /* Annotate this line. */
5642 bline = &a->lines[lineno - 1];
5643 if (bline->annotated)
5644 return NULL;
5645 err = got_object_id_str(&bline->id_str, id);
5646 if (err)
5647 return err;
5649 bline->committer = strdup(got_object_commit_get_committer(commit));
5650 if (bline->committer == NULL) {
5651 err = got_error_from_errno("strdup");
5652 goto done;
5655 committer_time = got_object_commit_get_committer_time(commit);
5656 if (gmtime_r(&committer_time, &tm) == NULL)
5657 return got_error_from_errno("gmtime_r");
5658 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5659 &tm) == 0) {
5660 err = got_error(GOT_ERR_NO_SPACE);
5661 goto done;
5663 bline->annotated = 1;
5665 /* Print lines annotated so far. */
5666 bline = &a->lines[a->lineno_cur - 1];
5667 if (!bline->annotated)
5668 goto done;
5670 offset = a->line_offsets[a->lineno_cur - 1];
5671 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5672 err = got_error_from_errno("fseeko");
5673 goto done;
5676 while (a->lineno_cur <= a->nlines && bline->annotated) {
5677 char *smallerthan, *at, *nl, *committer;
5678 size_t len;
5680 if (getline(&line, &linesize, a->f) == -1) {
5681 if (ferror(a->f))
5682 err = got_error_from_errno("getline");
5683 break;
5686 committer = bline->committer;
5687 smallerthan = strchr(committer, '<');
5688 if (smallerthan && smallerthan[1] != '\0')
5689 committer = smallerthan + 1;
5690 at = strchr(committer, '@');
5691 if (at)
5692 *at = '\0';
5693 len = strlen(committer);
5694 if (len >= 9)
5695 committer[8] = '\0';
5697 nl = strchr(line, '\n');
5698 if (nl)
5699 *nl = '\0';
5700 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5701 bline->id_str, bline->datebuf, committer, line);
5703 a->lineno_cur++;
5704 bline = &a->lines[a->lineno_cur - 1];
5706 done:
5707 free(line);
5708 return err;
5711 static const struct got_error *
5712 cmd_blame(int argc, char *argv[])
5714 const struct got_error *error;
5715 struct got_repository *repo = NULL;
5716 struct got_worktree *worktree = NULL;
5717 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5718 char *link_target = NULL;
5719 struct got_object_id *obj_id = NULL;
5720 struct got_object_id *commit_id = NULL;
5721 struct got_commit_object *commit = NULL;
5722 struct got_blob_object *blob = NULL;
5723 char *commit_id_str = NULL;
5724 struct blame_cb_args bca;
5725 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5726 off_t filesize;
5727 int *pack_fds = NULL;
5728 FILE *f1 = NULL, *f2 = NULL;
5730 fd1 = got_opentempfd();
5731 if (fd1 == -1)
5732 return got_error_from_errno("got_opentempfd");
5734 memset(&bca, 0, sizeof(bca));
5736 #ifndef PROFILE
5737 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5738 NULL) == -1)
5739 err(1, "pledge");
5740 #endif
5742 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5743 switch (ch) {
5744 case 'c':
5745 commit_id_str = optarg;
5746 break;
5747 case 'r':
5748 repo_path = realpath(optarg, NULL);
5749 if (repo_path == NULL)
5750 return got_error_from_errno2("realpath",
5751 optarg);
5752 got_path_strip_trailing_slashes(repo_path);
5753 break;
5754 default:
5755 usage_blame();
5756 /* NOTREACHED */
5760 argc -= optind;
5761 argv += optind;
5763 if (argc == 1)
5764 path = argv[0];
5765 else
5766 usage_blame();
5768 cwd = getcwd(NULL, 0);
5769 if (cwd == NULL) {
5770 error = got_error_from_errno("getcwd");
5771 goto done;
5774 error = got_repo_pack_fds_open(&pack_fds);
5775 if (error != NULL)
5776 goto done;
5778 if (repo_path == NULL) {
5779 error = got_worktree_open(&worktree, cwd);
5780 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5781 goto done;
5782 else
5783 error = NULL;
5784 if (worktree) {
5785 repo_path =
5786 strdup(got_worktree_get_repo_path(worktree));
5787 if (repo_path == NULL) {
5788 error = got_error_from_errno("strdup");
5789 if (error)
5790 goto done;
5792 } else {
5793 repo_path = strdup(cwd);
5794 if (repo_path == NULL) {
5795 error = got_error_from_errno("strdup");
5796 goto done;
5801 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5802 if (error != NULL)
5803 goto done;
5805 if (worktree) {
5806 const char *prefix = got_worktree_get_path_prefix(worktree);
5807 char *p;
5809 error = got_worktree_resolve_path(&p, worktree, path);
5810 if (error)
5811 goto done;
5812 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5813 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5814 p) == -1) {
5815 error = got_error_from_errno("asprintf");
5816 free(p);
5817 goto done;
5819 free(p);
5820 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5821 } else {
5822 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5823 if (error)
5824 goto done;
5825 error = got_repo_map_path(&in_repo_path, repo, path);
5827 if (error)
5828 goto done;
5830 if (commit_id_str == NULL) {
5831 struct got_reference *head_ref;
5832 error = got_ref_open(&head_ref, repo, worktree ?
5833 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5834 if (error != NULL)
5835 goto done;
5836 error = got_ref_resolve(&commit_id, repo, head_ref);
5837 got_ref_close(head_ref);
5838 if (error != NULL)
5839 goto done;
5840 } else {
5841 struct got_reflist_head refs;
5842 TAILQ_INIT(&refs);
5843 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5844 NULL);
5845 if (error)
5846 goto done;
5847 error = got_repo_match_object_id(&commit_id, NULL,
5848 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5849 got_ref_list_free(&refs);
5850 if (error)
5851 goto done;
5854 if (worktree) {
5855 /* Release work tree lock. */
5856 got_worktree_close(worktree);
5857 worktree = NULL;
5860 error = got_object_open_as_commit(&commit, repo, commit_id);
5861 if (error)
5862 goto done;
5864 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5865 commit, repo);
5866 if (error)
5867 goto done;
5869 error = got_object_id_by_path(&obj_id, repo, commit,
5870 link_target ? link_target : in_repo_path);
5871 if (error)
5872 goto done;
5874 error = got_object_get_type(&obj_type, repo, obj_id);
5875 if (error)
5876 goto done;
5878 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5879 error = got_error_path(link_target ? link_target : in_repo_path,
5880 GOT_ERR_OBJ_TYPE);
5881 goto done;
5884 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5885 if (error)
5886 goto done;
5887 bca.f = got_opentemp();
5888 if (bca.f == NULL) {
5889 error = got_error_from_errno("got_opentemp");
5890 goto done;
5892 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5893 &bca.line_offsets, bca.f, blob);
5894 if (error || bca.nlines == 0)
5895 goto done;
5897 /* Don't include \n at EOF in the blame line count. */
5898 if (bca.line_offsets[bca.nlines - 1] == filesize)
5899 bca.nlines--;
5901 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5902 if (bca.lines == NULL) {
5903 error = got_error_from_errno("calloc");
5904 goto done;
5906 bca.lineno_cur = 1;
5907 bca.nlines_prec = 0;
5908 i = bca.nlines;
5909 while (i > 0) {
5910 i /= 10;
5911 bca.nlines_prec++;
5913 bca.repo = repo;
5915 fd2 = got_opentempfd();
5916 if (fd2 == -1) {
5917 error = got_error_from_errno("got_opentempfd");
5918 goto done;
5920 fd3 = got_opentempfd();
5921 if (fd3 == -1) {
5922 error = got_error_from_errno("got_opentempfd");
5923 goto done;
5925 f1 = got_opentemp();
5926 if (f1 == NULL) {
5927 error = got_error_from_errno("got_opentemp");
5928 goto done;
5930 f2 = got_opentemp();
5931 if (f2 == NULL) {
5932 error = got_error_from_errno("got_opentemp");
5933 goto done;
5935 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5936 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5937 check_cancelled, NULL, fd2, fd3, f1, f2);
5938 done:
5939 free(in_repo_path);
5940 free(link_target);
5941 free(repo_path);
5942 free(cwd);
5943 free(commit_id);
5944 free(obj_id);
5945 if (commit)
5946 got_object_commit_close(commit);
5948 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5949 error = got_error_from_errno("close");
5950 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5951 error = got_error_from_errno("close");
5952 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5953 error = got_error_from_errno("close");
5954 if (f1 && fclose(f1) == EOF && error == NULL)
5955 error = got_error_from_errno("fclose");
5956 if (f2 && fclose(f2) == EOF && error == NULL)
5957 error = got_error_from_errno("fclose");
5959 if (blob)
5960 got_object_blob_close(blob);
5961 if (worktree)
5962 got_worktree_close(worktree);
5963 if (repo) {
5964 const struct got_error *close_err = got_repo_close(repo);
5965 if (error == NULL)
5966 error = close_err;
5968 if (pack_fds) {
5969 const struct got_error *pack_err =
5970 got_repo_pack_fds_close(pack_fds);
5971 if (error == NULL)
5972 error = pack_err;
5974 if (bca.lines) {
5975 for (i = 0; i < bca.nlines; i++) {
5976 struct blame_line *bline = &bca.lines[i];
5977 free(bline->id_str);
5978 free(bline->committer);
5980 free(bca.lines);
5982 free(bca.line_offsets);
5983 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5984 error = got_error_from_errno("fclose");
5985 return error;
5988 __dead static void
5989 usage_tree(void)
5991 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5992 "[path]\n", getprogname());
5993 exit(1);
5996 static const struct got_error *
5997 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5998 const char *root_path, struct got_repository *repo)
6000 const struct got_error *err = NULL;
6001 int is_root_path = (strcmp(path, root_path) == 0);
6002 const char *modestr = "";
6003 mode_t mode = got_tree_entry_get_mode(te);
6004 char *link_target = NULL;
6006 path += strlen(root_path);
6007 while (path[0] == '/')
6008 path++;
6010 if (got_object_tree_entry_is_submodule(te))
6011 modestr = "$";
6012 else if (S_ISLNK(mode)) {
6013 int i;
6015 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6016 if (err)
6017 return err;
6018 for (i = 0; link_target[i] != '\0'; i++) {
6019 if (!isprint((unsigned char)link_target[i]))
6020 link_target[i] = '?';
6023 modestr = "@";
6025 else if (S_ISDIR(mode))
6026 modestr = "/";
6027 else if (mode & S_IXUSR)
6028 modestr = "*";
6030 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6031 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6032 link_target ? " -> ": "", link_target ? link_target : "");
6034 free(link_target);
6035 return NULL;
6038 static const struct got_error *
6039 print_tree(const char *path, struct got_commit_object *commit,
6040 int show_ids, int recurse, const char *root_path,
6041 struct got_repository *repo)
6043 const struct got_error *err = NULL;
6044 struct got_object_id *tree_id = NULL;
6045 struct got_tree_object *tree = NULL;
6046 int nentries, i;
6048 err = got_object_id_by_path(&tree_id, repo, commit, path);
6049 if (err)
6050 goto done;
6052 err = got_object_open_as_tree(&tree, repo, tree_id);
6053 if (err)
6054 goto done;
6055 nentries = got_object_tree_get_nentries(tree);
6056 for (i = 0; i < nentries; i++) {
6057 struct got_tree_entry *te;
6058 char *id = NULL;
6060 if (sigint_received || sigpipe_received)
6061 break;
6063 te = got_object_tree_get_entry(tree, i);
6064 if (show_ids) {
6065 char *id_str;
6066 err = got_object_id_str(&id_str,
6067 got_tree_entry_get_id(te));
6068 if (err)
6069 goto done;
6070 if (asprintf(&id, "%s ", id_str) == -1) {
6071 err = got_error_from_errno("asprintf");
6072 free(id_str);
6073 goto done;
6075 free(id_str);
6077 err = print_entry(te, id, path, root_path, repo);
6078 free(id);
6079 if (err)
6080 goto done;
6082 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6083 char *child_path;
6084 if (asprintf(&child_path, "%s%s%s", path,
6085 path[0] == '/' && path[1] == '\0' ? "" : "/",
6086 got_tree_entry_get_name(te)) == -1) {
6087 err = got_error_from_errno("asprintf");
6088 goto done;
6090 err = print_tree(child_path, commit, show_ids, 1,
6091 root_path, repo);
6092 free(child_path);
6093 if (err)
6094 goto done;
6097 done:
6098 if (tree)
6099 got_object_tree_close(tree);
6100 free(tree_id);
6101 return err;
6104 static const struct got_error *
6105 cmd_tree(int argc, char *argv[])
6107 const struct got_error *error;
6108 struct got_repository *repo = NULL;
6109 struct got_worktree *worktree = NULL;
6110 const char *path, *refname = NULL;
6111 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6112 struct got_object_id *commit_id = NULL;
6113 struct got_commit_object *commit = NULL;
6114 char *commit_id_str = NULL;
6115 int show_ids = 0, recurse = 0;
6116 int ch;
6117 int *pack_fds = NULL;
6119 #ifndef PROFILE
6120 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6121 NULL) == -1)
6122 err(1, "pledge");
6123 #endif
6125 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6126 switch (ch) {
6127 case 'c':
6128 commit_id_str = optarg;
6129 break;
6130 case 'i':
6131 show_ids = 1;
6132 break;
6133 case 'R':
6134 recurse = 1;
6135 break;
6136 case 'r':
6137 repo_path = realpath(optarg, NULL);
6138 if (repo_path == NULL)
6139 return got_error_from_errno2("realpath",
6140 optarg);
6141 got_path_strip_trailing_slashes(repo_path);
6142 break;
6143 default:
6144 usage_tree();
6145 /* NOTREACHED */
6149 argc -= optind;
6150 argv += optind;
6152 if (argc == 1)
6153 path = argv[0];
6154 else if (argc > 1)
6155 usage_tree();
6156 else
6157 path = NULL;
6159 cwd = getcwd(NULL, 0);
6160 if (cwd == NULL) {
6161 error = got_error_from_errno("getcwd");
6162 goto done;
6165 error = got_repo_pack_fds_open(&pack_fds);
6166 if (error != NULL)
6167 goto done;
6169 if (repo_path == NULL) {
6170 error = got_worktree_open(&worktree, cwd);
6171 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6172 goto done;
6173 else
6174 error = NULL;
6175 if (worktree) {
6176 repo_path =
6177 strdup(got_worktree_get_repo_path(worktree));
6178 if (repo_path == NULL)
6179 error = got_error_from_errno("strdup");
6180 if (error)
6181 goto done;
6182 } else {
6183 repo_path = strdup(cwd);
6184 if (repo_path == NULL) {
6185 error = got_error_from_errno("strdup");
6186 goto done;
6191 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6192 if (error != NULL)
6193 goto done;
6195 if (worktree) {
6196 const char *prefix = got_worktree_get_path_prefix(worktree);
6197 char *p;
6199 if (path == NULL || got_path_is_root_dir(path))
6200 path = "";
6201 error = got_worktree_resolve_path(&p, worktree, path);
6202 if (error)
6203 goto done;
6204 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6205 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6206 p) == -1) {
6207 error = got_error_from_errno("asprintf");
6208 free(p);
6209 goto done;
6211 free(p);
6212 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6213 if (error)
6214 goto done;
6215 } else {
6216 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6217 if (error)
6218 goto done;
6219 if (path == NULL)
6220 path = "/";
6221 error = got_repo_map_path(&in_repo_path, repo, path);
6222 if (error != NULL)
6223 goto done;
6226 if (commit_id_str == NULL) {
6227 struct got_reference *head_ref;
6228 if (worktree)
6229 refname = got_worktree_get_head_ref_name(worktree);
6230 else
6231 refname = GOT_REF_HEAD;
6232 error = got_ref_open(&head_ref, repo, refname, 0);
6233 if (error != NULL)
6234 goto done;
6235 error = got_ref_resolve(&commit_id, repo, head_ref);
6236 got_ref_close(head_ref);
6237 if (error != NULL)
6238 goto done;
6239 } else {
6240 struct got_reflist_head refs;
6241 TAILQ_INIT(&refs);
6242 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6243 NULL);
6244 if (error)
6245 goto done;
6246 error = got_repo_match_object_id(&commit_id, NULL,
6247 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6248 got_ref_list_free(&refs);
6249 if (error)
6250 goto done;
6253 if (worktree) {
6254 /* Release work tree lock. */
6255 got_worktree_close(worktree);
6256 worktree = NULL;
6259 error = got_object_open_as_commit(&commit, repo, commit_id);
6260 if (error)
6261 goto done;
6263 error = print_tree(in_repo_path, commit, show_ids, recurse,
6264 in_repo_path, repo);
6265 done:
6266 free(in_repo_path);
6267 free(repo_path);
6268 free(cwd);
6269 free(commit_id);
6270 if (commit)
6271 got_object_commit_close(commit);
6272 if (worktree)
6273 got_worktree_close(worktree);
6274 if (repo) {
6275 const struct got_error *close_err = got_repo_close(repo);
6276 if (error == NULL)
6277 error = close_err;
6279 if (pack_fds) {
6280 const struct got_error *pack_err =
6281 got_repo_pack_fds_close(pack_fds);
6282 if (error == NULL)
6283 error = pack_err;
6285 return error;
6288 __dead static void
6289 usage_status(void)
6291 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6292 "[-s status-codes] [path ...]\n", getprogname());
6293 exit(1);
6296 struct got_status_arg {
6297 char *status_codes;
6298 int suppress;
6301 static const struct got_error *
6302 print_status(void *arg, unsigned char status, unsigned char staged_status,
6303 const char *path, struct got_object_id *blob_id,
6304 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6305 int dirfd, const char *de_name)
6307 struct got_status_arg *st = arg;
6309 if (status == staged_status && (status == GOT_STATUS_DELETE))
6310 status = GOT_STATUS_NO_CHANGE;
6311 if (st != NULL && st->status_codes) {
6312 size_t ncodes = strlen(st->status_codes);
6313 int i, j = 0;
6315 for (i = 0; i < ncodes ; i++) {
6316 if (st->suppress) {
6317 if (status == st->status_codes[i] ||
6318 staged_status == st->status_codes[i]) {
6319 j++;
6320 continue;
6322 } else {
6323 if (status == st->status_codes[i] ||
6324 staged_status == st->status_codes[i])
6325 break;
6329 if (st->suppress && j == 0)
6330 goto print;
6332 if (i == ncodes)
6333 return NULL;
6335 print:
6336 printf("%c%c %s\n", status, staged_status, path);
6337 return NULL;
6340 static const struct got_error *
6341 cmd_status(int argc, char *argv[])
6343 const struct got_error *error = NULL;
6344 struct got_repository *repo = NULL;
6345 struct got_worktree *worktree = NULL;
6346 struct got_status_arg st;
6347 char *cwd = NULL;
6348 struct got_pathlist_head paths;
6349 int ch, i, no_ignores = 0;
6350 int *pack_fds = NULL;
6352 TAILQ_INIT(&paths);
6354 memset(&st, 0, sizeof(st));
6355 st.status_codes = NULL;
6356 st.suppress = 0;
6358 #ifndef PROFILE
6359 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6360 NULL) == -1)
6361 err(1, "pledge");
6362 #endif
6364 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6365 switch (ch) {
6366 case 'I':
6367 no_ignores = 1;
6368 break;
6369 case 'S':
6370 if (st.status_codes != NULL && st.suppress == 0)
6371 option_conflict('S', 's');
6372 st.suppress = 1;
6373 /* fallthrough */
6374 case 's':
6375 for (i = 0; optarg[i] != '\0'; i++) {
6376 switch (optarg[i]) {
6377 case GOT_STATUS_MODIFY:
6378 case GOT_STATUS_ADD:
6379 case GOT_STATUS_DELETE:
6380 case GOT_STATUS_CONFLICT:
6381 case GOT_STATUS_MISSING:
6382 case GOT_STATUS_OBSTRUCTED:
6383 case GOT_STATUS_UNVERSIONED:
6384 case GOT_STATUS_MODE_CHANGE:
6385 case GOT_STATUS_NONEXISTENT:
6386 break;
6387 default:
6388 errx(1, "invalid status code '%c'",
6389 optarg[i]);
6392 if (ch == 's' && st.suppress)
6393 option_conflict('s', 'S');
6394 st.status_codes = optarg;
6395 break;
6396 default:
6397 usage_status();
6398 /* NOTREACHED */
6402 argc -= optind;
6403 argv += optind;
6405 cwd = getcwd(NULL, 0);
6406 if (cwd == NULL) {
6407 error = got_error_from_errno("getcwd");
6408 goto done;
6411 error = got_repo_pack_fds_open(&pack_fds);
6412 if (error != NULL)
6413 goto done;
6415 error = got_worktree_open(&worktree, cwd);
6416 if (error) {
6417 if (error->code == GOT_ERR_NOT_WORKTREE)
6418 error = wrap_not_worktree_error(error, "status", cwd);
6419 goto done;
6422 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6423 NULL, pack_fds);
6424 if (error != NULL)
6425 goto done;
6427 error = apply_unveil(got_repo_get_path(repo), 1,
6428 got_worktree_get_root_path(worktree));
6429 if (error)
6430 goto done;
6432 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6433 if (error)
6434 goto done;
6436 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6437 print_status, &st, check_cancelled, NULL);
6438 done:
6439 if (pack_fds) {
6440 const struct got_error *pack_err =
6441 got_repo_pack_fds_close(pack_fds);
6442 if (error == NULL)
6443 error = pack_err;
6445 if (repo) {
6446 const struct got_error *close_err = got_repo_close(repo);
6447 if (error == NULL)
6448 error = close_err;
6451 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6452 free(cwd);
6453 return error;
6456 __dead static void
6457 usage_ref(void)
6459 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6460 "[-s reference] [name]\n", getprogname());
6461 exit(1);
6464 static const struct got_error *
6465 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6467 static const struct got_error *err = NULL;
6468 struct got_reflist_head refs;
6469 struct got_reflist_entry *re;
6471 TAILQ_INIT(&refs);
6472 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6473 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6474 repo);
6475 if (err)
6476 return err;
6478 TAILQ_FOREACH(re, &refs, entry) {
6479 char *refstr;
6480 refstr = got_ref_to_str(re->ref);
6481 if (refstr == NULL) {
6482 err = got_error_from_errno("got_ref_to_str");
6483 break;
6485 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6486 free(refstr);
6489 got_ref_list_free(&refs);
6490 return err;
6493 static const struct got_error *
6494 delete_ref_by_name(struct got_repository *repo, const char *refname)
6496 const struct got_error *err;
6497 struct got_reference *ref;
6499 err = got_ref_open(&ref, repo, refname, 0);
6500 if (err)
6501 return err;
6503 err = delete_ref(repo, ref);
6504 got_ref_close(ref);
6505 return err;
6508 static const struct got_error *
6509 add_ref(struct got_repository *repo, const char *refname, const char *target)
6511 const struct got_error *err = NULL;
6512 struct got_object_id *id = NULL;
6513 struct got_reference *ref = NULL;
6514 struct got_reflist_head refs;
6517 * Don't let the user create a reference name with a leading '-'.
6518 * While technically a valid reference name, this case is usually
6519 * an unintended typo.
6521 if (refname[0] == '-')
6522 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6524 TAILQ_INIT(&refs);
6525 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6526 if (err)
6527 goto done;
6528 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6529 &refs, repo);
6530 got_ref_list_free(&refs);
6531 if (err)
6532 goto done;
6534 err = got_ref_alloc(&ref, refname, id);
6535 if (err)
6536 goto done;
6538 err = got_ref_write(ref, repo);
6539 done:
6540 if (ref)
6541 got_ref_close(ref);
6542 free(id);
6543 return err;
6546 static const struct got_error *
6547 add_symref(struct got_repository *repo, const char *refname, const char *target)
6549 const struct got_error *err = NULL;
6550 struct got_reference *ref = NULL;
6551 struct got_reference *target_ref = NULL;
6554 * Don't let the user create a reference name with a leading '-'.
6555 * While technically a valid reference name, this case is usually
6556 * an unintended typo.
6558 if (refname[0] == '-')
6559 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6561 err = got_ref_open(&target_ref, repo, target, 0);
6562 if (err)
6563 return err;
6565 err = got_ref_alloc_symref(&ref, refname, target_ref);
6566 if (err)
6567 goto done;
6569 err = got_ref_write(ref, repo);
6570 done:
6571 if (target_ref)
6572 got_ref_close(target_ref);
6573 if (ref)
6574 got_ref_close(ref);
6575 return err;
6578 static const struct got_error *
6579 cmd_ref(int argc, char *argv[])
6581 const struct got_error *error = NULL;
6582 struct got_repository *repo = NULL;
6583 struct got_worktree *worktree = NULL;
6584 char *cwd = NULL, *repo_path = NULL;
6585 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6586 const char *obj_arg = NULL, *symref_target= NULL;
6587 char *refname = NULL;
6588 int *pack_fds = NULL;
6590 #ifndef PROFILE
6591 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6592 "sendfd unveil", NULL) == -1)
6593 err(1, "pledge");
6594 #endif
6596 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6597 switch (ch) {
6598 case 'c':
6599 obj_arg = optarg;
6600 break;
6601 case 'd':
6602 do_delete = 1;
6603 break;
6604 case 'l':
6605 do_list = 1;
6606 break;
6607 case 'r':
6608 repo_path = realpath(optarg, NULL);
6609 if (repo_path == NULL)
6610 return got_error_from_errno2("realpath",
6611 optarg);
6612 got_path_strip_trailing_slashes(repo_path);
6613 break;
6614 case 's':
6615 symref_target = optarg;
6616 break;
6617 case 't':
6618 sort_by_time = 1;
6619 break;
6620 default:
6621 usage_ref();
6622 /* NOTREACHED */
6626 if (obj_arg && do_list)
6627 option_conflict('c', 'l');
6628 if (obj_arg && do_delete)
6629 option_conflict('c', 'd');
6630 if (obj_arg && symref_target)
6631 option_conflict('c', 's');
6632 if (symref_target && do_delete)
6633 option_conflict('s', 'd');
6634 if (symref_target && do_list)
6635 option_conflict('s', 'l');
6636 if (do_delete && do_list)
6637 option_conflict('d', 'l');
6638 if (sort_by_time && !do_list)
6639 errx(1, "-t option requires -l option");
6641 argc -= optind;
6642 argv += optind;
6644 if (do_list) {
6645 if (argc != 0 && argc != 1)
6646 usage_ref();
6647 if (argc == 1) {
6648 refname = strdup(argv[0]);
6649 if (refname == NULL) {
6650 error = got_error_from_errno("strdup");
6651 goto done;
6654 } else {
6655 if (argc != 1)
6656 usage_ref();
6657 refname = strdup(argv[0]);
6658 if (refname == NULL) {
6659 error = got_error_from_errno("strdup");
6660 goto done;
6664 if (refname)
6665 got_path_strip_trailing_slashes(refname);
6667 cwd = getcwd(NULL, 0);
6668 if (cwd == NULL) {
6669 error = got_error_from_errno("getcwd");
6670 goto done;
6673 error = got_repo_pack_fds_open(&pack_fds);
6674 if (error != NULL)
6675 goto done;
6677 if (repo_path == NULL) {
6678 error = got_worktree_open(&worktree, cwd);
6679 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6680 goto done;
6681 else
6682 error = NULL;
6683 if (worktree) {
6684 repo_path =
6685 strdup(got_worktree_get_repo_path(worktree));
6686 if (repo_path == NULL)
6687 error = got_error_from_errno("strdup");
6688 if (error)
6689 goto done;
6690 } else {
6691 repo_path = strdup(cwd);
6692 if (repo_path == NULL) {
6693 error = got_error_from_errno("strdup");
6694 goto done;
6699 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6700 if (error != NULL)
6701 goto done;
6703 #ifndef PROFILE
6704 if (do_list) {
6705 /* Remove "cpath" promise. */
6706 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6707 NULL) == -1)
6708 err(1, "pledge");
6710 #endif
6712 error = apply_unveil(got_repo_get_path(repo), do_list,
6713 worktree ? got_worktree_get_root_path(worktree) : NULL);
6714 if (error)
6715 goto done;
6717 if (do_list)
6718 error = list_refs(repo, refname, sort_by_time);
6719 else if (do_delete)
6720 error = delete_ref_by_name(repo, refname);
6721 else if (symref_target)
6722 error = add_symref(repo, refname, symref_target);
6723 else {
6724 if (obj_arg == NULL)
6725 usage_ref();
6726 error = add_ref(repo, refname, obj_arg);
6728 done:
6729 free(refname);
6730 if (repo) {
6731 const struct got_error *close_err = got_repo_close(repo);
6732 if (error == NULL)
6733 error = close_err;
6735 if (worktree)
6736 got_worktree_close(worktree);
6737 if (pack_fds) {
6738 const struct got_error *pack_err =
6739 got_repo_pack_fds_close(pack_fds);
6740 if (error == NULL)
6741 error = pack_err;
6743 free(cwd);
6744 free(repo_path);
6745 return error;
6748 __dead static void
6749 usage_branch(void)
6751 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6752 "[-r repository-path] [name]\n", getprogname());
6753 exit(1);
6756 static const struct got_error *
6757 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6758 struct got_reference *ref)
6760 const struct got_error *err = NULL;
6761 const char *refname, *marker = " ";
6762 char *refstr;
6764 refname = got_ref_get_name(ref);
6765 if (worktree && strcmp(refname,
6766 got_worktree_get_head_ref_name(worktree)) == 0) {
6767 struct got_object_id *id = NULL;
6769 err = got_ref_resolve(&id, repo, ref);
6770 if (err)
6771 return err;
6772 if (got_object_id_cmp(id,
6773 got_worktree_get_base_commit_id(worktree)) == 0)
6774 marker = "* ";
6775 else
6776 marker = "~ ";
6777 free(id);
6780 if (strncmp(refname, "refs/heads/", 11) == 0)
6781 refname += 11;
6782 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6783 refname += 18;
6784 if (strncmp(refname, "refs/remotes/", 13) == 0)
6785 refname += 13;
6787 refstr = got_ref_to_str(ref);
6788 if (refstr == NULL)
6789 return got_error_from_errno("got_ref_to_str");
6791 printf("%s%s: %s\n", marker, refname, refstr);
6792 free(refstr);
6793 return NULL;
6796 static const struct got_error *
6797 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6799 const char *refname;
6801 if (worktree == NULL)
6802 return got_error(GOT_ERR_NOT_WORKTREE);
6804 refname = got_worktree_get_head_ref_name(worktree);
6806 if (strncmp(refname, "refs/heads/", 11) == 0)
6807 refname += 11;
6808 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6809 refname += 18;
6811 printf("%s\n", refname);
6813 return NULL;
6816 static const struct got_error *
6817 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6818 int sort_by_time)
6820 static const struct got_error *err = NULL;
6821 struct got_reflist_head refs;
6822 struct got_reflist_entry *re;
6823 struct got_reference *temp_ref = NULL;
6824 int rebase_in_progress, histedit_in_progress;
6826 TAILQ_INIT(&refs);
6828 if (worktree) {
6829 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6830 worktree);
6831 if (err)
6832 return err;
6834 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6835 worktree);
6836 if (err)
6837 return err;
6839 if (rebase_in_progress || histedit_in_progress) {
6840 err = got_ref_open(&temp_ref, repo,
6841 got_worktree_get_head_ref_name(worktree), 0);
6842 if (err)
6843 return err;
6844 list_branch(repo, worktree, temp_ref);
6845 got_ref_close(temp_ref);
6849 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6850 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6851 repo);
6852 if (err)
6853 return err;
6855 TAILQ_FOREACH(re, &refs, entry)
6856 list_branch(repo, worktree, re->ref);
6858 got_ref_list_free(&refs);
6860 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6861 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6862 repo);
6863 if (err)
6864 return err;
6866 TAILQ_FOREACH(re, &refs, entry)
6867 list_branch(repo, worktree, re->ref);
6869 got_ref_list_free(&refs);
6871 return NULL;
6874 static const struct got_error *
6875 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6876 const char *branch_name)
6878 const struct got_error *err = NULL;
6879 struct got_reference *ref = NULL;
6880 char *refname, *remote_refname = NULL;
6882 if (strncmp(branch_name, "refs/", 5) == 0)
6883 branch_name += 5;
6884 if (strncmp(branch_name, "heads/", 6) == 0)
6885 branch_name += 6;
6886 else if (strncmp(branch_name, "remotes/", 8) == 0)
6887 branch_name += 8;
6889 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6890 return got_error_from_errno("asprintf");
6892 if (asprintf(&remote_refname, "refs/remotes/%s",
6893 branch_name) == -1) {
6894 err = got_error_from_errno("asprintf");
6895 goto done;
6898 err = got_ref_open(&ref, repo, refname, 0);
6899 if (err) {
6900 const struct got_error *err2;
6901 if (err->code != GOT_ERR_NOT_REF)
6902 goto done;
6904 * Keep 'err' intact such that if neither branch exists
6905 * we report "refs/heads" rather than "refs/remotes" in
6906 * our error message.
6908 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6909 if (err2)
6910 goto done;
6911 err = NULL;
6914 if (worktree &&
6915 strcmp(got_worktree_get_head_ref_name(worktree),
6916 got_ref_get_name(ref)) == 0) {
6917 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6918 "will not delete this work tree's current branch");
6919 goto done;
6922 err = delete_ref(repo, ref);
6923 done:
6924 if (ref)
6925 got_ref_close(ref);
6926 free(refname);
6927 free(remote_refname);
6928 return err;
6931 static const struct got_error *
6932 add_branch(struct got_repository *repo, const char *branch_name,
6933 struct got_object_id *base_commit_id)
6935 const struct got_error *err = NULL;
6936 struct got_reference *ref = NULL;
6937 char *refname = NULL;
6940 * Don't let the user create a branch name with a leading '-'.
6941 * While technically a valid reference name, this case is usually
6942 * an unintended typo.
6944 if (branch_name[0] == '-')
6945 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6947 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6948 branch_name += 11;
6950 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6951 err = got_error_from_errno("asprintf");
6952 goto done;
6955 err = got_ref_open(&ref, repo, refname, 0);
6956 if (err == NULL) {
6957 err = got_error(GOT_ERR_BRANCH_EXISTS);
6958 goto done;
6959 } else if (err->code != GOT_ERR_NOT_REF)
6960 goto done;
6962 err = got_ref_alloc(&ref, refname, base_commit_id);
6963 if (err)
6964 goto done;
6966 err = got_ref_write(ref, repo);
6967 done:
6968 if (ref)
6969 got_ref_close(ref);
6970 free(refname);
6971 return err;
6974 static const struct got_error *
6975 cmd_branch(int argc, char *argv[])
6977 const struct got_error *error = NULL;
6978 struct got_repository *repo = NULL;
6979 struct got_worktree *worktree = NULL;
6980 char *cwd = NULL, *repo_path = NULL;
6981 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6982 const char *delref = NULL, *commit_id_arg = NULL;
6983 struct got_reference *ref = NULL;
6984 struct got_pathlist_head paths;
6985 struct got_object_id *commit_id = NULL;
6986 char *commit_id_str = NULL, *keyword_idstr = NULL;;
6987 int *pack_fds = NULL;
6989 TAILQ_INIT(&paths);
6991 #ifndef PROFILE
6992 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6993 "sendfd unveil", NULL) == -1)
6994 err(1, "pledge");
6995 #endif
6997 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6998 switch (ch) {
6999 case 'c':
7000 commit_id_arg = optarg;
7001 break;
7002 case 'd':
7003 delref = optarg;
7004 break;
7005 case 'l':
7006 do_list = 1;
7007 break;
7008 case 'n':
7009 do_update = 0;
7010 break;
7011 case 'r':
7012 repo_path = realpath(optarg, NULL);
7013 if (repo_path == NULL)
7014 return got_error_from_errno2("realpath",
7015 optarg);
7016 got_path_strip_trailing_slashes(repo_path);
7017 break;
7018 case 't':
7019 sort_by_time = 1;
7020 break;
7021 default:
7022 usage_branch();
7023 /* NOTREACHED */
7027 if (do_list && delref)
7028 option_conflict('l', 'd');
7029 if (sort_by_time && !do_list)
7030 errx(1, "-t option requires -l option");
7032 argc -= optind;
7033 argv += optind;
7035 if (!do_list && !delref && argc == 0)
7036 do_show = 1;
7038 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7039 errx(1, "-c option can only be used when creating a branch");
7041 if (do_list || delref) {
7042 if (argc > 0)
7043 usage_branch();
7044 } else if (!do_show && argc != 1)
7045 usage_branch();
7047 cwd = getcwd(NULL, 0);
7048 if (cwd == NULL) {
7049 error = got_error_from_errno("getcwd");
7050 goto done;
7053 error = got_repo_pack_fds_open(&pack_fds);
7054 if (error != NULL)
7055 goto done;
7057 if (repo_path == NULL) {
7058 error = got_worktree_open(&worktree, cwd);
7059 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7060 goto done;
7061 else
7062 error = NULL;
7063 if (worktree) {
7064 repo_path =
7065 strdup(got_worktree_get_repo_path(worktree));
7066 if (repo_path == NULL)
7067 error = got_error_from_errno("strdup");
7068 if (error)
7069 goto done;
7070 } else {
7071 repo_path = strdup(cwd);
7072 if (repo_path == NULL) {
7073 error = got_error_from_errno("strdup");
7074 goto done;
7079 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7080 if (error != NULL)
7081 goto done;
7083 #ifndef PROFILE
7084 if (do_list || do_show) {
7085 /* Remove "cpath" promise. */
7086 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7087 NULL) == -1)
7088 err(1, "pledge");
7090 #endif
7092 error = apply_unveil(got_repo_get_path(repo), do_list,
7093 worktree ? got_worktree_get_root_path(worktree) : NULL);
7094 if (error)
7095 goto done;
7097 if (do_show)
7098 error = show_current_branch(repo, worktree);
7099 else if (do_list)
7100 error = list_branches(repo, worktree, sort_by_time);
7101 else if (delref)
7102 error = delete_branch(repo, worktree, delref);
7103 else {
7104 struct got_reflist_head refs;
7105 TAILQ_INIT(&refs);
7106 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7107 NULL);
7108 if (error)
7109 goto done;
7110 if (commit_id_arg == NULL)
7111 commit_id_arg = worktree ?
7112 got_worktree_get_head_ref_name(worktree) :
7113 GOT_REF_HEAD;
7114 else {
7115 error = got_keyword_to_idstr(&keyword_idstr,
7116 commit_id_arg, repo, worktree);
7117 if (error != NULL)
7118 goto done;
7119 if (keyword_idstr != NULL)
7120 commit_id_arg = keyword_idstr;
7122 error = got_repo_match_object_id(&commit_id, NULL,
7123 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7124 got_ref_list_free(&refs);
7125 if (error)
7126 goto done;
7127 error = add_branch(repo, argv[0], commit_id);
7128 if (error)
7129 goto done;
7130 if (worktree && do_update) {
7131 struct got_update_progress_arg upa;
7132 char *branch_refname = NULL;
7134 error = got_object_id_str(&commit_id_str, commit_id);
7135 if (error)
7136 goto done;
7137 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7138 worktree);
7139 if (error)
7140 goto done;
7141 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7142 == -1) {
7143 error = got_error_from_errno("asprintf");
7144 goto done;
7146 error = got_ref_open(&ref, repo, branch_refname, 0);
7147 free(branch_refname);
7148 if (error)
7149 goto done;
7150 error = switch_head_ref(ref, commit_id, worktree,
7151 repo);
7152 if (error)
7153 goto done;
7154 error = got_worktree_set_base_commit_id(worktree, repo,
7155 commit_id);
7156 if (error)
7157 goto done;
7158 memset(&upa, 0, sizeof(upa));
7159 error = got_worktree_checkout_files(worktree, &paths,
7160 repo, update_progress, &upa, check_cancelled,
7161 NULL);
7162 if (error)
7163 goto done;
7164 if (upa.did_something) {
7165 printf("Updated to %s: %s\n",
7166 got_worktree_get_head_ref_name(worktree),
7167 commit_id_str);
7169 print_update_progress_stats(&upa);
7172 done:
7173 free(keyword_idstr);
7174 if (ref)
7175 got_ref_close(ref);
7176 if (repo) {
7177 const struct got_error *close_err = got_repo_close(repo);
7178 if (error == NULL)
7179 error = close_err;
7181 if (worktree)
7182 got_worktree_close(worktree);
7183 if (pack_fds) {
7184 const struct got_error *pack_err =
7185 got_repo_pack_fds_close(pack_fds);
7186 if (error == NULL)
7187 error = pack_err;
7189 free(cwd);
7190 free(repo_path);
7191 free(commit_id);
7192 free(commit_id_str);
7193 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7194 return error;
7198 __dead static void
7199 usage_tag(void)
7201 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7202 "[-r repository-path] [-s signer-id] name\n", getprogname());
7203 exit(1);
7206 #if 0
7207 static const struct got_error *
7208 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7210 const struct got_error *err = NULL;
7211 struct got_reflist_entry *re, *se, *new;
7212 struct got_object_id *re_id, *se_id;
7213 struct got_tag_object *re_tag, *se_tag;
7214 time_t re_time, se_time;
7216 STAILQ_FOREACH(re, tags, entry) {
7217 se = STAILQ_FIRST(sorted);
7218 if (se == NULL) {
7219 err = got_reflist_entry_dup(&new, re);
7220 if (err)
7221 return err;
7222 STAILQ_INSERT_HEAD(sorted, new, entry);
7223 continue;
7224 } else {
7225 err = got_ref_resolve(&re_id, repo, re->ref);
7226 if (err)
7227 break;
7228 err = got_object_open_as_tag(&re_tag, repo, re_id);
7229 free(re_id);
7230 if (err)
7231 break;
7232 re_time = got_object_tag_get_tagger_time(re_tag);
7233 got_object_tag_close(re_tag);
7236 while (se) {
7237 err = got_ref_resolve(&se_id, repo, re->ref);
7238 if (err)
7239 break;
7240 err = got_object_open_as_tag(&se_tag, repo, se_id);
7241 free(se_id);
7242 if (err)
7243 break;
7244 se_time = got_object_tag_get_tagger_time(se_tag);
7245 got_object_tag_close(se_tag);
7247 if (se_time > re_time) {
7248 err = got_reflist_entry_dup(&new, re);
7249 if (err)
7250 return err;
7251 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7252 break;
7254 se = STAILQ_NEXT(se, entry);
7255 continue;
7258 done:
7259 return err;
7261 #endif
7263 static const struct got_error *
7264 get_tag_refname(char **refname, const char *tag_name)
7266 const struct got_error *err;
7268 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7269 *refname = strdup(tag_name);
7270 if (*refname == NULL)
7271 return got_error_from_errno("strdup");
7272 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7273 err = got_error_from_errno("asprintf");
7274 *refname = NULL;
7275 return err;
7278 return NULL;
7281 static const struct got_error *
7282 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7283 const char *allowed_signers, const char *revoked_signers, int verbosity)
7285 static const struct got_error *err = NULL;
7286 struct got_reflist_head refs;
7287 struct got_reflist_entry *re;
7288 char *wanted_refname = NULL;
7289 int bad_sigs = 0;
7291 TAILQ_INIT(&refs);
7293 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7294 if (err)
7295 return err;
7297 if (tag_name) {
7298 struct got_reference *ref;
7299 err = get_tag_refname(&wanted_refname, tag_name);
7300 if (err)
7301 goto done;
7302 /* Wanted tag reference should exist. */
7303 err = got_ref_open(&ref, repo, wanted_refname, 0);
7304 if (err)
7305 goto done;
7306 got_ref_close(ref);
7309 TAILQ_FOREACH(re, &refs, entry) {
7310 const char *refname;
7311 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7312 char datebuf[26];
7313 const char *tagger, *ssh_sig = NULL;
7314 char *sig_msg = NULL;
7315 time_t tagger_time;
7316 struct got_object_id *id;
7317 struct got_tag_object *tag;
7318 struct got_commit_object *commit = NULL;
7320 refname = got_ref_get_name(re->ref);
7321 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7322 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7323 continue;
7324 refname += 10;
7325 refstr = got_ref_to_str(re->ref);
7326 if (refstr == NULL) {
7327 err = got_error_from_errno("got_ref_to_str");
7328 break;
7331 err = got_ref_resolve(&id, repo, re->ref);
7332 if (err)
7333 break;
7334 err = got_object_open_as_tag(&tag, repo, id);
7335 if (err) {
7336 if (err->code != GOT_ERR_OBJ_TYPE) {
7337 free(id);
7338 break;
7340 /* "lightweight" tag */
7341 err = got_object_open_as_commit(&commit, repo, id);
7342 if (err) {
7343 free(id);
7344 break;
7346 tagger = got_object_commit_get_committer(commit);
7347 tagger_time =
7348 got_object_commit_get_committer_time(commit);
7349 err = got_object_id_str(&id_str, id);
7350 free(id);
7351 if (err)
7352 break;
7353 } else {
7354 free(id);
7355 tagger = got_object_tag_get_tagger(tag);
7356 tagger_time = got_object_tag_get_tagger_time(tag);
7357 err = got_object_id_str(&id_str,
7358 got_object_tag_get_object_id(tag));
7359 if (err)
7360 break;
7363 if (tag && verify_tags) {
7364 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7365 got_object_tag_get_message(tag));
7366 if (ssh_sig && allowed_signers == NULL) {
7367 err = got_error_msg(
7368 GOT_ERR_VERIFY_TAG_SIGNATURE,
7369 "SSH signature verification requires "
7370 "setting allowed_signers in "
7371 "got.conf(5)");
7372 break;
7376 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7377 free(refstr);
7378 printf("from: %s\n", tagger);
7379 datestr = get_datestr(&tagger_time, datebuf);
7380 if (datestr)
7381 printf("date: %s UTC\n", datestr);
7382 if (commit)
7383 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7384 else {
7385 switch (got_object_tag_get_object_type(tag)) {
7386 case GOT_OBJ_TYPE_BLOB:
7387 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7388 id_str);
7389 break;
7390 case GOT_OBJ_TYPE_TREE:
7391 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7392 id_str);
7393 break;
7394 case GOT_OBJ_TYPE_COMMIT:
7395 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7396 id_str);
7397 break;
7398 case GOT_OBJ_TYPE_TAG:
7399 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7400 id_str);
7401 break;
7402 default:
7403 break;
7406 free(id_str);
7408 if (ssh_sig) {
7409 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7410 allowed_signers, revoked_signers, verbosity);
7411 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7412 bad_sigs = 1;
7413 else if (err)
7414 break;
7415 printf("signature: %s", sig_msg);
7416 free(sig_msg);
7417 sig_msg = NULL;
7420 if (commit) {
7421 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7422 if (err)
7423 break;
7424 got_object_commit_close(commit);
7425 } else {
7426 tagmsg0 = strdup(got_object_tag_get_message(tag));
7427 got_object_tag_close(tag);
7428 if (tagmsg0 == NULL) {
7429 err = got_error_from_errno("strdup");
7430 break;
7434 tagmsg = tagmsg0;
7435 do {
7436 line = strsep(&tagmsg, "\n");
7437 if (line)
7438 printf(" %s\n", line);
7439 } while (line);
7440 free(tagmsg0);
7442 done:
7443 got_ref_list_free(&refs);
7444 free(wanted_refname);
7446 if (err == NULL && bad_sigs)
7447 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7448 return err;
7451 static const struct got_error *
7452 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7453 const char *tag_name, const char *repo_path)
7455 const struct got_error *err = NULL;
7456 char *template = NULL, *initial_content = NULL;
7457 char *editor = NULL;
7458 int initial_content_len;
7459 int fd = -1;
7461 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7462 err = got_error_from_errno("asprintf");
7463 goto done;
7466 initial_content_len = asprintf(&initial_content,
7467 "\n# tagging commit %s as %s\n",
7468 commit_id_str, tag_name);
7469 if (initial_content_len == -1) {
7470 err = got_error_from_errno("asprintf");
7471 goto done;
7474 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7475 if (err)
7476 goto done;
7478 if (write(fd, initial_content, initial_content_len) == -1) {
7479 err = got_error_from_errno2("write", *tagmsg_path);
7480 goto done;
7482 if (close(fd) == -1) {
7483 err = got_error_from_errno2("close", *tagmsg_path);
7484 goto done;
7486 fd = -1;
7488 err = get_editor(&editor);
7489 if (err)
7490 goto done;
7491 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7492 initial_content_len, 1);
7493 done:
7494 free(initial_content);
7495 free(template);
7496 free(editor);
7498 if (fd != -1 && close(fd) == -1 && err == NULL)
7499 err = got_error_from_errno2("close", *tagmsg_path);
7501 if (err) {
7502 free(*tagmsg);
7503 *tagmsg = NULL;
7505 return err;
7508 static const struct got_error *
7509 add_tag(struct got_repository *repo, const char *tagger,
7510 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7511 const char *signer_id, int verbosity)
7513 const struct got_error *err = NULL;
7514 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7515 char *label = NULL, *commit_id_str = NULL;
7516 struct got_reference *ref = NULL;
7517 char *refname = NULL, *tagmsg = NULL;
7518 char *tagmsg_path = NULL, *tag_id_str = NULL;
7519 int preserve_tagmsg = 0;
7520 struct got_reflist_head refs;
7522 TAILQ_INIT(&refs);
7525 * Don't let the user create a tag name with a leading '-'.
7526 * While technically a valid reference name, this case is usually
7527 * an unintended typo.
7529 if (tag_name[0] == '-')
7530 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7532 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7533 if (err)
7534 goto done;
7536 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7537 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7538 if (err)
7539 goto done;
7541 err = got_object_id_str(&commit_id_str, commit_id);
7542 if (err)
7543 goto done;
7545 err = get_tag_refname(&refname, tag_name);
7546 if (err)
7547 goto done;
7548 if (strncmp("refs/tags/", tag_name, 10) == 0)
7549 tag_name += 10;
7551 err = got_ref_open(&ref, repo, refname, 0);
7552 if (err == NULL) {
7553 err = got_error(GOT_ERR_TAG_EXISTS);
7554 goto done;
7555 } else if (err->code != GOT_ERR_NOT_REF)
7556 goto done;
7558 if (tagmsg_arg == NULL) {
7559 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7560 tag_name, got_repo_get_path(repo));
7561 if (err) {
7562 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7563 tagmsg_path != NULL)
7564 preserve_tagmsg = 1;
7565 goto done;
7567 /* Editor is done; we can now apply unveil(2) */
7568 err = got_sigs_apply_unveil();
7569 if (err)
7570 goto done;
7571 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7572 if (err)
7573 goto done;
7576 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7577 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7578 verbosity);
7579 if (err) {
7580 if (tagmsg_path)
7581 preserve_tagmsg = 1;
7582 goto done;
7585 err = got_ref_alloc(&ref, refname, tag_id);
7586 if (err) {
7587 if (tagmsg_path)
7588 preserve_tagmsg = 1;
7589 goto done;
7592 err = got_ref_write(ref, repo);
7593 if (err) {
7594 if (tagmsg_path)
7595 preserve_tagmsg = 1;
7596 goto done;
7599 err = got_object_id_str(&tag_id_str, tag_id);
7600 if (err) {
7601 if (tagmsg_path)
7602 preserve_tagmsg = 1;
7603 goto done;
7605 printf("Created tag %s\n", tag_id_str);
7606 done:
7607 if (preserve_tagmsg) {
7608 fprintf(stderr, "%s: tag message preserved in %s\n",
7609 getprogname(), tagmsg_path);
7610 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7611 err = got_error_from_errno2("unlink", tagmsg_path);
7612 free(tag_id_str);
7613 if (ref)
7614 got_ref_close(ref);
7615 free(commit_id);
7616 free(commit_id_str);
7617 free(refname);
7618 free(tagmsg);
7619 free(tagmsg_path);
7620 got_ref_list_free(&refs);
7621 return err;
7624 static const struct got_error *
7625 cmd_tag(int argc, char *argv[])
7627 const struct got_error *error = NULL;
7628 struct got_repository *repo = NULL;
7629 struct got_worktree *worktree = NULL;
7630 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7631 char *gitconfig_path = NULL, *tagger = NULL;
7632 char *allowed_signers = NULL, *revoked_signers = NULL;
7633 const char *signer_id = NULL;
7634 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7635 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7636 int *pack_fds = NULL;
7638 #ifndef PROFILE
7639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7640 "sendfd unveil", NULL) == -1)
7641 err(1, "pledge");
7642 #endif
7644 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7645 switch (ch) {
7646 case 'c':
7647 commit_id_arg = optarg;
7648 break;
7649 case 'l':
7650 do_list = 1;
7651 break;
7652 case 'm':
7653 tagmsg = optarg;
7654 break;
7655 case 'r':
7656 repo_path = realpath(optarg, NULL);
7657 if (repo_path == NULL) {
7658 error = got_error_from_errno2("realpath",
7659 optarg);
7660 goto done;
7662 got_path_strip_trailing_slashes(repo_path);
7663 break;
7664 case 's':
7665 signer_id = optarg;
7666 break;
7667 case 'V':
7668 verify_tags = 1;
7669 break;
7670 case 'v':
7671 if (verbosity < 0)
7672 verbosity = 0;
7673 else if (verbosity < 3)
7674 verbosity++;
7675 break;
7676 default:
7677 usage_tag();
7678 /* NOTREACHED */
7682 argc -= optind;
7683 argv += optind;
7685 if (do_list || verify_tags) {
7686 if (commit_id_arg != NULL)
7687 errx(1,
7688 "-c option can only be used when creating a tag");
7689 if (tagmsg) {
7690 if (do_list)
7691 option_conflict('l', 'm');
7692 else
7693 option_conflict('V', 'm');
7695 if (signer_id) {
7696 if (do_list)
7697 option_conflict('l', 's');
7698 else
7699 option_conflict('V', 's');
7701 if (argc > 1)
7702 usage_tag();
7703 } else if (argc != 1)
7704 usage_tag();
7706 if (argc == 1)
7707 tag_name = argv[0];
7709 cwd = getcwd(NULL, 0);
7710 if (cwd == NULL) {
7711 error = got_error_from_errno("getcwd");
7712 goto done;
7715 error = got_repo_pack_fds_open(&pack_fds);
7716 if (error != NULL)
7717 goto done;
7719 if (repo_path == NULL) {
7720 error = got_worktree_open(&worktree, cwd);
7721 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7722 goto done;
7723 else
7724 error = NULL;
7725 if (worktree) {
7726 repo_path =
7727 strdup(got_worktree_get_repo_path(worktree));
7728 if (repo_path == NULL)
7729 error = got_error_from_errno("strdup");
7730 if (error)
7731 goto done;
7732 } else {
7733 repo_path = strdup(cwd);
7734 if (repo_path == NULL) {
7735 error = got_error_from_errno("strdup");
7736 goto done;
7741 if (do_list || verify_tags) {
7742 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7743 if (error != NULL)
7744 goto done;
7745 error = get_allowed_signers(&allowed_signers, repo, worktree);
7746 if (error)
7747 goto done;
7748 error = get_revoked_signers(&revoked_signers, repo, worktree);
7749 if (error)
7750 goto done;
7751 if (worktree) {
7752 /* Release work tree lock. */
7753 got_worktree_close(worktree);
7754 worktree = NULL;
7758 * Remove "cpath" promise unless needed for signature tmpfile
7759 * creation.
7761 if (verify_tags)
7762 got_sigs_apply_unveil();
7763 else {
7764 #ifndef PROFILE
7765 if (pledge("stdio rpath wpath flock proc exec sendfd "
7766 "unveil", NULL) == -1)
7767 err(1, "pledge");
7768 #endif
7770 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7771 if (error)
7772 goto done;
7773 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7774 revoked_signers, verbosity);
7775 } else {
7776 error = get_gitconfig_path(&gitconfig_path);
7777 if (error)
7778 goto done;
7779 error = got_repo_open(&repo, repo_path, gitconfig_path,
7780 pack_fds);
7781 if (error != NULL)
7782 goto done;
7784 error = get_author(&tagger, repo, worktree);
7785 if (error)
7786 goto done;
7787 if (signer_id == NULL)
7788 signer_id = get_signer_id(repo, worktree);
7790 if (tagmsg) {
7791 if (signer_id) {
7792 error = got_sigs_apply_unveil();
7793 if (error)
7794 goto done;
7796 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7797 if (error)
7798 goto done;
7801 if (commit_id_arg == NULL) {
7802 struct got_reference *head_ref;
7803 struct got_object_id *commit_id;
7804 error = got_ref_open(&head_ref, repo,
7805 worktree ? got_worktree_get_head_ref_name(worktree)
7806 : GOT_REF_HEAD, 0);
7807 if (error)
7808 goto done;
7809 error = got_ref_resolve(&commit_id, repo, head_ref);
7810 got_ref_close(head_ref);
7811 if (error)
7812 goto done;
7813 error = got_object_id_str(&commit_id_str, commit_id);
7814 free(commit_id);
7815 if (error)
7816 goto done;
7819 if (worktree) {
7820 /* Release work tree lock. */
7821 got_worktree_close(worktree);
7822 worktree = NULL;
7825 error = add_tag(repo, tagger, tag_name,
7826 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7827 signer_id, verbosity);
7829 done:
7830 if (repo) {
7831 const struct got_error *close_err = got_repo_close(repo);
7832 if (error == NULL)
7833 error = close_err;
7835 if (worktree)
7836 got_worktree_close(worktree);
7837 if (pack_fds) {
7838 const struct got_error *pack_err =
7839 got_repo_pack_fds_close(pack_fds);
7840 if (error == NULL)
7841 error = pack_err;
7843 free(cwd);
7844 free(repo_path);
7845 free(gitconfig_path);
7846 free(commit_id_str);
7847 free(tagger);
7848 free(allowed_signers);
7849 free(revoked_signers);
7850 return error;
7853 __dead static void
7854 usage_add(void)
7856 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7857 exit(1);
7860 static const struct got_error *
7861 add_progress(void *arg, unsigned char status, const char *path)
7863 while (path[0] == '/')
7864 path++;
7865 printf("%c %s\n", status, path);
7866 return NULL;
7869 static const struct got_error *
7870 cmd_add(int argc, char *argv[])
7872 const struct got_error *error = NULL;
7873 struct got_repository *repo = NULL;
7874 struct got_worktree *worktree = NULL;
7875 char *cwd = NULL;
7876 struct got_pathlist_head paths;
7877 struct got_pathlist_entry *pe;
7878 int ch, can_recurse = 0, no_ignores = 0;
7879 int *pack_fds = NULL;
7881 TAILQ_INIT(&paths);
7883 #ifndef PROFILE
7884 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7885 NULL) == -1)
7886 err(1, "pledge");
7887 #endif
7889 while ((ch = getopt(argc, argv, "IR")) != -1) {
7890 switch (ch) {
7891 case 'I':
7892 no_ignores = 1;
7893 break;
7894 case 'R':
7895 can_recurse = 1;
7896 break;
7897 default:
7898 usage_add();
7899 /* NOTREACHED */
7903 argc -= optind;
7904 argv += optind;
7906 if (argc < 1)
7907 usage_add();
7909 cwd = getcwd(NULL, 0);
7910 if (cwd == NULL) {
7911 error = got_error_from_errno("getcwd");
7912 goto done;
7915 error = got_repo_pack_fds_open(&pack_fds);
7916 if (error != NULL)
7917 goto done;
7919 error = got_worktree_open(&worktree, cwd);
7920 if (error) {
7921 if (error->code == GOT_ERR_NOT_WORKTREE)
7922 error = wrap_not_worktree_error(error, "add", cwd);
7923 goto done;
7926 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7927 NULL, pack_fds);
7928 if (error != NULL)
7929 goto done;
7931 error = apply_unveil(got_repo_get_path(repo), 1,
7932 got_worktree_get_root_path(worktree));
7933 if (error)
7934 goto done;
7936 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7937 if (error)
7938 goto done;
7940 if (!can_recurse) {
7941 char *ondisk_path;
7942 struct stat sb;
7943 TAILQ_FOREACH(pe, &paths, entry) {
7944 if (asprintf(&ondisk_path, "%s/%s",
7945 got_worktree_get_root_path(worktree),
7946 pe->path) == -1) {
7947 error = got_error_from_errno("asprintf");
7948 goto done;
7950 if (lstat(ondisk_path, &sb) == -1) {
7951 if (errno == ENOENT) {
7952 free(ondisk_path);
7953 continue;
7955 error = got_error_from_errno2("lstat",
7956 ondisk_path);
7957 free(ondisk_path);
7958 goto done;
7960 free(ondisk_path);
7961 if (S_ISDIR(sb.st_mode)) {
7962 error = got_error_msg(GOT_ERR_BAD_PATH,
7963 "adding directories requires -R option");
7964 goto done;
7969 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7970 NULL, repo, no_ignores);
7971 done:
7972 if (repo) {
7973 const struct got_error *close_err = got_repo_close(repo);
7974 if (error == NULL)
7975 error = close_err;
7977 if (worktree)
7978 got_worktree_close(worktree);
7979 if (pack_fds) {
7980 const struct got_error *pack_err =
7981 got_repo_pack_fds_close(pack_fds);
7982 if (error == NULL)
7983 error = pack_err;
7985 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7986 free(cwd);
7987 return error;
7990 __dead static void
7991 usage_remove(void)
7993 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7994 getprogname());
7995 exit(1);
7998 static const struct got_error *
7999 print_remove_status(void *arg, unsigned char status,
8000 unsigned char staged_status, const char *path)
8002 while (path[0] == '/')
8003 path++;
8004 if (status == GOT_STATUS_NONEXISTENT)
8005 return NULL;
8006 if (status == staged_status && (status == GOT_STATUS_DELETE))
8007 status = GOT_STATUS_NO_CHANGE;
8008 printf("%c%c %s\n", status, staged_status, path);
8009 return NULL;
8012 static const struct got_error *
8013 cmd_remove(int argc, char *argv[])
8015 const struct got_error *error = NULL;
8016 struct got_worktree *worktree = NULL;
8017 struct got_repository *repo = NULL;
8018 const char *status_codes = NULL;
8019 char *cwd = NULL;
8020 struct got_pathlist_head paths;
8021 struct got_pathlist_entry *pe;
8022 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8023 int ignore_missing_paths = 0;
8024 int *pack_fds = NULL;
8026 TAILQ_INIT(&paths);
8028 #ifndef PROFILE
8029 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8030 NULL) == -1)
8031 err(1, "pledge");
8032 #endif
8034 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8035 switch (ch) {
8036 case 'f':
8037 delete_local_mods = 1;
8038 ignore_missing_paths = 1;
8039 break;
8040 case 'k':
8041 keep_on_disk = 1;
8042 break;
8043 case 'R':
8044 can_recurse = 1;
8045 break;
8046 case 's':
8047 for (i = 0; optarg[i] != '\0'; i++) {
8048 switch (optarg[i]) {
8049 case GOT_STATUS_MODIFY:
8050 delete_local_mods = 1;
8051 break;
8052 case GOT_STATUS_MISSING:
8053 ignore_missing_paths = 1;
8054 break;
8055 default:
8056 errx(1, "invalid status code '%c'",
8057 optarg[i]);
8060 status_codes = optarg;
8061 break;
8062 default:
8063 usage_remove();
8064 /* NOTREACHED */
8068 argc -= optind;
8069 argv += optind;
8071 if (argc < 1)
8072 usage_remove();
8074 cwd = getcwd(NULL, 0);
8075 if (cwd == NULL) {
8076 error = got_error_from_errno("getcwd");
8077 goto done;
8080 error = got_repo_pack_fds_open(&pack_fds);
8081 if (error != NULL)
8082 goto done;
8084 error = got_worktree_open(&worktree, cwd);
8085 if (error) {
8086 if (error->code == GOT_ERR_NOT_WORKTREE)
8087 error = wrap_not_worktree_error(error, "remove", cwd);
8088 goto done;
8091 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8092 NULL, pack_fds);
8093 if (error)
8094 goto done;
8096 error = apply_unveil(got_repo_get_path(repo), 1,
8097 got_worktree_get_root_path(worktree));
8098 if (error)
8099 goto done;
8101 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8102 if (error)
8103 goto done;
8105 if (!can_recurse) {
8106 char *ondisk_path;
8107 struct stat sb;
8108 TAILQ_FOREACH(pe, &paths, entry) {
8109 if (asprintf(&ondisk_path, "%s/%s",
8110 got_worktree_get_root_path(worktree),
8111 pe->path) == -1) {
8112 error = got_error_from_errno("asprintf");
8113 goto done;
8115 if (lstat(ondisk_path, &sb) == -1) {
8116 if (errno == ENOENT) {
8117 free(ondisk_path);
8118 continue;
8120 error = got_error_from_errno2("lstat",
8121 ondisk_path);
8122 free(ondisk_path);
8123 goto done;
8125 free(ondisk_path);
8126 if (S_ISDIR(sb.st_mode)) {
8127 error = got_error_msg(GOT_ERR_BAD_PATH,
8128 "removing directories requires -R option");
8129 goto done;
8134 error = got_worktree_schedule_delete(worktree, &paths,
8135 delete_local_mods, status_codes, print_remove_status, NULL,
8136 repo, keep_on_disk, ignore_missing_paths);
8137 done:
8138 if (repo) {
8139 const struct got_error *close_err = got_repo_close(repo);
8140 if (error == NULL)
8141 error = close_err;
8143 if (worktree)
8144 got_worktree_close(worktree);
8145 if (pack_fds) {
8146 const struct got_error *pack_err =
8147 got_repo_pack_fds_close(pack_fds);
8148 if (error == NULL)
8149 error = pack_err;
8151 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8152 free(cwd);
8153 return error;
8156 __dead static void
8157 usage_patch(void)
8159 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8160 "[patchfile]\n", getprogname());
8161 exit(1);
8164 static const struct got_error *
8165 patch_from_stdin(int *patchfd)
8167 const struct got_error *err = NULL;
8168 ssize_t r;
8169 char buf[BUFSIZ];
8170 sig_t sighup, sigint, sigquit;
8172 *patchfd = got_opentempfd();
8173 if (*patchfd == -1)
8174 return got_error_from_errno("got_opentempfd");
8176 sighup = signal(SIGHUP, SIG_DFL);
8177 sigint = signal(SIGINT, SIG_DFL);
8178 sigquit = signal(SIGQUIT, SIG_DFL);
8180 for (;;) {
8181 r = read(0, buf, sizeof(buf));
8182 if (r == -1) {
8183 err = got_error_from_errno("read");
8184 break;
8186 if (r == 0)
8187 break;
8188 if (write(*patchfd, buf, r) == -1) {
8189 err = got_error_from_errno("write");
8190 break;
8194 signal(SIGHUP, sighup);
8195 signal(SIGINT, sigint);
8196 signal(SIGQUIT, sigquit);
8198 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8199 err = got_error_from_errno("lseek");
8201 if (err != NULL) {
8202 close(*patchfd);
8203 *patchfd = -1;
8206 return err;
8209 struct got_patch_progress_arg {
8210 int did_something;
8211 int conflicts;
8212 int rejects;
8215 static const struct got_error *
8216 patch_progress(void *arg, const char *old, const char *new,
8217 unsigned char status, const struct got_error *error, int old_from,
8218 int old_lines, int new_from, int new_lines, int offset,
8219 int ws_mangled, const struct got_error *hunk_err)
8221 const char *path = new == NULL ? old : new;
8222 struct got_patch_progress_arg *a = arg;
8224 while (*path == '/')
8225 path++;
8227 if (status != GOT_STATUS_NO_CHANGE &&
8228 status != 0 /* per-hunk progress */) {
8229 printf("%c %s\n", status, path);
8230 a->did_something = 1;
8233 if (hunk_err == NULL) {
8234 if (status == GOT_STATUS_CANNOT_UPDATE)
8235 a->rejects++;
8236 else if (status == GOT_STATUS_CONFLICT)
8237 a->conflicts++;
8240 if (error != NULL)
8241 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8243 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8244 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8245 old_lines, new_from, new_lines);
8246 if (hunk_err != NULL)
8247 printf("%s\n", hunk_err->msg);
8248 else if (offset != 0)
8249 printf("applied with offset %d\n", offset);
8250 else
8251 printf("hunk contains mangled whitespace\n");
8254 return NULL;
8257 static void
8258 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8260 if (!ppa->did_something)
8261 return;
8263 if (ppa->conflicts > 0)
8264 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8266 if (ppa->rejects > 0) {
8267 printf("Files where patch failed to apply: %d\n",
8268 ppa->rejects);
8272 static const struct got_error *
8273 cmd_patch(int argc, char *argv[])
8275 const struct got_error *error = NULL, *close_error = NULL;
8276 struct got_worktree *worktree = NULL;
8277 struct got_repository *repo = NULL;
8278 struct got_reflist_head refs;
8279 struct got_object_id *commit_id = NULL;
8280 const char *commit_id_str = NULL;
8281 struct stat sb;
8282 const char *errstr;
8283 char *cwd = NULL, *keyword_idstr = NULL;
8284 int ch, nop = 0, strip = -1, reverse = 0;
8285 int patchfd;
8286 int *pack_fds = NULL;
8287 struct got_patch_progress_arg ppa;
8289 TAILQ_INIT(&refs);
8291 #ifndef PROFILE
8292 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8293 "unveil", NULL) == -1)
8294 err(1, "pledge");
8295 #endif
8297 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8298 switch (ch) {
8299 case 'c':
8300 commit_id_str = optarg;
8301 break;
8302 case 'n':
8303 nop = 1;
8304 break;
8305 case 'p':
8306 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8307 if (errstr != NULL)
8308 errx(1, "pathname strip count is %s: %s",
8309 errstr, optarg);
8310 break;
8311 case 'R':
8312 reverse = 1;
8313 break;
8314 default:
8315 usage_patch();
8316 /* NOTREACHED */
8320 argc -= optind;
8321 argv += optind;
8323 if (argc == 0) {
8324 error = patch_from_stdin(&patchfd);
8325 if (error)
8326 return error;
8327 } else if (argc == 1) {
8328 patchfd = open(argv[0], O_RDONLY);
8329 if (patchfd == -1) {
8330 error = got_error_from_errno2("open", argv[0]);
8331 return error;
8333 if (fstat(patchfd, &sb) == -1) {
8334 error = got_error_from_errno2("fstat", argv[0]);
8335 goto done;
8337 if (!S_ISREG(sb.st_mode)) {
8338 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8339 goto done;
8341 } else
8342 usage_patch();
8344 if ((cwd = getcwd(NULL, 0)) == NULL) {
8345 error = got_error_from_errno("getcwd");
8346 goto done;
8349 error = got_repo_pack_fds_open(&pack_fds);
8350 if (error != NULL)
8351 goto done;
8353 error = got_worktree_open(&worktree, cwd);
8354 if (error != NULL)
8355 goto done;
8357 const char *repo_path = got_worktree_get_repo_path(worktree);
8358 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8359 if (error != NULL)
8360 goto done;
8362 error = apply_unveil(got_repo_get_path(repo), 0,
8363 got_worktree_get_root_path(worktree));
8364 if (error != NULL)
8365 goto done;
8367 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8368 if (error)
8369 goto done;
8371 if (commit_id_str != NULL) {
8372 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8373 repo, worktree);
8374 if (error != NULL)
8375 goto done;
8377 error = got_repo_match_object_id(&commit_id, NULL,
8378 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8379 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8380 if (error)
8381 goto done;
8384 memset(&ppa, 0, sizeof(ppa));
8385 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8386 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8387 print_patch_progress_stats(&ppa);
8388 done:
8389 got_ref_list_free(&refs);
8390 free(keyword_idstr);
8391 free(commit_id);
8392 if (repo) {
8393 close_error = got_repo_close(repo);
8394 if (error == NULL)
8395 error = close_error;
8397 if (worktree != NULL) {
8398 close_error = got_worktree_close(worktree);
8399 if (error == NULL)
8400 error = close_error;
8402 if (pack_fds) {
8403 const struct got_error *pack_err =
8404 got_repo_pack_fds_close(pack_fds);
8405 if (error == NULL)
8406 error = pack_err;
8408 free(cwd);
8409 return error;
8412 __dead static void
8413 usage_revert(void)
8415 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8416 getprogname());
8417 exit(1);
8420 static const struct got_error *
8421 revert_progress(void *arg, unsigned char status, const char *path)
8423 if (status == GOT_STATUS_UNVERSIONED)
8424 return NULL;
8426 while (path[0] == '/')
8427 path++;
8428 printf("%c %s\n", status, path);
8429 return NULL;
8432 struct choose_patch_arg {
8433 FILE *patch_script_file;
8434 const char *action;
8437 static const struct got_error *
8438 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8439 int nchanges, const char *action)
8441 const struct got_error *err;
8442 char *line = NULL;
8443 size_t linesize = 0;
8444 ssize_t linelen;
8446 switch (status) {
8447 case GOT_STATUS_ADD:
8448 printf("A %s\n%s this addition? [y/n] ", path, action);
8449 break;
8450 case GOT_STATUS_DELETE:
8451 printf("D %s\n%s this deletion? [y/n] ", path, action);
8452 break;
8453 case GOT_STATUS_MODIFY:
8454 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8455 return got_error_from_errno("fseek");
8456 printf(GOT_COMMIT_SEP_STR);
8457 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8458 printf("%s", line);
8459 if (linelen == -1 && ferror(patch_file)) {
8460 err = got_error_from_errno("getline");
8461 free(line);
8462 return err;
8464 free(line);
8465 printf(GOT_COMMIT_SEP_STR);
8466 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8467 path, n, nchanges, action);
8468 break;
8469 default:
8470 return got_error_path(path, GOT_ERR_FILE_STATUS);
8473 fflush(stdout);
8474 return NULL;
8477 static const struct got_error *
8478 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8479 FILE *patch_file, int n, int nchanges)
8481 const struct got_error *err = NULL;
8482 char *line = NULL;
8483 size_t linesize = 0;
8484 ssize_t linelen;
8485 int resp = ' ';
8486 struct choose_patch_arg *a = arg;
8488 *choice = GOT_PATCH_CHOICE_NONE;
8490 if (a->patch_script_file) {
8491 char *nl;
8492 err = show_change(status, path, patch_file, n, nchanges,
8493 a->action);
8494 if (err)
8495 return err;
8496 linelen = getline(&line, &linesize, a->patch_script_file);
8497 if (linelen == -1) {
8498 if (ferror(a->patch_script_file))
8499 return got_error_from_errno("getline");
8500 return NULL;
8502 nl = strchr(line, '\n');
8503 if (nl)
8504 *nl = '\0';
8505 if (strcmp(line, "y") == 0) {
8506 *choice = GOT_PATCH_CHOICE_YES;
8507 printf("y\n");
8508 } else if (strcmp(line, "n") == 0) {
8509 *choice = GOT_PATCH_CHOICE_NO;
8510 printf("n\n");
8511 } else if (strcmp(line, "q") == 0 &&
8512 status == GOT_STATUS_MODIFY) {
8513 *choice = GOT_PATCH_CHOICE_QUIT;
8514 printf("q\n");
8515 } else
8516 printf("invalid response '%s'\n", line);
8517 free(line);
8518 return NULL;
8521 while (resp != 'y' && resp != 'n' && resp != 'q') {
8522 err = show_change(status, path, patch_file, n, nchanges,
8523 a->action);
8524 if (err)
8525 return err;
8526 resp = getchar();
8527 if (resp == '\n')
8528 resp = getchar();
8529 if (status == GOT_STATUS_MODIFY) {
8530 if (resp != 'y' && resp != 'n' && resp != 'q') {
8531 printf("invalid response '%c'\n", resp);
8532 resp = ' ';
8534 } else if (resp != 'y' && resp != 'n') {
8535 printf("invalid response '%c'\n", resp);
8536 resp = ' ';
8540 if (resp == 'y')
8541 *choice = GOT_PATCH_CHOICE_YES;
8542 else if (resp == 'n')
8543 *choice = GOT_PATCH_CHOICE_NO;
8544 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8545 *choice = GOT_PATCH_CHOICE_QUIT;
8547 return NULL;
8550 struct wt_commitable_path_arg {
8551 struct got_pathlist_head *commit_paths;
8552 int *has_changes;
8556 * Shortcut work tree status callback to determine if the set of paths scanned
8557 * has at least one versioned path that is being modified and, if not NULL, is
8558 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8559 * soon as a path is passed with a status that satisfies this criteria.
8561 static const struct got_error *
8562 worktree_has_commitable_path(void *arg, unsigned char status,
8563 unsigned char staged_status, const char *path,
8564 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8565 struct got_object_id *commit_id, int dirfd, const char *de_name)
8567 struct wt_commitable_path_arg *a = arg;
8569 if (status == staged_status && (status == GOT_STATUS_DELETE))
8570 status = GOT_STATUS_NO_CHANGE;
8572 if (!(status == GOT_STATUS_NO_CHANGE ||
8573 status == GOT_STATUS_UNVERSIONED) ||
8574 staged_status != GOT_STATUS_NO_CHANGE) {
8575 if (a->commit_paths != NULL) {
8576 struct got_pathlist_entry *pe;
8578 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8579 if (strncmp(path, pe->path,
8580 pe->path_len) == 0) {
8581 *a->has_changes = 1;
8582 break;
8585 } else
8586 *a->has_changes = 1;
8588 if (*a->has_changes)
8589 return got_error(GOT_ERR_FILE_MODIFIED);
8592 return NULL;
8596 * Check that the changeset of the commit identified by id is
8597 * comprised of at least one modified path that is being committed.
8599 static const struct got_error *
8600 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8601 struct got_object_id *id, struct got_worktree *worktree,
8602 struct got_repository *repo)
8604 const struct got_error *err;
8605 struct got_pathlist_head paths;
8606 struct got_commit_object *commit = NULL, *pcommit = NULL;
8607 struct got_tree_object *tree = NULL, *ptree = NULL;
8608 struct got_object_qid *pid;
8610 TAILQ_INIT(&paths);
8612 err = got_object_open_as_commit(&commit, repo, id);
8613 if (err)
8614 goto done;
8616 err = got_object_open_as_tree(&tree, repo,
8617 got_object_commit_get_tree_id(commit));
8618 if (err)
8619 goto done;
8621 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8622 if (pid != NULL) {
8623 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8624 if (err)
8625 goto done;
8627 err = got_object_open_as_tree(&ptree, repo,
8628 got_object_commit_get_tree_id(pcommit));
8629 if (err)
8630 goto done;
8633 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8634 got_diff_tree_collect_changed_paths, &paths, 0);
8635 if (err)
8636 goto done;
8638 err = got_worktree_status(worktree, &paths, repo, 0,
8639 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8640 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8642 * At least one changed path in the referenced commit is
8643 * modified in the work tree, that's all we need to know!
8645 err = NULL;
8648 done:
8649 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8650 if (commit)
8651 got_object_commit_close(commit);
8652 if (pcommit)
8653 got_object_commit_close(pcommit);
8654 if (tree)
8655 got_object_tree_close(tree);
8656 if (ptree)
8657 got_object_tree_close(ptree);
8658 return err;
8662 * Remove any "logmsg" reference comprised entirely of paths that have
8663 * been reverted in this work tree. If any path in the logmsg ref changeset
8664 * remains in a changed state in the worktree, do not remove the reference.
8666 static const struct got_error *
8667 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8669 const struct got_error *err;
8670 struct got_reflist_head refs;
8671 struct got_reflist_entry *re;
8672 struct got_commit_object *commit = NULL;
8673 struct got_object_id *commit_id = NULL;
8674 struct wt_commitable_path_arg wcpa;
8675 char *uuidstr = NULL;
8677 TAILQ_INIT(&refs);
8679 err = got_worktree_get_uuid(&uuidstr, worktree);
8680 if (err)
8681 goto done;
8683 err = got_ref_list(&refs, repo, "refs/got/worktree",
8684 got_ref_cmp_by_name, repo);
8685 if (err)
8686 goto done;
8688 TAILQ_FOREACH(re, &refs, entry) {
8689 const char *refname;
8690 int has_changes = 0;
8692 refname = got_ref_get_name(re->ref);
8694 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8695 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8696 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8697 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8698 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8699 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8700 else
8701 continue;
8703 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8704 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8705 else
8706 continue;
8708 err = got_repo_match_object_id(&commit_id, NULL, refname,
8709 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8710 if (err)
8711 goto done;
8713 err = got_object_open_as_commit(&commit, repo, commit_id);
8714 if (err)
8715 goto done;
8717 wcpa.commit_paths = NULL;
8718 wcpa.has_changes = &has_changes;
8720 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8721 worktree, repo);
8722 if (err)
8723 goto done;
8725 if (!has_changes) {
8726 err = got_ref_delete(re->ref, repo);
8727 if (err)
8728 goto done;
8731 got_object_commit_close(commit);
8732 commit = NULL;
8733 free(commit_id);
8734 commit_id = NULL;
8737 done:
8738 free(uuidstr);
8739 free(commit_id);
8740 got_ref_list_free(&refs);
8741 if (commit)
8742 got_object_commit_close(commit);
8743 return err;
8746 static const struct got_error *
8747 cmd_revert(int argc, char *argv[])
8749 const struct got_error *error = NULL;
8750 struct got_worktree *worktree = NULL;
8751 struct got_repository *repo = NULL;
8752 char *cwd = NULL, *path = NULL;
8753 struct got_pathlist_head paths;
8754 struct got_pathlist_entry *pe;
8755 int ch, can_recurse = 0, pflag = 0;
8756 FILE *patch_script_file = NULL;
8757 const char *patch_script_path = NULL;
8758 struct choose_patch_arg cpa;
8759 int *pack_fds = NULL;
8761 TAILQ_INIT(&paths);
8763 #ifndef PROFILE
8764 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8765 "unveil", NULL) == -1)
8766 err(1, "pledge");
8767 #endif
8769 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8770 switch (ch) {
8771 case 'F':
8772 patch_script_path = optarg;
8773 break;
8774 case 'p':
8775 pflag = 1;
8776 break;
8777 case 'R':
8778 can_recurse = 1;
8779 break;
8780 default:
8781 usage_revert();
8782 /* NOTREACHED */
8786 argc -= optind;
8787 argv += optind;
8789 if (argc < 1)
8790 usage_revert();
8791 if (patch_script_path && !pflag)
8792 errx(1, "-F option can only be used together with -p option");
8794 cwd = getcwd(NULL, 0);
8795 if (cwd == NULL) {
8796 error = got_error_from_errno("getcwd");
8797 goto done;
8800 error = got_repo_pack_fds_open(&pack_fds);
8801 if (error != NULL)
8802 goto done;
8804 error = got_worktree_open(&worktree, cwd);
8805 if (error) {
8806 if (error->code == GOT_ERR_NOT_WORKTREE)
8807 error = wrap_not_worktree_error(error, "revert", cwd);
8808 goto done;
8811 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8812 NULL, pack_fds);
8813 if (error != NULL)
8814 goto done;
8816 if (patch_script_path) {
8817 patch_script_file = fopen(patch_script_path, "re");
8818 if (patch_script_file == NULL) {
8819 error = got_error_from_errno2("fopen",
8820 patch_script_path);
8821 goto done;
8826 * XXX "c" perm needed on repo dir to delete merge references.
8828 error = apply_unveil(got_repo_get_path(repo), 0,
8829 got_worktree_get_root_path(worktree));
8830 if (error)
8831 goto done;
8833 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8834 if (error)
8835 goto done;
8837 if (!can_recurse) {
8838 char *ondisk_path;
8839 struct stat sb;
8840 TAILQ_FOREACH(pe, &paths, entry) {
8841 if (asprintf(&ondisk_path, "%s/%s",
8842 got_worktree_get_root_path(worktree),
8843 pe->path) == -1) {
8844 error = got_error_from_errno("asprintf");
8845 goto done;
8847 if (lstat(ondisk_path, &sb) == -1) {
8848 if (errno == ENOENT) {
8849 free(ondisk_path);
8850 continue;
8852 error = got_error_from_errno2("lstat",
8853 ondisk_path);
8854 free(ondisk_path);
8855 goto done;
8857 free(ondisk_path);
8858 if (S_ISDIR(sb.st_mode)) {
8859 error = got_error_msg(GOT_ERR_BAD_PATH,
8860 "reverting directories requires -R option");
8861 goto done;
8866 cpa.patch_script_file = patch_script_file;
8867 cpa.action = "revert";
8868 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8869 pflag ? choose_patch : NULL, &cpa, repo);
8871 error = rm_logmsg_ref(worktree, repo);
8872 done:
8873 if (patch_script_file && fclose(patch_script_file) == EOF &&
8874 error == NULL)
8875 error = got_error_from_errno2("fclose", patch_script_path);
8876 if (repo) {
8877 const struct got_error *close_err = got_repo_close(repo);
8878 if (error == NULL)
8879 error = close_err;
8881 if (worktree)
8882 got_worktree_close(worktree);
8883 if (pack_fds) {
8884 const struct got_error *pack_err =
8885 got_repo_pack_fds_close(pack_fds);
8886 if (error == NULL)
8887 error = pack_err;
8889 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8890 free(path);
8891 free(cwd);
8892 return error;
8895 __dead static void
8896 usage_commit(void)
8898 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8899 "[-m message] [path ...]\n", getprogname());
8900 exit(1);
8903 struct collect_commit_logmsg_arg {
8904 const char *cmdline_log;
8905 const char *prepared_log;
8906 const char *merged_log;
8907 int non_interactive;
8908 const char *editor;
8909 const char *worktree_path;
8910 const char *branch_name;
8911 const char *repo_path;
8912 char *logmsg_path;
8916 static const struct got_error *
8917 read_prepared_logmsg(char **logmsg, const char *path)
8919 const struct got_error *err = NULL;
8920 FILE *f = NULL;
8921 struct stat sb;
8922 size_t r;
8924 *logmsg = NULL;
8925 memset(&sb, 0, sizeof(sb));
8927 f = fopen(path, "re");
8928 if (f == NULL)
8929 return got_error_from_errno2("fopen", path);
8931 if (fstat(fileno(f), &sb) == -1) {
8932 err = got_error_from_errno2("fstat", path);
8933 goto done;
8935 if (sb.st_size == 0) {
8936 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8937 goto done;
8940 *logmsg = malloc(sb.st_size + 1);
8941 if (*logmsg == NULL) {
8942 err = got_error_from_errno("malloc");
8943 goto done;
8946 r = fread(*logmsg, 1, sb.st_size, f);
8947 if (r != sb.st_size) {
8948 if (ferror(f))
8949 err = got_error_from_errno2("fread", path);
8950 else
8951 err = got_error(GOT_ERR_IO);
8952 goto done;
8954 (*logmsg)[sb.st_size] = '\0';
8955 done:
8956 if (fclose(f) == EOF && err == NULL)
8957 err = got_error_from_errno2("fclose", path);
8958 if (err) {
8959 free(*logmsg);
8960 *logmsg = NULL;
8962 return err;
8965 static const struct got_error *
8966 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8967 const char *diff_path, char **logmsg, void *arg)
8969 char *initial_content = NULL;
8970 struct got_pathlist_entry *pe;
8971 const struct got_error *err = NULL;
8972 char *template = NULL;
8973 char *prepared_msg = NULL, *merged_msg = NULL;
8974 struct collect_commit_logmsg_arg *a = arg;
8975 int initial_content_len;
8976 int fd = -1;
8977 size_t len;
8979 /* if a message was specified on the command line, just use it */
8980 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
8981 len = strlen(a->cmdline_log) + 1;
8982 *logmsg = malloc(len + 1);
8983 if (*logmsg == NULL)
8984 return got_error_from_errno("malloc");
8985 strlcpy(*logmsg, a->cmdline_log, len);
8986 return NULL;
8987 } else if (a->prepared_log != NULL && a->non_interactive)
8988 return read_prepared_logmsg(logmsg, a->prepared_log);
8990 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8991 return got_error_from_errno("asprintf");
8993 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8994 if (err)
8995 goto done;
8997 if (a->prepared_log) {
8998 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8999 if (err)
9000 goto done;
9001 } else if (a->merged_log) {
9002 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9003 if (err)
9004 goto done;
9007 initial_content_len = asprintf(&initial_content,
9008 "%s%s\n# changes to be committed on branch %s:\n",
9009 prepared_msg ? prepared_msg : "",
9010 merged_msg ? merged_msg : "", a->branch_name);
9011 if (initial_content_len == -1) {
9012 err = got_error_from_errno("asprintf");
9013 goto done;
9016 if (write(fd, initial_content, initial_content_len) == -1) {
9017 err = got_error_from_errno2("write", a->logmsg_path);
9018 goto done;
9021 TAILQ_FOREACH(pe, commitable_paths, entry) {
9022 struct got_commitable *ct = pe->data;
9023 dprintf(fd, "# %c %s\n",
9024 got_commitable_get_status(ct),
9025 got_commitable_get_path(ct));
9028 if (diff_path) {
9029 dprintf(fd, "# detailed changes can be viewed in %s\n",
9030 diff_path);
9033 if (close(fd) == -1) {
9034 err = got_error_from_errno2("close", a->logmsg_path);
9035 goto done;
9037 fd = -1;
9039 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9040 initial_content_len, a->prepared_log ? 0 : 1);
9041 done:
9042 free(initial_content);
9043 free(template);
9044 free(prepared_msg);
9045 free(merged_msg);
9047 if (fd != -1 && close(fd) == -1 && err == NULL)
9048 err = got_error_from_errno2("close", a->logmsg_path);
9050 /* Editor is done; we can now apply unveil(2) */
9051 if (err == NULL)
9052 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9053 if (err) {
9054 free(*logmsg);
9055 *logmsg = NULL;
9057 return err;
9060 static const struct got_error *
9061 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9062 const char *type, int has_content)
9064 const struct got_error *err = NULL;
9065 char *logmsg = NULL;
9067 err = got_object_commit_get_logmsg(&logmsg, commit);
9068 if (err)
9069 return err;
9071 if (fprintf(f, "%s# log message of %s commit %s:%s",
9072 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9073 err = got_ferror(f, GOT_ERR_IO);
9075 free(logmsg);
9076 return err;
9080 * Lookup "logmsg" references of backed-out and cherrypicked commits
9081 * belonging to the current work tree. If found, and the worktree has
9082 * at least one modified file that was changed in the referenced commit,
9083 * add its log message to a new temporary file at *logmsg_path.
9084 * Add all refs found to matched_refs to be scheduled for removal on
9085 * successful commit.
9087 static const struct got_error *
9088 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9089 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9090 struct got_repository *repo)
9092 const struct got_error *err;
9093 struct got_commit_object *commit = NULL;
9094 struct got_object_id *id = NULL;
9095 struct got_reflist_head refs;
9096 struct got_reflist_entry *re, *re_match;
9097 FILE *f = NULL;
9098 char *uuidstr = NULL;
9099 int added_logmsg = 0;
9101 TAILQ_INIT(&refs);
9103 *logmsg_path = NULL;
9105 err = got_worktree_get_uuid(&uuidstr, worktree);
9106 if (err)
9107 goto done;
9109 err = got_ref_list(&refs, repo, "refs/got/worktree",
9110 got_ref_cmp_by_name, repo);
9111 if (err)
9112 goto done;
9114 TAILQ_FOREACH(re, &refs, entry) {
9115 const char *refname, *type;
9116 struct wt_commitable_path_arg wcpa;
9117 int add_logmsg = 0;
9119 refname = got_ref_get_name(re->ref);
9121 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9122 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9123 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9124 type = "cherrypicked";
9125 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9126 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9127 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9128 type = "backed-out";
9129 } else
9130 continue;
9132 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9133 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9134 else
9135 continue;
9137 err = got_repo_match_object_id(&id, NULL, refname,
9138 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9139 if (err)
9140 goto done;
9142 err = got_object_open_as_commit(&commit, repo, id);
9143 if (err)
9144 goto done;
9146 wcpa.commit_paths = paths;
9147 wcpa.has_changes = &add_logmsg;
9149 err = commit_path_changed_in_worktree(&wcpa, id,
9150 worktree, repo);
9151 if (err)
9152 goto done;
9154 if (add_logmsg) {
9155 if (f == NULL) {
9156 err = got_opentemp_named(logmsg_path, &f,
9157 "got-commit-logmsg", "");
9158 if (err)
9159 goto done;
9161 err = cat_logmsg(f, commit, refname, type,
9162 added_logmsg);
9163 if (err)
9164 goto done;
9165 if (!added_logmsg)
9166 ++added_logmsg;
9168 err = got_reflist_entry_dup(&re_match, re);
9169 if (err)
9170 goto done;
9171 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9174 got_object_commit_close(commit);
9175 commit = NULL;
9176 free(id);
9177 id = NULL;
9180 done:
9181 free(id);
9182 free(uuidstr);
9183 got_ref_list_free(&refs);
9184 if (commit)
9185 got_object_commit_close(commit);
9186 if (f && fclose(f) == EOF && err == NULL)
9187 err = got_error_from_errno("fclose");
9188 if (!added_logmsg) {
9189 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9190 err = got_error_from_errno2("unlink", *logmsg_path);
9191 *logmsg_path = NULL;
9193 return err;
9196 static const struct got_error *
9197 cmd_commit(int argc, char *argv[])
9199 const struct got_error *error = NULL;
9200 struct got_worktree *worktree = NULL;
9201 struct got_repository *repo = NULL;
9202 char *cwd = NULL, *id_str = NULL;
9203 struct got_object_id *id = NULL;
9204 const char *logmsg = NULL;
9205 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9206 struct collect_commit_logmsg_arg cl_arg;
9207 const char *author = NULL;
9208 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9209 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9210 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9211 int show_diff = 1, commit_conflicts = 0;
9212 struct got_pathlist_head paths;
9213 struct got_reflist_head refs;
9214 struct got_reflist_entry *re;
9215 int *pack_fds = NULL;
9217 TAILQ_INIT(&refs);
9218 TAILQ_INIT(&paths);
9219 cl_arg.logmsg_path = NULL;
9221 #ifndef PROFILE
9222 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9223 "unveil", NULL) == -1)
9224 err(1, "pledge");
9225 #endif
9227 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9228 switch (ch) {
9229 case 'A':
9230 author = optarg;
9231 error = valid_author(author);
9232 if (error)
9233 return error;
9234 break;
9235 case 'C':
9236 commit_conflicts = 1;
9237 break;
9238 case 'F':
9239 if (logmsg != NULL)
9240 option_conflict('F', 'm');
9241 prepared_logmsg = realpath(optarg, NULL);
9242 if (prepared_logmsg == NULL)
9243 return got_error_from_errno2("realpath",
9244 optarg);
9245 break;
9246 case 'm':
9247 if (prepared_logmsg)
9248 option_conflict('m', 'F');
9249 logmsg = optarg;
9250 break;
9251 case 'N':
9252 non_interactive = 1;
9253 break;
9254 case 'n':
9255 show_diff = 0;
9256 break;
9257 case 'S':
9258 allow_bad_symlinks = 1;
9259 break;
9260 default:
9261 usage_commit();
9262 /* NOTREACHED */
9266 argc -= optind;
9267 argv += optind;
9269 cwd = getcwd(NULL, 0);
9270 if (cwd == NULL) {
9271 error = got_error_from_errno("getcwd");
9272 goto done;
9275 error = got_repo_pack_fds_open(&pack_fds);
9276 if (error != NULL)
9277 goto done;
9279 error = got_worktree_open(&worktree, cwd);
9280 if (error) {
9281 if (error->code == GOT_ERR_NOT_WORKTREE)
9282 error = wrap_not_worktree_error(error, "commit", cwd);
9283 goto done;
9286 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9287 if (error)
9288 goto done;
9289 if (rebase_in_progress) {
9290 error = got_error(GOT_ERR_REBASING);
9291 goto done;
9294 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9295 worktree);
9296 if (error)
9297 goto done;
9299 error = get_gitconfig_path(&gitconfig_path);
9300 if (error)
9301 goto done;
9302 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9303 gitconfig_path, pack_fds);
9304 if (error != NULL)
9305 goto done;
9307 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9308 if (error)
9309 goto done;
9310 if (merge_in_progress) {
9311 error = got_error(GOT_ERR_MERGE_BUSY);
9312 goto done;
9315 error = get_author(&committer, repo, worktree);
9316 if (error)
9317 goto done;
9319 if (author == NULL)
9320 author = committer;
9323 * unveil(2) traverses exec(2); if an editor is used we have
9324 * to apply unveil after the log message has been written.
9326 if (logmsg == NULL || strlen(logmsg) == 0)
9327 error = get_editor(&editor);
9328 else
9329 error = apply_unveil(got_repo_get_path(repo), 0,
9330 got_worktree_get_root_path(worktree));
9331 if (error)
9332 goto done;
9334 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9335 if (error)
9336 goto done;
9338 if (prepared_logmsg == NULL) {
9339 error = lookup_logmsg_ref(&merged_logmsg,
9340 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9341 if (error)
9342 goto done;
9345 cl_arg.editor = editor;
9346 cl_arg.cmdline_log = logmsg;
9347 cl_arg.prepared_log = prepared_logmsg;
9348 cl_arg.merged_log = merged_logmsg;
9349 cl_arg.non_interactive = non_interactive;
9350 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9351 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9352 if (!histedit_in_progress) {
9353 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9354 error = got_error(GOT_ERR_COMMIT_BRANCH);
9355 goto done;
9357 cl_arg.branch_name += 11;
9359 cl_arg.repo_path = got_repo_get_path(repo);
9360 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9361 allow_bad_symlinks, show_diff, commit_conflicts,
9362 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9363 if (error) {
9364 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9365 cl_arg.logmsg_path != NULL)
9366 preserve_logmsg = 1;
9367 goto done;
9370 error = got_object_id_str(&id_str, id);
9371 if (error)
9372 goto done;
9373 printf("Created commit %s\n", id_str);
9375 TAILQ_FOREACH(re, &refs, entry) {
9376 error = got_ref_delete(re->ref, repo);
9377 if (error)
9378 goto done;
9381 done:
9382 if (preserve_logmsg) {
9383 fprintf(stderr, "%s: log message preserved in %s\n",
9384 getprogname(), cl_arg.logmsg_path);
9385 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9386 error == NULL)
9387 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9388 free(cl_arg.logmsg_path);
9389 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9390 error = got_error_from_errno2("unlink", merged_logmsg);
9391 free(merged_logmsg);
9392 if (repo) {
9393 const struct got_error *close_err = got_repo_close(repo);
9394 if (error == NULL)
9395 error = close_err;
9397 if (worktree)
9398 got_worktree_close(worktree);
9399 if (pack_fds) {
9400 const struct got_error *pack_err =
9401 got_repo_pack_fds_close(pack_fds);
9402 if (error == NULL)
9403 error = pack_err;
9405 got_ref_list_free(&refs);
9406 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9407 free(cwd);
9408 free(id_str);
9409 free(gitconfig_path);
9410 free(editor);
9411 free(committer);
9412 free(prepared_logmsg);
9413 return error;
9416 __dead static void
9417 usage_send(void)
9419 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9420 "[-r repository-path] [-t tag] [remote-repository]\n",
9421 getprogname());
9422 exit(1);
9425 static void
9426 print_load_info(int print_colored, int print_found, int print_trees,
9427 int ncolored, int nfound, int ntrees)
9429 if (print_colored) {
9430 printf("%d commit%s colored", ncolored,
9431 ncolored == 1 ? "" : "s");
9433 if (print_found) {
9434 printf("%s%d object%s found",
9435 ncolored > 0 ? "; " : "",
9436 nfound, nfound == 1 ? "" : "s");
9438 if (print_trees) {
9439 printf("; %d tree%s scanned", ntrees,
9440 ntrees == 1 ? "" : "s");
9444 struct got_send_progress_arg {
9445 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9446 int verbosity;
9447 int last_ncolored;
9448 int last_nfound;
9449 int last_ntrees;
9450 int loading_done;
9451 int last_ncommits;
9452 int last_nobj_total;
9453 int last_p_deltify;
9454 int last_p_written;
9455 int last_p_sent;
9456 int printed_something;
9457 int sent_something;
9458 struct got_pathlist_head *delete_branches;
9461 static const struct got_error *
9462 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9463 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9464 int nobj_written, off_t bytes_sent, const char *refname,
9465 const char *errmsg, int success)
9467 struct got_send_progress_arg *a = arg;
9468 char scaled_packsize[FMT_SCALED_STRSIZE];
9469 char scaled_sent[FMT_SCALED_STRSIZE];
9470 int p_deltify = 0, p_written = 0, p_sent = 0;
9471 int print_colored = 0, print_found = 0, print_trees = 0;
9472 int print_searching = 0, print_total = 0;
9473 int print_deltify = 0, print_written = 0, print_sent = 0;
9475 if (a->verbosity < 0)
9476 return NULL;
9478 if (refname) {
9479 const char *status = success ? "accepted" : "rejected";
9481 if (success) {
9482 struct got_pathlist_entry *pe;
9483 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9484 const char *branchname = pe->path;
9485 if (got_path_cmp(branchname, refname,
9486 strlen(branchname), strlen(refname)) == 0) {
9487 status = "deleted";
9488 a->sent_something = 1;
9489 break;
9494 if (a->printed_something)
9495 putchar('\n');
9496 printf("Server has %s %s", status, refname);
9497 if (errmsg)
9498 printf(": %s", errmsg);
9499 a->printed_something = 1;
9500 return NULL;
9503 if (a->last_ncolored != ncolored) {
9504 print_colored = 1;
9505 a->last_ncolored = ncolored;
9508 if (a->last_nfound != nfound) {
9509 print_colored = 1;
9510 print_found = 1;
9511 a->last_nfound = nfound;
9514 if (a->last_ntrees != ntrees) {
9515 print_colored = 1;
9516 print_found = 1;
9517 print_trees = 1;
9518 a->last_ntrees = ntrees;
9521 if ((print_colored || print_found || print_trees) &&
9522 !a->loading_done) {
9523 printf("\r");
9524 print_load_info(print_colored, print_found, print_trees,
9525 ncolored, nfound, ntrees);
9526 a->printed_something = 1;
9527 fflush(stdout);
9528 return NULL;
9529 } else if (!a->loading_done) {
9530 printf("\r");
9531 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9532 printf("\n");
9533 a->loading_done = 1;
9536 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9537 return got_error_from_errno("fmt_scaled");
9538 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9539 return got_error_from_errno("fmt_scaled");
9541 if (a->last_ncommits != ncommits) {
9542 print_searching = 1;
9543 a->last_ncommits = ncommits;
9546 if (a->last_nobj_total != nobj_total) {
9547 print_searching = 1;
9548 print_total = 1;
9549 a->last_nobj_total = nobj_total;
9552 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9553 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9554 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9555 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9556 return got_error(GOT_ERR_NO_SPACE);
9559 if (nobj_deltify > 0 || nobj_written > 0) {
9560 if (nobj_deltify > 0) {
9561 p_deltify = (nobj_deltify * 100) / nobj_total;
9562 if (p_deltify != a->last_p_deltify) {
9563 a->last_p_deltify = p_deltify;
9564 print_searching = 1;
9565 print_total = 1;
9566 print_deltify = 1;
9569 if (nobj_written > 0) {
9570 p_written = (nobj_written * 100) / nobj_total;
9571 if (p_written != a->last_p_written) {
9572 a->last_p_written = p_written;
9573 print_searching = 1;
9574 print_total = 1;
9575 print_deltify = 1;
9576 print_written = 1;
9581 if (bytes_sent > 0) {
9582 p_sent = (bytes_sent * 100) / packfile_size;
9583 if (p_sent != a->last_p_sent) {
9584 a->last_p_sent = p_sent;
9585 print_searching = 1;
9586 print_total = 1;
9587 print_deltify = 1;
9588 print_written = 1;
9589 print_sent = 1;
9591 a->sent_something = 1;
9594 if (print_searching || print_total || print_deltify || print_written ||
9595 print_sent)
9596 printf("\r");
9597 if (print_searching)
9598 printf("packing %d reference%s", ncommits,
9599 ncommits == 1 ? "" : "s");
9600 if (print_total)
9601 printf("; %d object%s", nobj_total,
9602 nobj_total == 1 ? "" : "s");
9603 if (print_deltify)
9604 printf("; deltify: %d%%", p_deltify);
9605 if (print_sent)
9606 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9607 scaled_packsize, p_sent);
9608 else if (print_written)
9609 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9610 scaled_packsize, p_written);
9611 if (print_searching || print_total || print_deltify ||
9612 print_written || print_sent) {
9613 a->printed_something = 1;
9614 fflush(stdout);
9616 return NULL;
9619 static const struct got_error *
9620 cmd_send(int argc, char *argv[])
9622 const struct got_error *error = NULL;
9623 char *cwd = NULL, *repo_path = NULL;
9624 const char *remote_name;
9625 char *proto = NULL, *host = NULL, *port = NULL;
9626 char *repo_name = NULL, *server_path = NULL;
9627 const struct got_remote_repo *remotes, *remote = NULL;
9628 int nremotes, nbranches = 0, ndelete_branches = 0;
9629 struct got_repository *repo = NULL;
9630 struct got_worktree *worktree = NULL;
9631 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9632 struct got_pathlist_head branches;
9633 struct got_pathlist_head tags;
9634 struct got_reflist_head all_branches;
9635 struct got_reflist_head all_tags;
9636 struct got_pathlist_head delete_args;
9637 struct got_pathlist_head delete_branches;
9638 struct got_reflist_entry *re;
9639 struct got_pathlist_entry *pe;
9640 int i, ch, sendfd = -1, sendstatus;
9641 pid_t sendpid = -1;
9642 struct got_send_progress_arg spa;
9643 int verbosity = 0, overwrite_refs = 0;
9644 int send_all_branches = 0, send_all_tags = 0;
9645 struct got_reference *ref = NULL;
9646 int *pack_fds = NULL;
9648 TAILQ_INIT(&branches);
9649 TAILQ_INIT(&tags);
9650 TAILQ_INIT(&all_branches);
9651 TAILQ_INIT(&all_tags);
9652 TAILQ_INIT(&delete_args);
9653 TAILQ_INIT(&delete_branches);
9655 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9656 switch (ch) {
9657 case 'a':
9658 send_all_branches = 1;
9659 break;
9660 case 'b':
9661 error = got_pathlist_append(&branches, optarg, NULL);
9662 if (error)
9663 return error;
9664 nbranches++;
9665 break;
9666 case 'd':
9667 error = got_pathlist_append(&delete_args, optarg, NULL);
9668 if (error)
9669 return error;
9670 break;
9671 case 'f':
9672 overwrite_refs = 1;
9673 break;
9674 case 'q':
9675 verbosity = -1;
9676 break;
9677 case 'r':
9678 repo_path = realpath(optarg, NULL);
9679 if (repo_path == NULL)
9680 return got_error_from_errno2("realpath",
9681 optarg);
9682 got_path_strip_trailing_slashes(repo_path);
9683 break;
9684 case 'T':
9685 send_all_tags = 1;
9686 break;
9687 case 't':
9688 error = got_pathlist_append(&tags, optarg, NULL);
9689 if (error)
9690 return error;
9691 break;
9692 case 'v':
9693 if (verbosity < 0)
9694 verbosity = 0;
9695 else if (verbosity < 3)
9696 verbosity++;
9697 break;
9698 default:
9699 usage_send();
9700 /* NOTREACHED */
9703 argc -= optind;
9704 argv += optind;
9706 if (send_all_branches && !TAILQ_EMPTY(&branches))
9707 option_conflict('a', 'b');
9708 if (send_all_tags && !TAILQ_EMPTY(&tags))
9709 option_conflict('T', 't');
9712 if (argc == 0)
9713 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9714 else if (argc == 1)
9715 remote_name = argv[0];
9716 else
9717 usage_send();
9719 cwd = getcwd(NULL, 0);
9720 if (cwd == NULL) {
9721 error = got_error_from_errno("getcwd");
9722 goto done;
9725 error = got_repo_pack_fds_open(&pack_fds);
9726 if (error != NULL)
9727 goto done;
9729 if (repo_path == NULL) {
9730 error = got_worktree_open(&worktree, cwd);
9731 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9732 goto done;
9733 else
9734 error = NULL;
9735 if (worktree) {
9736 repo_path =
9737 strdup(got_worktree_get_repo_path(worktree));
9738 if (repo_path == NULL)
9739 error = got_error_from_errno("strdup");
9740 if (error)
9741 goto done;
9742 } else {
9743 repo_path = strdup(cwd);
9744 if (repo_path == NULL) {
9745 error = got_error_from_errno("strdup");
9746 goto done;
9751 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9752 if (error)
9753 goto done;
9755 if (worktree) {
9756 worktree_conf = got_worktree_get_gotconfig(worktree);
9757 if (worktree_conf) {
9758 got_gotconfig_get_remotes(&nremotes, &remotes,
9759 worktree_conf);
9760 for (i = 0; i < nremotes; i++) {
9761 if (strcmp(remotes[i].name, remote_name) == 0) {
9762 remote = &remotes[i];
9763 break;
9768 if (remote == NULL) {
9769 repo_conf = got_repo_get_gotconfig(repo);
9770 if (repo_conf) {
9771 got_gotconfig_get_remotes(&nremotes, &remotes,
9772 repo_conf);
9773 for (i = 0; i < nremotes; i++) {
9774 if (strcmp(remotes[i].name, remote_name) == 0) {
9775 remote = &remotes[i];
9776 break;
9781 if (remote == NULL) {
9782 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9783 for (i = 0; i < nremotes; i++) {
9784 if (strcmp(remotes[i].name, remote_name) == 0) {
9785 remote = &remotes[i];
9786 break;
9790 if (remote == NULL) {
9791 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9792 goto done;
9795 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9796 &repo_name, remote->send_url);
9797 if (error)
9798 goto done;
9800 if (strcmp(proto, "git") == 0) {
9801 #ifndef PROFILE
9802 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9803 "sendfd dns inet unveil", NULL) == -1)
9804 err(1, "pledge");
9805 #endif
9806 } else if (strcmp(proto, "git+ssh") == 0 ||
9807 strcmp(proto, "ssh") == 0) {
9808 #ifndef PROFILE
9809 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9810 "sendfd unveil", NULL) == -1)
9811 err(1, "pledge");
9812 #endif
9813 } else if (strcmp(proto, "http") == 0 ||
9814 strcmp(proto, "git+http") == 0) {
9815 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9816 goto done;
9817 } else {
9818 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9819 goto done;
9822 error = got_dial_apply_unveil(proto);
9823 if (error)
9824 goto done;
9826 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9827 if (error)
9828 goto done;
9830 if (send_all_branches) {
9831 error = got_ref_list(&all_branches, repo, "refs/heads",
9832 got_ref_cmp_by_name, NULL);
9833 if (error)
9834 goto done;
9835 TAILQ_FOREACH(re, &all_branches, entry) {
9836 const char *branchname = got_ref_get_name(re->ref);
9837 error = got_pathlist_append(&branches,
9838 branchname, NULL);
9839 if (error)
9840 goto done;
9841 nbranches++;
9843 } else if (nbranches == 0) {
9844 for (i = 0; i < remote->nsend_branches; i++) {
9845 error = got_pathlist_append(&branches,
9846 remote->send_branches[i], NULL);
9847 if (error)
9848 goto done;
9852 if (send_all_tags) {
9853 error = got_ref_list(&all_tags, repo, "refs/tags",
9854 got_ref_cmp_by_name, NULL);
9855 if (error)
9856 goto done;
9857 TAILQ_FOREACH(re, &all_tags, entry) {
9858 const char *tagname = got_ref_get_name(re->ref);
9859 error = got_pathlist_append(&tags,
9860 tagname, NULL);
9861 if (error)
9862 goto done;
9867 * To prevent accidents only branches in refs/heads/ can be deleted
9868 * with 'got send -d'.
9869 * Deleting anything else requires local repository access or Git.
9871 TAILQ_FOREACH(pe, &delete_args, entry) {
9872 const char *branchname = pe->path;
9873 char *s;
9874 struct got_pathlist_entry *new;
9875 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9876 s = strdup(branchname);
9877 if (s == NULL) {
9878 error = got_error_from_errno("strdup");
9879 goto done;
9881 } else {
9882 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9883 error = got_error_from_errno("asprintf");
9884 goto done;
9887 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9888 if (error || new == NULL /* duplicate */)
9889 free(s);
9890 if (error)
9891 goto done;
9892 ndelete_branches++;
9895 if (nbranches == 0 && ndelete_branches == 0) {
9896 struct got_reference *head_ref;
9897 if (worktree)
9898 error = got_ref_open(&head_ref, repo,
9899 got_worktree_get_head_ref_name(worktree), 0);
9900 else
9901 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9902 if (error)
9903 goto done;
9904 if (got_ref_is_symbolic(head_ref)) {
9905 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9906 got_ref_close(head_ref);
9907 if (error)
9908 goto done;
9909 } else
9910 ref = head_ref;
9911 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9912 NULL);
9913 if (error)
9914 goto done;
9915 nbranches++;
9918 if (verbosity >= 0) {
9919 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9920 remote->name, proto, host,
9921 port ? ":" : "", port ? port : "",
9922 *server_path == '/' ? "" : "/", server_path);
9925 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9926 server_path, verbosity);
9927 if (error)
9928 goto done;
9930 memset(&spa, 0, sizeof(spa));
9931 spa.last_scaled_packsize[0] = '\0';
9932 spa.last_p_deltify = -1;
9933 spa.last_p_written = -1;
9934 spa.verbosity = verbosity;
9935 spa.delete_branches = &delete_branches;
9936 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9937 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9938 check_cancelled, NULL);
9939 if (spa.printed_something)
9940 putchar('\n');
9941 if (error)
9942 goto done;
9943 if (!spa.sent_something && verbosity >= 0)
9944 printf("Already up-to-date\n");
9945 done:
9946 if (sendpid > 0) {
9947 if (kill(sendpid, SIGTERM) == -1)
9948 error = got_error_from_errno("kill");
9949 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9950 error = got_error_from_errno("waitpid");
9952 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9953 error = got_error_from_errno("close");
9954 if (repo) {
9955 const struct got_error *close_err = got_repo_close(repo);
9956 if (error == NULL)
9957 error = close_err;
9959 if (worktree)
9960 got_worktree_close(worktree);
9961 if (pack_fds) {
9962 const struct got_error *pack_err =
9963 got_repo_pack_fds_close(pack_fds);
9964 if (error == NULL)
9965 error = pack_err;
9967 if (ref)
9968 got_ref_close(ref);
9969 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9970 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9971 got_ref_list_free(&all_branches);
9972 got_ref_list_free(&all_tags);
9973 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9974 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9975 free(cwd);
9976 free(repo_path);
9977 free(proto);
9978 free(host);
9979 free(port);
9980 free(server_path);
9981 free(repo_name);
9982 return error;
9986 * Print and if delete is set delete all ref_prefix references.
9987 * If wanted_ref is not NULL, only print or delete this reference.
9989 static const struct got_error *
9990 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9991 const char *wanted_ref, int delete, struct got_worktree *worktree,
9992 struct got_repository *repo)
9994 const struct got_error *err;
9995 struct got_pathlist_head paths;
9996 struct got_reflist_head refs;
9997 struct got_reflist_entry *re;
9998 struct got_reflist_object_id_map *refs_idmap = NULL;
9999 struct got_commit_object *commit = NULL;
10000 struct got_object_id *id = NULL;
10001 const char *header_prefix;
10002 char *uuidstr = NULL;
10003 int found = 0;
10005 TAILQ_INIT(&refs);
10006 TAILQ_INIT(&paths);
10008 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10009 if (err)
10010 goto done;
10012 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10013 if (err)
10014 goto done;
10016 if (worktree != NULL) {
10017 err = got_worktree_get_uuid(&uuidstr, worktree);
10018 if (err)
10019 goto done;
10022 if (wanted_ref) {
10023 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10024 wanted_ref += 11;
10027 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10028 header_prefix = "backout";
10029 else
10030 header_prefix = "cherrypick";
10032 TAILQ_FOREACH(re, &refs, entry) {
10033 const char *refname, *wt;
10035 refname = got_ref_get_name(re->ref);
10037 err = check_cancelled(NULL);
10038 if (err)
10039 goto done;
10041 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10042 refname += prefix_len + 1; /* skip '-' delimiter */
10043 else
10044 continue;
10046 wt = refname;
10048 if (worktree == NULL || strncmp(refname, uuidstr,
10049 GOT_WORKTREE_UUID_STRLEN) == 0)
10050 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10051 else
10052 continue;
10054 err = got_repo_match_object_id(&id, NULL, refname,
10055 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10056 if (err)
10057 goto done;
10059 err = got_object_open_as_commit(&commit, repo, id);
10060 if (err)
10061 goto done;
10063 if (wanted_ref)
10064 found = strncmp(wanted_ref, refname,
10065 strlen(wanted_ref)) == 0;
10066 if (wanted_ref && !found) {
10067 struct got_reflist_head *ci_refs;
10069 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10070 id);
10072 if (ci_refs) {
10073 char *refs_str = NULL;
10074 char const *r = NULL;
10076 err = build_refs_str(&refs_str, ci_refs, id,
10077 repo, 1);
10078 if (err)
10079 goto done;
10081 r = refs_str;
10082 while (r) {
10083 if (strncmp(r, wanted_ref,
10084 strlen(wanted_ref)) == 0) {
10085 found = 1;
10086 break;
10088 r = strchr(r, ' ');
10089 if (r)
10090 ++r;
10092 free(refs_str);
10096 if (wanted_ref == NULL || found) {
10097 if (delete) {
10098 err = got_ref_delete(re->ref, repo);
10099 if (err)
10100 goto done;
10101 printf("Deleted: ");
10102 err = print_commit_oneline(commit, id, repo,
10103 refs_idmap);
10104 } else {
10106 * Print paths modified by commit to help
10107 * associate commits with worktree changes.
10109 err = get_changed_paths(&paths, commit,
10110 repo, NULL);
10111 if (err)
10112 goto done;
10114 err = print_commit(commit, id, repo, NULL,
10115 &paths, NULL, 0, 0, refs_idmap, NULL,
10116 header_prefix);
10117 got_pathlist_free(&paths,
10118 GOT_PATHLIST_FREE_ALL);
10120 if (worktree == NULL)
10121 printf("work tree: %.*s\n\n",
10122 GOT_WORKTREE_UUID_STRLEN, wt);
10124 if (err || found)
10125 goto done;
10128 got_object_commit_close(commit);
10129 commit = NULL;
10130 free(id);
10131 id = NULL;
10134 if (wanted_ref != NULL && !found)
10135 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10137 done:
10138 free(id);
10139 free(uuidstr);
10140 got_ref_list_free(&refs);
10141 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10142 if (refs_idmap)
10143 got_reflist_object_id_map_free(refs_idmap);
10144 if (commit)
10145 got_object_commit_close(commit);
10146 return err;
10150 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10151 * identified by id for log messages to prepopulate the editor on commit.
10153 static const struct got_error *
10154 logmsg_ref(struct got_object_id *id, const char *prefix,
10155 struct got_worktree *worktree, struct got_repository *repo)
10157 const struct got_error *err = NULL;
10158 char *idstr, *ref = NULL, *refname = NULL;
10159 int histedit_in_progress;
10160 int rebase_in_progress, merge_in_progress;
10163 * Silenty refuse to create merge reference if any histedit, merge,
10164 * or rebase operation is in progress.
10166 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10167 worktree);
10168 if (err)
10169 return err;
10170 if (histedit_in_progress)
10171 return NULL;
10173 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10174 if (err)
10175 return err;
10176 if (rebase_in_progress)
10177 return NULL;
10179 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10180 repo);
10181 if (err)
10182 return err;
10183 if (merge_in_progress)
10184 return NULL;
10186 err = got_object_id_str(&idstr, id);
10187 if (err)
10188 return err;
10190 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10191 if (err)
10192 goto done;
10194 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10195 err = got_error_from_errno("asprintf");
10196 goto done;
10199 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10200 -1, repo);
10201 done:
10202 free(ref);
10203 free(idstr);
10204 free(refname);
10205 return err;
10208 __dead static void
10209 usage_cherrypick(void)
10211 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10212 getprogname());
10213 exit(1);
10216 static const struct got_error *
10217 cmd_cherrypick(int argc, char *argv[])
10219 const struct got_error *error = NULL;
10220 struct got_worktree *worktree = NULL;
10221 struct got_repository *repo = NULL;
10222 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10223 struct got_object_id *commit_id = NULL;
10224 struct got_commit_object *commit = NULL;
10225 struct got_object_qid *pid;
10226 int ch, list_refs = 0, remove_refs = 0;
10227 struct got_update_progress_arg upa;
10228 int *pack_fds = NULL;
10230 #ifndef PROFILE
10231 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10232 "unveil", NULL) == -1)
10233 err(1, "pledge");
10234 #endif
10236 while ((ch = getopt(argc, argv, "lX")) != -1) {
10237 switch (ch) {
10238 case 'l':
10239 list_refs = 1;
10240 break;
10241 case 'X':
10242 remove_refs = 1;
10243 break;
10244 default:
10245 usage_cherrypick();
10246 /* NOTREACHED */
10250 argc -= optind;
10251 argv += optind;
10253 if (list_refs || remove_refs) {
10254 if (argc != 0 && argc != 1)
10255 usage_cherrypick();
10256 } else if (argc != 1)
10257 usage_cherrypick();
10258 if (list_refs && remove_refs)
10259 option_conflict('l', 'X');
10261 cwd = getcwd(NULL, 0);
10262 if (cwd == NULL) {
10263 error = got_error_from_errno("getcwd");
10264 goto done;
10267 error = got_repo_pack_fds_open(&pack_fds);
10268 if (error != NULL)
10269 goto done;
10271 error = got_worktree_open(&worktree, cwd);
10272 if (error) {
10273 if (list_refs || remove_refs) {
10274 if (error->code != GOT_ERR_NOT_WORKTREE)
10275 goto done;
10276 } else {
10277 if (error->code == GOT_ERR_NOT_WORKTREE)
10278 error = wrap_not_worktree_error(error,
10279 "cherrypick", cwd);
10280 goto done;
10284 error = got_repo_open(&repo,
10285 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10286 NULL, pack_fds);
10287 if (error != NULL)
10288 goto done;
10290 error = apply_unveil(got_repo_get_path(repo), 0,
10291 worktree ? got_worktree_get_root_path(worktree) : NULL);
10292 if (error)
10293 goto done;
10295 if (list_refs || remove_refs) {
10296 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10297 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10298 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10299 goto done;
10302 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10303 if (error != NULL)
10304 goto done;
10306 error = got_repo_match_object_id(&commit_id, NULL,
10307 keyword_idstr != NULL ? keyword_idstr : argv[0],
10308 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10309 if (error)
10310 goto done;
10311 error = got_object_id_str(&commit_id_str, commit_id);
10312 if (error)
10313 goto done;
10315 error = got_object_open_as_commit(&commit, repo, commit_id);
10316 if (error)
10317 goto done;
10318 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10319 memset(&upa, 0, sizeof(upa));
10320 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10321 commit_id, repo, update_progress, &upa, check_cancelled,
10322 NULL);
10323 if (error != NULL)
10324 goto done;
10326 if (upa.did_something) {
10327 error = logmsg_ref(commit_id,
10328 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10329 if (error)
10330 goto done;
10331 printf("Merged commit %s\n", commit_id_str);
10333 print_merge_progress_stats(&upa);
10334 done:
10335 free(cwd);
10336 free(keyword_idstr);
10337 if (commit)
10338 got_object_commit_close(commit);
10339 free(commit_id_str);
10340 if (worktree)
10341 got_worktree_close(worktree);
10342 if (repo) {
10343 const struct got_error *close_err = got_repo_close(repo);
10344 if (error == NULL)
10345 error = close_err;
10347 if (pack_fds) {
10348 const struct got_error *pack_err =
10349 got_repo_pack_fds_close(pack_fds);
10350 if (error == NULL)
10351 error = pack_err;
10354 return error;
10357 __dead static void
10358 usage_backout(void)
10360 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10361 exit(1);
10364 static const struct got_error *
10365 cmd_backout(int argc, char *argv[])
10367 const struct got_error *error = NULL;
10368 struct got_worktree *worktree = NULL;
10369 struct got_repository *repo = NULL;
10370 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10371 struct got_object_id *commit_id = NULL;
10372 struct got_commit_object *commit = NULL;
10373 struct got_object_qid *pid;
10374 int ch, list_refs = 0, remove_refs = 0;
10375 struct got_update_progress_arg upa;
10376 int *pack_fds = NULL;
10378 #ifndef PROFILE
10379 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10380 "unveil", NULL) == -1)
10381 err(1, "pledge");
10382 #endif
10384 while ((ch = getopt(argc, argv, "lX")) != -1) {
10385 switch (ch) {
10386 case 'l':
10387 list_refs = 1;
10388 break;
10389 case 'X':
10390 remove_refs = 1;
10391 break;
10392 default:
10393 usage_backout();
10394 /* NOTREACHED */
10398 argc -= optind;
10399 argv += optind;
10401 if (list_refs || remove_refs) {
10402 if (argc != 0 && argc != 1)
10403 usage_backout();
10404 } else if (argc != 1)
10405 usage_backout();
10406 if (list_refs && remove_refs)
10407 option_conflict('l', 'X');
10409 cwd = getcwd(NULL, 0);
10410 if (cwd == NULL) {
10411 error = got_error_from_errno("getcwd");
10412 goto done;
10415 error = got_repo_pack_fds_open(&pack_fds);
10416 if (error != NULL)
10417 goto done;
10419 error = got_worktree_open(&worktree, cwd);
10420 if (error) {
10421 if (list_refs || remove_refs) {
10422 if (error->code != GOT_ERR_NOT_WORKTREE)
10423 goto done;
10424 } else {
10425 if (error->code == GOT_ERR_NOT_WORKTREE)
10426 error = wrap_not_worktree_error(error,
10427 "backout", cwd);
10428 goto done;
10432 error = got_repo_open(&repo,
10433 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10434 NULL, pack_fds);
10435 if (error != NULL)
10436 goto done;
10438 error = apply_unveil(got_repo_get_path(repo), 0,
10439 worktree ? got_worktree_get_root_path(worktree) : NULL);
10440 if (error)
10441 goto done;
10443 if (list_refs || remove_refs) {
10444 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10445 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10446 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10447 goto done;
10450 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10451 if (error != NULL)
10452 goto done;
10454 error = got_repo_match_object_id(&commit_id, NULL,
10455 keyword_idstr != NULL ? keyword_idstr : argv[0],
10456 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10457 if (error)
10458 goto done;
10459 error = got_object_id_str(&commit_id_str, commit_id);
10460 if (error)
10461 goto done;
10463 error = got_object_open_as_commit(&commit, repo, commit_id);
10464 if (error)
10465 goto done;
10466 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10467 if (pid == NULL) {
10468 error = got_error(GOT_ERR_ROOT_COMMIT);
10469 goto done;
10472 memset(&upa, 0, sizeof(upa));
10473 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10474 repo, update_progress, &upa, check_cancelled, NULL);
10475 if (error != NULL)
10476 goto done;
10478 if (upa.did_something) {
10479 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10480 worktree, repo);
10481 if (error)
10482 goto done;
10483 printf("Backed out commit %s\n", commit_id_str);
10485 print_merge_progress_stats(&upa);
10486 done:
10487 free(cwd);
10488 free(keyword_idstr);
10489 if (commit)
10490 got_object_commit_close(commit);
10491 free(commit_id_str);
10492 if (worktree)
10493 got_worktree_close(worktree);
10494 if (repo) {
10495 const struct got_error *close_err = got_repo_close(repo);
10496 if (error == NULL)
10497 error = close_err;
10499 if (pack_fds) {
10500 const struct got_error *pack_err =
10501 got_repo_pack_fds_close(pack_fds);
10502 if (error == NULL)
10503 error = pack_err;
10505 return error;
10508 __dead static void
10509 usage_rebase(void)
10511 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10512 exit(1);
10515 static void
10516 trim_logmsg(char *logmsg, int limit)
10518 char *nl;
10519 size_t len;
10521 len = strlen(logmsg);
10522 if (len > limit)
10523 len = limit;
10524 logmsg[len] = '\0';
10525 nl = strchr(logmsg, '\n');
10526 if (nl)
10527 *nl = '\0';
10530 static const struct got_error *
10531 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10533 const struct got_error *err;
10534 char *logmsg0 = NULL;
10535 const char *s;
10537 err = got_object_commit_get_logmsg(&logmsg0, commit);
10538 if (err)
10539 return err;
10541 s = logmsg0;
10542 while (isspace((unsigned char)s[0]))
10543 s++;
10545 *logmsg = strdup(s);
10546 if (*logmsg == NULL) {
10547 err = got_error_from_errno("strdup");
10548 goto done;
10551 trim_logmsg(*logmsg, limit);
10552 done:
10553 free(logmsg0);
10554 return err;
10557 static const struct got_error *
10558 show_rebase_merge_conflict(struct got_object_id *id,
10559 struct got_repository *repo)
10561 const struct got_error *err;
10562 struct got_commit_object *commit = NULL;
10563 char *id_str = NULL, *logmsg = NULL;
10565 err = got_object_open_as_commit(&commit, repo, id);
10566 if (err)
10567 return err;
10569 err = got_object_id_str(&id_str, id);
10570 if (err)
10571 goto done;
10573 id_str[12] = '\0';
10575 err = get_short_logmsg(&logmsg, 42, commit);
10576 if (err)
10577 goto done;
10579 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10580 done:
10581 free(id_str);
10582 got_object_commit_close(commit);
10583 free(logmsg);
10584 return err;
10587 static const struct got_error *
10588 show_rebase_progress(struct got_commit_object *commit,
10589 struct got_object_id *old_id, struct got_object_id *new_id)
10591 const struct got_error *err;
10592 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10594 err = got_object_id_str(&old_id_str, old_id);
10595 if (err)
10596 goto done;
10598 if (new_id) {
10599 err = got_object_id_str(&new_id_str, new_id);
10600 if (err)
10601 goto done;
10604 old_id_str[12] = '\0';
10605 if (new_id_str)
10606 new_id_str[12] = '\0';
10608 err = get_short_logmsg(&logmsg, 42, commit);
10609 if (err)
10610 goto done;
10612 printf("%s -> %s: %s\n", old_id_str,
10613 new_id_str ? new_id_str : "no-op change", logmsg);
10614 done:
10615 free(old_id_str);
10616 free(new_id_str);
10617 free(logmsg);
10618 return err;
10621 static const struct got_error *
10622 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10623 struct got_reference *branch, struct got_reference *tmp_branch,
10624 struct got_repository *repo, int create_backup)
10626 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10627 return got_worktree_rebase_complete(worktree, fileindex,
10628 tmp_branch, branch, repo, create_backup);
10631 static const struct got_error *
10632 rebase_commit(struct got_pathlist_head *merged_paths,
10633 struct got_worktree *worktree, struct got_fileindex *fileindex,
10634 struct got_reference *tmp_branch, const char *committer,
10635 struct got_object_id *commit_id, int allow_conflict,
10636 struct got_repository *repo)
10638 const struct got_error *error;
10639 struct got_commit_object *commit;
10640 struct got_object_id *new_commit_id;
10642 error = got_object_open_as_commit(&commit, repo, commit_id);
10643 if (error)
10644 return error;
10646 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10647 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10648 allow_conflict, repo);
10649 if (error) {
10650 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10651 goto done;
10652 error = show_rebase_progress(commit, commit_id, NULL);
10653 } else {
10654 error = show_rebase_progress(commit, commit_id, new_commit_id);
10655 free(new_commit_id);
10657 done:
10658 got_object_commit_close(commit);
10659 return error;
10662 struct check_path_prefix_arg {
10663 const char *path_prefix;
10664 size_t len;
10665 int errcode;
10668 static const struct got_error *
10669 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10670 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10671 struct got_object_id *id1, struct got_object_id *id2,
10672 const char *path1, const char *path2,
10673 mode_t mode1, mode_t mode2, struct got_repository *repo)
10675 struct check_path_prefix_arg *a = arg;
10677 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10678 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10679 return got_error(a->errcode);
10681 return NULL;
10684 static const struct got_error *
10685 check_path_prefix(struct got_object_id *parent_id,
10686 struct got_object_id *commit_id, const char *path_prefix,
10687 int errcode, struct got_repository *repo)
10689 const struct got_error *err;
10690 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10691 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10692 struct check_path_prefix_arg cpp_arg;
10694 if (got_path_is_root_dir(path_prefix))
10695 return NULL;
10697 err = got_object_open_as_commit(&commit, repo, commit_id);
10698 if (err)
10699 goto done;
10701 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10702 if (err)
10703 goto done;
10705 err = got_object_open_as_tree(&tree1, repo,
10706 got_object_commit_get_tree_id(parent_commit));
10707 if (err)
10708 goto done;
10710 err = got_object_open_as_tree(&tree2, repo,
10711 got_object_commit_get_tree_id(commit));
10712 if (err)
10713 goto done;
10715 cpp_arg.path_prefix = path_prefix;
10716 while (cpp_arg.path_prefix[0] == '/')
10717 cpp_arg.path_prefix++;
10718 cpp_arg.len = strlen(cpp_arg.path_prefix);
10719 cpp_arg.errcode = errcode;
10720 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10721 check_path_prefix_in_diff, &cpp_arg, 0);
10722 done:
10723 if (tree1)
10724 got_object_tree_close(tree1);
10725 if (tree2)
10726 got_object_tree_close(tree2);
10727 if (commit)
10728 got_object_commit_close(commit);
10729 if (parent_commit)
10730 got_object_commit_close(parent_commit);
10731 return err;
10734 static const struct got_error *
10735 collect_commits(struct got_object_id_queue *commits,
10736 struct got_object_id *initial_commit_id,
10737 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10738 const char *path_prefix, int path_prefix_errcode,
10739 struct got_repository *repo)
10741 const struct got_error *err = NULL;
10742 struct got_commit_graph *graph = NULL;
10743 struct got_object_id parent_id, commit_id;
10744 struct got_object_qid *qid;
10746 err = got_commit_graph_open(&graph, "/", 1);
10747 if (err)
10748 return err;
10750 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10751 check_cancelled, NULL);
10752 if (err)
10753 goto done;
10755 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10756 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10757 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10758 check_cancelled, NULL);
10759 if (err) {
10760 if (err->code == GOT_ERR_ITER_COMPLETED) {
10761 err = got_error_msg(GOT_ERR_ANCESTRY,
10762 "ran out of commits to rebase before "
10763 "youngest common ancestor commit has "
10764 "been reached?!?");
10766 goto done;
10767 } else {
10768 err = check_path_prefix(&parent_id, &commit_id,
10769 path_prefix, path_prefix_errcode, repo);
10770 if (err)
10771 goto done;
10773 err = got_object_qid_alloc(&qid, &commit_id);
10774 if (err)
10775 goto done;
10776 STAILQ_INSERT_HEAD(commits, qid, entry);
10778 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10781 done:
10782 got_commit_graph_close(graph);
10783 return err;
10786 static const struct got_error *
10787 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10789 const struct got_error *err = NULL;
10790 time_t committer_time;
10791 struct tm tm;
10792 char datebuf[11]; /* YYYY-MM-DD + NUL */
10793 char *author0 = NULL, *author, *smallerthan;
10794 char *logmsg0 = NULL, *logmsg, *newline;
10796 committer_time = got_object_commit_get_committer_time(commit);
10797 if (gmtime_r(&committer_time, &tm) == NULL)
10798 return got_error_from_errno("gmtime_r");
10799 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10800 return got_error(GOT_ERR_NO_SPACE);
10802 author0 = strdup(got_object_commit_get_author(commit));
10803 if (author0 == NULL)
10804 return got_error_from_errno("strdup");
10805 author = author0;
10806 smallerthan = strchr(author, '<');
10807 if (smallerthan && smallerthan[1] != '\0')
10808 author = smallerthan + 1;
10809 author[strcspn(author, "@>")] = '\0';
10811 err = got_object_commit_get_logmsg(&logmsg0, commit);
10812 if (err)
10813 goto done;
10814 logmsg = logmsg0;
10815 while (*logmsg == '\n')
10816 logmsg++;
10817 newline = strchr(logmsg, '\n');
10818 if (newline)
10819 *newline = '\0';
10821 if (asprintf(brief_str, "%s %s %s",
10822 datebuf, author, logmsg) == -1)
10823 err = got_error_from_errno("asprintf");
10824 done:
10825 free(author0);
10826 free(logmsg0);
10827 return err;
10830 static const struct got_error *
10831 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10832 struct got_repository *repo)
10834 const struct got_error *err;
10835 char *id_str;
10837 err = got_object_id_str(&id_str, id);
10838 if (err)
10839 return err;
10841 err = got_ref_delete(ref, repo);
10842 if (err)
10843 goto done;
10845 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10846 done:
10847 free(id_str);
10848 return err;
10851 static const struct got_error *
10852 print_backup_ref(const char *branch_name, const char *new_id_str,
10853 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10854 struct got_reflist_object_id_map *refs_idmap,
10855 struct got_repository *repo)
10857 const struct got_error *err = NULL;
10858 struct got_reflist_head *refs;
10859 char *refs_str = NULL;
10860 struct got_object_id *new_commit_id = NULL;
10861 struct got_commit_object *new_commit = NULL;
10862 char *new_commit_brief_str = NULL;
10863 struct got_object_id *yca_id = NULL;
10864 struct got_commit_object *yca_commit = NULL;
10865 char *yca_id_str = NULL, *yca_brief_str = NULL;
10866 char *custom_refs_str;
10868 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10869 return got_error_from_errno("asprintf");
10871 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10872 0, 0, refs_idmap, custom_refs_str, NULL);
10873 if (err)
10874 goto done;
10876 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10877 if (err)
10878 goto done;
10880 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10881 if (refs) {
10882 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10883 if (err)
10884 goto done;
10887 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10888 if (err)
10889 goto done;
10891 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10892 if (err)
10893 goto done;
10895 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10896 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10897 if (err)
10898 goto done;
10900 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10901 refs_str ? " (" : "", refs_str ? refs_str : "",
10902 refs_str ? ")" : "", new_commit_brief_str);
10903 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10904 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10905 free(refs_str);
10906 refs_str = NULL;
10908 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10909 if (err)
10910 goto done;
10912 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10913 if (err)
10914 goto done;
10916 err = got_object_id_str(&yca_id_str, yca_id);
10917 if (err)
10918 goto done;
10920 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10921 if (refs) {
10922 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10923 if (err)
10924 goto done;
10926 printf("history forked at %s%s%s%s\n %s\n",
10927 yca_id_str,
10928 refs_str ? " (" : "", refs_str ? refs_str : "",
10929 refs_str ? ")" : "", yca_brief_str);
10931 done:
10932 free(custom_refs_str);
10933 free(new_commit_id);
10934 free(refs_str);
10935 free(yca_id);
10936 free(yca_id_str);
10937 free(yca_brief_str);
10938 if (new_commit)
10939 got_object_commit_close(new_commit);
10940 if (yca_commit)
10941 got_object_commit_close(yca_commit);
10943 return err;
10946 static const struct got_error *
10947 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10948 struct got_repository *repo)
10950 const struct got_error *err;
10951 struct got_reflist_head refs;
10952 struct got_reflist_entry *re;
10953 char *uuidstr = NULL;
10954 static char msg[160];
10956 TAILQ_INIT(&refs);
10958 err = got_worktree_get_uuid(&uuidstr, worktree);
10959 if (err)
10960 goto done;
10962 err = got_ref_list(&refs, repo, "refs/got/worktree",
10963 got_ref_cmp_by_name, repo);
10964 if (err)
10965 goto done;
10967 TAILQ_FOREACH(re, &refs, entry) {
10968 const char *cmd, *refname, *type;
10970 refname = got_ref_get_name(re->ref);
10972 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10973 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10974 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10975 cmd = "cherrypick";
10976 type = "cherrypicked";
10977 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10978 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10979 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10980 cmd = "backout";
10981 type = "backed-out";
10982 } else
10983 continue;
10985 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10986 continue;
10988 snprintf(msg, sizeof(msg),
10989 "work tree has references created by %s commits which "
10990 "must be removed with 'got %s -X' before running the %s "
10991 "command", type, cmd, caller);
10992 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10993 goto done;
10996 done:
10997 free(uuidstr);
10998 got_ref_list_free(&refs);
10999 return err;
11002 static const struct got_error *
11003 process_backup_refs(const char *backup_ref_prefix,
11004 const char *wanted_branch_name,
11005 int delete, struct got_repository *repo)
11007 const struct got_error *err;
11008 struct got_reflist_head refs, backup_refs;
11009 struct got_reflist_entry *re;
11010 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11011 struct got_object_id *old_commit_id = NULL;
11012 char *branch_name = NULL;
11013 struct got_commit_object *old_commit = NULL;
11014 struct got_reflist_object_id_map *refs_idmap = NULL;
11015 int wanted_branch_found = 0;
11017 TAILQ_INIT(&refs);
11018 TAILQ_INIT(&backup_refs);
11020 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11021 if (err)
11022 return err;
11024 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11025 if (err)
11026 goto done;
11028 if (wanted_branch_name) {
11029 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11030 wanted_branch_name += 11;
11033 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11034 got_ref_cmp_by_commit_timestamp_descending, repo);
11035 if (err)
11036 goto done;
11038 TAILQ_FOREACH(re, &backup_refs, entry) {
11039 const char *refname = got_ref_get_name(re->ref);
11040 char *slash;
11042 err = check_cancelled(NULL);
11043 if (err)
11044 break;
11046 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11047 if (err)
11048 break;
11050 err = got_object_open_as_commit(&old_commit, repo,
11051 old_commit_id);
11052 if (err)
11053 break;
11055 if (strncmp(backup_ref_prefix, refname,
11056 backup_ref_prefix_len) == 0)
11057 refname += backup_ref_prefix_len;
11059 while (refname[0] == '/')
11060 refname++;
11062 branch_name = strdup(refname);
11063 if (branch_name == NULL) {
11064 err = got_error_from_errno("strdup");
11065 break;
11067 slash = strrchr(branch_name, '/');
11068 if (slash) {
11069 *slash = '\0';
11070 refname += strlen(branch_name) + 1;
11073 if (wanted_branch_name == NULL ||
11074 strcmp(wanted_branch_name, branch_name) == 0) {
11075 wanted_branch_found = 1;
11076 if (delete) {
11077 err = delete_backup_ref(re->ref,
11078 old_commit_id, repo);
11079 } else {
11080 err = print_backup_ref(branch_name, refname,
11081 old_commit_id, old_commit, refs_idmap,
11082 repo);
11084 if (err)
11085 break;
11088 free(old_commit_id);
11089 old_commit_id = NULL;
11090 free(branch_name);
11091 branch_name = NULL;
11092 got_object_commit_close(old_commit);
11093 old_commit = NULL;
11096 if (wanted_branch_name && !wanted_branch_found) {
11097 err = got_error_fmt(GOT_ERR_NOT_REF,
11098 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11100 done:
11101 if (refs_idmap)
11102 got_reflist_object_id_map_free(refs_idmap);
11103 got_ref_list_free(&refs);
11104 got_ref_list_free(&backup_refs);
11105 free(old_commit_id);
11106 free(branch_name);
11107 if (old_commit)
11108 got_object_commit_close(old_commit);
11109 return err;
11112 static const struct got_error *
11113 abort_progress(void *arg, unsigned char status, const char *path)
11116 * Unversioned files should not clutter progress output when
11117 * an operation is aborted.
11119 if (status == GOT_STATUS_UNVERSIONED)
11120 return NULL;
11122 return update_progress(arg, status, path);
11125 static const struct got_error *
11126 cmd_rebase(int argc, char *argv[])
11128 const struct got_error *error = NULL;
11129 struct got_worktree *worktree = NULL;
11130 struct got_repository *repo = NULL;
11131 struct got_fileindex *fileindex = NULL;
11132 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11133 struct got_reference *branch = NULL;
11134 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11135 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11136 struct got_object_id *resume_commit_id = NULL;
11137 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11138 struct got_object_id *head_commit_id = NULL;
11139 struct got_reference *head_ref = NULL;
11140 struct got_commit_object *commit = NULL;
11141 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11142 int histedit_in_progress = 0, merge_in_progress = 0;
11143 int create_backup = 1, list_backups = 0, delete_backups = 0;
11144 int allow_conflict = 0;
11145 struct got_object_id_queue commits;
11146 struct got_pathlist_head merged_paths;
11147 const struct got_object_id_queue *parent_ids;
11148 struct got_object_qid *qid, *pid;
11149 struct got_update_progress_arg upa;
11150 int *pack_fds = NULL;
11152 STAILQ_INIT(&commits);
11153 TAILQ_INIT(&merged_paths);
11154 memset(&upa, 0, sizeof(upa));
11156 #ifndef PROFILE
11157 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11158 "unveil", NULL) == -1)
11159 err(1, "pledge");
11160 #endif
11162 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11163 switch (ch) {
11164 case 'a':
11165 abort_rebase = 1;
11166 break;
11167 case 'C':
11168 allow_conflict = 1;
11169 break;
11170 case 'c':
11171 continue_rebase = 1;
11172 break;
11173 case 'l':
11174 list_backups = 1;
11175 break;
11176 case 'X':
11177 delete_backups = 1;
11178 break;
11179 default:
11180 usage_rebase();
11181 /* NOTREACHED */
11185 argc -= optind;
11186 argv += optind;
11188 if (list_backups) {
11189 if (abort_rebase)
11190 option_conflict('l', 'a');
11191 if (allow_conflict)
11192 option_conflict('l', 'C');
11193 if (continue_rebase)
11194 option_conflict('l', 'c');
11195 if (delete_backups)
11196 option_conflict('l', 'X');
11197 if (argc != 0 && argc != 1)
11198 usage_rebase();
11199 } else if (delete_backups) {
11200 if (abort_rebase)
11201 option_conflict('X', 'a');
11202 if (allow_conflict)
11203 option_conflict('X', 'C');
11204 if (continue_rebase)
11205 option_conflict('X', 'c');
11206 if (list_backups)
11207 option_conflict('l', 'X');
11208 if (argc != 0 && argc != 1)
11209 usage_rebase();
11210 } else if (allow_conflict) {
11211 if (abort_rebase)
11212 option_conflict('C', 'a');
11213 if (!continue_rebase)
11214 errx(1, "-C option requires -c");
11215 } else {
11216 if (abort_rebase && continue_rebase)
11217 usage_rebase();
11218 else if (abort_rebase || continue_rebase) {
11219 if (argc != 0)
11220 usage_rebase();
11221 } else if (argc != 1)
11222 usage_rebase();
11225 cwd = getcwd(NULL, 0);
11226 if (cwd == NULL) {
11227 error = got_error_from_errno("getcwd");
11228 goto done;
11231 error = got_repo_pack_fds_open(&pack_fds);
11232 if (error != NULL)
11233 goto done;
11235 error = got_worktree_open(&worktree, cwd);
11236 if (error) {
11237 if (list_backups || delete_backups) {
11238 if (error->code != GOT_ERR_NOT_WORKTREE)
11239 goto done;
11240 } else {
11241 if (error->code == GOT_ERR_NOT_WORKTREE)
11242 error = wrap_not_worktree_error(error,
11243 "rebase", cwd);
11244 goto done;
11248 error = get_gitconfig_path(&gitconfig_path);
11249 if (error)
11250 goto done;
11251 error = got_repo_open(&repo,
11252 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11253 gitconfig_path, pack_fds);
11254 if (error != NULL)
11255 goto done;
11257 if (worktree != NULL && !list_backups && !delete_backups) {
11258 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11259 if (error)
11260 goto done;
11263 error = get_author(&committer, repo, worktree);
11264 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11265 goto done;
11267 error = apply_unveil(got_repo_get_path(repo), 0,
11268 worktree ? got_worktree_get_root_path(worktree) : NULL);
11269 if (error)
11270 goto done;
11272 if (list_backups || delete_backups) {
11273 error = process_backup_refs(
11274 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11275 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11276 goto done; /* nothing else to do */
11279 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11280 worktree);
11281 if (error)
11282 goto done;
11283 if (histedit_in_progress) {
11284 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11285 goto done;
11288 error = got_worktree_merge_in_progress(&merge_in_progress,
11289 worktree, repo);
11290 if (error)
11291 goto done;
11292 if (merge_in_progress) {
11293 error = got_error(GOT_ERR_MERGE_BUSY);
11294 goto done;
11297 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11298 if (error)
11299 goto done;
11301 if (abort_rebase) {
11302 if (!rebase_in_progress) {
11303 error = got_error(GOT_ERR_NOT_REBASING);
11304 goto done;
11306 error = got_worktree_rebase_continue(&resume_commit_id,
11307 &new_base_branch, &tmp_branch, &branch, &fileindex,
11308 worktree, repo);
11309 if (error)
11310 goto done;
11311 printf("Switching work tree to %s\n",
11312 got_ref_get_symref_target(new_base_branch));
11313 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11314 new_base_branch, abort_progress, &upa);
11315 if (error)
11316 goto done;
11317 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11318 print_merge_progress_stats(&upa);
11319 goto done; /* nothing else to do */
11322 if (continue_rebase) {
11323 if (!rebase_in_progress) {
11324 error = got_error(GOT_ERR_NOT_REBASING);
11325 goto done;
11327 error = got_worktree_rebase_continue(&resume_commit_id,
11328 &new_base_branch, &tmp_branch, &branch, &fileindex,
11329 worktree, repo);
11330 if (error)
11331 goto done;
11333 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11334 committer, resume_commit_id, allow_conflict, repo);
11335 if (error)
11336 goto done;
11338 yca_id = got_object_id_dup(resume_commit_id);
11339 if (yca_id == NULL) {
11340 error = got_error_from_errno("got_object_id_dup");
11341 goto done;
11343 } else {
11344 error = got_ref_open(&branch, repo, argv[0], 0);
11345 if (error != NULL)
11346 goto done;
11347 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11348 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11349 "will not rebase a branch which lives outside "
11350 "the \"refs/heads/\" reference namespace");
11351 goto done;
11355 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11356 if (error)
11357 goto done;
11359 if (!continue_rebase) {
11360 struct got_object_id *base_commit_id;
11362 error = got_ref_open(&head_ref, repo,
11363 got_worktree_get_head_ref_name(worktree), 0);
11364 if (error)
11365 goto done;
11366 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11367 if (error)
11368 goto done;
11369 base_commit_id = got_worktree_get_base_commit_id(worktree);
11370 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11371 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11372 goto done;
11375 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11376 base_commit_id, branch_head_commit_id, 1, repo,
11377 check_cancelled, NULL);
11378 if (error) {
11379 if (error->code == GOT_ERR_ANCESTRY) {
11380 error = got_error_msg(GOT_ERR_ANCESTRY,
11381 "specified branch shares no common "
11382 "ancestry with work tree's branch");
11384 goto done;
11387 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11388 struct got_pathlist_head paths;
11389 printf("%s is already based on %s\n",
11390 got_ref_get_name(branch),
11391 got_worktree_get_head_ref_name(worktree));
11392 error = switch_head_ref(branch, branch_head_commit_id,
11393 worktree, repo);
11394 if (error)
11395 goto done;
11396 error = got_worktree_set_base_commit_id(worktree, repo,
11397 branch_head_commit_id);
11398 if (error)
11399 goto done;
11400 TAILQ_INIT(&paths);
11401 error = got_pathlist_append(&paths, "", NULL);
11402 if (error)
11403 goto done;
11404 error = got_worktree_checkout_files(worktree,
11405 &paths, repo, update_progress, &upa,
11406 check_cancelled, NULL);
11407 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11408 if (error)
11409 goto done;
11410 if (upa.did_something) {
11411 char *id_str;
11412 error = got_object_id_str(&id_str,
11413 branch_head_commit_id);
11414 if (error)
11415 goto done;
11416 printf("Updated to %s: %s\n",
11417 got_worktree_get_head_ref_name(worktree),
11418 id_str);
11419 free(id_str);
11420 } else
11421 printf("Already up-to-date\n");
11422 print_update_progress_stats(&upa);
11423 goto done;
11427 commit_id = branch_head_commit_id;
11428 error = got_object_open_as_commit(&commit, repo, commit_id);
11429 if (error)
11430 goto done;
11432 parent_ids = got_object_commit_get_parent_ids(commit);
11433 pid = STAILQ_FIRST(parent_ids);
11434 if (pid) {
11435 error = collect_commits(&commits, commit_id, &pid->id,
11436 yca_id, got_worktree_get_path_prefix(worktree),
11437 GOT_ERR_REBASE_PATH, repo);
11438 if (error)
11439 goto done;
11442 got_object_commit_close(commit);
11443 commit = NULL;
11445 if (!continue_rebase) {
11446 error = got_worktree_rebase_prepare(&new_base_branch,
11447 &tmp_branch, &fileindex, worktree, branch, repo);
11448 if (error)
11449 goto done;
11452 if (STAILQ_EMPTY(&commits)) {
11453 if (continue_rebase) {
11454 error = rebase_complete(worktree, fileindex,
11455 branch, tmp_branch, repo, create_backup);
11456 goto done;
11457 } else {
11458 /* Fast-forward the reference of the branch. */
11459 struct got_object_id *new_head_commit_id;
11460 char *id_str;
11461 error = got_ref_resolve(&new_head_commit_id, repo,
11462 new_base_branch);
11463 if (error)
11464 goto done;
11465 error = got_object_id_str(&id_str, new_head_commit_id);
11466 if (error)
11467 goto done;
11468 printf("Forwarding %s to commit %s\n",
11469 got_ref_get_name(branch), id_str);
11470 free(id_str);
11471 error = got_ref_change_ref(branch,
11472 new_head_commit_id);
11473 if (error)
11474 goto done;
11475 /* No backup needed since objects did not change. */
11476 create_backup = 0;
11480 pid = NULL;
11481 STAILQ_FOREACH(qid, &commits, entry) {
11483 commit_id = &qid->id;
11484 parent_id = pid ? &pid->id : yca_id;
11485 pid = qid;
11487 memset(&upa, 0, sizeof(upa));
11488 error = got_worktree_rebase_merge_files(&merged_paths,
11489 worktree, fileindex, parent_id, commit_id, repo,
11490 update_progress, &upa, check_cancelled, NULL);
11491 if (error)
11492 goto done;
11494 print_merge_progress_stats(&upa);
11495 if (upa.conflicts > 0 || upa.missing > 0 ||
11496 upa.not_deleted > 0 || upa.unversioned > 0) {
11497 if (upa.conflicts > 0) {
11498 error = show_rebase_merge_conflict(&qid->id,
11499 repo);
11500 if (error)
11501 goto done;
11503 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11504 break;
11507 error = rebase_commit(&merged_paths, worktree, fileindex,
11508 tmp_branch, committer, commit_id, 0, repo);
11509 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11510 if (error)
11511 goto done;
11514 if (upa.conflicts > 0 || upa.missing > 0 ||
11515 upa.not_deleted > 0 || upa.unversioned > 0) {
11516 error = got_worktree_rebase_postpone(worktree, fileindex);
11517 if (error)
11518 goto done;
11519 if (upa.conflicts > 0 && upa.missing == 0 &&
11520 upa.not_deleted == 0 && upa.unversioned == 0) {
11521 error = got_error_msg(GOT_ERR_CONFLICTS,
11522 "conflicts must be resolved before rebasing "
11523 "can continue");
11524 } else if (upa.conflicts > 0) {
11525 error = got_error_msg(GOT_ERR_CONFLICTS,
11526 "conflicts must be resolved before rebasing "
11527 "can continue; changes destined for some "
11528 "files were not yet merged and should be "
11529 "merged manually if required before the "
11530 "rebase operation is continued");
11531 } else {
11532 error = got_error_msg(GOT_ERR_CONFLICTS,
11533 "changes destined for some files were not "
11534 "yet merged and should be merged manually "
11535 "if required before the rebase operation "
11536 "is continued");
11538 } else
11539 error = rebase_complete(worktree, fileindex, branch,
11540 tmp_branch, repo, create_backup);
11541 done:
11542 free(cwd);
11543 free(committer);
11544 free(gitconfig_path);
11545 got_object_id_queue_free(&commits);
11546 free(branch_head_commit_id);
11547 free(resume_commit_id);
11548 free(head_commit_id);
11549 free(yca_id);
11550 if (commit)
11551 got_object_commit_close(commit);
11552 if (branch)
11553 got_ref_close(branch);
11554 if (new_base_branch)
11555 got_ref_close(new_base_branch);
11556 if (tmp_branch)
11557 got_ref_close(tmp_branch);
11558 if (head_ref)
11559 got_ref_close(head_ref);
11560 if (worktree)
11561 got_worktree_close(worktree);
11562 if (repo) {
11563 const struct got_error *close_err = got_repo_close(repo);
11564 if (error == NULL)
11565 error = close_err;
11567 if (pack_fds) {
11568 const struct got_error *pack_err =
11569 got_repo_pack_fds_close(pack_fds);
11570 if (error == NULL)
11571 error = pack_err;
11573 return error;
11576 __dead static void
11577 usage_histedit(void)
11579 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11580 "[branch]\n", getprogname());
11581 exit(1);
11584 #define GOT_HISTEDIT_PICK 'p'
11585 #define GOT_HISTEDIT_EDIT 'e'
11586 #define GOT_HISTEDIT_FOLD 'f'
11587 #define GOT_HISTEDIT_DROP 'd'
11588 #define GOT_HISTEDIT_MESG 'm'
11590 static const struct got_histedit_cmd {
11591 unsigned char code;
11592 const char *name;
11593 const char *desc;
11594 } got_histedit_cmds[] = {
11595 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11596 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11597 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11598 "be used" },
11599 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11600 { GOT_HISTEDIT_MESG, "mesg",
11601 "single-line log message for commit above (open editor if empty)" },
11604 struct got_histedit_list_entry {
11605 TAILQ_ENTRY(got_histedit_list_entry) entry;
11606 struct got_object_id *commit_id;
11607 const struct got_histedit_cmd *cmd;
11608 char *logmsg;
11610 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11612 static const struct got_error *
11613 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11614 FILE *f, struct got_repository *repo)
11616 const struct got_error *err = NULL;
11617 char *logmsg = NULL, *id_str = NULL;
11618 struct got_commit_object *commit = NULL;
11619 int n;
11621 err = got_object_open_as_commit(&commit, repo, commit_id);
11622 if (err)
11623 goto done;
11625 err = get_short_logmsg(&logmsg, 34, commit);
11626 if (err)
11627 goto done;
11629 err = got_object_id_str(&id_str, commit_id);
11630 if (err)
11631 goto done;
11633 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11634 if (n < 0)
11635 err = got_ferror(f, GOT_ERR_IO);
11636 done:
11637 if (commit)
11638 got_object_commit_close(commit);
11639 free(id_str);
11640 free(logmsg);
11641 return err;
11644 static const struct got_error *
11645 histedit_write_commit_list(struct got_object_id_queue *commits,
11646 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11647 int edit_only, struct got_repository *repo)
11649 const struct got_error *err = NULL;
11650 struct got_object_qid *qid;
11651 const char *histedit_cmd = NULL;
11653 if (STAILQ_EMPTY(commits))
11654 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11656 STAILQ_FOREACH(qid, commits, entry) {
11657 histedit_cmd = got_histedit_cmds[0].name;
11658 if (drop_only)
11659 histedit_cmd = "drop";
11660 else if (edit_only)
11661 histedit_cmd = "edit";
11662 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11663 histedit_cmd = "fold";
11664 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11665 if (err)
11666 break;
11667 if (edit_logmsg_only) {
11668 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11669 if (n < 0) {
11670 err = got_ferror(f, GOT_ERR_IO);
11671 break;
11676 return err;
11679 static const struct got_error *
11680 write_cmd_list(FILE *f, const char *branch_name,
11681 struct got_object_id_queue *commits)
11683 const struct got_error *err = NULL;
11684 size_t i;
11685 int n;
11686 char *id_str;
11687 struct got_object_qid *qid;
11689 qid = STAILQ_FIRST(commits);
11690 err = got_object_id_str(&id_str, &qid->id);
11691 if (err)
11692 return err;
11694 n = fprintf(f,
11695 "# Editing the history of branch '%s' starting at\n"
11696 "# commit %s\n"
11697 "# Commits will be processed in order from top to "
11698 "bottom of this file.\n", branch_name, id_str);
11699 if (n < 0) {
11700 err = got_ferror(f, GOT_ERR_IO);
11701 goto done;
11704 n = fprintf(f, "# Available histedit commands:\n");
11705 if (n < 0) {
11706 err = got_ferror(f, GOT_ERR_IO);
11707 goto done;
11710 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11711 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11712 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11713 cmd->desc);
11714 if (n < 0) {
11715 err = got_ferror(f, GOT_ERR_IO);
11716 break;
11719 done:
11720 free(id_str);
11721 return err;
11724 static const struct got_error *
11725 histedit_syntax_error(int lineno)
11727 static char msg[42];
11728 int ret;
11730 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11731 lineno);
11732 if (ret < 0 || (size_t)ret >= sizeof(msg))
11733 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11735 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11738 static const struct got_error *
11739 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11740 char *logmsg, struct got_repository *repo)
11742 const struct got_error *err;
11743 struct got_commit_object *folded_commit = NULL;
11744 char *id_str, *folded_logmsg = NULL;
11746 err = got_object_id_str(&id_str, hle->commit_id);
11747 if (err)
11748 return err;
11750 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11751 if (err)
11752 goto done;
11754 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11755 if (err)
11756 goto done;
11757 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11758 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11759 folded_logmsg) == -1) {
11760 err = got_error_from_errno("asprintf");
11762 done:
11763 if (folded_commit)
11764 got_object_commit_close(folded_commit);
11765 free(id_str);
11766 free(folded_logmsg);
11767 return err;
11770 static struct got_histedit_list_entry *
11771 get_folded_commits(struct got_histedit_list_entry *hle)
11773 struct got_histedit_list_entry *prev, *folded = NULL;
11775 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11776 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11777 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11778 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11779 folded = prev;
11780 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11783 return folded;
11786 static const struct got_error *
11787 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11788 struct got_repository *repo)
11790 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11791 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11792 const struct got_error *err = NULL;
11793 struct got_commit_object *commit = NULL;
11794 int logmsg_len;
11795 int fd = -1;
11796 struct got_histedit_list_entry *folded = NULL;
11798 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11799 if (err)
11800 return err;
11802 folded = get_folded_commits(hle);
11803 if (folded) {
11804 while (folded != hle) {
11805 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11806 folded = TAILQ_NEXT(folded, entry);
11807 continue;
11809 err = append_folded_commit_msg(&new_msg, folded,
11810 logmsg, repo);
11811 if (err)
11812 goto done;
11813 free(logmsg);
11814 logmsg = new_msg;
11815 folded = TAILQ_NEXT(folded, entry);
11819 err = got_object_id_str(&id_str, hle->commit_id);
11820 if (err)
11821 goto done;
11822 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11823 if (err)
11824 goto done;
11825 logmsg_len = asprintf(&new_msg,
11826 "%s\n# original log message of commit %s: %s",
11827 logmsg ? logmsg : "", id_str, orig_logmsg);
11828 if (logmsg_len == -1) {
11829 err = got_error_from_errno("asprintf");
11830 goto done;
11832 free(logmsg);
11833 logmsg = new_msg;
11835 err = got_object_id_str(&id_str, hle->commit_id);
11836 if (err)
11837 goto done;
11839 err = got_opentemp_named_fd(&logmsg_path, &fd,
11840 GOT_TMPDIR_STR "/got-logmsg", "");
11841 if (err)
11842 goto done;
11844 if (write(fd, logmsg, logmsg_len) == -1) {
11845 err = got_error_from_errno2("write", logmsg_path);
11846 goto done;
11848 if (close(fd) == -1) {
11849 err = got_error_from_errno2("close", logmsg_path);
11850 goto done;
11852 fd = -1;
11854 err = get_editor(&editor);
11855 if (err)
11856 goto done;
11858 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11859 logmsg_len, 0);
11860 if (err) {
11861 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11862 goto done;
11863 err = NULL;
11864 hle->logmsg = strdup(new_msg);
11865 if (hle->logmsg == NULL)
11866 err = got_error_from_errno("strdup");
11868 done:
11869 if (fd != -1 && close(fd) == -1 && err == NULL)
11870 err = got_error_from_errno2("close", logmsg_path);
11871 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11872 err = got_error_from_errno2("unlink", logmsg_path);
11873 free(logmsg_path);
11874 free(logmsg);
11875 free(orig_logmsg);
11876 free(editor);
11877 if (commit)
11878 got_object_commit_close(commit);
11879 return err;
11882 static const struct got_error *
11883 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11884 FILE *f, struct got_repository *repo)
11886 const struct got_error *err = NULL;
11887 char *line = NULL, *p, *end;
11888 size_t i, linesize = 0;
11889 ssize_t linelen;
11890 int lineno = 0, lastcmd = -1;
11891 const struct got_histedit_cmd *cmd;
11892 struct got_object_id *commit_id = NULL;
11893 struct got_histedit_list_entry *hle = NULL;
11895 for (;;) {
11896 linelen = getline(&line, &linesize, f);
11897 if (linelen == -1) {
11898 const struct got_error *getline_err;
11899 if (feof(f))
11900 break;
11901 getline_err = got_error_from_errno("getline");
11902 err = got_ferror(f, getline_err->code);
11903 break;
11905 lineno++;
11906 p = line;
11907 while (isspace((unsigned char)p[0]))
11908 p++;
11909 if (p[0] == '#' || p[0] == '\0')
11910 continue;
11911 cmd = NULL;
11912 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11913 cmd = &got_histedit_cmds[i];
11914 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11915 isspace((unsigned char)p[strlen(cmd->name)])) {
11916 p += strlen(cmd->name);
11917 break;
11919 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11920 p++;
11921 break;
11924 if (i == nitems(got_histedit_cmds)) {
11925 err = histedit_syntax_error(lineno);
11926 break;
11928 while (isspace((unsigned char)p[0]))
11929 p++;
11930 if (cmd->code == GOT_HISTEDIT_MESG) {
11931 if (lastcmd != GOT_HISTEDIT_PICK &&
11932 lastcmd != GOT_HISTEDIT_EDIT) {
11933 err = got_error(GOT_ERR_HISTEDIT_CMD);
11934 break;
11936 if (p[0] == '\0') {
11937 err = histedit_edit_logmsg(hle, repo);
11938 if (err)
11939 break;
11940 } else {
11941 hle->logmsg = strdup(p);
11942 if (hle->logmsg == NULL) {
11943 err = got_error_from_errno("strdup");
11944 break;
11947 lastcmd = cmd->code;
11948 continue;
11949 } else {
11950 end = p;
11951 while (end[0] && !isspace((unsigned char)end[0]))
11952 end++;
11953 *end = '\0';
11955 err = got_object_resolve_id_str(&commit_id, repo, p);
11956 if (err) {
11957 /* override error code */
11958 err = histedit_syntax_error(lineno);
11959 break;
11962 hle = malloc(sizeof(*hle));
11963 if (hle == NULL) {
11964 err = got_error_from_errno("malloc");
11965 break;
11967 hle->cmd = cmd;
11968 hle->commit_id = commit_id;
11969 hle->logmsg = NULL;
11970 commit_id = NULL;
11971 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11972 lastcmd = cmd->code;
11975 free(line);
11976 free(commit_id);
11977 return err;
11980 static const struct got_error *
11981 histedit_check_script(struct got_histedit_list *histedit_cmds,
11982 struct got_object_id_queue *commits, struct got_repository *repo)
11984 const struct got_error *err = NULL;
11985 struct got_object_qid *qid;
11986 struct got_histedit_list_entry *hle;
11987 static char msg[92];
11988 char *id_str;
11990 if (TAILQ_EMPTY(histedit_cmds))
11991 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11992 "histedit script contains no commands");
11993 if (STAILQ_EMPTY(commits))
11994 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11996 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11997 struct got_histedit_list_entry *hle2;
11998 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11999 if (hle == hle2)
12000 continue;
12001 if (got_object_id_cmp(hle->commit_id,
12002 hle2->commit_id) != 0)
12003 continue;
12004 err = got_object_id_str(&id_str, hle->commit_id);
12005 if (err)
12006 return err;
12007 snprintf(msg, sizeof(msg), "commit %s is listed "
12008 "more than once in histedit script", id_str);
12009 free(id_str);
12010 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12014 STAILQ_FOREACH(qid, commits, entry) {
12015 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12016 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12017 break;
12019 if (hle == NULL) {
12020 err = got_object_id_str(&id_str, &qid->id);
12021 if (err)
12022 return err;
12023 snprintf(msg, sizeof(msg),
12024 "commit %s missing from histedit script", id_str);
12025 free(id_str);
12026 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12030 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12031 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12032 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12033 "last commit in histedit script cannot be folded");
12035 return NULL;
12038 static const struct got_error *
12039 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12040 const char *path, struct got_object_id_queue *commits,
12041 struct got_repository *repo)
12043 const struct got_error *err = NULL;
12044 struct stat st, st2;
12045 struct timespec timeout;
12046 char *editor;
12047 FILE *f = NULL;
12049 err = get_editor(&editor);
12050 if (err)
12051 return err;
12053 if (stat(path, &st) == -1) {
12054 err = got_error_from_errno2("stat", path);
12055 goto done;
12058 if (spawn_editor(editor, path) == -1) {
12059 err = got_error_from_errno("failed spawning editor");
12060 goto done;
12063 timeout.tv_sec = 0;
12064 timeout.tv_nsec = 1;
12065 nanosleep(&timeout, NULL);
12067 if (stat(path, &st2) == -1) {
12068 err = got_error_from_errno2("stat", path);
12069 goto done;
12072 if (st.st_size == st2.st_size &&
12073 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12074 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12075 "no changes made to histedit script, aborting");
12076 goto done;
12079 f = fopen(path, "re");
12080 if (f == NULL) {
12081 err = got_error_from_errno("fopen");
12082 goto done;
12084 err = histedit_parse_list(histedit_cmds, f, repo);
12085 if (err)
12086 goto done;
12088 err = histedit_check_script(histedit_cmds, commits, repo);
12089 done:
12090 if (f && fclose(f) == EOF && err == NULL)
12091 err = got_error_from_errno("fclose");
12092 free(editor);
12093 return err;
12096 static const struct got_error *
12097 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12098 struct got_object_id_queue *, const char *, const char *,
12099 struct got_repository *);
12101 static const struct got_error *
12102 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12103 struct got_object_id_queue *commits, const char *branch_name,
12104 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12105 struct got_repository *repo)
12107 const struct got_error *err;
12108 FILE *f = NULL;
12109 char *path = NULL;
12111 err = got_opentemp_named(&path, &f, "got-histedit", "");
12112 if (err)
12113 return err;
12115 err = write_cmd_list(f, branch_name, commits);
12116 if (err)
12117 goto done;
12119 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12120 fold_only, drop_only, edit_only, repo);
12121 if (err)
12122 goto done;
12124 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12125 rewind(f);
12126 err = histedit_parse_list(histedit_cmds, f, repo);
12127 } else {
12128 if (fclose(f) == EOF) {
12129 err = got_error_from_errno("fclose");
12130 goto done;
12132 f = NULL;
12133 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12134 if (err) {
12135 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12136 err->code != GOT_ERR_HISTEDIT_CMD)
12137 goto done;
12138 err = histedit_edit_list_retry(histedit_cmds, err,
12139 commits, path, branch_name, repo);
12142 done:
12143 if (f && fclose(f) == EOF && err == NULL)
12144 err = got_error_from_errno("fclose");
12145 if (path && unlink(path) != 0 && err == NULL)
12146 err = got_error_from_errno2("unlink", path);
12147 free(path);
12148 return err;
12151 static const struct got_error *
12152 histedit_save_list(struct got_histedit_list *histedit_cmds,
12153 struct got_worktree *worktree, struct got_repository *repo)
12155 const struct got_error *err = NULL;
12156 char *path = NULL;
12157 FILE *f = NULL;
12158 struct got_histedit_list_entry *hle;
12159 struct got_commit_object *commit = NULL;
12161 err = got_worktree_get_histedit_script_path(&path, worktree);
12162 if (err)
12163 return err;
12165 f = fopen(path, "we");
12166 if (f == NULL) {
12167 err = got_error_from_errno2("fopen", path);
12168 goto done;
12170 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12171 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12172 repo);
12173 if (err)
12174 break;
12176 if (hle->logmsg) {
12177 int n = fprintf(f, "%c %s\n",
12178 GOT_HISTEDIT_MESG, hle->logmsg);
12179 if (n < 0) {
12180 err = got_ferror(f, GOT_ERR_IO);
12181 break;
12185 done:
12186 if (f && fclose(f) == EOF && err == NULL)
12187 err = got_error_from_errno("fclose");
12188 free(path);
12189 if (commit)
12190 got_object_commit_close(commit);
12191 return err;
12194 static void
12195 histedit_free_list(struct got_histedit_list *histedit_cmds)
12197 struct got_histedit_list_entry *hle;
12199 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12200 TAILQ_REMOVE(histedit_cmds, hle, entry);
12201 free(hle);
12205 static const struct got_error *
12206 histedit_load_list(struct got_histedit_list *histedit_cmds,
12207 const char *path, struct got_repository *repo)
12209 const struct got_error *err = NULL;
12210 FILE *f = NULL;
12212 f = fopen(path, "re");
12213 if (f == NULL) {
12214 err = got_error_from_errno2("fopen", path);
12215 goto done;
12218 err = histedit_parse_list(histedit_cmds, f, repo);
12219 done:
12220 if (f && fclose(f) == EOF && err == NULL)
12221 err = got_error_from_errno("fclose");
12222 return err;
12225 static const struct got_error *
12226 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12227 const struct got_error *edit_err, struct got_object_id_queue *commits,
12228 const char *path, const char *branch_name, struct got_repository *repo)
12230 const struct got_error *err = NULL, *prev_err = edit_err;
12231 int resp = ' ';
12233 while (resp != 'c' && resp != 'r' && resp != 'a') {
12234 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12235 "or (a)bort: ", getprogname(), prev_err->msg);
12236 resp = getchar();
12237 if (resp == '\n')
12238 resp = getchar();
12239 if (resp == 'c') {
12240 histedit_free_list(histedit_cmds);
12241 err = histedit_run_editor(histedit_cmds, path, commits,
12242 repo);
12243 if (err) {
12244 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12245 err->code != GOT_ERR_HISTEDIT_CMD)
12246 break;
12247 prev_err = err;
12248 resp = ' ';
12249 continue;
12251 break;
12252 } else if (resp == 'r') {
12253 histedit_free_list(histedit_cmds);
12254 err = histedit_edit_script(histedit_cmds,
12255 commits, branch_name, 0, 0, 0, 0, repo);
12256 if (err) {
12257 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12258 err->code != GOT_ERR_HISTEDIT_CMD)
12259 break;
12260 prev_err = err;
12261 resp = ' ';
12262 continue;
12264 break;
12265 } else if (resp == 'a') {
12266 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12267 break;
12268 } else
12269 printf("invalid response '%c'\n", resp);
12272 return err;
12275 static const struct got_error *
12276 histedit_complete(struct got_worktree *worktree,
12277 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12278 struct got_reference *branch, struct got_repository *repo)
12280 printf("Switching work tree to %s\n",
12281 got_ref_get_symref_target(branch));
12282 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12283 branch, repo);
12286 static const struct got_error *
12287 show_histedit_progress(struct got_commit_object *commit,
12288 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12290 const struct got_error *err;
12291 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12293 err = got_object_id_str(&old_id_str, hle->commit_id);
12294 if (err)
12295 goto done;
12297 if (new_id) {
12298 err = got_object_id_str(&new_id_str, new_id);
12299 if (err)
12300 goto done;
12303 old_id_str[12] = '\0';
12304 if (new_id_str)
12305 new_id_str[12] = '\0';
12307 if (hle->logmsg) {
12308 logmsg = strdup(hle->logmsg);
12309 if (logmsg == NULL) {
12310 err = got_error_from_errno("strdup");
12311 goto done;
12313 trim_logmsg(logmsg, 42);
12314 } else {
12315 err = get_short_logmsg(&logmsg, 42, commit);
12316 if (err)
12317 goto done;
12320 switch (hle->cmd->code) {
12321 case GOT_HISTEDIT_PICK:
12322 case GOT_HISTEDIT_EDIT:
12323 printf("%s -> %s: %s\n", old_id_str,
12324 new_id_str ? new_id_str : "no-op change", logmsg);
12325 break;
12326 case GOT_HISTEDIT_DROP:
12327 case GOT_HISTEDIT_FOLD:
12328 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12329 logmsg);
12330 break;
12331 default:
12332 break;
12334 done:
12335 free(old_id_str);
12336 free(new_id_str);
12337 return err;
12340 static const struct got_error *
12341 histedit_commit(struct got_pathlist_head *merged_paths,
12342 struct got_worktree *worktree, struct got_fileindex *fileindex,
12343 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12344 const char *committer, int allow_conflict, struct got_repository *repo)
12346 const struct got_error *err;
12347 struct got_commit_object *commit;
12348 struct got_object_id *new_commit_id;
12350 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12351 && hle->logmsg == NULL) {
12352 err = histedit_edit_logmsg(hle, repo);
12353 if (err)
12354 return err;
12357 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12358 if (err)
12359 return err;
12361 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12362 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12363 hle->logmsg, allow_conflict, repo);
12364 if (err) {
12365 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12366 goto done;
12367 err = show_histedit_progress(commit, hle, NULL);
12368 } else {
12369 err = show_histedit_progress(commit, hle, new_commit_id);
12370 free(new_commit_id);
12372 done:
12373 got_object_commit_close(commit);
12374 return err;
12377 static const struct got_error *
12378 histedit_skip_commit(struct got_histedit_list_entry *hle,
12379 struct got_worktree *worktree, struct got_repository *repo)
12381 const struct got_error *error;
12382 struct got_commit_object *commit;
12384 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12385 repo);
12386 if (error)
12387 return error;
12389 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12390 if (error)
12391 return error;
12393 error = show_histedit_progress(commit, hle, NULL);
12394 got_object_commit_close(commit);
12395 return error;
12398 static const struct got_error *
12399 check_local_changes(void *arg, unsigned char status,
12400 unsigned char staged_status, const char *path,
12401 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12402 struct got_object_id *commit_id, int dirfd, const char *de_name)
12404 int *have_local_changes = arg;
12406 switch (status) {
12407 case GOT_STATUS_ADD:
12408 case GOT_STATUS_DELETE:
12409 case GOT_STATUS_MODIFY:
12410 case GOT_STATUS_CONFLICT:
12411 *have_local_changes = 1;
12412 return got_error(GOT_ERR_CANCELLED);
12413 default:
12414 break;
12417 switch (staged_status) {
12418 case GOT_STATUS_ADD:
12419 case GOT_STATUS_DELETE:
12420 case GOT_STATUS_MODIFY:
12421 *have_local_changes = 1;
12422 return got_error(GOT_ERR_CANCELLED);
12423 default:
12424 break;
12427 return NULL;
12430 static const struct got_error *
12431 cmd_histedit(int argc, char *argv[])
12433 const struct got_error *error = NULL;
12434 struct got_worktree *worktree = NULL;
12435 struct got_fileindex *fileindex = NULL;
12436 struct got_repository *repo = NULL;
12437 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12438 struct got_reference *branch = NULL;
12439 struct got_reference *tmp_branch = NULL;
12440 struct got_object_id *resume_commit_id = NULL;
12441 struct got_object_id *base_commit_id = NULL;
12442 struct got_object_id *head_commit_id = NULL;
12443 struct got_commit_object *commit = NULL;
12444 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12445 struct got_update_progress_arg upa;
12446 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12447 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12448 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12449 const char *edit_script_path = NULL;
12450 struct got_object_id_queue commits;
12451 struct got_pathlist_head merged_paths;
12452 const struct got_object_id_queue *parent_ids;
12453 struct got_object_qid *pid;
12454 struct got_histedit_list histedit_cmds;
12455 struct got_histedit_list_entry *hle;
12456 int *pack_fds = NULL;
12458 STAILQ_INIT(&commits);
12459 TAILQ_INIT(&histedit_cmds);
12460 TAILQ_INIT(&merged_paths);
12461 memset(&upa, 0, sizeof(upa));
12463 #ifndef PROFILE
12464 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12465 "unveil", NULL) == -1)
12466 err(1, "pledge");
12467 #endif
12469 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12470 switch (ch) {
12471 case 'a':
12472 abort_edit = 1;
12473 break;
12474 case 'C':
12475 allow_conflict = 1;
12476 break;
12477 case 'c':
12478 continue_edit = 1;
12479 break;
12480 case 'd':
12481 drop_only = 1;
12482 break;
12483 case 'e':
12484 edit_only = 1;
12485 break;
12486 case 'F':
12487 edit_script_path = optarg;
12488 break;
12489 case 'f':
12490 fold_only = 1;
12491 break;
12492 case 'l':
12493 list_backups = 1;
12494 break;
12495 case 'm':
12496 edit_logmsg_only = 1;
12497 break;
12498 case 'X':
12499 delete_backups = 1;
12500 break;
12501 default:
12502 usage_histedit();
12503 /* NOTREACHED */
12507 argc -= optind;
12508 argv += optind;
12510 if (abort_edit && allow_conflict)
12511 option_conflict('a', 'C');
12512 if (abort_edit && continue_edit)
12513 option_conflict('a', 'c');
12514 if (edit_script_path && allow_conflict)
12515 option_conflict('F', 'C');
12516 if (edit_script_path && edit_logmsg_only)
12517 option_conflict('F', 'm');
12518 if (abort_edit && edit_logmsg_only)
12519 option_conflict('a', 'm');
12520 if (edit_logmsg_only && allow_conflict)
12521 option_conflict('m', 'C');
12522 if (continue_edit && edit_logmsg_only)
12523 option_conflict('c', 'm');
12524 if (abort_edit && fold_only)
12525 option_conflict('a', 'f');
12526 if (fold_only && allow_conflict)
12527 option_conflict('f', 'C');
12528 if (continue_edit && fold_only)
12529 option_conflict('c', 'f');
12530 if (fold_only && edit_logmsg_only)
12531 option_conflict('f', 'm');
12532 if (edit_script_path && fold_only)
12533 option_conflict('F', 'f');
12534 if (abort_edit && edit_only)
12535 option_conflict('a', 'e');
12536 if (continue_edit && edit_only)
12537 option_conflict('c', 'e');
12538 if (edit_only && edit_logmsg_only)
12539 option_conflict('e', 'm');
12540 if (edit_script_path && edit_only)
12541 option_conflict('F', 'e');
12542 if (fold_only && edit_only)
12543 option_conflict('f', 'e');
12544 if (drop_only && abort_edit)
12545 option_conflict('d', 'a');
12546 if (drop_only && allow_conflict)
12547 option_conflict('d', 'C');
12548 if (drop_only && continue_edit)
12549 option_conflict('d', 'c');
12550 if (drop_only && edit_logmsg_only)
12551 option_conflict('d', 'm');
12552 if (drop_only && edit_only)
12553 option_conflict('d', 'e');
12554 if (drop_only && edit_script_path)
12555 option_conflict('d', 'F');
12556 if (drop_only && fold_only)
12557 option_conflict('d', 'f');
12558 if (list_backups) {
12559 if (abort_edit)
12560 option_conflict('l', 'a');
12561 if (allow_conflict)
12562 option_conflict('l', 'C');
12563 if (continue_edit)
12564 option_conflict('l', 'c');
12565 if (edit_script_path)
12566 option_conflict('l', 'F');
12567 if (edit_logmsg_only)
12568 option_conflict('l', 'm');
12569 if (drop_only)
12570 option_conflict('l', 'd');
12571 if (fold_only)
12572 option_conflict('l', 'f');
12573 if (edit_only)
12574 option_conflict('l', 'e');
12575 if (delete_backups)
12576 option_conflict('l', 'X');
12577 if (argc != 0 && argc != 1)
12578 usage_histedit();
12579 } else if (delete_backups) {
12580 if (abort_edit)
12581 option_conflict('X', 'a');
12582 if (allow_conflict)
12583 option_conflict('X', 'C');
12584 if (continue_edit)
12585 option_conflict('X', 'c');
12586 if (drop_only)
12587 option_conflict('X', 'd');
12588 if (edit_script_path)
12589 option_conflict('X', 'F');
12590 if (edit_logmsg_only)
12591 option_conflict('X', 'm');
12592 if (fold_only)
12593 option_conflict('X', 'f');
12594 if (edit_only)
12595 option_conflict('X', 'e');
12596 if (list_backups)
12597 option_conflict('X', 'l');
12598 if (argc != 0 && argc != 1)
12599 usage_histedit();
12600 } else if (allow_conflict && !continue_edit)
12601 errx(1, "-C option requires -c");
12602 else if (argc != 0)
12603 usage_histedit();
12606 * This command cannot apply unveil(2) in all cases because the
12607 * user may choose to run an editor to edit the histedit script
12608 * and to edit individual commit log messages.
12609 * unveil(2) traverses exec(2); if an editor is used we have to
12610 * apply unveil after edit script and log messages have been written.
12611 * XXX TODO: Make use of unveil(2) where possible.
12614 cwd = getcwd(NULL, 0);
12615 if (cwd == NULL) {
12616 error = got_error_from_errno("getcwd");
12617 goto done;
12620 error = got_repo_pack_fds_open(&pack_fds);
12621 if (error != NULL)
12622 goto done;
12624 error = got_worktree_open(&worktree, cwd);
12625 if (error) {
12626 if (list_backups || delete_backups) {
12627 if (error->code != GOT_ERR_NOT_WORKTREE)
12628 goto done;
12629 } else {
12630 if (error->code == GOT_ERR_NOT_WORKTREE)
12631 error = wrap_not_worktree_error(error,
12632 "histedit", cwd);
12633 goto done;
12637 if (list_backups || delete_backups) {
12638 error = got_repo_open(&repo,
12639 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12640 NULL, pack_fds);
12641 if (error != NULL)
12642 goto done;
12643 error = apply_unveil(got_repo_get_path(repo), 0,
12644 worktree ? got_worktree_get_root_path(worktree) : NULL);
12645 if (error)
12646 goto done;
12647 error = process_backup_refs(
12648 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12649 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12650 goto done; /* nothing else to do */
12653 error = get_gitconfig_path(&gitconfig_path);
12654 if (error)
12655 goto done;
12656 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12657 gitconfig_path, pack_fds);
12658 if (error != NULL)
12659 goto done;
12661 if (worktree != NULL && !list_backups && !delete_backups) {
12662 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12663 if (error)
12664 goto done;
12667 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12668 if (error)
12669 goto done;
12670 if (rebase_in_progress) {
12671 error = got_error(GOT_ERR_REBASING);
12672 goto done;
12675 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12676 repo);
12677 if (error)
12678 goto done;
12679 if (merge_in_progress) {
12680 error = got_error(GOT_ERR_MERGE_BUSY);
12681 goto done;
12684 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12685 if (error)
12686 goto done;
12688 if (edit_in_progress && edit_logmsg_only) {
12689 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12690 "histedit operation is in progress in this "
12691 "work tree and must be continued or aborted "
12692 "before the -m option can be used");
12693 goto done;
12695 if (edit_in_progress && drop_only) {
12696 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12697 "histedit operation is in progress in this "
12698 "work tree and must be continued or aborted "
12699 "before the -d option can be used");
12700 goto done;
12702 if (edit_in_progress && fold_only) {
12703 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12704 "histedit operation is in progress in this "
12705 "work tree and must be continued or aborted "
12706 "before the -f option can be used");
12707 goto done;
12709 if (edit_in_progress && edit_only) {
12710 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12711 "histedit operation is in progress in this "
12712 "work tree and must be continued or aborted "
12713 "before the -e option can be used");
12714 goto done;
12717 if (edit_in_progress && abort_edit) {
12718 error = got_worktree_histedit_continue(&resume_commit_id,
12719 &tmp_branch, &branch, &base_commit_id, &fileindex,
12720 worktree, repo);
12721 if (error)
12722 goto done;
12723 printf("Switching work tree to %s\n",
12724 got_ref_get_symref_target(branch));
12725 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12726 branch, base_commit_id, abort_progress, &upa);
12727 if (error)
12728 goto done;
12729 printf("Histedit of %s aborted\n",
12730 got_ref_get_symref_target(branch));
12731 print_merge_progress_stats(&upa);
12732 goto done; /* nothing else to do */
12733 } else if (abort_edit) {
12734 error = got_error(GOT_ERR_NOT_HISTEDIT);
12735 goto done;
12738 error = get_author(&committer, repo, worktree);
12739 if (error)
12740 goto done;
12742 if (continue_edit) {
12743 char *path;
12745 if (!edit_in_progress) {
12746 error = got_error(GOT_ERR_NOT_HISTEDIT);
12747 goto done;
12750 error = got_worktree_get_histedit_script_path(&path, worktree);
12751 if (error)
12752 goto done;
12754 error = histedit_load_list(&histedit_cmds, path, repo);
12755 free(path);
12756 if (error)
12757 goto done;
12759 error = got_worktree_histedit_continue(&resume_commit_id,
12760 &tmp_branch, &branch, &base_commit_id, &fileindex,
12761 worktree, repo);
12762 if (error)
12763 goto done;
12765 error = got_ref_resolve(&head_commit_id, repo, branch);
12766 if (error)
12767 goto done;
12769 error = got_object_open_as_commit(&commit, repo,
12770 head_commit_id);
12771 if (error)
12772 goto done;
12773 parent_ids = got_object_commit_get_parent_ids(commit);
12774 pid = STAILQ_FIRST(parent_ids);
12775 if (pid == NULL) {
12776 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12777 goto done;
12779 error = collect_commits(&commits, head_commit_id, &pid->id,
12780 base_commit_id, got_worktree_get_path_prefix(worktree),
12781 GOT_ERR_HISTEDIT_PATH, repo);
12782 got_object_commit_close(commit);
12783 commit = NULL;
12784 if (error)
12785 goto done;
12786 } else {
12787 if (edit_in_progress) {
12788 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12789 goto done;
12792 error = got_ref_open(&branch, repo,
12793 got_worktree_get_head_ref_name(worktree), 0);
12794 if (error != NULL)
12795 goto done;
12797 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12798 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12799 "will not edit commit history of a branch outside "
12800 "the \"refs/heads/\" reference namespace");
12801 goto done;
12804 error = got_ref_resolve(&head_commit_id, repo, branch);
12805 got_ref_close(branch);
12806 branch = NULL;
12807 if (error)
12808 goto done;
12810 error = got_object_open_as_commit(&commit, repo,
12811 head_commit_id);
12812 if (error)
12813 goto done;
12814 parent_ids = got_object_commit_get_parent_ids(commit);
12815 pid = STAILQ_FIRST(parent_ids);
12816 if (pid == NULL) {
12817 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12818 goto done;
12820 error = collect_commits(&commits, head_commit_id, &pid->id,
12821 got_worktree_get_base_commit_id(worktree),
12822 got_worktree_get_path_prefix(worktree),
12823 GOT_ERR_HISTEDIT_PATH, repo);
12824 got_object_commit_close(commit);
12825 commit = NULL;
12826 if (error)
12827 goto done;
12829 if (STAILQ_EMPTY(&commits)) {
12830 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12831 goto done;
12834 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12835 &base_commit_id, &fileindex, worktree, repo);
12836 if (error)
12837 goto done;
12839 if (edit_script_path) {
12840 error = histedit_load_list(&histedit_cmds,
12841 edit_script_path, repo);
12842 if (error) {
12843 got_worktree_histedit_abort(worktree, fileindex,
12844 repo, branch, base_commit_id,
12845 abort_progress, &upa);
12846 print_merge_progress_stats(&upa);
12847 goto done;
12849 } else {
12850 const char *branch_name;
12851 branch_name = got_ref_get_symref_target(branch);
12852 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12853 branch_name += 11;
12854 error = histedit_edit_script(&histedit_cmds, &commits,
12855 branch_name, edit_logmsg_only, fold_only,
12856 drop_only, edit_only, repo);
12857 if (error) {
12858 got_worktree_histedit_abort(worktree, fileindex,
12859 repo, branch, base_commit_id,
12860 abort_progress, &upa);
12861 print_merge_progress_stats(&upa);
12862 goto done;
12867 error = histedit_save_list(&histedit_cmds, worktree,
12868 repo);
12869 if (error) {
12870 got_worktree_histedit_abort(worktree, fileindex,
12871 repo, branch, base_commit_id,
12872 abort_progress, &upa);
12873 print_merge_progress_stats(&upa);
12874 goto done;
12879 error = histedit_check_script(&histedit_cmds, &commits, repo);
12880 if (error)
12881 goto done;
12883 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12884 if (resume_commit_id) {
12885 if (got_object_id_cmp(hle->commit_id,
12886 resume_commit_id) != 0)
12887 continue;
12889 resume_commit_id = NULL;
12890 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12891 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12892 error = histedit_skip_commit(hle, worktree,
12893 repo);
12894 if (error)
12895 goto done;
12896 } else {
12897 struct got_pathlist_head paths;
12898 int have_changes = 0;
12900 TAILQ_INIT(&paths);
12901 error = got_pathlist_append(&paths, "", NULL);
12902 if (error)
12903 goto done;
12904 error = got_worktree_status(worktree, &paths,
12905 repo, 0, check_local_changes, &have_changes,
12906 check_cancelled, NULL);
12907 got_pathlist_free(&paths,
12908 GOT_PATHLIST_FREE_NONE);
12909 if (error) {
12910 if (error->code != GOT_ERR_CANCELLED)
12911 goto done;
12912 if (sigint_received || sigpipe_received)
12913 goto done;
12915 if (have_changes) {
12916 error = histedit_commit(NULL, worktree,
12917 fileindex, tmp_branch, hle,
12918 committer, allow_conflict, repo);
12919 if (error)
12920 goto done;
12921 } else {
12922 error = got_object_open_as_commit(
12923 &commit, repo, hle->commit_id);
12924 if (error)
12925 goto done;
12926 error = show_histedit_progress(commit,
12927 hle, NULL);
12928 got_object_commit_close(commit);
12929 commit = NULL;
12930 if (error)
12931 goto done;
12934 continue;
12937 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12938 error = histedit_skip_commit(hle, worktree, repo);
12939 if (error)
12940 goto done;
12941 continue;
12944 error = got_object_open_as_commit(&commit, repo,
12945 hle->commit_id);
12946 if (error)
12947 goto done;
12948 parent_ids = got_object_commit_get_parent_ids(commit);
12949 pid = STAILQ_FIRST(parent_ids);
12951 error = got_worktree_histedit_merge_files(&merged_paths,
12952 worktree, fileindex, &pid->id, hle->commit_id, repo,
12953 update_progress, &upa, check_cancelled, NULL);
12954 if (error)
12955 goto done;
12956 got_object_commit_close(commit);
12957 commit = NULL;
12959 print_merge_progress_stats(&upa);
12960 if (upa.conflicts > 0 || upa.missing > 0 ||
12961 upa.not_deleted > 0 || upa.unversioned > 0) {
12962 if (upa.conflicts > 0) {
12963 error = show_rebase_merge_conflict(
12964 hle->commit_id, repo);
12965 if (error)
12966 goto done;
12968 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12969 break;
12972 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12973 char *id_str;
12974 error = got_object_id_str(&id_str, hle->commit_id);
12975 if (error)
12976 goto done;
12977 printf("Stopping histedit for amending commit %s\n",
12978 id_str);
12979 free(id_str);
12980 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12981 error = got_worktree_histedit_postpone(worktree,
12982 fileindex);
12983 goto done;
12986 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12987 error = histedit_skip_commit(hle, worktree, repo);
12988 if (error)
12989 goto done;
12990 continue;
12993 error = histedit_commit(&merged_paths, worktree, fileindex,
12994 tmp_branch, hle, committer, allow_conflict, repo);
12995 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12996 if (error)
12997 goto done;
13000 if (upa.conflicts > 0 || upa.missing > 0 ||
13001 upa.not_deleted > 0 || upa.unversioned > 0) {
13002 error = got_worktree_histedit_postpone(worktree, fileindex);
13003 if (error)
13004 goto done;
13005 if (upa.conflicts > 0 && upa.missing == 0 &&
13006 upa.not_deleted == 0 && upa.unversioned == 0) {
13007 error = got_error_msg(GOT_ERR_CONFLICTS,
13008 "conflicts must be resolved before histedit "
13009 "can continue");
13010 } else if (upa.conflicts > 0) {
13011 error = got_error_msg(GOT_ERR_CONFLICTS,
13012 "conflicts must be resolved before histedit "
13013 "can continue; changes destined for some "
13014 "files were not yet merged and should be "
13015 "merged manually if required before the "
13016 "histedit operation is continued");
13017 } else {
13018 error = got_error_msg(GOT_ERR_CONFLICTS,
13019 "changes destined for some files were not "
13020 "yet merged and should be merged manually "
13021 "if required before the histedit operation "
13022 "is continued");
13024 } else
13025 error = histedit_complete(worktree, fileindex, tmp_branch,
13026 branch, repo);
13027 done:
13028 free(cwd);
13029 free(committer);
13030 free(gitconfig_path);
13031 got_object_id_queue_free(&commits);
13032 histedit_free_list(&histedit_cmds);
13033 free(head_commit_id);
13034 free(base_commit_id);
13035 free(resume_commit_id);
13036 if (commit)
13037 got_object_commit_close(commit);
13038 if (branch)
13039 got_ref_close(branch);
13040 if (tmp_branch)
13041 got_ref_close(tmp_branch);
13042 if (worktree)
13043 got_worktree_close(worktree);
13044 if (repo) {
13045 const struct got_error *close_err = got_repo_close(repo);
13046 if (error == NULL)
13047 error = close_err;
13049 if (pack_fds) {
13050 const struct got_error *pack_err =
13051 got_repo_pack_fds_close(pack_fds);
13052 if (error == NULL)
13053 error = pack_err;
13055 return error;
13058 __dead static void
13059 usage_integrate(void)
13061 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13062 exit(1);
13065 static const struct got_error *
13066 cmd_integrate(int argc, char *argv[])
13068 const struct got_error *error = NULL;
13069 struct got_repository *repo = NULL;
13070 struct got_worktree *worktree = NULL;
13071 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13072 const char *branch_arg = NULL;
13073 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13074 struct got_fileindex *fileindex = NULL;
13075 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13076 int ch;
13077 struct got_update_progress_arg upa;
13078 int *pack_fds = NULL;
13080 #ifndef PROFILE
13081 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13082 "unveil", NULL) == -1)
13083 err(1, "pledge");
13084 #endif
13086 while ((ch = getopt(argc, argv, "")) != -1) {
13087 switch (ch) {
13088 default:
13089 usage_integrate();
13090 /* NOTREACHED */
13094 argc -= optind;
13095 argv += optind;
13097 if (argc != 1)
13098 usage_integrate();
13099 branch_arg = argv[0];
13101 cwd = getcwd(NULL, 0);
13102 if (cwd == NULL) {
13103 error = got_error_from_errno("getcwd");
13104 goto done;
13107 error = got_repo_pack_fds_open(&pack_fds);
13108 if (error != NULL)
13109 goto done;
13111 error = got_worktree_open(&worktree, cwd);
13112 if (error) {
13113 if (error->code == GOT_ERR_NOT_WORKTREE)
13114 error = wrap_not_worktree_error(error, "integrate",
13115 cwd);
13116 goto done;
13119 error = check_rebase_or_histedit_in_progress(worktree);
13120 if (error)
13121 goto done;
13123 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13124 NULL, pack_fds);
13125 if (error != NULL)
13126 goto done;
13128 error = apply_unveil(got_repo_get_path(repo), 0,
13129 got_worktree_get_root_path(worktree));
13130 if (error)
13131 goto done;
13133 error = check_merge_in_progress(worktree, repo);
13134 if (error)
13135 goto done;
13137 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13138 error = got_error_from_errno("asprintf");
13139 goto done;
13142 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13143 &base_branch_ref, worktree, refname, repo);
13144 if (error)
13145 goto done;
13147 refname = strdup(got_ref_get_name(branch_ref));
13148 if (refname == NULL) {
13149 error = got_error_from_errno("strdup");
13150 got_worktree_integrate_abort(worktree, fileindex, repo,
13151 branch_ref, base_branch_ref);
13152 goto done;
13154 base_refname = strdup(got_ref_get_name(base_branch_ref));
13155 if (base_refname == NULL) {
13156 error = got_error_from_errno("strdup");
13157 got_worktree_integrate_abort(worktree, fileindex, repo,
13158 branch_ref, base_branch_ref);
13159 goto done;
13161 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13162 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13163 got_worktree_integrate_abort(worktree, fileindex, repo,
13164 branch_ref, base_branch_ref);
13165 goto done;
13168 error = got_ref_resolve(&commit_id, repo, branch_ref);
13169 if (error)
13170 goto done;
13172 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13173 if (error)
13174 goto done;
13176 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13177 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13178 "specified branch has already been integrated");
13179 got_worktree_integrate_abort(worktree, fileindex, repo,
13180 branch_ref, base_branch_ref);
13181 goto done;
13184 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13185 if (error) {
13186 if (error->code == GOT_ERR_ANCESTRY)
13187 error = got_error(GOT_ERR_REBASE_REQUIRED);
13188 got_worktree_integrate_abort(worktree, fileindex, repo,
13189 branch_ref, base_branch_ref);
13190 goto done;
13193 memset(&upa, 0, sizeof(upa));
13194 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13195 branch_ref, base_branch_ref, update_progress, &upa,
13196 check_cancelled, NULL);
13197 if (error)
13198 goto done;
13200 printf("Integrated %s into %s\n", refname, base_refname);
13201 print_update_progress_stats(&upa);
13202 done:
13203 if (repo) {
13204 const struct got_error *close_err = got_repo_close(repo);
13205 if (error == NULL)
13206 error = close_err;
13208 if (worktree)
13209 got_worktree_close(worktree);
13210 if (pack_fds) {
13211 const struct got_error *pack_err =
13212 got_repo_pack_fds_close(pack_fds);
13213 if (error == NULL)
13214 error = pack_err;
13216 free(cwd);
13217 free(base_commit_id);
13218 free(commit_id);
13219 free(refname);
13220 free(base_refname);
13221 return error;
13224 __dead static void
13225 usage_merge(void)
13227 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13228 exit(1);
13231 static const struct got_error *
13232 cmd_merge(int argc, char *argv[])
13234 const struct got_error *error = NULL;
13235 struct got_worktree *worktree = NULL;
13236 struct got_repository *repo = NULL;
13237 struct got_fileindex *fileindex = NULL;
13238 char *cwd = NULL, *id_str = NULL, *author = NULL;
13239 char *gitconfig_path = NULL;
13240 struct got_reference *branch = NULL, *wt_branch = NULL;
13241 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13242 struct got_object_id *wt_branch_tip = NULL;
13243 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13244 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13245 struct got_update_progress_arg upa;
13246 struct got_object_id *merge_commit_id = NULL;
13247 char *branch_name = NULL;
13248 int *pack_fds = NULL;
13250 memset(&upa, 0, sizeof(upa));
13252 #ifndef PROFILE
13253 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13254 "unveil", NULL) == -1)
13255 err(1, "pledge");
13256 #endif
13258 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13259 switch (ch) {
13260 case 'a':
13261 abort_merge = 1;
13262 break;
13263 case 'C':
13264 allow_conflict = 1;
13265 break;
13266 case 'c':
13267 continue_merge = 1;
13268 break;
13269 case 'M':
13270 prefer_fast_forward = 0;
13271 break;
13272 case 'n':
13273 interrupt_merge = 1;
13274 break;
13275 default:
13276 usage_merge();
13277 /* NOTREACHED */
13281 argc -= optind;
13282 argv += optind;
13284 if (abort_merge) {
13285 if (continue_merge)
13286 option_conflict('a', 'c');
13287 if (!prefer_fast_forward)
13288 option_conflict('a', 'M');
13289 if (interrupt_merge)
13290 option_conflict('a', 'n');
13291 } else if (continue_merge) {
13292 if (!prefer_fast_forward)
13293 option_conflict('c', 'M');
13294 if (interrupt_merge)
13295 option_conflict('c', 'n');
13297 if (allow_conflict) {
13298 if (!continue_merge)
13299 errx(1, "-C option requires -c");
13301 if (abort_merge || continue_merge) {
13302 if (argc != 0)
13303 usage_merge();
13304 } else if (argc != 1)
13305 usage_merge();
13307 cwd = getcwd(NULL, 0);
13308 if (cwd == NULL) {
13309 error = got_error_from_errno("getcwd");
13310 goto done;
13313 error = got_repo_pack_fds_open(&pack_fds);
13314 if (error != NULL)
13315 goto done;
13317 error = got_worktree_open(&worktree, cwd);
13318 if (error) {
13319 if (error->code == GOT_ERR_NOT_WORKTREE)
13320 error = wrap_not_worktree_error(error,
13321 "merge", cwd);
13322 goto done;
13325 error = get_gitconfig_path(&gitconfig_path);
13326 if (error)
13327 goto done;
13328 error = got_repo_open(&repo,
13329 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13330 gitconfig_path, pack_fds);
13331 if (error != NULL)
13332 goto done;
13334 if (worktree != NULL) {
13335 error = worktree_has_logmsg_ref("merge", worktree, repo);
13336 if (error)
13337 goto done;
13340 error = apply_unveil(got_repo_get_path(repo), 0,
13341 worktree ? got_worktree_get_root_path(worktree) : NULL);
13342 if (error)
13343 goto done;
13345 error = check_rebase_or_histedit_in_progress(worktree);
13346 if (error)
13347 goto done;
13349 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13350 repo);
13351 if (error)
13352 goto done;
13354 if (merge_in_progress && !(abort_merge || continue_merge)) {
13355 error = got_error(GOT_ERR_MERGE_BUSY);
13356 goto done;
13359 if (!merge_in_progress && (abort_merge || continue_merge)) {
13360 error = got_error(GOT_ERR_NOT_MERGING);
13361 goto done;
13364 if (abort_merge) {
13365 error = got_worktree_merge_continue(&branch_name,
13366 &branch_tip, &fileindex, worktree, repo);
13367 if (error)
13368 goto done;
13369 error = got_worktree_merge_abort(worktree, fileindex, repo,
13370 abort_progress, &upa);
13371 if (error)
13372 goto done;
13373 printf("Merge of %s aborted\n", branch_name);
13374 goto done; /* nothing else to do */
13377 if (strncmp(got_worktree_get_head_ref_name(worktree),
13378 "refs/heads/", 11) != 0) {
13379 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13380 "work tree's current branch %s is outside the "
13381 "\"refs/heads/\" reference namespace; "
13382 "update -b required",
13383 got_worktree_get_head_ref_name(worktree));
13384 goto done;
13387 error = get_author(&author, repo, worktree);
13388 if (error)
13389 goto done;
13391 error = got_ref_open(&wt_branch, repo,
13392 got_worktree_get_head_ref_name(worktree), 0);
13393 if (error)
13394 goto done;
13395 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13396 if (error)
13397 goto done;
13399 if (continue_merge) {
13400 struct got_object_id *base_commit_id;
13401 base_commit_id = got_worktree_get_base_commit_id(worktree);
13402 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13403 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13404 goto done;
13406 error = got_worktree_merge_continue(&branch_name,
13407 &branch_tip, &fileindex, worktree, repo);
13408 if (error)
13409 goto done;
13410 } else {
13411 error = got_ref_open(&branch, repo, argv[0], 0);
13412 if (error != NULL)
13413 goto done;
13414 branch_name = strdup(got_ref_get_name(branch));
13415 if (branch_name == NULL) {
13416 error = got_error_from_errno("strdup");
13417 goto done;
13419 error = got_ref_resolve(&branch_tip, repo, branch);
13420 if (error)
13421 goto done;
13424 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13425 wt_branch_tip, branch_tip, 0, repo,
13426 check_cancelled, NULL);
13427 if (error && error->code != GOT_ERR_ANCESTRY)
13428 goto done;
13430 if (!continue_merge) {
13431 error = check_path_prefix(wt_branch_tip, branch_tip,
13432 got_worktree_get_path_prefix(worktree),
13433 GOT_ERR_MERGE_PATH, repo);
13434 if (error)
13435 goto done;
13436 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13437 if (error)
13438 goto done;
13439 if (prefer_fast_forward && yca_id &&
13440 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13441 struct got_pathlist_head paths;
13442 if (interrupt_merge) {
13443 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13444 "there are no changes to merge since %s "
13445 "is already based on %s; merge cannot be "
13446 "interrupted for amending; -n",
13447 branch_name, got_ref_get_name(wt_branch));
13448 goto done;
13450 printf("Forwarding %s to %s\n",
13451 got_ref_get_name(wt_branch), branch_name);
13452 error = got_ref_change_ref(wt_branch, branch_tip);
13453 if (error)
13454 goto done;
13455 error = got_ref_write(wt_branch, repo);
13456 if (error)
13457 goto done;
13458 error = got_worktree_set_base_commit_id(worktree, repo,
13459 branch_tip);
13460 if (error)
13461 goto done;
13462 TAILQ_INIT(&paths);
13463 error = got_pathlist_append(&paths, "", NULL);
13464 if (error)
13465 goto done;
13466 error = got_worktree_checkout_files(worktree,
13467 &paths, repo, update_progress, &upa,
13468 check_cancelled, NULL);
13469 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13470 if (error)
13471 goto done;
13472 if (upa.did_something) {
13473 char *id_str;
13474 error = got_object_id_str(&id_str, branch_tip);
13475 if (error)
13476 goto done;
13477 printf("Updated to commit %s\n", id_str);
13478 free(id_str);
13479 } else
13480 printf("Already up-to-date\n");
13481 print_update_progress_stats(&upa);
13482 goto done;
13484 error = got_worktree_merge_write_refs(worktree, branch, repo);
13485 if (error)
13486 goto done;
13488 error = got_worktree_merge_branch(worktree, fileindex,
13489 yca_id, branch_tip, repo, update_progress, &upa,
13490 check_cancelled, NULL);
13491 if (error)
13492 goto done;
13493 print_merge_progress_stats(&upa);
13494 if (!upa.did_something) {
13495 error = got_worktree_merge_abort(worktree, fileindex,
13496 repo, abort_progress, &upa);
13497 if (error)
13498 goto done;
13499 printf("Already up-to-date\n");
13500 goto done;
13504 if (interrupt_merge) {
13505 error = got_worktree_merge_postpone(worktree, fileindex);
13506 if (error)
13507 goto done;
13508 printf("Merge of %s interrupted on request\n", branch_name);
13509 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13510 upa.not_deleted > 0 || upa.unversioned > 0) {
13511 error = got_worktree_merge_postpone(worktree, fileindex);
13512 if (error)
13513 goto done;
13514 if (upa.conflicts > 0 && upa.missing == 0 &&
13515 upa.not_deleted == 0 && upa.unversioned == 0) {
13516 error = got_error_msg(GOT_ERR_CONFLICTS,
13517 "conflicts must be resolved before merging "
13518 "can continue");
13519 } else if (upa.conflicts > 0) {
13520 error = got_error_msg(GOT_ERR_CONFLICTS,
13521 "conflicts must be resolved before merging "
13522 "can continue; changes destined for some "
13523 "files were not yet merged and "
13524 "should be merged manually if required before the "
13525 "merge operation is continued");
13526 } else {
13527 error = got_error_msg(GOT_ERR_CONFLICTS,
13528 "changes destined for some "
13529 "files were not yet merged and should be "
13530 "merged manually if required before the "
13531 "merge operation is continued");
13533 goto done;
13534 } else {
13535 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13536 fileindex, author, NULL, 1, branch_tip, branch_name,
13537 allow_conflict, repo, continue_merge ? print_status : NULL,
13538 NULL);
13539 if (error)
13540 goto done;
13541 error = got_worktree_merge_complete(worktree, fileindex, repo);
13542 if (error)
13543 goto done;
13544 error = got_object_id_str(&id_str, merge_commit_id);
13545 if (error)
13546 goto done;
13547 printf("Merged %s into %s: %s\n", branch_name,
13548 got_worktree_get_head_ref_name(worktree),
13549 id_str);
13552 done:
13553 free(gitconfig_path);
13554 free(id_str);
13555 free(merge_commit_id);
13556 free(author);
13557 free(branch_tip);
13558 free(branch_name);
13559 free(yca_id);
13560 if (branch)
13561 got_ref_close(branch);
13562 if (wt_branch)
13563 got_ref_close(wt_branch);
13564 if (worktree)
13565 got_worktree_close(worktree);
13566 if (repo) {
13567 const struct got_error *close_err = got_repo_close(repo);
13568 if (error == NULL)
13569 error = close_err;
13571 if (pack_fds) {
13572 const struct got_error *pack_err =
13573 got_repo_pack_fds_close(pack_fds);
13574 if (error == NULL)
13575 error = pack_err;
13577 return error;
13580 __dead static void
13581 usage_stage(void)
13583 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13584 "[path ...]\n", getprogname());
13585 exit(1);
13588 static const struct got_error *
13589 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13590 const char *path, struct got_object_id *blob_id,
13591 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13592 int dirfd, const char *de_name)
13594 const struct got_error *err = NULL;
13595 char *id_str = NULL;
13597 if (staged_status != GOT_STATUS_ADD &&
13598 staged_status != GOT_STATUS_MODIFY &&
13599 staged_status != GOT_STATUS_DELETE)
13600 return NULL;
13602 if (staged_status == GOT_STATUS_ADD ||
13603 staged_status == GOT_STATUS_MODIFY)
13604 err = got_object_id_str(&id_str, staged_blob_id);
13605 else
13606 err = got_object_id_str(&id_str, blob_id);
13607 if (err)
13608 return err;
13610 printf("%s %c %s\n", id_str, staged_status, path);
13611 free(id_str);
13612 return NULL;
13615 static const struct got_error *
13616 cmd_stage(int argc, char *argv[])
13618 const struct got_error *error = NULL;
13619 struct got_repository *repo = NULL;
13620 struct got_worktree *worktree = NULL;
13621 char *cwd = NULL;
13622 struct got_pathlist_head paths;
13623 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13624 FILE *patch_script_file = NULL;
13625 const char *patch_script_path = NULL;
13626 struct choose_patch_arg cpa;
13627 int *pack_fds = NULL;
13629 TAILQ_INIT(&paths);
13631 #ifndef PROFILE
13632 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13633 "unveil", NULL) == -1)
13634 err(1, "pledge");
13635 #endif
13637 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13638 switch (ch) {
13639 case 'F':
13640 patch_script_path = optarg;
13641 break;
13642 case 'l':
13643 list_stage = 1;
13644 break;
13645 case 'p':
13646 pflag = 1;
13647 break;
13648 case 'S':
13649 allow_bad_symlinks = 1;
13650 break;
13651 default:
13652 usage_stage();
13653 /* NOTREACHED */
13657 argc -= optind;
13658 argv += optind;
13660 if (list_stage && (pflag || patch_script_path))
13661 errx(1, "-l option cannot be used with other options");
13662 if (patch_script_path && !pflag)
13663 errx(1, "-F option can only be used together with -p option");
13665 cwd = getcwd(NULL, 0);
13666 if (cwd == NULL) {
13667 error = got_error_from_errno("getcwd");
13668 goto done;
13671 error = got_repo_pack_fds_open(&pack_fds);
13672 if (error != NULL)
13673 goto done;
13675 error = got_worktree_open(&worktree, cwd);
13676 if (error) {
13677 if (error->code == GOT_ERR_NOT_WORKTREE)
13678 error = wrap_not_worktree_error(error, "stage", cwd);
13679 goto done;
13682 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13683 NULL, pack_fds);
13684 if (error != NULL)
13685 goto done;
13687 if (patch_script_path) {
13688 patch_script_file = fopen(patch_script_path, "re");
13689 if (patch_script_file == NULL) {
13690 error = got_error_from_errno2("fopen",
13691 patch_script_path);
13692 goto done;
13695 error = apply_unveil(got_repo_get_path(repo), 0,
13696 got_worktree_get_root_path(worktree));
13697 if (error)
13698 goto done;
13700 error = check_merge_in_progress(worktree, repo);
13701 if (error)
13702 goto done;
13704 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13705 if (error)
13706 goto done;
13708 if (list_stage)
13709 error = got_worktree_status(worktree, &paths, repo, 0,
13710 print_stage, NULL, check_cancelled, NULL);
13711 else {
13712 cpa.patch_script_file = patch_script_file;
13713 cpa.action = "stage";
13714 error = got_worktree_stage(worktree, &paths,
13715 pflag ? NULL : print_status, NULL,
13716 pflag ? choose_patch : NULL, &cpa,
13717 allow_bad_symlinks, repo);
13719 done:
13720 if (patch_script_file && fclose(patch_script_file) == EOF &&
13721 error == NULL)
13722 error = got_error_from_errno2("fclose", patch_script_path);
13723 if (repo) {
13724 const struct got_error *close_err = got_repo_close(repo);
13725 if (error == NULL)
13726 error = close_err;
13728 if (worktree)
13729 got_worktree_close(worktree);
13730 if (pack_fds) {
13731 const struct got_error *pack_err =
13732 got_repo_pack_fds_close(pack_fds);
13733 if (error == NULL)
13734 error = pack_err;
13736 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13737 free(cwd);
13738 return error;
13741 __dead static void
13742 usage_unstage(void)
13744 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13745 "[path ...]\n", getprogname());
13746 exit(1);
13750 static const struct got_error *
13751 cmd_unstage(int argc, char *argv[])
13753 const struct got_error *error = NULL;
13754 struct got_repository *repo = NULL;
13755 struct got_worktree *worktree = NULL;
13756 char *cwd = NULL;
13757 struct got_pathlist_head paths;
13758 int ch, pflag = 0;
13759 struct got_update_progress_arg upa;
13760 FILE *patch_script_file = NULL;
13761 const char *patch_script_path = NULL;
13762 struct choose_patch_arg cpa;
13763 int *pack_fds = NULL;
13765 TAILQ_INIT(&paths);
13767 #ifndef PROFILE
13768 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13769 "unveil", NULL) == -1)
13770 err(1, "pledge");
13771 #endif
13773 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13774 switch (ch) {
13775 case 'F':
13776 patch_script_path = optarg;
13777 break;
13778 case 'p':
13779 pflag = 1;
13780 break;
13781 default:
13782 usage_unstage();
13783 /* NOTREACHED */
13787 argc -= optind;
13788 argv += optind;
13790 if (patch_script_path && !pflag)
13791 errx(1, "-F option can only be used together with -p option");
13793 cwd = getcwd(NULL, 0);
13794 if (cwd == NULL) {
13795 error = got_error_from_errno("getcwd");
13796 goto done;
13799 error = got_repo_pack_fds_open(&pack_fds);
13800 if (error != NULL)
13801 goto done;
13803 error = got_worktree_open(&worktree, cwd);
13804 if (error) {
13805 if (error->code == GOT_ERR_NOT_WORKTREE)
13806 error = wrap_not_worktree_error(error, "unstage", cwd);
13807 goto done;
13810 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13811 NULL, pack_fds);
13812 if (error != NULL)
13813 goto done;
13815 if (patch_script_path) {
13816 patch_script_file = fopen(patch_script_path, "re");
13817 if (patch_script_file == NULL) {
13818 error = got_error_from_errno2("fopen",
13819 patch_script_path);
13820 goto done;
13824 error = apply_unveil(got_repo_get_path(repo), 0,
13825 got_worktree_get_root_path(worktree));
13826 if (error)
13827 goto done;
13829 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13830 if (error)
13831 goto done;
13833 cpa.patch_script_file = patch_script_file;
13834 cpa.action = "unstage";
13835 memset(&upa, 0, sizeof(upa));
13836 error = got_worktree_unstage(worktree, &paths, update_progress,
13837 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13838 if (!error)
13839 print_merge_progress_stats(&upa);
13840 done:
13841 if (patch_script_file && fclose(patch_script_file) == EOF &&
13842 error == NULL)
13843 error = got_error_from_errno2("fclose", patch_script_path);
13844 if (repo) {
13845 const struct got_error *close_err = got_repo_close(repo);
13846 if (error == NULL)
13847 error = close_err;
13849 if (worktree)
13850 got_worktree_close(worktree);
13851 if (pack_fds) {
13852 const struct got_error *pack_err =
13853 got_repo_pack_fds_close(pack_fds);
13854 if (error == NULL)
13855 error = pack_err;
13857 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13858 free(cwd);
13859 return error;
13862 __dead static void
13863 usage_cat(void)
13865 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13866 "arg ...\n", getprogname());
13867 exit(1);
13870 static const struct got_error *
13871 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13873 const struct got_error *err;
13874 struct got_blob_object *blob;
13875 int fd = -1;
13877 fd = got_opentempfd();
13878 if (fd == -1)
13879 return got_error_from_errno("got_opentempfd");
13881 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13882 if (err)
13883 goto done;
13885 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13886 done:
13887 if (fd != -1 && close(fd) == -1 && err == NULL)
13888 err = got_error_from_errno("close");
13889 if (blob)
13890 got_object_blob_close(blob);
13891 return err;
13894 static const struct got_error *
13895 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13897 const struct got_error *err;
13898 struct got_tree_object *tree;
13899 int nentries, i;
13901 err = got_object_open_as_tree(&tree, repo, id);
13902 if (err)
13903 return err;
13905 nentries = got_object_tree_get_nentries(tree);
13906 for (i = 0; i < nentries; i++) {
13907 struct got_tree_entry *te;
13908 char *id_str;
13909 if (sigint_received || sigpipe_received)
13910 break;
13911 te = got_object_tree_get_entry(tree, i);
13912 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13913 if (err)
13914 break;
13915 fprintf(outfile, "%s %.7o %s\n", id_str,
13916 got_tree_entry_get_mode(te),
13917 got_tree_entry_get_name(te));
13918 free(id_str);
13921 got_object_tree_close(tree);
13922 return err;
13925 static const struct got_error *
13926 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13928 const struct got_error *err;
13929 struct got_commit_object *commit;
13930 const struct got_object_id_queue *parent_ids;
13931 struct got_object_qid *pid;
13932 char *id_str = NULL;
13933 const char *logmsg = NULL;
13934 char gmtoff[6];
13936 err = got_object_open_as_commit(&commit, repo, id);
13937 if (err)
13938 return err;
13940 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13941 if (err)
13942 goto done;
13944 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13945 parent_ids = got_object_commit_get_parent_ids(commit);
13946 fprintf(outfile, "numparents %d\n",
13947 got_object_commit_get_nparents(commit));
13948 STAILQ_FOREACH(pid, parent_ids, entry) {
13949 char *pid_str;
13950 err = got_object_id_str(&pid_str, &pid->id);
13951 if (err)
13952 goto done;
13953 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13954 free(pid_str);
13956 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13957 got_object_commit_get_author_gmtoff(commit));
13958 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13959 got_object_commit_get_author(commit),
13960 (long long)got_object_commit_get_author_time(commit),
13961 gmtoff);
13963 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13964 got_object_commit_get_committer_gmtoff(commit));
13965 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13966 got_object_commit_get_committer(commit),
13967 (long long)got_object_commit_get_committer_time(commit),
13968 gmtoff);
13970 logmsg = got_object_commit_get_logmsg_raw(commit);
13971 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13972 fprintf(outfile, "%s", logmsg);
13973 done:
13974 free(id_str);
13975 got_object_commit_close(commit);
13976 return err;
13979 static const struct got_error *
13980 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13982 const struct got_error *err;
13983 struct got_tag_object *tag;
13984 char *id_str = NULL;
13985 const char *tagmsg = NULL;
13986 char gmtoff[6];
13988 err = got_object_open_as_tag(&tag, repo, id);
13989 if (err)
13990 return err;
13992 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13993 if (err)
13994 goto done;
13996 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13998 switch (got_object_tag_get_object_type(tag)) {
13999 case GOT_OBJ_TYPE_BLOB:
14000 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14001 GOT_OBJ_LABEL_BLOB);
14002 break;
14003 case GOT_OBJ_TYPE_TREE:
14004 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14005 GOT_OBJ_LABEL_TREE);
14006 break;
14007 case GOT_OBJ_TYPE_COMMIT:
14008 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14009 GOT_OBJ_LABEL_COMMIT);
14010 break;
14011 case GOT_OBJ_TYPE_TAG:
14012 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14013 GOT_OBJ_LABEL_TAG);
14014 break;
14015 default:
14016 break;
14019 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14020 got_object_tag_get_name(tag));
14022 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14023 got_object_tag_get_tagger_gmtoff(tag));
14024 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14025 got_object_tag_get_tagger(tag),
14026 (long long)got_object_tag_get_tagger_time(tag),
14027 gmtoff);
14029 tagmsg = got_object_tag_get_message(tag);
14030 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14031 fprintf(outfile, "%s", tagmsg);
14032 done:
14033 free(id_str);
14034 got_object_tag_close(tag);
14035 return err;
14038 static const struct got_error *
14039 cmd_cat(int argc, char *argv[])
14041 const struct got_error *error;
14042 struct got_repository *repo = NULL;
14043 struct got_worktree *worktree = NULL;
14044 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14045 const char *commit_id_str = NULL;
14046 struct got_object_id *id = NULL, *commit_id = NULL;
14047 struct got_commit_object *commit = NULL;
14048 int ch, obj_type, i, force_path = 0;
14049 struct got_reflist_head refs;
14050 int *pack_fds = NULL;
14052 TAILQ_INIT(&refs);
14054 #ifndef PROFILE
14055 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14056 NULL) == -1)
14057 err(1, "pledge");
14058 #endif
14060 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14061 switch (ch) {
14062 case 'c':
14063 commit_id_str = optarg;
14064 break;
14065 case 'P':
14066 force_path = 1;
14067 break;
14068 case 'r':
14069 repo_path = realpath(optarg, NULL);
14070 if (repo_path == NULL)
14071 return got_error_from_errno2("realpath",
14072 optarg);
14073 got_path_strip_trailing_slashes(repo_path);
14074 break;
14075 default:
14076 usage_cat();
14077 /* NOTREACHED */
14081 argc -= optind;
14082 argv += optind;
14084 cwd = getcwd(NULL, 0);
14085 if (cwd == NULL) {
14086 error = got_error_from_errno("getcwd");
14087 goto done;
14090 error = got_repo_pack_fds_open(&pack_fds);
14091 if (error != NULL)
14092 goto done;
14094 if (repo_path == NULL) {
14095 error = got_worktree_open(&worktree, cwd);
14096 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14097 goto done;
14098 if (worktree) {
14099 repo_path = strdup(
14100 got_worktree_get_repo_path(worktree));
14101 if (repo_path == NULL) {
14102 error = got_error_from_errno("strdup");
14103 goto done;
14106 /* Release work tree lock. */
14107 got_worktree_close(worktree);
14108 worktree = NULL;
14112 if (repo_path == NULL) {
14113 repo_path = strdup(cwd);
14114 if (repo_path == NULL)
14115 return got_error_from_errno("strdup");
14118 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14119 free(repo_path);
14120 if (error != NULL)
14121 goto done;
14123 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14124 if (error)
14125 goto done;
14127 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14128 if (error)
14129 goto done;
14131 if (commit_id_str == NULL)
14132 commit_id_str = GOT_REF_HEAD;
14133 error = got_repo_match_object_id(&commit_id, NULL,
14134 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14135 if (error)
14136 goto done;
14138 error = got_object_open_as_commit(&commit, repo, commit_id);
14139 if (error)
14140 goto done;
14142 for (i = 0; i < argc; i++) {
14143 if (force_path) {
14144 error = got_object_id_by_path(&id, repo, commit,
14145 argv[i]);
14146 if (error)
14147 break;
14148 } else {
14149 error = got_repo_match_object_id(&id, &label, argv[i],
14150 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14151 repo);
14152 if (error) {
14153 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14154 error->code != GOT_ERR_NOT_REF)
14155 break;
14156 error = got_object_id_by_path(&id, repo,
14157 commit, argv[i]);
14158 if (error)
14159 break;
14163 error = got_object_get_type(&obj_type, repo, id);
14164 if (error)
14165 break;
14167 switch (obj_type) {
14168 case GOT_OBJ_TYPE_BLOB:
14169 error = cat_blob(id, repo, stdout);
14170 break;
14171 case GOT_OBJ_TYPE_TREE:
14172 error = cat_tree(id, repo, stdout);
14173 break;
14174 case GOT_OBJ_TYPE_COMMIT:
14175 error = cat_commit(id, repo, stdout);
14176 break;
14177 case GOT_OBJ_TYPE_TAG:
14178 error = cat_tag(id, repo, stdout);
14179 break;
14180 default:
14181 error = got_error(GOT_ERR_OBJ_TYPE);
14182 break;
14184 if (error)
14185 break;
14186 free(label);
14187 label = NULL;
14188 free(id);
14189 id = NULL;
14191 done:
14192 free(label);
14193 free(id);
14194 free(commit_id);
14195 if (commit)
14196 got_object_commit_close(commit);
14197 if (worktree)
14198 got_worktree_close(worktree);
14199 if (repo) {
14200 const struct got_error *close_err = got_repo_close(repo);
14201 if (error == NULL)
14202 error = close_err;
14204 if (pack_fds) {
14205 const struct got_error *pack_err =
14206 got_repo_pack_fds_close(pack_fds);
14207 if (error == NULL)
14208 error = pack_err;
14211 got_ref_list_free(&refs);
14212 return error;
14215 __dead static void
14216 usage_info(void)
14218 fprintf(stderr, "usage: %s info [path ...]\n",
14219 getprogname());
14220 exit(1);
14223 static const struct got_error *
14224 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14225 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14226 struct got_object_id *commit_id)
14228 const struct got_error *err = NULL;
14229 char *id_str = NULL;
14230 char datebuf[128];
14231 struct tm mytm, *tm;
14232 struct got_pathlist_head *paths = arg;
14233 struct got_pathlist_entry *pe;
14236 * Clear error indication from any of the path arguments which
14237 * would cause this file index entry to be displayed.
14239 TAILQ_FOREACH(pe, paths, entry) {
14240 if (got_path_cmp(path, pe->path, strlen(path),
14241 pe->path_len) == 0 ||
14242 got_path_is_child(path, pe->path, pe->path_len))
14243 pe->data = NULL; /* no error */
14246 printf(GOT_COMMIT_SEP_STR);
14247 if (S_ISLNK(mode))
14248 printf("symlink: %s\n", path);
14249 else if (S_ISREG(mode)) {
14250 printf("file: %s\n", path);
14251 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14252 } else if (S_ISDIR(mode))
14253 printf("directory: %s\n", path);
14254 else
14255 printf("something: %s\n", path);
14257 tm = localtime_r(&mtime, &mytm);
14258 if (tm == NULL)
14259 return NULL;
14260 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14261 return got_error(GOT_ERR_NO_SPACE);
14262 printf("timestamp: %s\n", datebuf);
14264 if (blob_id) {
14265 err = got_object_id_str(&id_str, blob_id);
14266 if (err)
14267 return err;
14268 printf("based on blob: %s\n", id_str);
14269 free(id_str);
14272 if (staged_blob_id) {
14273 err = got_object_id_str(&id_str, staged_blob_id);
14274 if (err)
14275 return err;
14276 printf("based on staged blob: %s\n", id_str);
14277 free(id_str);
14280 if (commit_id) {
14281 err = got_object_id_str(&id_str, commit_id);
14282 if (err)
14283 return err;
14284 printf("based on commit: %s\n", id_str);
14285 free(id_str);
14288 return NULL;
14291 static const struct got_error *
14292 cmd_info(int argc, char *argv[])
14294 const struct got_error *error = NULL;
14295 struct got_worktree *worktree = NULL;
14296 char *cwd = NULL, *id_str = NULL;
14297 struct got_pathlist_head paths;
14298 char *uuidstr = NULL;
14299 int ch, show_files = 0;
14301 TAILQ_INIT(&paths);
14303 #ifndef PROFILE
14304 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14305 NULL) == -1)
14306 err(1, "pledge");
14307 #endif
14309 while ((ch = getopt(argc, argv, "")) != -1) {
14310 switch (ch) {
14311 default:
14312 usage_info();
14313 /* NOTREACHED */
14317 argc -= optind;
14318 argv += optind;
14320 cwd = getcwd(NULL, 0);
14321 if (cwd == NULL) {
14322 error = got_error_from_errno("getcwd");
14323 goto done;
14326 error = got_worktree_open(&worktree, cwd);
14327 if (error) {
14328 if (error->code == GOT_ERR_NOT_WORKTREE)
14329 error = wrap_not_worktree_error(error, "info", cwd);
14330 goto done;
14333 #ifndef PROFILE
14334 /* Remove "wpath cpath proc exec sendfd" promises. */
14335 if (pledge("stdio rpath flock unveil", NULL) == -1)
14336 err(1, "pledge");
14337 #endif
14338 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14339 if (error)
14340 goto done;
14342 if (argc >= 1) {
14343 error = get_worktree_paths_from_argv(&paths, argc, argv,
14344 worktree);
14345 if (error)
14346 goto done;
14347 show_files = 1;
14350 error = got_object_id_str(&id_str,
14351 got_worktree_get_base_commit_id(worktree));
14352 if (error)
14353 goto done;
14355 error = got_worktree_get_uuid(&uuidstr, worktree);
14356 if (error)
14357 goto done;
14359 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14360 printf("work tree base commit: %s\n", id_str);
14361 printf("work tree path prefix: %s\n",
14362 got_worktree_get_path_prefix(worktree));
14363 printf("work tree branch reference: %s\n",
14364 got_worktree_get_head_ref_name(worktree));
14365 printf("work tree UUID: %s\n", uuidstr);
14366 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14368 if (show_files) {
14369 struct got_pathlist_entry *pe;
14370 TAILQ_FOREACH(pe, &paths, entry) {
14371 if (pe->path_len == 0)
14372 continue;
14374 * Assume this path will fail. This will be corrected
14375 * in print_path_info() in case the path does suceeed.
14377 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14379 error = got_worktree_path_info(worktree, &paths,
14380 print_path_info, &paths, check_cancelled, NULL);
14381 if (error)
14382 goto done;
14383 TAILQ_FOREACH(pe, &paths, entry) {
14384 if (pe->data != NULL) {
14385 const struct got_error *perr;
14387 perr = pe->data;
14388 error = got_error_fmt(perr->code, "%s",
14389 pe->path);
14390 break;
14394 done:
14395 if (worktree)
14396 got_worktree_close(worktree);
14397 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14398 free(cwd);
14399 free(id_str);
14400 free(uuidstr);
14401 return error;