8 #include "environment.h"
11 #include "parse-options.h"
16 #include "run-command.h"
19 #include "submodule.h"
25 #define BUILTIN_WORKTREE_ADD_USAGE \
26 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
27 " [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
29 #define BUILTIN_WORKTREE_LIST_USAGE \
30 N_("git worktree list [-v | --porcelain [-z]]")
31 #define BUILTIN_WORKTREE_LOCK_USAGE \
32 N_("git worktree lock [--reason <string>] <worktree>")
33 #define BUILTIN_WORKTREE_MOVE_USAGE \
34 N_("git worktree move <worktree> <new-path>")
35 #define BUILTIN_WORKTREE_PRUNE_USAGE \
36 N_("git worktree prune [-n] [-v] [--expire <expire>]")
37 #define BUILTIN_WORKTREE_REMOVE_USAGE \
38 N_("git worktree remove [-f] <worktree>")
39 #define BUILTIN_WORKTREE_REPAIR_USAGE \
40 N_("git worktree repair [<path>...]")
41 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
42 N_("git worktree unlock <worktree>")
44 #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \
45 _("No possible source branch, inferring '--orphan'")
47 #define WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT \
48 _("If you meant to create a worktree containing a new orphan branch\n" \
49 "(branch with no commits) for this repository, you can do so\n" \
50 "using the --orphan flag:\n" \
52 " git worktree add --orphan -b %s %s\n")
54 #define WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT \
55 _("If you meant to create a worktree containing a new orphan branch\n" \
56 "(branch with no commits) for this repository, you can do so\n" \
57 "using the --orphan flag:\n" \
59 " git worktree add --orphan %s\n")
61 static const char * const git_worktree_usage
[] = {
62 BUILTIN_WORKTREE_ADD_USAGE
,
63 BUILTIN_WORKTREE_LIST_USAGE
,
64 BUILTIN_WORKTREE_LOCK_USAGE
,
65 BUILTIN_WORKTREE_MOVE_USAGE
,
66 BUILTIN_WORKTREE_PRUNE_USAGE
,
67 BUILTIN_WORKTREE_REMOVE_USAGE
,
68 BUILTIN_WORKTREE_REPAIR_USAGE
,
69 BUILTIN_WORKTREE_UNLOCK_USAGE
,
73 static const char * const git_worktree_add_usage
[] = {
74 BUILTIN_WORKTREE_ADD_USAGE
,
78 static const char * const git_worktree_list_usage
[] = {
79 BUILTIN_WORKTREE_LIST_USAGE
,
83 static const char * const git_worktree_lock_usage
[] = {
84 BUILTIN_WORKTREE_LOCK_USAGE
,
88 static const char * const git_worktree_move_usage
[] = {
89 BUILTIN_WORKTREE_MOVE_USAGE
,
93 static const char * const git_worktree_prune_usage
[] = {
94 BUILTIN_WORKTREE_PRUNE_USAGE
,
98 static const char * const git_worktree_remove_usage
[] = {
99 BUILTIN_WORKTREE_REMOVE_USAGE
,
103 static const char * const git_worktree_repair_usage
[] = {
104 BUILTIN_WORKTREE_REPAIR_USAGE
,
108 static const char * const git_worktree_unlock_usage
[] = {
109 BUILTIN_WORKTREE_UNLOCK_USAGE
,
119 const char *keep_locked
;
122 static int show_only
;
124 static int guess_remote
;
125 static timestamp_t expire
;
127 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
129 if (!strcmp(var
, "worktree.guessremote")) {
130 guess_remote
= git_config_bool(var
, value
);
134 return git_default_config(var
, value
, cb
);
137 static int delete_git_dir(const char *id
)
139 struct strbuf sb
= STRBUF_INIT
;
142 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
143 ret
= remove_dir_recursively(&sb
, 0);
144 if (ret
< 0 && errno
== ENOTDIR
)
145 ret
= unlink(sb
.buf
);
147 error_errno(_("failed to delete '%s'"), sb
.buf
);
152 static void delete_worktrees_dir_if_empty(void)
154 rmdir(git_path("worktrees")); /* ignore failed removal */
157 static void prune_worktree(const char *id
, const char *reason
)
159 if (show_only
|| verbose
)
160 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
165 static int prune_cmp(const void *a
, const void *b
)
167 const struct string_list_item
*x
= a
;
168 const struct string_list_item
*y
= b
;
171 if ((c
= fspathcmp(x
->string
, y
->string
)))
174 * paths same; prune_dupes() removes all but the first worktree entry
175 * having the same path, so sort main worktree ('util' is NULL) above
176 * linked worktrees ('util' not NULL) since main worktree can't be
183 /* paths same; sort by .git/worktrees/<id> */
184 return strcmp(x
->util
, y
->util
);
187 static void prune_dups(struct string_list
*l
)
191 QSORT(l
->items
, l
->nr
, prune_cmp
);
192 for (i
= 1; i
< l
->nr
; i
++) {
193 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
194 prune_worktree(l
->items
[i
].util
, "duplicate entry");
198 static void prune_worktrees(void)
200 struct strbuf reason
= STRBUF_INIT
;
201 struct strbuf main_path
= STRBUF_INIT
;
202 struct string_list kept
= STRING_LIST_INIT_DUP
;
203 DIR *dir
= opendir(git_path("worktrees"));
207 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
209 strbuf_reset(&reason
);
210 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
211 prune_worktree(d
->d_name
, reason
.buf
);
213 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
217 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
218 /* massage main worktree absolute path to match 'gitdir' content */
219 strbuf_strip_suffix(&main_path
, "/.");
220 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
222 string_list_clear(&kept
, 1);
225 delete_worktrees_dir_if_empty();
226 strbuf_release(&reason
);
229 static int prune(int ac
, const char **av
, const char *prefix
)
231 struct option options
[] = {
232 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
233 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
234 OPT_EXPIRY_DATE(0, "expire", &expire
,
235 N_("expire working trees older than <time>")),
240 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
243 usage_with_options(git_worktree_prune_usage
, options
);
248 static char *junk_work_tree
;
249 static char *junk_git_dir
;
251 static pid_t junk_pid
;
253 static void remove_junk(void)
255 struct strbuf sb
= STRBUF_INIT
;
256 if (!is_junk
|| getpid() != junk_pid
)
259 strbuf_addstr(&sb
, junk_git_dir
);
260 remove_dir_recursively(&sb
, 0);
263 if (junk_work_tree
) {
264 strbuf_addstr(&sb
, junk_work_tree
);
265 remove_dir_recursively(&sb
, 0);
270 static void remove_junk_on_signal(int signo
)
277 static const char *worktree_basename(const char *path
, int *olen
)
283 while (len
&& is_dir_sep(path
[len
- 1]))
286 for (name
= path
+ len
- 1; name
> path
; name
--)
287 if (is_dir_sep(*name
)) {
296 /* check that path is viable location for worktree */
297 static void check_candidate_path(const char *path
,
299 struct worktree
**worktrees
,
305 if (file_exists(path
) && !is_empty_dir(path
))
306 die(_("'%s' already exists"), path
);
308 wt
= find_worktree_by_path(worktrees
, path
);
312 locked
= !!worktree_lock_reason(wt
);
313 if ((!locked
&& force
) || (locked
&& force
> 1)) {
314 if (delete_git_dir(wt
->id
))
315 die(_("unusable worktree destination '%s'"), path
);
320 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
322 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
325 static void copy_sparse_checkout(const char *worktree_git_dir
)
327 char *from_file
= git_pathdup("info/sparse-checkout");
328 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
330 if (file_exists(from_file
)) {
331 if (safe_create_leading_directories(to_file
) ||
332 copy_file(to_file
, from_file
, 0666))
333 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
341 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
343 char *from_file
= git_pathdup("config.worktree");
344 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
346 if (file_exists(from_file
)) {
347 struct config_set cs
= { { 0 } };
350 if (safe_create_leading_directories(to_file
) ||
351 copy_file(to_file
, from_file
, 0666)) {
352 error(_("failed to copy worktree config from '%s' to '%s'"),
354 goto worktree_copy_cleanup
;
357 git_configset_init(&cs
);
358 git_configset_add_file(&cs
, from_file
);
360 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
362 git_config_set_multivar_in_file_gently(
363 to_file
, "core.bare", NULL
, "true", 0))
364 error(_("failed to unset '%s' in '%s'"),
365 "core.bare", to_file
);
366 if (!git_configset_get(&cs
, "core.worktree") &&
367 git_config_set_in_file_gently(to_file
,
368 "core.worktree", NULL
))
369 error(_("failed to unset '%s' in '%s'"),
370 "core.worktree", to_file
);
372 git_configset_clear(&cs
);
375 worktree_copy_cleanup
:
380 static int checkout_worktree(const struct add_opts
*opts
,
381 struct strvec
*child_env
)
383 struct child_process cp
= CHILD_PROCESS_INIT
;
385 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
387 strvec_push(&cp
.args
, "--quiet");
388 strvec_pushv(&cp
.env
, child_env
->v
);
389 return run_command(&cp
);
392 static int make_worktree_orphan(const char * ref
, const struct add_opts
*opts
,
393 struct strvec
*child_env
)
395 struct strbuf symref
= STRBUF_INIT
;
396 struct child_process cp
= CHILD_PROCESS_INIT
;
398 validate_new_branchname(ref
, &symref
, 0);
399 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD", symref
.buf
, NULL
);
401 strvec_push(&cp
.args
, "--quiet");
402 strvec_pushv(&cp
.env
, child_env
->v
);
403 strbuf_release(&symref
);
405 return run_command(&cp
);
408 static int add_worktree(const char *path
, const char *refname
,
409 const struct add_opts
*opts
)
411 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
412 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_INIT
;
414 struct child_process cp
= CHILD_PROCESS_INIT
;
415 struct strvec child_env
= STRVEC_INIT
;
416 unsigned int counter
= 0;
418 struct strbuf symref
= STRBUF_INIT
;
419 struct commit
*commit
= NULL
;
421 struct strbuf sb_name
= STRBUF_INIT
;
422 struct worktree
**worktrees
;
424 worktrees
= get_worktrees();
425 check_candidate_path(path
, opts
->force
, worktrees
, "add");
426 free_worktrees(worktrees
);
429 /* is 'refname' a branch or commit? */
430 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
431 ref_exists(symref
.buf
)) {
434 die_if_checked_out(symref
.buf
, 0);
436 commit
= lookup_commit_reference_by_name(refname
);
437 if (!commit
&& !opts
->orphan
)
438 die(_("invalid reference: %s"), refname
);
440 name
= worktree_basename(path
, &len
);
441 strbuf_add(&sb
, name
, path
+ len
- name
);
442 sanitize_refname_component(sb
.buf
, &sb_name
);
444 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
447 git_path_buf(&sb_repo
, "worktrees/%s", name
);
449 if (safe_create_leading_directories_const(sb_repo
.buf
))
450 die_errno(_("could not create leading directories of '%s'"),
453 while (mkdir(sb_repo
.buf
, 0777)) {
455 if ((errno
!= EEXIST
) || !counter
/* overflow */)
456 die_errno(_("could not create directory of '%s'"),
458 strbuf_setlen(&sb_repo
, len
);
459 strbuf_addf(&sb_repo
, "%d", counter
);
461 name
= strrchr(sb_repo
.buf
, '/') + 1;
465 sigchain_push_common(remove_junk_on_signal
);
467 junk_git_dir
= xstrdup(sb_repo
.buf
);
471 * lock the incomplete repo so prune won't delete it, unlock
472 * after the preparation is over.
474 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
475 if (opts
->keep_locked
)
476 write_file(sb
.buf
, "%s", opts
->keep_locked
);
478 write_file(sb
.buf
, _("initializing"));
480 strbuf_addf(&sb_git
, "%s/.git", path
);
481 if (safe_create_leading_directories_const(sb_git
.buf
))
482 die_errno(_("could not create leading directories of '%s'"),
484 junk_work_tree
= xstrdup(path
);
487 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
488 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
489 write_file(sb
.buf
, "%s", realpath
.buf
);
490 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
491 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
494 * This is to keep resolve_ref() happy. We need a valid HEAD
495 * or is_git_directory() will reject the directory. Any value which
496 * looks like an object ID will do since it will be immediately
497 * replaced by the symbolic-ref or update-ref invocation in the new
501 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
502 write_file(sb
.buf
, "%s", oid_to_hex(null_oid()));
504 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
505 write_file(sb
.buf
, "../..");
508 * If the current worktree has sparse-checkout enabled, then copy
509 * the sparse-checkout patterns from the current worktree.
511 if (core_apply_sparse_checkout
)
512 copy_sparse_checkout(sb_repo
.buf
);
515 * If we are using worktree config, then copy all current config
516 * values from the current worktree into the new one, that way the
517 * new worktree behaves the same as this one.
519 if (repository_format_worktree_config
)
520 copy_filtered_worktree_config(sb_repo
.buf
);
522 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
523 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
526 if (!is_branch
&& commit
) {
527 strvec_pushl(&cp
.args
, "update-ref", "HEAD",
528 oid_to_hex(&commit
->object
.oid
), NULL
);
530 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD",
533 strvec_push(&cp
.args
, "--quiet");
536 strvec_pushv(&cp
.env
, child_env
.v
);
537 ret
= run_command(&cp
);
542 (ret
= make_worktree_orphan(refname
, opts
, &child_env
)))
545 if (opts
->checkout
&&
546 (ret
= checkout_worktree(opts
, &child_env
)))
550 FREE_AND_NULL(junk_work_tree
);
551 FREE_AND_NULL(junk_git_dir
);
554 if (ret
|| !opts
->keep_locked
) {
556 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
557 unlink_or_warn(sb
.buf
);
561 * Hook failure does not warrant worktree deletion, so run hook after
562 * is_junk is cleared, but do return appropriate code when hook fails.
564 if (!ret
&& opts
->checkout
&& !opts
->orphan
) {
565 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
567 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
568 strvec_pushl(&opt
.args
,
569 oid_to_hex(null_oid()),
570 oid_to_hex(&commit
->object
.oid
),
575 ret
= run_hooks_opt("post-checkout", &opt
);
578 strvec_clear(&child_env
);
580 strbuf_release(&symref
);
581 strbuf_release(&sb_repo
);
582 strbuf_release(&sb_git
);
583 strbuf_release(&sb_name
);
584 strbuf_release(&realpath
);
588 static void print_preparing_worktree_line(int detach
,
590 const char *new_branch
,
591 int force_new_branch
)
593 if (force_new_branch
) {
594 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
596 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
598 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
600 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
601 } else if (new_branch
) {
602 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
604 struct strbuf s
= STRBUF_INIT
;
605 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
607 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
610 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
612 BUG(_("unreachable: invalid reference: %s"), branch
);
613 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
614 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
621 * Callback to short circuit iteration over refs on the first reference
622 * corresponding to a valid oid.
624 * Returns 0 on failure and non-zero on success.
626 static int first_valid_ref(const char *refname
,
627 const struct object_id
*oid
,
635 * Verifies HEAD and determines whether there exist any valid local references.
637 * - Checks whether HEAD points to a valid reference.
639 * - Checks whether any valid local branches exist.
641 * - Emits a warning if there exist any valid branches but HEAD does not point
642 * to a valid reference.
644 * Returns 1 if any of the previous checks are true, otherwise returns 0.
646 static int can_use_local_refs(const struct add_opts
*opts
)
648 if (head_ref(first_valid_ref
, NULL
)) {
650 } else if (for_each_branch_ref(first_valid_ref
, NULL
)) {
652 struct strbuf path
= STRBUF_INIT
;
653 struct strbuf contents
= STRBUF_INIT
;
655 strbuf_add_real_path(&path
, get_worktree_git_dir(NULL
));
656 strbuf_addstr(&path
, "/HEAD");
657 strbuf_read_file(&contents
, path
.buf
, 64);
658 strbuf_stripspace(&contents
, 0);
659 strbuf_strip_suffix(&contents
, "\n");
661 warning(_("HEAD points to an invalid (or orphaned) reference.\n"
663 "HEAD contents: '%s'"),
664 path
.buf
, contents
.buf
);
665 strbuf_release(&path
);
666 strbuf_release(&contents
);
674 * Reports whether the necessary flags were set and whether the repository has
675 * remote references to attempt DWIM tracking of upstream branches.
677 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
679 * 2. Checks whether any valid remote branches exist.
681 * 3. Checks that there exists at least one remote and emits a warning/error
682 * if both checks 1. and 2. are false (can be bypassed with `--force`).
684 * Returns 1 if checks 1. and 2. are true, otherwise 0.
686 static int can_use_remote_refs(const struct add_opts
*opts
)
690 } else if (for_each_remote_ref(first_valid_ref
, NULL
)) {
692 } else if (!opts
->force
&& remote_get(NULL
)) {
693 die(_("No local or remote refs exist despite at least one remote\n"
694 "present, stopping; use 'add -f' to override or fetch a remote first"));
700 * Determines whether `--orphan` should be inferred in the evaluation of
701 * `worktree add path/` or `worktree add -b branch path/` and emits an error
702 * if the supplied arguments would produce an illegal combination when the
703 * `--orphan` flag is included.
705 * `opts` and `opt_track` contain the other options & flags supplied to the
708 * remote determines whether to check `can_use_remote_refs()` or not. This
709 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
711 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
712 * `--orphan` is inferred but doing so produces an illegal combination of
713 * options and flags. Additionally produces an error when remote refs are
714 * checked and the repo is in a state that looks like the user added a remote
715 * but forgot to fetch (and did not override the warning with -f).
717 static int dwim_orphan(const struct add_opts
*opts
, int opt_track
, int remote
)
719 if (can_use_local_refs(opts
)) {
721 } else if (remote
&& can_use_remote_refs(opts
)) {
723 } else if (!opts
->quiet
) {
724 fprintf_ln(stderr
, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT
);
728 die(_("'%s' and '%s' cannot be used together"), "--orphan",
730 } else if (!opts
->checkout
) {
731 die(_("'%s' and '%s' cannot be used together"), "--orphan",
737 static const char *dwim_branch(const char *path
, const char **new_branch
)
741 const char *s
= worktree_basename(path
, &n
);
742 const char *branchname
= xstrndup(s
, n
);
743 struct strbuf ref
= STRBUF_INIT
;
747 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
749 strbuf_release(&ref
);
753 *new_branch
= branchname
;
755 struct object_id oid
;
757 unique_tracking_name(*new_branch
, &oid
, NULL
);
763 static int add(int ac
, const char **av
, const char *prefix
)
765 struct add_opts opts
;
766 const char *new_branch_force
= NULL
;
769 const char *new_branch
= NULL
;
770 const char *opt_track
= NULL
;
771 const char *lock_reason
= NULL
;
773 int used_new_branch_options
;
774 struct option options
[] = {
775 OPT__FORCE(&opts
.force
,
776 N_("checkout <branch> even if already checked out in other worktree"),
777 PARSE_OPT_NOCOMPLETE
),
778 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
779 N_("create a new branch")),
780 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
781 N_("create or reset a branch")),
782 OPT_BOOL(0, "orphan", &opts
.orphan
, N_("create unborn/orphaned branch")),
783 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
784 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
785 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
786 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
787 N_("reason for locking")),
788 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
789 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
790 N_("set up tracking mode (see git-branch(1))"),
791 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
792 OPT_BOOL(0, "guess-remote", &guess_remote
,
793 N_("try to match the new branch name with a remote-tracking branch")),
798 memset(&opts
, 0, sizeof(opts
));
800 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
801 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
802 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
803 if (opts
.detach
&& opts
.orphan
)
804 die(_("options '%s', and '%s' cannot be used together"),
805 "--orphan", "--detach");
806 if (opts
.orphan
&& opt_track
)
807 die(_("'%s' and '%s' cannot be used together"), "--orphan", "--track");
808 if (opts
.orphan
&& !opts
.checkout
)
809 die(_("'%s' and '%s' cannot be used together"), "--orphan",
811 if (opts
.orphan
&& ac
== 2)
812 die(_("'%s' and '%s' cannot be used together"), "--orphan",
814 if (lock_reason
&& !keep_locked
)
815 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
817 opts
.keep_locked
= lock_reason
;
818 else if (keep_locked
)
819 opts
.keep_locked
= _("added with --lock");
821 if (ac
< 1 || ac
> 2)
822 usage_with_options(git_worktree_add_usage
, options
);
824 path
= prefix_filename(prefix
, av
[0]);
825 branch
= ac
< 2 ? "HEAD" : av
[1];
826 used_new_branch_options
= new_branch
|| new_branch_force
;
828 if (!strcmp(branch
, "-"))
831 if (new_branch_force
) {
832 struct strbuf symref
= STRBUF_INIT
;
834 new_branch
= new_branch_force
;
837 !strbuf_check_branch_ref(&symref
, new_branch
) &&
838 ref_exists(symref
.buf
))
839 die_if_checked_out(symref
.buf
, 0);
840 strbuf_release(&symref
);
843 if (opts
.orphan
&& !new_branch
) {
845 const char *s
= worktree_basename(path
, &n
);
846 new_branch
= xstrndup(s
, n
);
847 } else if (opts
.orphan
) {
849 } else if (opts
.detach
) {
851 if (!strcmp(branch
, "HEAD"))
852 can_use_local_refs(&opts
);
853 } else if (ac
< 2 && new_branch
) {
854 // DWIM: Infer --orphan when repo has no refs.
855 opts
.orphan
= dwim_orphan(&opts
, !!opt_track
, 0);
857 // DWIM: Guess branch name from path.
858 const char *s
= dwim_branch(path
, &new_branch
);
862 // DWIM: Infer --orphan when repo has no refs.
863 opts
.orphan
= (!s
) && dwim_orphan(&opts
, !!opt_track
, 1);
864 } else if (ac
== 2) {
865 struct object_id oid
;
866 struct commit
*commit
;
869 commit
= lookup_commit_reference_by_name(branch
);
871 remote
= unique_tracking_name(branch
, &oid
, NULL
);
878 if (!strcmp(branch
, "HEAD"))
879 can_use_local_refs(&opts
);
883 if (!opts
.orphan
&& !lookup_commit_reference_by_name(branch
)) {
884 int attempt_hint
= !opts
.quiet
&& (ac
< 2);
885 if (attempt_hint
&& used_new_branch_options
) {
886 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
887 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT
,
889 } else if (attempt_hint
) {
890 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
891 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT
, path
);
893 die(_("invalid reference: %s"), branch
);
897 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
901 } else if (new_branch
) {
902 struct child_process cp
= CHILD_PROCESS_INIT
;
904 strvec_push(&cp
.args
, "branch");
905 if (new_branch_force
)
906 strvec_push(&cp
.args
, "--force");
908 strvec_push(&cp
.args
, "--quiet");
909 strvec_push(&cp
.args
, new_branch
);
910 strvec_push(&cp
.args
, branch
);
912 strvec_push(&cp
.args
, opt_track
);
913 if (run_command(&cp
))
916 } else if (opt_track
) {
917 die(_("--[no-]track can only be used if a new branch is created"));
920 ret
= add_worktree(path
, branch
, &opts
);
925 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
929 printf("worktree %s%c", wt
->path
, line_terminator
);
931 printf("bare%c", line_terminator
);
933 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
935 printf("detached%c", line_terminator
);
936 else if (wt
->head_ref
)
937 printf("branch %s%c", wt
->head_ref
, line_terminator
);
940 reason
= worktree_lock_reason(wt
);
942 fputs("locked", stdout
);
945 write_name_quoted(reason
, stdout
, line_terminator
);
947 fputc(line_terminator
, stdout
);
951 reason
= worktree_prune_reason(wt
, expire
);
953 printf("prunable %s%c", reason
, line_terminator
);
955 fputc(line_terminator
, stdout
);
958 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
960 struct strbuf sb
= STRBUF_INIT
;
961 int cur_path_len
= strlen(wt
->path
);
962 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
965 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
967 strbuf_addstr(&sb
, "(bare)");
969 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
970 repo_find_unique_abbrev(the_repository
, &wt
->head_oid
, DEFAULT_ABBREV
));
972 strbuf_addstr(&sb
, "(detached HEAD)");
973 else if (wt
->head_ref
) {
974 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
975 strbuf_addf(&sb
, "[%s]", ref
);
978 strbuf_addstr(&sb
, "(error)");
981 reason
= worktree_lock_reason(wt
);
982 if (verbose
&& reason
&& *reason
)
983 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
985 strbuf_addstr(&sb
, " locked");
987 reason
= worktree_prune_reason(wt
, expire
);
988 if (verbose
&& reason
)
989 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
991 strbuf_addstr(&sb
, " prunable");
993 printf("%s\n", sb
.buf
);
997 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
1001 for (i
= 0; wt
[i
]; i
++) {
1003 int path_len
= strlen(wt
[i
]->path
);
1005 if (path_len
> *maxlen
)
1007 sha1_len
= strlen(repo_find_unique_abbrev(the_repository
, &wt
[i
]->head_oid
, *abbrev
));
1008 if (sha1_len
> *abbrev
)
1013 static int pathcmp(const void *a_
, const void *b_
)
1015 const struct worktree
*const *a
= a_
;
1016 const struct worktree
*const *b
= b_
;
1017 return fspathcmp((*a
)->path
, (*b
)->path
);
1020 static void pathsort(struct worktree
**wt
)
1023 struct worktree
**p
= wt
;
1027 QSORT(wt
, n
, pathcmp
);
1030 static int list(int ac
, const char **av
, const char *prefix
)
1033 int line_terminator
= '\n';
1035 struct option options
[] = {
1036 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
1037 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
1038 OPT_EXPIRY_DATE(0, "expire", &expire
,
1039 N_("add 'prunable' annotation to worktrees older than <time>")),
1040 OPT_SET_INT('z', NULL
, &line_terminator
,
1041 N_("terminate records with a NUL character"), '\0'),
1046 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
1048 usage_with_options(git_worktree_list_usage
, options
);
1049 else if (verbose
&& porcelain
)
1050 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1051 else if (!line_terminator
&& !porcelain
)
1052 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1054 struct worktree
**worktrees
= get_worktrees();
1055 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
1057 /* sort worktrees by path but keep main worktree at top */
1058 pathsort(worktrees
+ 1);
1061 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
1063 for (i
= 0; worktrees
[i
]; i
++) {
1065 show_worktree_porcelain(worktrees
[i
],
1068 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
1070 free_worktrees(worktrees
);
1075 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
1077 const char *reason
= "", *old_reason
;
1078 struct option options
[] = {
1079 OPT_STRING(0, "reason", &reason
, N_("string"),
1080 N_("reason for locking")),
1083 struct worktree
**worktrees
, *wt
;
1085 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
1087 usage_with_options(git_worktree_lock_usage
, options
);
1089 worktrees
= get_worktrees();
1090 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1092 die(_("'%s' is not a working tree"), av
[0]);
1093 if (is_main_worktree(wt
))
1094 die(_("The main working tree cannot be locked or unlocked"));
1096 old_reason
= worktree_lock_reason(wt
);
1099 die(_("'%s' is already locked, reason: %s"),
1101 die(_("'%s' is already locked"), av
[0]);
1104 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
1106 free_worktrees(worktrees
);
1110 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
1112 struct option options
[] = {
1115 struct worktree
**worktrees
, *wt
;
1118 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
1120 usage_with_options(git_worktree_unlock_usage
, options
);
1122 worktrees
= get_worktrees();
1123 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1125 die(_("'%s' is not a working tree"), av
[0]);
1126 if (is_main_worktree(wt
))
1127 die(_("The main working tree cannot be locked or unlocked"));
1128 if (!worktree_lock_reason(wt
))
1129 die(_("'%s' is not locked"), av
[0]);
1130 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
1131 free_worktrees(worktrees
);
1135 static void validate_no_submodules(const struct worktree
*wt
)
1137 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1138 struct strbuf path
= STRBUF_INIT
;
1139 int i
, found_submodules
= 0;
1141 if (is_directory(worktree_git_path(wt
, "modules"))) {
1143 * There could be false positives, e.g. the "modules"
1144 * directory exists but is empty. But it's a rare case and
1145 * this simpler check is probably good enough for now.
1147 found_submodules
= 1;
1148 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
1149 get_worktree_git_dir(wt
)) > 0) {
1150 for (i
= 0; i
< istate
.cache_nr
; i
++) {
1151 struct cache_entry
*ce
= istate
.cache
[i
];
1154 if (!S_ISGITLINK(ce
->ce_mode
))
1157 strbuf_reset(&path
);
1158 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
1159 if (!is_submodule_populated_gently(path
.buf
, &err
))
1162 found_submodules
= 1;
1166 discard_index(&istate
);
1167 strbuf_release(&path
);
1169 if (found_submodules
)
1170 die(_("working trees containing submodules cannot be moved or removed"));
1173 static int move_worktree(int ac
, const char **av
, const char *prefix
)
1176 struct option options
[] = {
1178 N_("force move even if worktree is dirty or locked"),
1179 PARSE_OPT_NOCOMPLETE
),
1182 struct worktree
**worktrees
, *wt
;
1183 struct strbuf dst
= STRBUF_INIT
;
1184 struct strbuf errmsg
= STRBUF_INIT
;
1185 const char *reason
= NULL
;
1188 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
1191 usage_with_options(git_worktree_move_usage
, options
);
1193 path
= prefix_filename(prefix
, av
[1]);
1194 strbuf_addstr(&dst
, path
);
1197 worktrees
= get_worktrees();
1198 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1200 die(_("'%s' is not a working tree"), av
[0]);
1201 if (is_main_worktree(wt
))
1202 die(_("'%s' is a main working tree"), av
[0]);
1203 if (is_directory(dst
.buf
)) {
1204 const char *sep
= find_last_dir_sep(wt
->path
);
1207 die(_("could not figure out destination name from '%s'"),
1209 strbuf_trim_trailing_dir_sep(&dst
);
1210 strbuf_addstr(&dst
, sep
);
1212 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1214 validate_no_submodules(wt
);
1217 reason
= worktree_lock_reason(wt
);
1220 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1222 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1224 if (validate_worktree(wt
, &errmsg
, 0))
1225 die(_("validation failed, cannot move working tree: %s"),
1227 strbuf_release(&errmsg
);
1229 if (rename(wt
->path
, dst
.buf
) == -1)
1230 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1232 update_worktree_location(wt
, dst
.buf
);
1234 strbuf_release(&dst
);
1235 free_worktrees(worktrees
);
1240 * Note, "git status --porcelain" is used to determine if it's safe to
1241 * delete a whole worktree. "git status" does not ignore user
1242 * configuration, so if a normal "git status" shows "clean" for the
1243 * user, then it's ok to remove it.
1245 * This assumption may be a bad one. We may want to ignore
1246 * (potentially bad) user settings and only delete a worktree when
1247 * it's absolutely safe to do so from _our_ point of view because we
1250 static void check_clean_worktree(struct worktree
*wt
,
1251 const char *original_path
)
1253 struct child_process cp
;
1258 * Until we sort this out, all submodules are "dirty" and
1259 * will abort this function.
1261 validate_no_submodules(wt
);
1263 child_process_init(&cp
);
1264 strvec_pushf(&cp
.env
, "%s=%s/.git",
1265 GIT_DIR_ENVIRONMENT
, wt
->path
);
1266 strvec_pushf(&cp
.env
, "%s=%s",
1267 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1268 strvec_pushl(&cp
.args
, "status",
1269 "--porcelain", "--ignore-submodules=none",
1274 ret
= start_command(&cp
);
1276 die_errno(_("failed to run 'git status' on '%s'"),
1278 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1280 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1283 ret
= finish_command(&cp
);
1285 die_errno(_("failed to run 'git status' on '%s', code %d"),
1286 original_path
, ret
);
1289 static int delete_git_work_tree(struct worktree
*wt
)
1291 struct strbuf sb
= STRBUF_INIT
;
1294 strbuf_addstr(&sb
, wt
->path
);
1295 if (remove_dir_recursively(&sb
, 0)) {
1296 error_errno(_("failed to delete '%s'"), sb
.buf
);
1299 strbuf_release(&sb
);
1303 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1306 struct option options
[] = {
1308 N_("force removal even if worktree is dirty or locked"),
1309 PARSE_OPT_NOCOMPLETE
),
1312 struct worktree
**worktrees
, *wt
;
1313 struct strbuf errmsg
= STRBUF_INIT
;
1314 const char *reason
= NULL
;
1317 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1319 usage_with_options(git_worktree_remove_usage
, options
);
1321 worktrees
= get_worktrees();
1322 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1324 die(_("'%s' is not a working tree"), av
[0]);
1325 if (is_main_worktree(wt
))
1326 die(_("'%s' is a main working tree"), av
[0]);
1328 reason
= worktree_lock_reason(wt
);
1331 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1333 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1335 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1336 die(_("validation failed, cannot remove working tree: %s"),
1338 strbuf_release(&errmsg
);
1340 if (file_exists(wt
->path
)) {
1342 check_clean_worktree(wt
, av
[0]);
1344 ret
|= delete_git_work_tree(wt
);
1347 * continue on even if ret is non-zero, there's no going back
1350 ret
|= delete_git_dir(wt
->id
);
1351 delete_worktrees_dir_if_empty();
1353 free_worktrees(worktrees
);
1357 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1360 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1362 int *exit_status
= (int *)cb_data
;
1363 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1368 static int repair(int ac
, const char **av
, const char *prefix
)
1371 const char *self
[] = { ".", NULL
};
1372 struct option options
[] = {
1377 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1378 p
= ac
> 0 ? av
: self
;
1380 repair_worktree_at_path(*p
, report_repair
, &rc
);
1381 repair_worktrees(report_repair
, &rc
);
1385 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1387 parse_opt_subcommand_fn
*fn
= NULL
;
1388 struct option options
[] = {
1389 OPT_SUBCOMMAND("add", &fn
, add
),
1390 OPT_SUBCOMMAND("prune", &fn
, prune
),
1391 OPT_SUBCOMMAND("list", &fn
, list
),
1392 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1393 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1394 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1395 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1396 OPT_SUBCOMMAND("repair", &fn
, repair
),
1400 git_config(git_worktree_config
, NULL
);
1405 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1406 return fn(ac
, av
, prefix
);