9 #include "environment.h"
12 #include "object-file.h"
13 #include "object-name.h"
14 #include "parse-options.h"
19 #include "repository.h"
20 #include "run-command.h"
23 #include "submodule.h"
29 #define BUILTIN_WORKTREE_ADD_USAGE \
30 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
31 " [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
33 #define BUILTIN_WORKTREE_LIST_USAGE \
34 N_("git worktree list [-v | --porcelain [-z]]")
35 #define BUILTIN_WORKTREE_LOCK_USAGE \
36 N_("git worktree lock [--reason <string>] <worktree>")
37 #define BUILTIN_WORKTREE_MOVE_USAGE \
38 N_("git worktree move <worktree> <new-path>")
39 #define BUILTIN_WORKTREE_PRUNE_USAGE \
40 N_("git worktree prune [-n] [-v] [--expire <expire>]")
41 #define BUILTIN_WORKTREE_REMOVE_USAGE \
42 N_("git worktree remove [-f] <worktree>")
43 #define BUILTIN_WORKTREE_REPAIR_USAGE \
44 N_("git worktree repair [<path>...]")
45 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
46 N_("git worktree unlock <worktree>")
48 #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \
49 _("No possible source branch, inferring '--orphan'")
51 #define WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT \
52 _("If you meant to create a worktree containing a new orphan branch\n" \
53 "(branch with no commits) for this repository, you can do so\n" \
54 "using the --orphan flag:\n" \
56 " git worktree add --orphan -b %s %s\n")
58 #define WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT \
59 _("If you meant to create a worktree containing a new orphan branch\n" \
60 "(branch with no commits) for this repository, you can do so\n" \
61 "using the --orphan flag:\n" \
63 " git worktree add --orphan %s\n")
65 static const char * const git_worktree_usage
[] = {
66 BUILTIN_WORKTREE_ADD_USAGE
,
67 BUILTIN_WORKTREE_LIST_USAGE
,
68 BUILTIN_WORKTREE_LOCK_USAGE
,
69 BUILTIN_WORKTREE_MOVE_USAGE
,
70 BUILTIN_WORKTREE_PRUNE_USAGE
,
71 BUILTIN_WORKTREE_REMOVE_USAGE
,
72 BUILTIN_WORKTREE_REPAIR_USAGE
,
73 BUILTIN_WORKTREE_UNLOCK_USAGE
,
77 static const char * const git_worktree_add_usage
[] = {
78 BUILTIN_WORKTREE_ADD_USAGE
,
82 static const char * const git_worktree_list_usage
[] = {
83 BUILTIN_WORKTREE_LIST_USAGE
,
87 static const char * const git_worktree_lock_usage
[] = {
88 BUILTIN_WORKTREE_LOCK_USAGE
,
92 static const char * const git_worktree_move_usage
[] = {
93 BUILTIN_WORKTREE_MOVE_USAGE
,
97 static const char * const git_worktree_prune_usage
[] = {
98 BUILTIN_WORKTREE_PRUNE_USAGE
,
102 static const char * const git_worktree_remove_usage
[] = {
103 BUILTIN_WORKTREE_REMOVE_USAGE
,
107 static const char * const git_worktree_repair_usage
[] = {
108 BUILTIN_WORKTREE_REPAIR_USAGE
,
112 static const char * const git_worktree_unlock_usage
[] = {
113 BUILTIN_WORKTREE_UNLOCK_USAGE
,
123 const char *keep_locked
;
126 static int show_only
;
128 static int guess_remote
;
129 static timestamp_t expire
;
131 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
133 if (!strcmp(var
, "worktree.guessremote")) {
134 guess_remote
= git_config_bool(var
, value
);
138 return git_default_config(var
, value
, cb
);
141 static int delete_git_dir(const char *id
)
143 struct strbuf sb
= STRBUF_INIT
;
146 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
147 ret
= remove_dir_recursively(&sb
, 0);
148 if (ret
< 0 && errno
== ENOTDIR
)
149 ret
= unlink(sb
.buf
);
151 error_errno(_("failed to delete '%s'"), sb
.buf
);
156 static void delete_worktrees_dir_if_empty(void)
158 rmdir(git_path("worktrees")); /* ignore failed removal */
161 static void prune_worktree(const char *id
, const char *reason
)
163 if (show_only
|| verbose
)
164 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
169 static int prune_cmp(const void *a
, const void *b
)
171 const struct string_list_item
*x
= a
;
172 const struct string_list_item
*y
= b
;
175 if ((c
= fspathcmp(x
->string
, y
->string
)))
178 * paths same; prune_dupes() removes all but the first worktree entry
179 * having the same path, so sort main worktree ('util' is NULL) above
180 * linked worktrees ('util' not NULL) since main worktree can't be
187 /* paths same; sort by .git/worktrees/<id> */
188 return strcmp(x
->util
, y
->util
);
191 static void prune_dups(struct string_list
*l
)
195 QSORT(l
->items
, l
->nr
, prune_cmp
);
196 for (i
= 1; i
< l
->nr
; i
++) {
197 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
198 prune_worktree(l
->items
[i
].util
, "duplicate entry");
202 static void prune_worktrees(void)
204 struct strbuf reason
= STRBUF_INIT
;
205 struct strbuf main_path
= STRBUF_INIT
;
206 struct string_list kept
= STRING_LIST_INIT_DUP
;
207 DIR *dir
= opendir(git_path("worktrees"));
211 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
213 strbuf_reset(&reason
);
214 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
215 prune_worktree(d
->d_name
, reason
.buf
);
217 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
221 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
222 /* massage main worktree absolute path to match 'gitdir' content */
223 strbuf_strip_suffix(&main_path
, "/.");
224 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
226 string_list_clear(&kept
, 1);
229 delete_worktrees_dir_if_empty();
230 strbuf_release(&reason
);
233 static int prune(int ac
, const char **av
, const char *prefix
)
235 struct option options
[] = {
236 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
237 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
238 OPT_EXPIRY_DATE(0, "expire", &expire
,
239 N_("expire working trees older than <time>")),
244 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
247 usage_with_options(git_worktree_prune_usage
, options
);
252 static char *junk_work_tree
;
253 static char *junk_git_dir
;
255 static pid_t junk_pid
;
257 static void remove_junk(void)
259 struct strbuf sb
= STRBUF_INIT
;
260 if (!is_junk
|| getpid() != junk_pid
)
263 strbuf_addstr(&sb
, junk_git_dir
);
264 remove_dir_recursively(&sb
, 0);
267 if (junk_work_tree
) {
268 strbuf_addstr(&sb
, junk_work_tree
);
269 remove_dir_recursively(&sb
, 0);
274 static void remove_junk_on_signal(int signo
)
281 static const char *worktree_basename(const char *path
, int *olen
)
287 while (len
&& is_dir_sep(path
[len
- 1]))
290 for (name
= path
+ len
- 1; name
> path
; name
--)
291 if (is_dir_sep(*name
)) {
300 /* check that path is viable location for worktree */
301 static void check_candidate_path(const char *path
,
303 struct worktree
**worktrees
,
309 if (file_exists(path
) && !is_empty_dir(path
))
310 die(_("'%s' already exists"), path
);
312 wt
= find_worktree_by_path(worktrees
, path
);
316 locked
= !!worktree_lock_reason(wt
);
317 if ((!locked
&& force
) || (locked
&& force
> 1)) {
318 if (delete_git_dir(wt
->id
))
319 die(_("unusable worktree destination '%s'"), path
);
324 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
326 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
329 static void copy_sparse_checkout(const char *worktree_git_dir
)
331 char *from_file
= git_pathdup("info/sparse-checkout");
332 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
334 if (file_exists(from_file
)) {
335 if (safe_create_leading_directories(to_file
) ||
336 copy_file(to_file
, from_file
, 0666))
337 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
345 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
347 char *from_file
= git_pathdup("config.worktree");
348 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
350 if (file_exists(from_file
)) {
351 struct config_set cs
= { { 0 } };
354 if (safe_create_leading_directories(to_file
) ||
355 copy_file(to_file
, from_file
, 0666)) {
356 error(_("failed to copy worktree config from '%s' to '%s'"),
358 goto worktree_copy_cleanup
;
361 git_configset_init(&cs
);
362 git_configset_add_file(&cs
, from_file
);
364 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
366 git_config_set_multivar_in_file_gently(
367 to_file
, "core.bare", NULL
, "true", 0))
368 error(_("failed to unset '%s' in '%s'"),
369 "core.bare", to_file
);
370 if (!git_configset_get(&cs
, "core.worktree") &&
371 git_config_set_in_file_gently(to_file
,
372 "core.worktree", NULL
))
373 error(_("failed to unset '%s' in '%s'"),
374 "core.worktree", to_file
);
376 git_configset_clear(&cs
);
379 worktree_copy_cleanup
:
384 static int checkout_worktree(const struct add_opts
*opts
,
385 struct strvec
*child_env
)
387 struct child_process cp
= CHILD_PROCESS_INIT
;
389 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
391 strvec_push(&cp
.args
, "--quiet");
392 strvec_pushv(&cp
.env
, child_env
->v
);
393 return run_command(&cp
);
396 static int make_worktree_orphan(const char * ref
, const struct add_opts
*opts
,
397 struct strvec
*child_env
)
399 struct strbuf symref
= STRBUF_INIT
;
400 struct child_process cp
= CHILD_PROCESS_INIT
;
402 validate_new_branchname(ref
, &symref
, 0);
403 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD", symref
.buf
, NULL
);
405 strvec_push(&cp
.args
, "--quiet");
406 strvec_pushv(&cp
.env
, child_env
->v
);
407 strbuf_release(&symref
);
409 return run_command(&cp
);
412 static int add_worktree(const char *path
, const char *refname
,
413 const struct add_opts
*opts
)
415 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
416 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_INIT
;
418 struct child_process cp
= CHILD_PROCESS_INIT
;
419 struct strvec child_env
= STRVEC_INIT
;
420 unsigned int counter
= 0;
422 struct strbuf symref
= STRBUF_INIT
;
423 struct commit
*commit
= NULL
;
425 struct strbuf sb_name
= STRBUF_INIT
;
426 struct worktree
**worktrees
;
428 worktrees
= get_worktrees();
429 check_candidate_path(path
, opts
->force
, worktrees
, "add");
430 free_worktrees(worktrees
);
433 /* is 'refname' a branch or commit? */
434 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
435 ref_exists(symref
.buf
)) {
438 die_if_checked_out(symref
.buf
, 0);
440 commit
= lookup_commit_reference_by_name(refname
);
441 if (!commit
&& !opts
->orphan
)
442 die(_("invalid reference: %s"), refname
);
444 name
= worktree_basename(path
, &len
);
445 strbuf_add(&sb
, name
, path
+ len
- name
);
446 sanitize_refname_component(sb
.buf
, &sb_name
);
448 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
451 git_path_buf(&sb_repo
, "worktrees/%s", name
);
453 if (safe_create_leading_directories_const(sb_repo
.buf
))
454 die_errno(_("could not create leading directories of '%s'"),
457 while (mkdir(sb_repo
.buf
, 0777)) {
459 if ((errno
!= EEXIST
) || !counter
/* overflow */)
460 die_errno(_("could not create directory of '%s'"),
462 strbuf_setlen(&sb_repo
, len
);
463 strbuf_addf(&sb_repo
, "%d", counter
);
465 name
= strrchr(sb_repo
.buf
, '/') + 1;
469 sigchain_push_common(remove_junk_on_signal
);
471 junk_git_dir
= xstrdup(sb_repo
.buf
);
475 * lock the incomplete repo so prune won't delete it, unlock
476 * after the preparation is over.
478 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
479 if (opts
->keep_locked
)
480 write_file(sb
.buf
, "%s", opts
->keep_locked
);
482 write_file(sb
.buf
, _("initializing"));
484 strbuf_addf(&sb_git
, "%s/.git", path
);
485 if (safe_create_leading_directories_const(sb_git
.buf
))
486 die_errno(_("could not create leading directories of '%s'"),
488 junk_work_tree
= xstrdup(path
);
491 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
492 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
493 write_file(sb
.buf
, "%s", realpath
.buf
);
494 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
495 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
498 * This is to keep resolve_ref() happy. We need a valid HEAD
499 * or is_git_directory() will reject the directory. Any value which
500 * looks like an object ID will do since it will be immediately
501 * replaced by the symbolic-ref or update-ref invocation in the new
505 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
506 write_file(sb
.buf
, "%s", oid_to_hex(null_oid()));
508 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
509 write_file(sb
.buf
, "../..");
512 * If the current worktree has sparse-checkout enabled, then copy
513 * the sparse-checkout patterns from the current worktree.
515 if (core_apply_sparse_checkout
)
516 copy_sparse_checkout(sb_repo
.buf
);
519 * If we are using worktree config, then copy all current config
520 * values from the current worktree into the new one, that way the
521 * new worktree behaves the same as this one.
523 if (the_repository
->repository_format_worktree_config
)
524 copy_filtered_worktree_config(sb_repo
.buf
);
526 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
527 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
530 if (!is_branch
&& commit
) {
531 strvec_pushl(&cp
.args
, "update-ref", "HEAD",
532 oid_to_hex(&commit
->object
.oid
), NULL
);
534 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD",
537 strvec_push(&cp
.args
, "--quiet");
540 strvec_pushv(&cp
.env
, child_env
.v
);
541 ret
= run_command(&cp
);
546 (ret
= make_worktree_orphan(refname
, opts
, &child_env
)))
549 if (opts
->checkout
&&
550 (ret
= checkout_worktree(opts
, &child_env
)))
554 FREE_AND_NULL(junk_work_tree
);
555 FREE_AND_NULL(junk_git_dir
);
558 if (ret
|| !opts
->keep_locked
) {
560 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
561 unlink_or_warn(sb
.buf
);
565 * Hook failure does not warrant worktree deletion, so run hook after
566 * is_junk is cleared, but do return appropriate code when hook fails.
568 if (!ret
&& opts
->checkout
&& !opts
->orphan
) {
569 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
571 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
572 strvec_pushl(&opt
.args
,
573 oid_to_hex(null_oid()),
574 oid_to_hex(&commit
->object
.oid
),
579 ret
= run_hooks_opt("post-checkout", &opt
);
582 strvec_clear(&child_env
);
584 strbuf_release(&symref
);
585 strbuf_release(&sb_repo
);
586 strbuf_release(&sb_git
);
587 strbuf_release(&sb_name
);
588 strbuf_release(&realpath
);
592 static void print_preparing_worktree_line(int detach
,
594 const char *new_branch
,
595 int force_new_branch
)
597 if (force_new_branch
) {
598 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
600 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
602 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
604 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
605 } else if (new_branch
) {
606 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
608 struct strbuf s
= STRBUF_INIT
;
609 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
611 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
614 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
616 BUG(_("unreachable: invalid reference: %s"), branch
);
617 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
618 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
625 * Callback to short circuit iteration over refs on the first reference
626 * corresponding to a valid oid.
628 * Returns 0 on failure and non-zero on success.
630 static int first_valid_ref(const char *refname
,
631 const struct object_id
*oid
,
639 * Verifies HEAD and determines whether there exist any valid local references.
641 * - Checks whether HEAD points to a valid reference.
643 * - Checks whether any valid local branches exist.
645 * - Emits a warning if there exist any valid branches but HEAD does not point
646 * to a valid reference.
648 * Returns 1 if any of the previous checks are true, otherwise returns 0.
650 static int can_use_local_refs(const struct add_opts
*opts
)
652 if (head_ref(first_valid_ref
, NULL
)) {
654 } else if (for_each_branch_ref(first_valid_ref
, NULL
)) {
656 struct strbuf path
= STRBUF_INIT
;
657 struct strbuf contents
= STRBUF_INIT
;
659 strbuf_add_real_path(&path
, get_worktree_git_dir(NULL
));
660 strbuf_addstr(&path
, "/HEAD");
661 strbuf_read_file(&contents
, path
.buf
, 64);
662 strbuf_stripspace(&contents
, 0);
663 strbuf_strip_suffix(&contents
, "\n");
665 warning(_("HEAD points to an invalid (or orphaned) reference.\n"
667 "HEAD contents: '%s'"),
668 path
.buf
, contents
.buf
);
669 strbuf_release(&path
);
670 strbuf_release(&contents
);
678 * Reports whether the necessary flags were set and whether the repository has
679 * remote references to attempt DWIM tracking of upstream branches.
681 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
683 * 2. Checks whether any valid remote branches exist.
685 * 3. Checks that there exists at least one remote and emits a warning/error
686 * if both checks 1. and 2. are false (can be bypassed with `--force`).
688 * Returns 1 if checks 1. and 2. are true, otherwise 0.
690 static int can_use_remote_refs(const struct add_opts
*opts
)
694 } else if (for_each_remote_ref(first_valid_ref
, NULL
)) {
696 } else if (!opts
->force
&& remote_get(NULL
)) {
697 die(_("No local or remote refs exist despite at least one remote\n"
698 "present, stopping; use 'add -f' to overide or fetch a remote first"));
704 * Determines whether `--orphan` should be inferred in the evaluation of
705 * `worktree add path/` or `worktree add -b branch path/` and emits an error
706 * if the supplied arguments would produce an illegal combination when the
707 * `--orphan` flag is included.
709 * `opts` and `opt_track` contain the other options & flags supplied to the
712 * remote determines whether to check `can_use_remote_refs()` or not. This
713 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
715 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
716 * `--orphan` is inferred but doing so produces an illegal combination of
717 * options and flags. Additionally produces an error when remote refs are
718 * checked and the repo is in a state that looks like the user added a remote
719 * but forgot to fetch (and did not override the warning with -f).
721 static int dwim_orphan(const struct add_opts
*opts
, int opt_track
, int remote
)
723 if (can_use_local_refs(opts
)) {
725 } else if (remote
&& can_use_remote_refs(opts
)) {
727 } else if (!opts
->quiet
) {
728 fprintf_ln(stderr
, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT
);
732 die(_("'%s' and '%s' cannot be used together"), "--orphan",
734 } else if (!opts
->checkout
) {
735 die(_("'%s' and '%s' cannot be used together"), "--orphan",
741 static const char *dwim_branch(const char *path
, const char **new_branch
)
745 const char *s
= worktree_basename(path
, &n
);
746 const char *branchname
= xstrndup(s
, n
);
747 struct strbuf ref
= STRBUF_INIT
;
751 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
753 strbuf_release(&ref
);
757 *new_branch
= branchname
;
759 struct object_id oid
;
761 unique_tracking_name(*new_branch
, &oid
, NULL
);
767 static int add(int ac
, const char **av
, const char *prefix
)
769 struct add_opts opts
;
770 const char *new_branch_force
= NULL
;
773 const char *new_branch
= NULL
;
774 const char *opt_track
= NULL
;
775 const char *lock_reason
= NULL
;
777 int used_new_branch_options
;
778 struct option options
[] = {
779 OPT__FORCE(&opts
.force
,
780 N_("checkout <branch> even if already checked out in other worktree"),
781 PARSE_OPT_NOCOMPLETE
),
782 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
783 N_("create a new branch")),
784 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
785 N_("create or reset a branch")),
786 OPT_BOOL(0, "orphan", &opts
.orphan
, N_("create unborn/orphaned branch")),
787 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
788 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
789 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
790 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
791 N_("reason for locking")),
792 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
793 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
794 N_("set up tracking mode (see git-branch(1))"),
795 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
796 OPT_BOOL(0, "guess-remote", &guess_remote
,
797 N_("try to match the new branch name with a remote-tracking branch")),
802 memset(&opts
, 0, sizeof(opts
));
804 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
805 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
806 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
807 if (opts
.detach
&& opts
.orphan
)
808 die(_("options '%s', and '%s' cannot be used together"),
809 "--orphan", "--detach");
810 if (opts
.orphan
&& opt_track
)
811 die(_("'%s' and '%s' cannot be used together"), "--orphan", "--track");
812 if (opts
.orphan
&& !opts
.checkout
)
813 die(_("'%s' and '%s' cannot be used together"), "--orphan",
815 if (opts
.orphan
&& ac
== 2)
816 die(_("'%s' and '%s' cannot be used together"), "--orphan",
818 if (lock_reason
&& !keep_locked
)
819 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
821 opts
.keep_locked
= lock_reason
;
822 else if (keep_locked
)
823 opts
.keep_locked
= _("added with --lock");
825 if (ac
< 1 || ac
> 2)
826 usage_with_options(git_worktree_add_usage
, options
);
828 path
= prefix_filename(prefix
, av
[0]);
829 branch
= ac
< 2 ? "HEAD" : av
[1];
830 used_new_branch_options
= new_branch
|| new_branch_force
;
832 if (!strcmp(branch
, "-"))
835 if (new_branch_force
) {
836 struct strbuf symref
= STRBUF_INIT
;
838 new_branch
= new_branch_force
;
841 !strbuf_check_branch_ref(&symref
, new_branch
) &&
842 ref_exists(symref
.buf
))
843 die_if_checked_out(symref
.buf
, 0);
844 strbuf_release(&symref
);
847 if (opts
.orphan
&& !new_branch
) {
849 const char *s
= worktree_basename(path
, &n
);
850 new_branch
= xstrndup(s
, n
);
851 } else if (opts
.orphan
) {
853 } else if (opts
.detach
) {
855 if (!strcmp(branch
, "HEAD"))
856 can_use_local_refs(&opts
);
857 } else if (ac
< 2 && new_branch
) {
858 // DWIM: Infer --orphan when repo has no refs.
859 opts
.orphan
= dwim_orphan(&opts
, !!opt_track
, 0);
861 // DWIM: Guess branch name from path.
862 const char *s
= dwim_branch(path
, &new_branch
);
866 // DWIM: Infer --orphan when repo has no refs.
867 opts
.orphan
= (!s
) && dwim_orphan(&opts
, !!opt_track
, 1);
868 } else if (ac
== 2) {
869 struct object_id oid
;
870 struct commit
*commit
;
873 commit
= lookup_commit_reference_by_name(branch
);
875 remote
= unique_tracking_name(branch
, &oid
, NULL
);
882 if (!strcmp(branch
, "HEAD"))
883 can_use_local_refs(&opts
);
887 if (!opts
.orphan
&& !lookup_commit_reference_by_name(branch
)) {
888 int attempt_hint
= !opts
.quiet
&& (ac
< 2);
889 if (attempt_hint
&& used_new_branch_options
) {
890 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
891 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT
,
893 } else if (attempt_hint
) {
894 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
895 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT
, path
);
897 die(_("invalid reference: %s"), branch
);
901 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
905 } else if (new_branch
) {
906 struct child_process cp
= CHILD_PROCESS_INIT
;
908 strvec_push(&cp
.args
, "branch");
909 if (new_branch_force
)
910 strvec_push(&cp
.args
, "--force");
912 strvec_push(&cp
.args
, "--quiet");
913 strvec_push(&cp
.args
, new_branch
);
914 strvec_push(&cp
.args
, branch
);
916 strvec_push(&cp
.args
, opt_track
);
917 if (run_command(&cp
))
920 } else if (opt_track
) {
921 die(_("--[no-]track can only be used if a new branch is created"));
924 ret
= add_worktree(path
, branch
, &opts
);
929 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
933 printf("worktree %s%c", wt
->path
, line_terminator
);
935 printf("bare%c", line_terminator
);
937 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
939 printf("detached%c", line_terminator
);
940 else if (wt
->head_ref
)
941 printf("branch %s%c", wt
->head_ref
, line_terminator
);
944 reason
= worktree_lock_reason(wt
);
946 fputs("locked", stdout
);
949 write_name_quoted(reason
, stdout
, line_terminator
);
951 fputc(line_terminator
, stdout
);
955 reason
= worktree_prune_reason(wt
, expire
);
957 printf("prunable %s%c", reason
, line_terminator
);
959 fputc(line_terminator
, stdout
);
962 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
964 struct strbuf sb
= STRBUF_INIT
;
965 int cur_path_len
= strlen(wt
->path
);
966 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
969 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
971 strbuf_addstr(&sb
, "(bare)");
973 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
974 repo_find_unique_abbrev(the_repository
, &wt
->head_oid
, DEFAULT_ABBREV
));
976 strbuf_addstr(&sb
, "(detached HEAD)");
977 else if (wt
->head_ref
) {
978 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
979 strbuf_addf(&sb
, "[%s]", ref
);
982 strbuf_addstr(&sb
, "(error)");
985 reason
= worktree_lock_reason(wt
);
986 if (verbose
&& reason
&& *reason
)
987 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
989 strbuf_addstr(&sb
, " locked");
991 reason
= worktree_prune_reason(wt
, expire
);
992 if (verbose
&& reason
)
993 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
995 strbuf_addstr(&sb
, " prunable");
997 printf("%s\n", sb
.buf
);
1001 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
1005 for (i
= 0; wt
[i
]; i
++) {
1007 int path_len
= strlen(wt
[i
]->path
);
1009 if (path_len
> *maxlen
)
1011 sha1_len
= strlen(repo_find_unique_abbrev(the_repository
, &wt
[i
]->head_oid
, *abbrev
));
1012 if (sha1_len
> *abbrev
)
1017 static int pathcmp(const void *a_
, const void *b_
)
1019 const struct worktree
*const *a
= a_
;
1020 const struct worktree
*const *b
= b_
;
1021 return fspathcmp((*a
)->path
, (*b
)->path
);
1024 static void pathsort(struct worktree
**wt
)
1027 struct worktree
**p
= wt
;
1031 QSORT(wt
, n
, pathcmp
);
1034 static int list(int ac
, const char **av
, const char *prefix
)
1037 int line_terminator
= '\n';
1039 struct option options
[] = {
1040 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
1041 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
1042 OPT_EXPIRY_DATE(0, "expire", &expire
,
1043 N_("add 'prunable' annotation to worktrees older than <time>")),
1044 OPT_SET_INT('z', NULL
, &line_terminator
,
1045 N_("terminate records with a NUL character"), '\0'),
1050 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
1052 usage_with_options(git_worktree_list_usage
, options
);
1053 else if (verbose
&& porcelain
)
1054 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1055 else if (!line_terminator
&& !porcelain
)
1056 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1058 struct worktree
**worktrees
= get_worktrees();
1059 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
1061 /* sort worktrees by path but keep main worktree at top */
1062 pathsort(worktrees
+ 1);
1065 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
1067 for (i
= 0; worktrees
[i
]; i
++) {
1069 show_worktree_porcelain(worktrees
[i
],
1072 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
1074 free_worktrees(worktrees
);
1079 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
1081 const char *reason
= "", *old_reason
;
1082 struct option options
[] = {
1083 OPT_STRING(0, "reason", &reason
, N_("string"),
1084 N_("reason for locking")),
1087 struct worktree
**worktrees
, *wt
;
1089 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
1091 usage_with_options(git_worktree_lock_usage
, options
);
1093 worktrees
= get_worktrees();
1094 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1096 die(_("'%s' is not a working tree"), av
[0]);
1097 if (is_main_worktree(wt
))
1098 die(_("The main working tree cannot be locked or unlocked"));
1100 old_reason
= worktree_lock_reason(wt
);
1103 die(_("'%s' is already locked, reason: %s"),
1105 die(_("'%s' is already locked"), av
[0]);
1108 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
1110 free_worktrees(worktrees
);
1114 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
1116 struct option options
[] = {
1119 struct worktree
**worktrees
, *wt
;
1122 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
1124 usage_with_options(git_worktree_unlock_usage
, options
);
1126 worktrees
= get_worktrees();
1127 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1129 die(_("'%s' is not a working tree"), av
[0]);
1130 if (is_main_worktree(wt
))
1131 die(_("The main working tree cannot be locked or unlocked"));
1132 if (!worktree_lock_reason(wt
))
1133 die(_("'%s' is not locked"), av
[0]);
1134 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
1135 free_worktrees(worktrees
);
1139 static void validate_no_submodules(const struct worktree
*wt
)
1141 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1142 struct strbuf path
= STRBUF_INIT
;
1143 int i
, found_submodules
= 0;
1145 if (is_directory(worktree_git_path(wt
, "modules"))) {
1147 * There could be false positives, e.g. the "modules"
1148 * directory exists but is empty. But it's a rare case and
1149 * this simpler check is probably good enough for now.
1151 found_submodules
= 1;
1152 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
1153 get_worktree_git_dir(wt
)) > 0) {
1154 for (i
= 0; i
< istate
.cache_nr
; i
++) {
1155 struct cache_entry
*ce
= istate
.cache
[i
];
1158 if (!S_ISGITLINK(ce
->ce_mode
))
1161 strbuf_reset(&path
);
1162 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
1163 if (!is_submodule_populated_gently(path
.buf
, &err
))
1166 found_submodules
= 1;
1170 discard_index(&istate
);
1171 strbuf_release(&path
);
1173 if (found_submodules
)
1174 die(_("working trees containing submodules cannot be moved or removed"));
1177 static int move_worktree(int ac
, const char **av
, const char *prefix
)
1180 struct option options
[] = {
1182 N_("force move even if worktree is dirty or locked"),
1183 PARSE_OPT_NOCOMPLETE
),
1186 struct worktree
**worktrees
, *wt
;
1187 struct strbuf dst
= STRBUF_INIT
;
1188 struct strbuf errmsg
= STRBUF_INIT
;
1189 const char *reason
= NULL
;
1192 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
1195 usage_with_options(git_worktree_move_usage
, options
);
1197 path
= prefix_filename(prefix
, av
[1]);
1198 strbuf_addstr(&dst
, path
);
1201 worktrees
= get_worktrees();
1202 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1204 die(_("'%s' is not a working tree"), av
[0]);
1205 if (is_main_worktree(wt
))
1206 die(_("'%s' is a main working tree"), av
[0]);
1207 if (is_directory(dst
.buf
)) {
1208 const char *sep
= find_last_dir_sep(wt
->path
);
1211 die(_("could not figure out destination name from '%s'"),
1213 strbuf_trim_trailing_dir_sep(&dst
);
1214 strbuf_addstr(&dst
, sep
);
1216 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1218 validate_no_submodules(wt
);
1221 reason
= worktree_lock_reason(wt
);
1224 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1226 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1228 if (validate_worktree(wt
, &errmsg
, 0))
1229 die(_("validation failed, cannot move working tree: %s"),
1231 strbuf_release(&errmsg
);
1233 if (rename(wt
->path
, dst
.buf
) == -1)
1234 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1236 update_worktree_location(wt
, dst
.buf
);
1238 strbuf_release(&dst
);
1239 free_worktrees(worktrees
);
1244 * Note, "git status --porcelain" is used to determine if it's safe to
1245 * delete a whole worktree. "git status" does not ignore user
1246 * configuration, so if a normal "git status" shows "clean" for the
1247 * user, then it's ok to remove it.
1249 * This assumption may be a bad one. We may want to ignore
1250 * (potentially bad) user settings and only delete a worktree when
1251 * it's absolutely safe to do so from _our_ point of view because we
1254 static void check_clean_worktree(struct worktree
*wt
,
1255 const char *original_path
)
1257 struct child_process cp
;
1262 * Until we sort this out, all submodules are "dirty" and
1263 * will abort this function.
1265 validate_no_submodules(wt
);
1267 child_process_init(&cp
);
1268 strvec_pushf(&cp
.env
, "%s=%s/.git",
1269 GIT_DIR_ENVIRONMENT
, wt
->path
);
1270 strvec_pushf(&cp
.env
, "%s=%s",
1271 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1272 strvec_pushl(&cp
.args
, "status",
1273 "--porcelain", "--ignore-submodules=none",
1278 ret
= start_command(&cp
);
1280 die_errno(_("failed to run 'git status' on '%s'"),
1282 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1284 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1287 ret
= finish_command(&cp
);
1289 die_errno(_("failed to run 'git status' on '%s', code %d"),
1290 original_path
, ret
);
1293 static int delete_git_work_tree(struct worktree
*wt
)
1295 struct strbuf sb
= STRBUF_INIT
;
1298 strbuf_addstr(&sb
, wt
->path
);
1299 if (remove_dir_recursively(&sb
, 0)) {
1300 error_errno(_("failed to delete '%s'"), sb
.buf
);
1303 strbuf_release(&sb
);
1307 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1310 struct option options
[] = {
1312 N_("force removal even if worktree is dirty or locked"),
1313 PARSE_OPT_NOCOMPLETE
),
1316 struct worktree
**worktrees
, *wt
;
1317 struct strbuf errmsg
= STRBUF_INIT
;
1318 const char *reason
= NULL
;
1321 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1323 usage_with_options(git_worktree_remove_usage
, options
);
1325 worktrees
= get_worktrees();
1326 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1328 die(_("'%s' is not a working tree"), av
[0]);
1329 if (is_main_worktree(wt
))
1330 die(_("'%s' is a main working tree"), av
[0]);
1332 reason
= worktree_lock_reason(wt
);
1335 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1337 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1339 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1340 die(_("validation failed, cannot remove working tree: %s"),
1342 strbuf_release(&errmsg
);
1344 if (file_exists(wt
->path
)) {
1346 check_clean_worktree(wt
, av
[0]);
1348 ret
|= delete_git_work_tree(wt
);
1351 * continue on even if ret is non-zero, there's no going back
1354 ret
|= delete_git_dir(wt
->id
);
1355 delete_worktrees_dir_if_empty();
1357 free_worktrees(worktrees
);
1361 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1364 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1366 int *exit_status
= (int *)cb_data
;
1367 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1372 static int repair(int ac
, const char **av
, const char *prefix
)
1375 const char *self
[] = { ".", NULL
};
1376 struct option options
[] = {
1381 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1382 p
= ac
> 0 ? av
: self
;
1384 repair_worktree_at_path(*p
, report_repair
, &rc
);
1385 repair_worktrees(report_repair
, &rc
);
1389 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1391 parse_opt_subcommand_fn
*fn
= NULL
;
1392 struct option options
[] = {
1393 OPT_SUBCOMMAND("add", &fn
, add
),
1394 OPT_SUBCOMMAND("prune", &fn
, prune
),
1395 OPT_SUBCOMMAND("list", &fn
, list
),
1396 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1397 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1398 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1399 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1400 OPT_SUBCOMMAND("repair", &fn
, repair
),
1404 git_config(git_worktree_config
, NULL
);
1409 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1410 return fn(ac
, av
, prefix
);