8 #include "environment.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "parse-options.h"
17 #include "read-cache-ll.h"
20 #include "repository.h"
21 #include "run-command.h"
24 #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 unborn 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 unborn 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
,
132 const struct config_context
*ctx
, void *cb
)
134 if (!strcmp(var
, "worktree.guessremote")) {
135 guess_remote
= git_config_bool(var
, value
);
139 return git_default_config(var
, value
, ctx
, cb
);
142 static int delete_git_dir(const char *id
)
144 struct strbuf sb
= STRBUF_INIT
;
147 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
148 ret
= remove_dir_recursively(&sb
, 0);
149 if (ret
< 0 && errno
== ENOTDIR
)
150 ret
= unlink(sb
.buf
);
152 error_errno(_("failed to delete '%s'"), sb
.buf
);
157 static void delete_worktrees_dir_if_empty(void)
159 rmdir(git_path("worktrees")); /* ignore failed removal */
162 static void prune_worktree(const char *id
, const char *reason
)
164 if (show_only
|| verbose
)
165 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
170 static int prune_cmp(const void *a
, const void *b
)
172 const struct string_list_item
*x
= a
;
173 const struct string_list_item
*y
= b
;
176 if ((c
= fspathcmp(x
->string
, y
->string
)))
179 * paths same; prune_dupes() removes all but the first worktree entry
180 * having the same path, so sort main worktree ('util' is NULL) above
181 * linked worktrees ('util' not NULL) since main worktree can't be
188 /* paths same; sort by .git/worktrees/<id> */
189 return strcmp(x
->util
, y
->util
);
192 static void prune_dups(struct string_list
*l
)
196 QSORT(l
->items
, l
->nr
, prune_cmp
);
197 for (i
= 1; i
< l
->nr
; i
++) {
198 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
199 prune_worktree(l
->items
[i
].util
, "duplicate entry");
203 static void prune_worktrees(void)
205 struct strbuf reason
= STRBUF_INIT
;
206 struct strbuf main_path
= STRBUF_INIT
;
207 struct string_list kept
= STRING_LIST_INIT_DUP
;
208 DIR *dir
= opendir(git_path("worktrees"));
212 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
214 strbuf_reset(&reason
);
215 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
216 prune_worktree(d
->d_name
, reason
.buf
);
218 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
222 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
223 /* massage main worktree absolute path to match 'gitdir' content */
224 strbuf_strip_suffix(&main_path
, "/.");
225 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
227 string_list_clear(&kept
, 1);
230 delete_worktrees_dir_if_empty();
231 strbuf_release(&reason
);
234 static int prune(int ac
, const char **av
, const char *prefix
)
236 struct option options
[] = {
237 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
238 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
239 OPT_EXPIRY_DATE(0, "expire", &expire
,
240 N_("expire working trees older than <time>")),
245 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
248 usage_with_options(git_worktree_prune_usage
, options
);
253 static char *junk_work_tree
;
254 static char *junk_git_dir
;
256 static pid_t junk_pid
;
258 static void remove_junk(void)
260 struct strbuf sb
= STRBUF_INIT
;
261 if (!is_junk
|| getpid() != junk_pid
)
264 strbuf_addstr(&sb
, junk_git_dir
);
265 remove_dir_recursively(&sb
, 0);
268 if (junk_work_tree
) {
269 strbuf_addstr(&sb
, junk_work_tree
);
270 remove_dir_recursively(&sb
, 0);
275 static void remove_junk_on_signal(int signo
)
282 static const char *worktree_basename(const char *path
, int *olen
)
288 while (len
&& is_dir_sep(path
[len
- 1]))
291 for (name
= path
+ len
- 1; name
> path
; name
--)
292 if (is_dir_sep(*name
)) {
301 /* check that path is viable location for worktree */
302 static void check_candidate_path(const char *path
,
304 struct worktree
**worktrees
,
310 if (file_exists(path
) && !is_empty_dir(path
))
311 die(_("'%s' already exists"), path
);
313 wt
= find_worktree_by_path(worktrees
, path
);
317 locked
= !!worktree_lock_reason(wt
);
318 if ((!locked
&& force
) || (locked
&& force
> 1)) {
319 if (delete_git_dir(wt
->id
))
320 die(_("unusable worktree destination '%s'"), path
);
325 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
327 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
330 static void copy_sparse_checkout(const char *worktree_git_dir
)
332 char *from_file
= git_pathdup("info/sparse-checkout");
333 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
335 if (file_exists(from_file
)) {
336 if (safe_create_leading_directories(to_file
) ||
337 copy_file(to_file
, from_file
, 0666))
338 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
346 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
348 char *from_file
= git_pathdup("config.worktree");
349 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
351 if (file_exists(from_file
)) {
352 struct config_set cs
= { { 0 } };
355 if (safe_create_leading_directories(to_file
) ||
356 copy_file(to_file
, from_file
, 0666)) {
357 error(_("failed to copy worktree config from '%s' to '%s'"),
359 goto worktree_copy_cleanup
;
362 git_configset_init(&cs
);
363 git_configset_add_file(&cs
, from_file
);
365 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
367 git_config_set_multivar_in_file_gently(
368 to_file
, "core.bare", NULL
, "true", NULL
, 0))
369 error(_("failed to unset '%s' in '%s'"),
370 "core.bare", to_file
);
371 if (!git_configset_get(&cs
, "core.worktree") &&
372 git_config_set_in_file_gently(to_file
,
373 "core.worktree", NULL
, NULL
))
374 error(_("failed to unset '%s' in '%s'"),
375 "core.worktree", to_file
);
377 git_configset_clear(&cs
);
380 worktree_copy_cleanup
:
385 static int checkout_worktree(const struct add_opts
*opts
,
386 struct strvec
*child_env
)
388 struct child_process cp
= CHILD_PROCESS_INIT
;
390 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
392 strvec_push(&cp
.args
, "--quiet");
393 strvec_pushv(&cp
.env
, child_env
->v
);
394 return run_command(&cp
);
397 static int make_worktree_orphan(const char * ref
, const struct add_opts
*opts
,
398 struct strvec
*child_env
)
400 struct strbuf symref
= STRBUF_INIT
;
401 struct child_process cp
= CHILD_PROCESS_INIT
;
403 validate_new_branchname(ref
, &symref
, 0);
404 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD", symref
.buf
, NULL
);
406 strvec_push(&cp
.args
, "--quiet");
407 strvec_pushv(&cp
.env
, child_env
->v
);
408 strbuf_release(&symref
);
410 return run_command(&cp
);
413 static int add_worktree(const char *path
, const char *refname
,
414 const struct add_opts
*opts
)
416 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
417 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_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
, *wt
= NULL
;
427 struct ref_store
*wt_refs
;
429 worktrees
= get_worktrees();
430 check_candidate_path(path
, opts
->force
, worktrees
, "add");
431 free_worktrees(worktrees
);
434 /* is 'refname' a branch or commit? */
435 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
436 ref_exists(symref
.buf
)) {
439 die_if_checked_out(symref
.buf
, 0);
441 commit
= lookup_commit_reference_by_name(refname
);
442 if (!commit
&& !opts
->orphan
)
443 die(_("invalid reference: %s"), refname
);
445 name
= worktree_basename(path
, &len
);
446 strbuf_add(&sb
, name
, path
+ len
- name
);
447 sanitize_refname_component(sb
.buf
, &sb_name
);
449 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
452 git_path_buf(&sb_repo
, "worktrees/%s", name
);
454 if (safe_create_leading_directories_const(sb_repo
.buf
))
455 die_errno(_("could not create leading directories of '%s'"),
458 while (mkdir(sb_repo
.buf
, 0777)) {
460 if ((errno
!= EEXIST
) || !counter
/* overflow */)
461 die_errno(_("could not create directory of '%s'"),
463 strbuf_setlen(&sb_repo
, len
);
464 strbuf_addf(&sb_repo
, "%d", counter
);
466 name
= strrchr(sb_repo
.buf
, '/') + 1;
470 sigchain_push_common(remove_junk_on_signal
);
472 junk_git_dir
= xstrdup(sb_repo
.buf
);
476 * lock the incomplete repo so prune won't delete it, unlock
477 * after the preparation is over.
479 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
480 if (opts
->keep_locked
)
481 write_file(sb
.buf
, "%s", opts
->keep_locked
);
483 write_file(sb
.buf
, _("initializing"));
485 strbuf_addf(&sb_git
, "%s/.git", path
);
486 if (safe_create_leading_directories_const(sb_git
.buf
))
487 die_errno(_("could not create leading directories of '%s'"),
489 junk_work_tree
= xstrdup(path
);
492 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
493 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
494 write_file(sb
.buf
, "%s", realpath
.buf
);
495 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
496 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
499 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
500 write_file(sb
.buf
, "../..");
503 * Set up the ref store of the worktree and create the HEAD reference.
505 wt
= get_linked_worktree(name
, 1);
507 ret
= error(_("could not find created worktree '%s'"), name
);
510 wt_refs
= get_worktree_ref_store(wt
);
512 ret
= refs_init_db(wt_refs
, REFS_INIT_DB_IS_WORKTREE
, &sb
);
516 if (!is_branch
&& commit
)
517 ret
= refs_update_ref(wt_refs
, NULL
, "HEAD", &commit
->object
.oid
,
518 NULL
, 0, UPDATE_REFS_MSG_ON_ERR
);
520 ret
= refs_create_symref(wt_refs
, "HEAD", symref
.buf
, NULL
);
525 * If the current worktree has sparse-checkout enabled, then copy
526 * the sparse-checkout patterns from the current worktree.
528 if (core_apply_sparse_checkout
)
529 copy_sparse_checkout(sb_repo
.buf
);
532 * If we are using worktree config, then copy all current config
533 * values from the current worktree into the new one, that way the
534 * new worktree behaves the same as this one.
536 if (the_repository
->repository_format_worktree_config
)
537 copy_filtered_worktree_config(sb_repo
.buf
);
539 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
540 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
543 (ret
= make_worktree_orphan(refname
, opts
, &child_env
)))
546 if (opts
->checkout
&&
547 (ret
= checkout_worktree(opts
, &child_env
)))
551 FREE_AND_NULL(junk_work_tree
);
552 FREE_AND_NULL(junk_git_dir
);
555 if (ret
|| !opts
->keep_locked
) {
557 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
558 unlink_or_warn(sb
.buf
);
562 * Hook failure does not warrant worktree deletion, so run hook after
563 * is_junk is cleared, but do return appropriate code when hook fails.
565 if (!ret
&& opts
->checkout
&& !opts
->orphan
) {
566 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
568 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
569 strvec_pushl(&opt
.args
,
570 oid_to_hex(null_oid()),
571 oid_to_hex(&commit
->object
.oid
),
576 ret
= run_hooks_opt("post-checkout", &opt
);
579 strvec_clear(&child_env
);
581 strbuf_release(&symref
);
582 strbuf_release(&sb_repo
);
583 strbuf_release(&sb_git
);
584 strbuf_release(&sb_name
);
585 strbuf_release(&realpath
);
590 static void print_preparing_worktree_line(int detach
,
592 const char *new_branch
,
593 int force_new_branch
)
595 if (force_new_branch
) {
596 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
598 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
600 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
602 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
603 } else if (new_branch
) {
604 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
606 struct strbuf s
= STRBUF_INIT
;
607 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
609 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
612 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
614 BUG(_("unreachable: invalid reference: %s"), branch
);
615 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
616 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
623 * Callback to short circuit iteration over refs on the first reference
624 * corresponding to a valid oid.
626 * Returns 0 on failure and non-zero on success.
628 static int first_valid_ref(const char *refname UNUSED
,
629 const struct object_id
*oid UNUSED
,
631 void *cb_data UNUSED
)
637 * Verifies HEAD and determines whether there exist any valid local references.
639 * - Checks whether HEAD points to a valid reference.
641 * - Checks whether any valid local branches exist.
643 * - Emits a warning if there exist any valid branches but HEAD does not point
644 * to a valid reference.
646 * Returns 1 if any of the previous checks are true, otherwise returns 0.
648 static int can_use_local_refs(const struct add_opts
*opts
)
650 if (head_ref(first_valid_ref
, NULL
)) {
652 } else if (for_each_branch_ref(first_valid_ref
, NULL
)) {
654 struct strbuf path
= STRBUF_INIT
;
655 struct strbuf contents
= STRBUF_INIT
;
657 strbuf_add_real_path(&path
, get_worktree_git_dir(NULL
));
658 strbuf_addstr(&path
, "/HEAD");
659 strbuf_read_file(&contents
, path
.buf
, 64);
660 strbuf_stripspace(&contents
, NULL
);
661 strbuf_strip_suffix(&contents
, "\n");
663 warning(_("HEAD points to an invalid (or orphaned) reference.\n"
665 "HEAD contents: '%s'"),
666 path
.buf
, contents
.buf
);
667 strbuf_release(&path
);
668 strbuf_release(&contents
);
676 * Reports whether the necessary flags were set and whether the repository has
677 * remote references to attempt DWIM tracking of upstream branches.
679 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
681 * 2. Checks whether any valid remote branches exist.
683 * 3. Checks that there exists at least one remote and emits a warning/error
684 * if both checks 1. and 2. are false (can be bypassed with `--force`).
686 * Returns 1 if checks 1. and 2. are true, otherwise 0.
688 static int can_use_remote_refs(const struct add_opts
*opts
)
692 } else if (for_each_remote_ref(first_valid_ref
, NULL
)) {
694 } else if (!opts
->force
&& remote_get(NULL
)) {
695 die(_("No local or remote refs exist despite at least one remote\n"
696 "present, stopping; use 'add -f' to override or fetch a remote first"));
702 * Determines whether `--orphan` should be inferred in the evaluation of
703 * `worktree add path/` or `worktree add -b branch path/` and emits an error
704 * if the supplied arguments would produce an illegal combination when the
705 * `--orphan` flag is included.
707 * `opts` and `opt_track` contain the other options & flags supplied to the
710 * remote determines whether to check `can_use_remote_refs()` or not. This
711 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
713 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
714 * `--orphan` is inferred but doing so produces an illegal combination of
715 * options and flags. Additionally produces an error when remote refs are
716 * checked and the repo is in a state that looks like the user added a remote
717 * but forgot to fetch (and did not override the warning with -f).
719 static int dwim_orphan(const struct add_opts
*opts
, int opt_track
, int remote
)
721 if (can_use_local_refs(opts
)) {
723 } else if (remote
&& can_use_remote_refs(opts
)) {
725 } else if (!opts
->quiet
) {
726 fprintf_ln(stderr
, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT
);
730 die(_("options '%s' and '%s' cannot be used together"),
731 "--orphan", "--track");
732 } else if (!opts
->checkout
) {
733 die(_("options '%s' and '%s' cannot be used together"),
734 "--orphan", "--no-checkout");
739 static const char *dwim_branch(const char *path
, const char **new_branch
)
743 const char *s
= worktree_basename(path
, &n
);
744 const char *branchname
= xstrndup(s
, n
);
745 struct strbuf ref
= STRBUF_INIT
;
749 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
751 strbuf_release(&ref
);
755 *new_branch
= branchname
;
757 struct object_id oid
;
759 unique_tracking_name(*new_branch
, &oid
, NULL
);
765 static int add(int ac
, const char **av
, const char *prefix
)
767 struct add_opts opts
;
768 const char *new_branch_force
= NULL
;
771 const char *new_branch
= NULL
;
772 const char *opt_track
= NULL
;
773 const char *lock_reason
= NULL
;
775 int used_new_branch_options
;
776 struct option options
[] = {
777 OPT__FORCE(&opts
.force
,
778 N_("checkout <branch> even if already checked out in other worktree"),
779 PARSE_OPT_NOCOMPLETE
),
780 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
781 N_("create a new branch")),
782 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
783 N_("create or reset a branch")),
784 OPT_BOOL(0, "orphan", &opts
.orphan
, N_("create unborn branch")),
785 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
786 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
787 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
788 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
789 N_("reason for locking")),
790 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
791 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
792 N_("set up tracking mode (see git-branch(1))"),
793 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
794 OPT_BOOL(0, "guess-remote", &guess_remote
,
795 N_("try to match the new branch name with a remote-tracking branch")),
800 memset(&opts
, 0, sizeof(opts
));
802 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
803 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
804 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
805 if (opts
.detach
&& opts
.orphan
)
806 die(_("options '%s' and '%s' cannot be used together"),
807 "--orphan", "--detach");
808 if (opts
.orphan
&& opt_track
)
809 die(_("options '%s' and '%s' cannot be used together"),
810 "--orphan", "--track");
811 if (opts
.orphan
&& !opts
.checkout
)
812 die(_("options '%s' and '%s' cannot be used together"),
813 "--orphan", "--no-checkout");
814 if (opts
.orphan
&& ac
== 2)
815 die(_("option '%s' and commit-ish cannot be used together"),
817 if (lock_reason
&& !keep_locked
)
818 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
820 opts
.keep_locked
= lock_reason
;
821 else if (keep_locked
)
822 opts
.keep_locked
= _("added with --lock");
824 if (ac
< 1 || ac
> 2)
825 usage_with_options(git_worktree_add_usage
, options
);
827 path
= prefix_filename(prefix
, av
[0]);
828 branch
= ac
< 2 ? "HEAD" : av
[1];
829 used_new_branch_options
= new_branch
|| new_branch_force
;
831 if (!strcmp(branch
, "-"))
834 if (new_branch_force
) {
835 struct strbuf symref
= STRBUF_INIT
;
837 new_branch
= new_branch_force
;
840 !strbuf_check_branch_ref(&symref
, new_branch
) &&
841 ref_exists(symref
.buf
))
842 die_if_checked_out(symref
.buf
, 0);
843 strbuf_release(&symref
);
846 if (opts
.orphan
&& !new_branch
) {
848 const char *s
= worktree_basename(path
, &n
);
849 new_branch
= xstrndup(s
, n
);
850 } else if (opts
.orphan
) {
852 } else if (opts
.detach
) {
854 if (!strcmp(branch
, "HEAD"))
855 can_use_local_refs(&opts
);
856 } else if (ac
< 2 && new_branch
) {
857 /* DWIM: Infer --orphan when repo has no refs. */
858 opts
.orphan
= dwim_orphan(&opts
, !!opt_track
, 0);
860 /* DWIM: Guess branch name from path. */
861 const char *s
= dwim_branch(path
, &new_branch
);
865 /* DWIM: Infer --orphan when repo has no refs. */
866 opts
.orphan
= (!s
) && dwim_orphan(&opts
, !!opt_track
, 1);
867 } else if (ac
== 2) {
868 struct object_id oid
;
869 struct commit
*commit
;
872 commit
= lookup_commit_reference_by_name(branch
);
874 remote
= unique_tracking_name(branch
, &oid
, NULL
);
881 if (!strcmp(branch
, "HEAD"))
882 can_use_local_refs(&opts
);
886 if (!opts
.orphan
&& !lookup_commit_reference_by_name(branch
)) {
887 int attempt_hint
= !opts
.quiet
&& (ac
< 2);
888 if (attempt_hint
&& used_new_branch_options
) {
889 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
890 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT
,
892 } else if (attempt_hint
) {
893 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN
,
894 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT
, path
);
896 die(_("invalid reference: %s"), branch
);
900 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
904 } else if (new_branch
) {
905 struct child_process cp
= CHILD_PROCESS_INIT
;
907 strvec_push(&cp
.args
, "branch");
908 if (new_branch_force
)
909 strvec_push(&cp
.args
, "--force");
911 strvec_push(&cp
.args
, "--quiet");
912 strvec_push(&cp
.args
, new_branch
);
913 strvec_push(&cp
.args
, branch
);
915 strvec_push(&cp
.args
, opt_track
);
916 if (run_command(&cp
))
919 } else if (opt_track
) {
920 die(_("--[no-]track can only be used if a new branch is created"));
923 ret
= add_worktree(path
, branch
, &opts
);
928 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
932 printf("worktree %s%c", wt
->path
, line_terminator
);
934 printf("bare%c", line_terminator
);
936 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
938 printf("detached%c", line_terminator
);
939 else if (wt
->head_ref
)
940 printf("branch %s%c", wt
->head_ref
, line_terminator
);
943 reason
= worktree_lock_reason(wt
);
945 fputs("locked", stdout
);
948 write_name_quoted(reason
, stdout
, line_terminator
);
950 fputc(line_terminator
, stdout
);
954 reason
= worktree_prune_reason(wt
, expire
);
956 printf("prunable %s%c", reason
, line_terminator
);
958 fputc(line_terminator
, stdout
);
961 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
963 struct strbuf sb
= STRBUF_INIT
;
964 int cur_path_len
= strlen(wt
->path
);
965 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
968 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
970 strbuf_addstr(&sb
, "(bare)");
972 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
973 repo_find_unique_abbrev(the_repository
, &wt
->head_oid
, DEFAULT_ABBREV
));
975 strbuf_addstr(&sb
, "(detached HEAD)");
976 else if (wt
->head_ref
) {
977 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
978 strbuf_addf(&sb
, "[%s]", ref
);
981 strbuf_addstr(&sb
, "(error)");
984 reason
= worktree_lock_reason(wt
);
985 if (verbose
&& reason
&& *reason
)
986 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
988 strbuf_addstr(&sb
, " locked");
990 reason
= worktree_prune_reason(wt
, expire
);
991 if (verbose
&& reason
)
992 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
994 strbuf_addstr(&sb
, " prunable");
996 printf("%s\n", sb
.buf
);
1000 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
1004 for (i
= 0; wt
[i
]; i
++) {
1006 int path_len
= strlen(wt
[i
]->path
);
1008 if (path_len
> *maxlen
)
1010 sha1_len
= strlen(repo_find_unique_abbrev(the_repository
, &wt
[i
]->head_oid
, *abbrev
));
1011 if (sha1_len
> *abbrev
)
1016 static int pathcmp(const void *a_
, const void *b_
)
1018 const struct worktree
*const *a
= a_
;
1019 const struct worktree
*const *b
= b_
;
1020 return fspathcmp((*a
)->path
, (*b
)->path
);
1023 static void pathsort(struct worktree
**wt
)
1026 struct worktree
**p
= wt
;
1030 QSORT(wt
, n
, pathcmp
);
1033 static int list(int ac
, const char **av
, const char *prefix
)
1036 int line_terminator
= '\n';
1038 struct option options
[] = {
1039 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
1040 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
1041 OPT_EXPIRY_DATE(0, "expire", &expire
,
1042 N_("add 'prunable' annotation to worktrees older than <time>")),
1043 OPT_SET_INT('z', NULL
, &line_terminator
,
1044 N_("terminate records with a NUL character"), '\0'),
1049 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
1051 usage_with_options(git_worktree_list_usage
, options
);
1052 else if (verbose
&& porcelain
)
1053 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1054 else if (!line_terminator
&& !porcelain
)
1055 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1057 struct worktree
**worktrees
= get_worktrees();
1058 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
1060 /* sort worktrees by path but keep main worktree at top */
1061 pathsort(worktrees
+ 1);
1064 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
1066 for (i
= 0; worktrees
[i
]; i
++) {
1068 show_worktree_porcelain(worktrees
[i
],
1071 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
1073 free_worktrees(worktrees
);
1078 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
1080 const char *reason
= "", *old_reason
;
1081 struct option options
[] = {
1082 OPT_STRING(0, "reason", &reason
, N_("string"),
1083 N_("reason for locking")),
1086 struct worktree
**worktrees
, *wt
;
1088 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
1090 usage_with_options(git_worktree_lock_usage
, options
);
1092 worktrees
= get_worktrees();
1093 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1095 die(_("'%s' is not a working tree"), av
[0]);
1096 if (is_main_worktree(wt
))
1097 die(_("The main working tree cannot be locked or unlocked"));
1099 old_reason
= worktree_lock_reason(wt
);
1102 die(_("'%s' is already locked, reason: %s"),
1104 die(_("'%s' is already locked"), av
[0]);
1107 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
1109 free_worktrees(worktrees
);
1113 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
1115 struct option options
[] = {
1118 struct worktree
**worktrees
, *wt
;
1121 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
1123 usage_with_options(git_worktree_unlock_usage
, options
);
1125 worktrees
= get_worktrees();
1126 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1128 die(_("'%s' is not a working tree"), av
[0]);
1129 if (is_main_worktree(wt
))
1130 die(_("The main working tree cannot be locked or unlocked"));
1131 if (!worktree_lock_reason(wt
))
1132 die(_("'%s' is not locked"), av
[0]);
1133 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
1134 free_worktrees(worktrees
);
1138 static void validate_no_submodules(const struct worktree
*wt
)
1140 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
1141 struct strbuf path
= STRBUF_INIT
;
1142 int i
, found_submodules
= 0;
1144 if (is_directory(worktree_git_path(wt
, "modules"))) {
1146 * There could be false positives, e.g. the "modules"
1147 * directory exists but is empty. But it's a rare case and
1148 * this simpler check is probably good enough for now.
1150 found_submodules
= 1;
1151 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
1152 get_worktree_git_dir(wt
)) > 0) {
1153 for (i
= 0; i
< istate
.cache_nr
; i
++) {
1154 struct cache_entry
*ce
= istate
.cache
[i
];
1157 if (!S_ISGITLINK(ce
->ce_mode
))
1160 strbuf_reset(&path
);
1161 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
1162 if (!is_submodule_populated_gently(path
.buf
, &err
))
1165 found_submodules
= 1;
1169 discard_index(&istate
);
1170 strbuf_release(&path
);
1172 if (found_submodules
)
1173 die(_("working trees containing submodules cannot be moved or removed"));
1176 static int move_worktree(int ac
, const char **av
, const char *prefix
)
1179 struct option options
[] = {
1181 N_("force move even if worktree is dirty or locked"),
1182 PARSE_OPT_NOCOMPLETE
),
1185 struct worktree
**worktrees
, *wt
;
1186 struct strbuf dst
= STRBUF_INIT
;
1187 struct strbuf errmsg
= STRBUF_INIT
;
1188 const char *reason
= NULL
;
1191 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
1194 usage_with_options(git_worktree_move_usage
, options
);
1196 path
= prefix_filename(prefix
, av
[1]);
1197 strbuf_addstr(&dst
, path
);
1200 worktrees
= get_worktrees();
1201 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1203 die(_("'%s' is not a working tree"), av
[0]);
1204 if (is_main_worktree(wt
))
1205 die(_("'%s' is a main working tree"), av
[0]);
1206 if (is_directory(dst
.buf
)) {
1207 const char *sep
= find_last_dir_sep(wt
->path
);
1210 die(_("could not figure out destination name from '%s'"),
1212 strbuf_trim_trailing_dir_sep(&dst
);
1213 strbuf_addstr(&dst
, sep
);
1215 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1217 validate_no_submodules(wt
);
1220 reason
= worktree_lock_reason(wt
);
1223 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1225 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1227 if (validate_worktree(wt
, &errmsg
, 0))
1228 die(_("validation failed, cannot move working tree: %s"),
1230 strbuf_release(&errmsg
);
1232 if (rename(wt
->path
, dst
.buf
) == -1)
1233 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1235 update_worktree_location(wt
, dst
.buf
);
1237 strbuf_release(&dst
);
1238 free_worktrees(worktrees
);
1243 * Note, "git status --porcelain" is used to determine if it's safe to
1244 * delete a whole worktree. "git status" does not ignore user
1245 * configuration, so if a normal "git status" shows "clean" for the
1246 * user, then it's ok to remove it.
1248 * This assumption may be a bad one. We may want to ignore
1249 * (potentially bad) user settings and only delete a worktree when
1250 * it's absolutely safe to do so from _our_ point of view because we
1253 static void check_clean_worktree(struct worktree
*wt
,
1254 const char *original_path
)
1256 struct child_process cp
;
1261 * Until we sort this out, all submodules are "dirty" and
1262 * will abort this function.
1264 validate_no_submodules(wt
);
1266 child_process_init(&cp
);
1267 strvec_pushf(&cp
.env
, "%s=%s/.git",
1268 GIT_DIR_ENVIRONMENT
, wt
->path
);
1269 strvec_pushf(&cp
.env
, "%s=%s",
1270 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1271 strvec_pushl(&cp
.args
, "status",
1272 "--porcelain", "--ignore-submodules=none",
1277 ret
= start_command(&cp
);
1279 die_errno(_("failed to run 'git status' on '%s'"),
1281 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1283 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1286 ret
= finish_command(&cp
);
1288 die_errno(_("failed to run 'git status' on '%s', code %d"),
1289 original_path
, ret
);
1292 static int delete_git_work_tree(struct worktree
*wt
)
1294 struct strbuf sb
= STRBUF_INIT
;
1297 strbuf_addstr(&sb
, wt
->path
);
1298 if (remove_dir_recursively(&sb
, 0)) {
1299 error_errno(_("failed to delete '%s'"), sb
.buf
);
1302 strbuf_release(&sb
);
1306 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1309 struct option options
[] = {
1311 N_("force removal even if worktree is dirty or locked"),
1312 PARSE_OPT_NOCOMPLETE
),
1315 struct worktree
**worktrees
, *wt
;
1316 struct strbuf errmsg
= STRBUF_INIT
;
1317 const char *reason
= NULL
;
1320 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1322 usage_with_options(git_worktree_remove_usage
, options
);
1324 worktrees
= get_worktrees();
1325 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1327 die(_("'%s' is not a working tree"), av
[0]);
1328 if (is_main_worktree(wt
))
1329 die(_("'%s' is a main working tree"), av
[0]);
1331 reason
= worktree_lock_reason(wt
);
1334 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1336 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1338 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1339 die(_("validation failed, cannot remove working tree: %s"),
1341 strbuf_release(&errmsg
);
1343 if (file_exists(wt
->path
)) {
1345 check_clean_worktree(wt
, av
[0]);
1347 ret
|= delete_git_work_tree(wt
);
1350 * continue on even if ret is non-zero, there's no going back
1353 ret
|= delete_git_dir(wt
->id
);
1354 delete_worktrees_dir_if_empty();
1356 free_worktrees(worktrees
);
1360 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1363 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1365 int *exit_status
= (int *)cb_data
;
1366 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1371 static int repair(int ac
, const char **av
, const char *prefix
)
1374 const char *self
[] = { ".", NULL
};
1375 struct option options
[] = {
1380 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1381 p
= ac
> 0 ? av
: self
;
1383 repair_worktree_at_path(*p
, report_repair
, &rc
);
1384 repair_worktrees(report_repair
, &rc
);
1388 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1390 parse_opt_subcommand_fn
*fn
= NULL
;
1391 struct option options
[] = {
1392 OPT_SUBCOMMAND("add", &fn
, add
),
1393 OPT_SUBCOMMAND("prune", &fn
, prune
),
1394 OPT_SUBCOMMAND("list", &fn
, list
),
1395 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1396 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1397 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1398 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1399 OPT_SUBCOMMAND("repair", &fn
, repair
),
1403 git_config(git_worktree_config
, NULL
);
1408 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1410 prepare_repo_settings(the_repository
);
1411 the_repository
->settings
.command_requires_full_index
= 0;
1413 return fn(ac
, av
, prefix
);