6 #include "parse-options.h"
7 #include "argv-array.h"
10 #include "run-command.h"
16 static const char * const worktree_usage[] = {
17 N_("git worktree add [<options>] <path> [<commit-ish>]"),
18 N_("git worktree list [<options>]"),
19 N_("git worktree lock [<options>] <path>"),
20 N_("git worktree move <worktree> <new-path>"),
21 N_("git worktree prune [<options>]"),
22 N_("git worktree remove [<options>] <worktree>"),
23 N_("git worktree unlock <path>"),
36 static int guess_remote;
37 static timestamp_t expire;
39 static int git_worktree_config(const char *var, const char *value, void *cb)
41 if (!strcmp(var, "worktree.guessremote")) {
42 guess_remote = git_config_bool(var, value);
46 return git_default_config(var, value, cb);
49 static int prune_worktree(const char *id, struct strbuf *reason)
57 if (!is_directory(git_path("worktrees/%s", id))) {
58 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
61 if (file_exists(git_path("worktrees/%s/locked", id)))
63 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
64 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
67 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
69 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
73 len = xsize_t(st.st_size);
76 read_result = read_in_full(fd, path, len);
77 if (read_result < 0) {
78 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
86 if (read_result != len) {
88 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
89 id, (uintmax_t)len, (uintmax_t)read_result);
93 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
96 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
101 if (!file_exists(path)) {
103 if (stat(git_path("worktrees/%s/index", id), &st) ||
104 st.st_mtime <= expire) {
105 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
115 static void prune_worktrees(void)
117 struct strbuf reason = STRBUF_INIT;
118 struct strbuf path = STRBUF_INIT;
119 DIR *dir = opendir(git_path("worktrees"));
124 while ((d = readdir(dir)) != NULL) {
125 if (is_dot_or_dotdot(d->d_name))
127 strbuf_reset(&reason);
128 if (!prune_worktree(d->d_name, &reason))
130 if (show_only || verbose)
131 printf("%s\n", reason.buf);
134 git_path_buf(&path, "worktrees/%s", d->d_name);
135 ret = remove_dir_recursively(&path, 0);
136 if (ret < 0 && errno == ENOTDIR)
137 ret = unlink(path.buf);
139 error_errno(_("failed to remove '%s'"), path.buf);
143 rmdir(git_path("worktrees"));
144 strbuf_release(&reason);
145 strbuf_release(&path);
148 static int prune(int ac, const char **av, const char *prefix)
150 struct option options[] = {
151 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
152 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
153 OPT_EXPIRY_DATE(0, "expire", &expire,
154 N_("expire working trees older than <time>")),
159 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
161 usage_with_options(worktree_usage, options);
166 static char *junk_work_tree;
167 static char *junk_git_dir;
169 static pid_t junk_pid;
171 static void remove_junk(void)
173 struct strbuf sb = STRBUF_INIT;
174 if (!is_junk || getpid() != junk_pid)
177 strbuf_addstr(&sb, junk_git_dir);
178 remove_dir_recursively(&sb, 0);
181 if (junk_work_tree) {
182 strbuf_addstr(&sb, junk_work_tree);
183 remove_dir_recursively(&sb, 0);
188 static void remove_junk_on_signal(int signo)
195 static const char *worktree_basename(const char *path, int *olen)
201 while (len && is_dir_sep(path[len - 1]))
204 for (name = path + len - 1; name > path; name--)
205 if (is_dir_sep(*name)) {
214 static int add_worktree(const char *path, const char *refname,
215 const struct add_opts *opts)
217 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
218 struct strbuf sb = STRBUF_INIT;
221 struct child_process cp = CHILD_PROCESS_INIT;
222 struct argv_array child_env = ARGV_ARRAY_INIT;
223 int counter = 0, len, ret;
224 struct strbuf symref = STRBUF_INIT;
225 struct commit *commit = NULL;
228 if (file_exists(path) && !is_empty_dir(path))
229 die(_("'%s' already exists"), path);
231 /* is 'refname' a branch or commit? */
232 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
233 ref_exists(symref.buf)) {
236 die_if_checked_out(symref.buf, 0);
238 commit = lookup_commit_reference_by_name(refname);
240 die(_("invalid reference: %s"), refname);
242 name = worktree_basename(path, &len);
243 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
245 if (safe_create_leading_directories_const(sb_repo.buf))
246 die_errno(_("could not create leading directories of '%s'"),
248 while (!stat(sb_repo.buf, &st)) {
250 strbuf_setlen(&sb_repo, len);
251 strbuf_addf(&sb_repo, "%d", counter);
253 name = strrchr(sb_repo.buf, '/') + 1;
257 sigchain_push_common(remove_junk_on_signal);
259 if (mkdir(sb_repo.buf, 0777))
260 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
261 junk_git_dir = xstrdup(sb_repo.buf);
265 * lock the incomplete repo so prune won't delete it, unlock
266 * after the preparation is over.
268 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
269 if (!opts->keep_locked)
270 write_file(sb.buf, "initializing");
272 write_file(sb.buf, "added with --lock");
274 strbuf_addf(&sb_git, "%s/.git", path);
275 if (safe_create_leading_directories_const(sb_git.buf))
276 die_errno(_("could not create leading directories of '%s'"),
278 junk_work_tree = xstrdup(path);
281 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
282 write_file(sb.buf, "%s", real_path(sb_git.buf));
283 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
284 real_path(get_git_common_dir()), name);
286 * This is to keep resolve_ref() happy. We need a valid HEAD
287 * or is_git_directory() will reject the directory. Any value which
288 * looks like an object ID will do since it will be immediately
289 * replaced by the symbolic-ref or update-ref invocation in the new
293 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
294 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
296 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
297 write_file(sb.buf, "../..");
299 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
300 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
304 argv_array_pushl(&cp.args, "update-ref", "HEAD",
305 oid_to_hex(&commit->object.oid), NULL);
307 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
309 cp.env = child_env.argv;
310 ret = run_command(&cp);
314 if (opts->checkout) {
316 argv_array_clear(&cp.args);
317 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
318 cp.env = child_env.argv;
319 ret = run_command(&cp);
325 FREE_AND_NULL(junk_work_tree);
326 FREE_AND_NULL(junk_git_dir);
329 if (ret || !opts->keep_locked) {
331 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
332 unlink_or_warn(sb.buf);
336 * Hook failure does not warrant worktree deletion, so run hook after
337 * is_junk is cleared, but do return appropriate code when hook fails.
339 if (!ret && opts->checkout) {
340 const char *hook = find_hook("post-checkout");
342 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
345 cp.stdout_to_stderr = 1;
349 argv_array_pushl(&cp.args, absolute_path(hook),
350 oid_to_hex(&null_oid),
351 oid_to_hex(&commit->object.oid),
353 ret = run_command(&cp);
357 argv_array_clear(&child_env);
359 strbuf_release(&symref);
360 strbuf_release(&sb_repo);
361 strbuf_release(&sb_git);
365 static void print_preparing_worktree_line(int detach,
367 const char *new_branch,
368 int force_new_branch)
370 if (force_new_branch) {
371 struct commit *commit = lookup_commit_reference_by_name(new_branch);
373 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
375 printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
377 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
378 } else if (new_branch) {
379 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
381 struct strbuf s = STRBUF_INIT;
382 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
384 printf_ln(_("Preparing worktree (checking out '%s')"),
387 struct commit *commit = lookup_commit_reference_by_name(branch);
389 die(_("invalid reference: %s"), branch);
390 printf_ln(_("Preparing worktree (detached HEAD %s)"),
391 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
397 static const char *dwim_branch(const char *path, const char **new_branch)
400 const char *s = worktree_basename(path, &n);
401 const char *branchname = xstrndup(s, n);
402 struct strbuf ref = STRBUF_INIT;
405 if (!strbuf_check_branch_ref(&ref, branchname) &&
406 ref_exists(ref.buf)) {
407 strbuf_release(&ref);
411 *new_branch = branchname;
413 struct object_id oid;
415 unique_tracking_name(*new_branch, &oid);
421 static int add(int ac, const char **av, const char *prefix)
423 struct add_opts opts;
424 const char *new_branch_force = NULL;
427 const char *new_branch = NULL;
428 const char *opt_track = NULL;
429 struct option options[] = {
430 OPT__FORCE(&opts.force,
431 N_("checkout <branch> even if already checked out in other worktree"),
432 PARSE_OPT_NOCOMPLETE),
433 OPT_STRING('b', NULL, &new_branch, N_("branch"),
434 N_("create a new branch")),
435 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
436 N_("create or reset a branch")),
437 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
438 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
439 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
440 OPT_PASSTHRU(0, "track", &opt_track, NULL,
441 N_("set up tracking mode (see git-branch(1))"),
442 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
443 OPT_BOOL(0, "guess-remote", &guess_remote,
444 N_("try to match the new branch name with a remote-tracking branch")),
448 memset(&opts, 0, sizeof(opts));
450 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
451 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
452 die(_("-b, -B, and --detach are mutually exclusive"));
453 if (ac < 1 || ac > 2)
454 usage_with_options(worktree_usage, options);
456 path = prefix_filename(prefix, av[0]);
457 branch = ac < 2 ? "HEAD" : av[1];
459 if (!strcmp(branch, "-"))
462 if (new_branch_force) {
463 struct strbuf symref = STRBUF_INIT;
465 new_branch = new_branch_force;
468 !strbuf_check_branch_ref(&symref, new_branch) &&
469 ref_exists(symref.buf))
470 die_if_checked_out(symref.buf, 0);
471 strbuf_release(&symref);
474 if (ac < 2 && !new_branch && !opts.detach) {
475 const char *s = dwim_branch(path, &new_branch);
480 if (ac == 2 && !new_branch && !opts.detach) {
481 struct object_id oid;
482 struct commit *commit;
485 commit = lookup_commit_reference_by_name(branch);
487 remote = unique_tracking_name(branch, &oid);
495 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
498 struct child_process cp = CHILD_PROCESS_INIT;
500 argv_array_push(&cp.args, "branch");
501 if (new_branch_force)
502 argv_array_push(&cp.args, "--force");
503 argv_array_push(&cp.args, new_branch);
504 argv_array_push(&cp.args, branch);
506 argv_array_push(&cp.args, opt_track);
507 if (run_command(&cp))
510 } else if (opt_track) {
511 die(_("--[no-]track can only be used if a new branch is created"));
516 return add_worktree(path, branch, &opts);
519 static void show_worktree_porcelain(struct worktree *wt)
521 printf("worktree %s\n", wt->path);
525 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
527 printf("detached\n");
528 else if (wt->head_ref)
529 printf("branch %s\n", wt->head_ref);
534 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
536 struct strbuf sb = STRBUF_INIT;
537 int cur_path_len = strlen(wt->path);
538 int path_adj = cur_path_len - utf8_strwidth(wt->path);
540 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
542 strbuf_addstr(&sb, "(bare)");
544 strbuf_addf(&sb, "%-*s ", abbrev_len,
545 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
547 strbuf_addstr(&sb, "(detached HEAD)");
548 else if (wt->head_ref) {
549 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
550 strbuf_addf(&sb, "[%s]", ref);
553 strbuf_addstr(&sb, "(error)");
555 printf("%s\n", sb.buf);
560 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
564 for (i = 0; wt[i]; i++) {
566 int path_len = strlen(wt[i]->path);
568 if (path_len > *maxlen)
570 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
571 if (sha1_len > *abbrev)
576 static int list(int ac, const char **av, const char *prefix)
580 struct option options[] = {
581 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
585 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
587 usage_with_options(worktree_usage, options);
589 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
590 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
593 measure_widths(worktrees, &abbrev, &path_maxlen);
595 for (i = 0; worktrees[i]; i++) {
597 show_worktree_porcelain(worktrees[i]);
599 show_worktree(worktrees[i], path_maxlen, abbrev);
601 free_worktrees(worktrees);
606 static int lock_worktree(int ac, const char **av, const char *prefix)
608 const char *reason = "", *old_reason;
609 struct option options[] = {
610 OPT_STRING(0, "reason", &reason, N_("string"),
611 N_("reason for locking")),
614 struct worktree **worktrees, *wt;
616 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
618 usage_with_options(worktree_usage, options);
620 worktrees = get_worktrees(0);
621 wt = find_worktree(worktrees, prefix, av[0]);
623 die(_("'%s' is not a working tree"), av[0]);
624 if (is_main_worktree(wt))
625 die(_("The main working tree cannot be locked or unlocked"));
627 old_reason = is_worktree_locked(wt);
630 die(_("'%s' is already locked, reason: %s"),
632 die(_("'%s' is already locked"), av[0]);
635 write_file(git_common_path("worktrees/%s/locked", wt->id),
637 free_worktrees(worktrees);
641 static int unlock_worktree(int ac, const char **av, const char *prefix)
643 struct option options[] = {
646 struct worktree **worktrees, *wt;
649 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
651 usage_with_options(worktree_usage, options);
653 worktrees = get_worktrees(0);
654 wt = find_worktree(worktrees, prefix, av[0]);
656 die(_("'%s' is not a working tree"), av[0]);
657 if (is_main_worktree(wt))
658 die(_("The main working tree cannot be locked or unlocked"));
659 if (!is_worktree_locked(wt))
660 die(_("'%s' is not locked"), av[0]);
661 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
662 free_worktrees(worktrees);
666 static void validate_no_submodules(const struct worktree *wt)
668 struct index_state istate = { NULL };
669 int i, found_submodules = 0;
671 if (read_index_from(&istate, worktree_git_path(wt, "index"),
672 get_worktree_git_dir(wt)) > 0) {
673 for (i = 0; i < istate.cache_nr; i++) {
674 struct cache_entry *ce = istate.cache[i];
676 if (S_ISGITLINK(ce->ce_mode)) {
677 found_submodules = 1;
682 discard_index(&istate);
684 if (found_submodules)
685 die(_("working trees containing submodules cannot be moved or removed"));
688 static int move_worktree(int ac, const char **av, const char *prefix)
690 struct option options[] = {
693 struct worktree **worktrees, *wt;
694 struct strbuf dst = STRBUF_INIT;
695 struct strbuf errmsg = STRBUF_INIT;
699 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
701 usage_with_options(worktree_usage, options);
703 path = prefix_filename(prefix, av[1]);
704 strbuf_addstr(&dst, path);
707 worktrees = get_worktrees(0);
708 wt = find_worktree(worktrees, prefix, av[0]);
710 die(_("'%s' is not a working tree"), av[0]);
711 if (is_main_worktree(wt))
712 die(_("'%s' is a main working tree"), av[0]);
713 if (is_directory(dst.buf)) {
714 const char *sep = find_last_dir_sep(wt->path);
717 die(_("could not figure out destination name from '%s'"),
719 strbuf_trim_trailing_dir_sep(&dst);
720 strbuf_addstr(&dst, sep);
722 if (file_exists(dst.buf))
723 die(_("target '%s' already exists"), dst.buf);
725 validate_no_submodules(wt);
727 reason = is_worktree_locked(wt);
730 die(_("cannot move a locked working tree, lock reason: %s"),
732 die(_("cannot move a locked working tree"));
734 if (validate_worktree(wt, &errmsg, 0))
735 die(_("validation failed, cannot move working tree: %s"),
737 strbuf_release(&errmsg);
739 if (rename(wt->path, dst.buf) == -1)
740 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
742 update_worktree_location(wt, dst.buf);
744 strbuf_release(&dst);
745 free_worktrees(worktrees);
750 * Note, "git status --porcelain" is used to determine if it's safe to
751 * delete a whole worktree. "git status" does not ignore user
752 * configuration, so if a normal "git status" shows "clean" for the
753 * user, then it's ok to remove it.
755 * This assumption may be a bad one. We may want to ignore
756 * (potentially bad) user settings and only delete a worktree when
757 * it's absolutely safe to do so from _our_ point of view because we
760 static void check_clean_worktree(struct worktree *wt,
761 const char *original_path)
763 struct argv_array child_env = ARGV_ARRAY_INIT;
764 struct child_process cp;
769 * Until we sort this out, all submodules are "dirty" and
770 * will abort this function.
772 validate_no_submodules(wt);
774 argv_array_pushf(&child_env, "%s=%s/.git",
775 GIT_DIR_ENVIRONMENT, wt->path);
776 argv_array_pushf(&child_env, "%s=%s",
777 GIT_WORK_TREE_ENVIRONMENT, wt->path);
778 memset(&cp, 0, sizeof(cp));
779 argv_array_pushl(&cp.args, "status",
780 "--porcelain", "--ignore-submodules=none",
782 cp.env = child_env.argv;
786 ret = start_command(&cp);
788 die_errno(_("failed to run 'git status' on '%s'"),
790 ret = xread(cp.out, buf, sizeof(buf));
792 die(_("'%s' is dirty, use --force to delete it"),
795 ret = finish_command(&cp);
797 die_errno(_("failed to run 'git status' on '%s', code %d"),
801 static int delete_git_work_tree(struct worktree *wt)
803 struct strbuf sb = STRBUF_INIT;
806 strbuf_addstr(&sb, wt->path);
807 if (remove_dir_recursively(&sb, 0)) {
808 error_errno(_("failed to delete '%s'"), sb.buf);
815 static int delete_git_dir(struct worktree *wt)
817 struct strbuf sb = STRBUF_INIT;
820 strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
821 if (remove_dir_recursively(&sb, 0)) {
822 error_errno(_("failed to delete '%s'"), sb.buf);
829 static int remove_worktree(int ac, const char **av, const char *prefix)
832 struct option options[] = {
834 N_("force removing even if the worktree is dirty"),
835 PARSE_OPT_NOCOMPLETE),
838 struct worktree **worktrees, *wt;
839 struct strbuf errmsg = STRBUF_INIT;
843 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
845 usage_with_options(worktree_usage, options);
847 worktrees = get_worktrees(0);
848 wt = find_worktree(worktrees, prefix, av[0]);
850 die(_("'%s' is not a working tree"), av[0]);
851 if (is_main_worktree(wt))
852 die(_("'%s' is a main working tree"), av[0]);
853 reason = is_worktree_locked(wt);
856 die(_("cannot remove a locked working tree, lock reason: %s"),
858 die(_("cannot remove a locked working tree"));
860 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
861 die(_("validation failed, cannot remove working tree: %s"),
863 strbuf_release(&errmsg);
865 if (file_exists(wt->path)) {
867 check_clean_worktree(wt, av[0]);
869 ret |= delete_git_work_tree(wt);
872 * continue on even if ret is non-zero, there's no going back
875 ret |= delete_git_dir(wt);
877 free_worktrees(worktrees);
881 int cmd_worktree(int ac, const char **av, const char *prefix)
883 struct option options[] = {
887 git_config(git_worktree_config, NULL);
890 usage_with_options(worktree_usage, options);
893 if (!strcmp(av[1], "add"))
894 return add(ac - 1, av + 1, prefix);
895 if (!strcmp(av[1], "prune"))
896 return prune(ac - 1, av + 1, prefix);
897 if (!strcmp(av[1], "list"))
898 return list(ac - 1, av + 1, prefix);
899 if (!strcmp(av[1], "lock"))
900 return lock_worktree(ac - 1, av + 1, prefix);
901 if (!strcmp(av[1], "unlock"))
902 return unlock_worktree(ac - 1, av + 1, prefix);
903 if (!strcmp(av[1], "move"))
904 return move_worktree(ac - 1, av + 1, prefix);
905 if (!strcmp(av[1], "remove"))
906 return remove_worktree(ac - 1, av + 1, prefix);
907 usage_with_options(worktree_usage, options);