7 #include "environment.h"
10 #include "object-name.h"
11 #include "parse-options.h"
15 #include "run-command.h"
18 #include "submodule.h"
24 #define BUILTIN_WORKTREE_ADD_USAGE \
25 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
26 " [-b <new-branch>] <path> [<commit-ish>]")
27 #define BUILTIN_WORKTREE_LIST_USAGE \
28 N_("git worktree list [-v | --porcelain [-z]]")
29 #define BUILTIN_WORKTREE_LOCK_USAGE \
30 N_("git worktree lock [--reason <string>] <worktree>")
31 #define BUILTIN_WORKTREE_MOVE_USAGE \
32 N_("git worktree move <worktree> <new-path>")
33 #define BUILTIN_WORKTREE_PRUNE_USAGE \
34 N_("git worktree prune [-n] [-v] [--expire <expire>]")
35 #define BUILTIN_WORKTREE_REMOVE_USAGE \
36 N_("git worktree remove [-f] <worktree>")
37 #define BUILTIN_WORKTREE_REPAIR_USAGE \
38 N_("git worktree repair [<path>...]")
39 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
40 N_("git worktree unlock <worktree>")
42 static const char * const git_worktree_usage
[] = {
43 BUILTIN_WORKTREE_ADD_USAGE
,
44 BUILTIN_WORKTREE_LIST_USAGE
,
45 BUILTIN_WORKTREE_LOCK_USAGE
,
46 BUILTIN_WORKTREE_MOVE_USAGE
,
47 BUILTIN_WORKTREE_PRUNE_USAGE
,
48 BUILTIN_WORKTREE_REMOVE_USAGE
,
49 BUILTIN_WORKTREE_REPAIR_USAGE
,
50 BUILTIN_WORKTREE_UNLOCK_USAGE
,
54 static const char * const git_worktree_add_usage
[] = {
55 BUILTIN_WORKTREE_ADD_USAGE
,
59 static const char * const git_worktree_list_usage
[] = {
60 BUILTIN_WORKTREE_LIST_USAGE
,
64 static const char * const git_worktree_lock_usage
[] = {
65 BUILTIN_WORKTREE_LOCK_USAGE
,
69 static const char * const git_worktree_move_usage
[] = {
70 BUILTIN_WORKTREE_MOVE_USAGE
,
74 static const char * const git_worktree_prune_usage
[] = {
75 BUILTIN_WORKTREE_PRUNE_USAGE
,
79 static const char * const git_worktree_remove_usage
[] = {
80 BUILTIN_WORKTREE_REMOVE_USAGE
,
84 static const char * const git_worktree_repair_usage
[] = {
85 BUILTIN_WORKTREE_REPAIR_USAGE
,
89 static const char * const git_worktree_unlock_usage
[] = {
90 BUILTIN_WORKTREE_UNLOCK_USAGE
,
99 const char *keep_locked
;
102 static int show_only
;
104 static int guess_remote
;
105 static timestamp_t expire
;
107 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
109 if (!strcmp(var
, "worktree.guessremote")) {
110 guess_remote
= git_config_bool(var
, value
);
114 return git_default_config(var
, value
, cb
);
117 static int delete_git_dir(const char *id
)
119 struct strbuf sb
= STRBUF_INIT
;
122 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
123 ret
= remove_dir_recursively(&sb
, 0);
124 if (ret
< 0 && errno
== ENOTDIR
)
125 ret
= unlink(sb
.buf
);
127 error_errno(_("failed to delete '%s'"), sb
.buf
);
132 static void delete_worktrees_dir_if_empty(void)
134 rmdir(git_path("worktrees")); /* ignore failed removal */
137 static void prune_worktree(const char *id
, const char *reason
)
139 if (show_only
|| verbose
)
140 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
145 static int prune_cmp(const void *a
, const void *b
)
147 const struct string_list_item
*x
= a
;
148 const struct string_list_item
*y
= b
;
151 if ((c
= fspathcmp(x
->string
, y
->string
)))
154 * paths same; prune_dupes() removes all but the first worktree entry
155 * having the same path, so sort main worktree ('util' is NULL) above
156 * linked worktrees ('util' not NULL) since main worktree can't be
163 /* paths same; sort by .git/worktrees/<id> */
164 return strcmp(x
->util
, y
->util
);
167 static void prune_dups(struct string_list
*l
)
171 QSORT(l
->items
, l
->nr
, prune_cmp
);
172 for (i
= 1; i
< l
->nr
; i
++) {
173 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
174 prune_worktree(l
->items
[i
].util
, "duplicate entry");
178 static void prune_worktrees(void)
180 struct strbuf reason
= STRBUF_INIT
;
181 struct strbuf main_path
= STRBUF_INIT
;
182 struct string_list kept
= STRING_LIST_INIT_DUP
;
183 DIR *dir
= opendir(git_path("worktrees"));
187 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
189 strbuf_reset(&reason
);
190 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
191 prune_worktree(d
->d_name
, reason
.buf
);
193 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
197 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
198 /* massage main worktree absolute path to match 'gitdir' content */
199 strbuf_strip_suffix(&main_path
, "/.");
200 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
202 string_list_clear(&kept
, 1);
205 delete_worktrees_dir_if_empty();
206 strbuf_release(&reason
);
209 static int prune(int ac
, const char **av
, const char *prefix
)
211 struct option options
[] = {
212 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
213 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
214 OPT_EXPIRY_DATE(0, "expire", &expire
,
215 N_("expire working trees older than <time>")),
220 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
223 usage_with_options(git_worktree_prune_usage
, options
);
228 static char *junk_work_tree
;
229 static char *junk_git_dir
;
231 static pid_t junk_pid
;
233 static void remove_junk(void)
235 struct strbuf sb
= STRBUF_INIT
;
236 if (!is_junk
|| getpid() != junk_pid
)
239 strbuf_addstr(&sb
, junk_git_dir
);
240 remove_dir_recursively(&sb
, 0);
243 if (junk_work_tree
) {
244 strbuf_addstr(&sb
, junk_work_tree
);
245 remove_dir_recursively(&sb
, 0);
250 static void remove_junk_on_signal(int signo
)
257 static const char *worktree_basename(const char *path
, int *olen
)
263 while (len
&& is_dir_sep(path
[len
- 1]))
266 for (name
= path
+ len
- 1; name
> path
; name
--)
267 if (is_dir_sep(*name
)) {
276 /* check that path is viable location for worktree */
277 static void check_candidate_path(const char *path
,
279 struct worktree
**worktrees
,
285 if (file_exists(path
) && !is_empty_dir(path
))
286 die(_("'%s' already exists"), path
);
288 wt
= find_worktree_by_path(worktrees
, path
);
292 locked
= !!worktree_lock_reason(wt
);
293 if ((!locked
&& force
) || (locked
&& force
> 1)) {
294 if (delete_git_dir(wt
->id
))
295 die(_("unusable worktree destination '%s'"), path
);
300 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
302 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
305 static void copy_sparse_checkout(const char *worktree_git_dir
)
307 char *from_file
= git_pathdup("info/sparse-checkout");
308 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
310 if (file_exists(from_file
)) {
311 if (safe_create_leading_directories(to_file
) ||
312 copy_file(to_file
, from_file
, 0666))
313 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
321 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
323 char *from_file
= git_pathdup("config.worktree");
324 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
326 if (file_exists(from_file
)) {
327 struct config_set cs
= { { 0 } };
328 const char *core_worktree
;
331 if (safe_create_leading_directories(to_file
) ||
332 copy_file(to_file
, from_file
, 0666)) {
333 error(_("failed to copy worktree config from '%s' to '%s'"),
335 goto worktree_copy_cleanup
;
338 git_configset_init(&cs
);
339 git_configset_add_file(&cs
, from_file
);
341 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
343 git_config_set_multivar_in_file_gently(
344 to_file
, "core.bare", NULL
, "true", 0))
345 error(_("failed to unset '%s' in '%s'"),
346 "core.bare", to_file
);
347 if (!git_configset_get_value(&cs
, "core.worktree", &core_worktree
) &&
348 git_config_set_in_file_gently(to_file
,
349 "core.worktree", NULL
))
350 error(_("failed to unset '%s' in '%s'"),
351 "core.worktree", to_file
);
353 git_configset_clear(&cs
);
356 worktree_copy_cleanup
:
361 static int checkout_worktree(const struct add_opts
*opts
,
362 struct strvec
*child_env
)
364 struct child_process cp
= CHILD_PROCESS_INIT
;
366 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
368 strvec_push(&cp
.args
, "--quiet");
369 strvec_pushv(&cp
.env
, child_env
->v
);
370 return run_command(&cp
);
373 static int add_worktree(const char *path
, const char *refname
,
374 const struct add_opts
*opts
)
376 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
377 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_INIT
;
379 struct child_process cp
= CHILD_PROCESS_INIT
;
380 struct strvec child_env
= STRVEC_INIT
;
381 unsigned int counter
= 0;
383 struct strbuf symref
= STRBUF_INIT
;
384 struct commit
*commit
= NULL
;
386 struct strbuf sb_name
= STRBUF_INIT
;
387 struct worktree
**worktrees
;
389 worktrees
= get_worktrees();
390 check_candidate_path(path
, opts
->force
, worktrees
, "add");
391 free_worktrees(worktrees
);
394 /* is 'refname' a branch or commit? */
395 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
396 ref_exists(symref
.buf
)) {
399 die_if_checked_out(symref
.buf
, 0);
401 commit
= lookup_commit_reference_by_name(refname
);
403 die(_("invalid reference: %s"), refname
);
405 name
= worktree_basename(path
, &len
);
406 strbuf_add(&sb
, name
, path
+ len
- name
);
407 sanitize_refname_component(sb
.buf
, &sb_name
);
409 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
412 git_path_buf(&sb_repo
, "worktrees/%s", name
);
414 if (safe_create_leading_directories_const(sb_repo
.buf
))
415 die_errno(_("could not create leading directories of '%s'"),
418 while (mkdir(sb_repo
.buf
, 0777)) {
420 if ((errno
!= EEXIST
) || !counter
/* overflow */)
421 die_errno(_("could not create directory of '%s'"),
423 strbuf_setlen(&sb_repo
, len
);
424 strbuf_addf(&sb_repo
, "%d", counter
);
426 name
= strrchr(sb_repo
.buf
, '/') + 1;
430 sigchain_push_common(remove_junk_on_signal
);
432 junk_git_dir
= xstrdup(sb_repo
.buf
);
436 * lock the incomplete repo so prune won't delete it, unlock
437 * after the preparation is over.
439 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
440 if (opts
->keep_locked
)
441 write_file(sb
.buf
, "%s", opts
->keep_locked
);
443 write_file(sb
.buf
, _("initializing"));
445 strbuf_addf(&sb_git
, "%s/.git", path
);
446 if (safe_create_leading_directories_const(sb_git
.buf
))
447 die_errno(_("could not create leading directories of '%s'"),
449 junk_work_tree
= xstrdup(path
);
452 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
453 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
454 write_file(sb
.buf
, "%s", realpath
.buf
);
455 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
456 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
459 * This is to keep resolve_ref() happy. We need a valid HEAD
460 * or is_git_directory() will reject the directory. Any value which
461 * looks like an object ID will do since it will be immediately
462 * replaced by the symbolic-ref or update-ref invocation in the new
466 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
467 write_file(sb
.buf
, "%s", oid_to_hex(null_oid()));
469 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
470 write_file(sb
.buf
, "../..");
473 * If the current worktree has sparse-checkout enabled, then copy
474 * the sparse-checkout patterns from the current worktree.
476 if (core_apply_sparse_checkout
)
477 copy_sparse_checkout(sb_repo
.buf
);
480 * If we are using worktree config, then copy all current config
481 * values from the current worktree into the new one, that way the
482 * new worktree behaves the same as this one.
484 if (repository_format_worktree_config
)
485 copy_filtered_worktree_config(sb_repo
.buf
);
487 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
488 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
492 strvec_pushl(&cp
.args
, "update-ref", "HEAD",
493 oid_to_hex(&commit
->object
.oid
), NULL
);
495 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD",
498 strvec_push(&cp
.args
, "--quiet");
501 strvec_pushv(&cp
.env
, child_env
.v
);
502 ret
= run_command(&cp
);
506 if (opts
->checkout
&&
507 (ret
= checkout_worktree(opts
, &child_env
)))
511 FREE_AND_NULL(junk_work_tree
);
512 FREE_AND_NULL(junk_git_dir
);
515 if (ret
|| !opts
->keep_locked
) {
517 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
518 unlink_or_warn(sb
.buf
);
522 * Hook failure does not warrant worktree deletion, so run hook after
523 * is_junk is cleared, but do return appropriate code when hook fails.
525 if (!ret
&& opts
->checkout
) {
526 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
528 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
529 strvec_pushl(&opt
.args
,
530 oid_to_hex(null_oid()),
531 oid_to_hex(&commit
->object
.oid
),
536 ret
= run_hooks_opt("post-checkout", &opt
);
539 strvec_clear(&child_env
);
541 strbuf_release(&symref
);
542 strbuf_release(&sb_repo
);
543 strbuf_release(&sb_git
);
544 strbuf_release(&sb_name
);
545 strbuf_release(&realpath
);
549 static void print_preparing_worktree_line(int detach
,
551 const char *new_branch
,
552 int force_new_branch
)
554 if (force_new_branch
) {
555 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
557 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
559 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
561 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
562 } else if (new_branch
) {
563 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
565 struct strbuf s
= STRBUF_INIT
;
566 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
568 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
571 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
573 die(_("invalid reference: %s"), branch
);
574 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
575 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
581 static const char *dwim_branch(const char *path
, const char **new_branch
)
585 const char *s
= worktree_basename(path
, &n
);
586 const char *branchname
= xstrndup(s
, n
);
587 struct strbuf ref
= STRBUF_INIT
;
591 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
593 strbuf_release(&ref
);
597 *new_branch
= branchname
;
599 struct object_id oid
;
601 unique_tracking_name(*new_branch
, &oid
, NULL
);
607 static int add(int ac
, const char **av
, const char *prefix
)
609 struct add_opts opts
;
610 const char *new_branch_force
= NULL
;
613 const char *new_branch
= NULL
;
614 const char *opt_track
= NULL
;
615 const char *lock_reason
= NULL
;
617 struct option options
[] = {
618 OPT__FORCE(&opts
.force
,
619 N_("checkout <branch> even if already checked out in other worktree"),
620 PARSE_OPT_NOCOMPLETE
),
621 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
622 N_("create a new branch")),
623 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
624 N_("create or reset a branch")),
625 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
626 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
627 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
628 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
629 N_("reason for locking")),
630 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
631 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
632 N_("set up tracking mode (see git-branch(1))"),
633 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
634 OPT_BOOL(0, "guess-remote", &guess_remote
,
635 N_("try to match the new branch name with a remote-tracking branch")),
640 memset(&opts
, 0, sizeof(opts
));
642 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
643 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
644 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
645 if (lock_reason
&& !keep_locked
)
646 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
648 opts
.keep_locked
= lock_reason
;
649 else if (keep_locked
)
650 opts
.keep_locked
= _("added with --lock");
652 if (ac
< 1 || ac
> 2)
653 usage_with_options(git_worktree_add_usage
, options
);
655 path
= prefix_filename(prefix
, av
[0]);
656 branch
= ac
< 2 ? "HEAD" : av
[1];
658 if (!strcmp(branch
, "-"))
661 if (new_branch_force
) {
662 struct strbuf symref
= STRBUF_INIT
;
664 new_branch
= new_branch_force
;
667 !strbuf_check_branch_ref(&symref
, new_branch
) &&
668 ref_exists(symref
.buf
))
669 die_if_checked_out(symref
.buf
, 0);
670 strbuf_release(&symref
);
673 if (ac
< 2 && !new_branch
&& !opts
.detach
) {
674 const char *s
= dwim_branch(path
, &new_branch
);
679 if (ac
== 2 && !new_branch
&& !opts
.detach
) {
680 struct object_id oid
;
681 struct commit
*commit
;
684 commit
= lookup_commit_reference_by_name(branch
);
686 remote
= unique_tracking_name(branch
, &oid
, NULL
);
694 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
697 struct child_process cp
= CHILD_PROCESS_INIT
;
699 strvec_push(&cp
.args
, "branch");
700 if (new_branch_force
)
701 strvec_push(&cp
.args
, "--force");
703 strvec_push(&cp
.args
, "--quiet");
704 strvec_push(&cp
.args
, new_branch
);
705 strvec_push(&cp
.args
, branch
);
707 strvec_push(&cp
.args
, opt_track
);
708 if (run_command(&cp
))
711 } else if (opt_track
) {
712 die(_("--[no-]track can only be used if a new branch is created"));
715 ret
= add_worktree(path
, branch
, &opts
);
720 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
724 printf("worktree %s%c", wt
->path
, line_terminator
);
726 printf("bare%c", line_terminator
);
728 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
730 printf("detached%c", line_terminator
);
731 else if (wt
->head_ref
)
732 printf("branch %s%c", wt
->head_ref
, line_terminator
);
735 reason
= worktree_lock_reason(wt
);
737 fputs("locked", stdout
);
740 write_name_quoted(reason
, stdout
, line_terminator
);
742 fputc(line_terminator
, stdout
);
746 reason
= worktree_prune_reason(wt
, expire
);
748 printf("prunable %s%c", reason
, line_terminator
);
750 fputc(line_terminator
, stdout
);
753 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
755 struct strbuf sb
= STRBUF_INIT
;
756 int cur_path_len
= strlen(wt
->path
);
757 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
760 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
762 strbuf_addstr(&sb
, "(bare)");
764 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
765 repo_find_unique_abbrev(the_repository
, &wt
->head_oid
, DEFAULT_ABBREV
));
767 strbuf_addstr(&sb
, "(detached HEAD)");
768 else if (wt
->head_ref
) {
769 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
770 strbuf_addf(&sb
, "[%s]", ref
);
773 strbuf_addstr(&sb
, "(error)");
776 reason
= worktree_lock_reason(wt
);
777 if (verbose
&& reason
&& *reason
)
778 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
780 strbuf_addstr(&sb
, " locked");
782 reason
= worktree_prune_reason(wt
, expire
);
783 if (verbose
&& reason
)
784 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
786 strbuf_addstr(&sb
, " prunable");
788 printf("%s\n", sb
.buf
);
792 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
796 for (i
= 0; wt
[i
]; i
++) {
798 int path_len
= strlen(wt
[i
]->path
);
800 if (path_len
> *maxlen
)
802 sha1_len
= strlen(repo_find_unique_abbrev(the_repository
, &wt
[i
]->head_oid
, *abbrev
));
803 if (sha1_len
> *abbrev
)
808 static int pathcmp(const void *a_
, const void *b_
)
810 const struct worktree
*const *a
= a_
;
811 const struct worktree
*const *b
= b_
;
812 return fspathcmp((*a
)->path
, (*b
)->path
);
815 static void pathsort(struct worktree
**wt
)
818 struct worktree
**p
= wt
;
822 QSORT(wt
, n
, pathcmp
);
825 static int list(int ac
, const char **av
, const char *prefix
)
828 int line_terminator
= '\n';
830 struct option options
[] = {
831 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
832 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
833 OPT_EXPIRY_DATE(0, "expire", &expire
,
834 N_("add 'prunable' annotation to worktrees older than <time>")),
835 OPT_SET_INT('z', NULL
, &line_terminator
,
836 N_("terminate records with a NUL character"), '\0'),
841 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
843 usage_with_options(git_worktree_list_usage
, options
);
844 else if (verbose
&& porcelain
)
845 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
846 else if (!line_terminator
&& !porcelain
)
847 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
849 struct worktree
**worktrees
= get_worktrees();
850 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
852 /* sort worktrees by path but keep main worktree at top */
853 pathsort(worktrees
+ 1);
856 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
858 for (i
= 0; worktrees
[i
]; i
++) {
860 show_worktree_porcelain(worktrees
[i
],
863 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
865 free_worktrees(worktrees
);
870 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
872 const char *reason
= "", *old_reason
;
873 struct option options
[] = {
874 OPT_STRING(0, "reason", &reason
, N_("string"),
875 N_("reason for locking")),
878 struct worktree
**worktrees
, *wt
;
880 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
882 usage_with_options(git_worktree_lock_usage
, options
);
884 worktrees
= get_worktrees();
885 wt
= find_worktree(worktrees
, prefix
, av
[0]);
887 die(_("'%s' is not a working tree"), av
[0]);
888 if (is_main_worktree(wt
))
889 die(_("The main working tree cannot be locked or unlocked"));
891 old_reason
= worktree_lock_reason(wt
);
894 die(_("'%s' is already locked, reason: %s"),
896 die(_("'%s' is already locked"), av
[0]);
899 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
901 free_worktrees(worktrees
);
905 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
907 struct option options
[] = {
910 struct worktree
**worktrees
, *wt
;
913 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
915 usage_with_options(git_worktree_unlock_usage
, options
);
917 worktrees
= get_worktrees();
918 wt
= find_worktree(worktrees
, prefix
, av
[0]);
920 die(_("'%s' is not a working tree"), av
[0]);
921 if (is_main_worktree(wt
))
922 die(_("The main working tree cannot be locked or unlocked"));
923 if (!worktree_lock_reason(wt
))
924 die(_("'%s' is not locked"), av
[0]);
925 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
926 free_worktrees(worktrees
);
930 static void validate_no_submodules(const struct worktree
*wt
)
932 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
933 struct strbuf path
= STRBUF_INIT
;
934 int i
, found_submodules
= 0;
936 if (is_directory(worktree_git_path(wt
, "modules"))) {
938 * There could be false positives, e.g. the "modules"
939 * directory exists but is empty. But it's a rare case and
940 * this simpler check is probably good enough for now.
942 found_submodules
= 1;
943 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
944 get_worktree_git_dir(wt
)) > 0) {
945 for (i
= 0; i
< istate
.cache_nr
; i
++) {
946 struct cache_entry
*ce
= istate
.cache
[i
];
949 if (!S_ISGITLINK(ce
->ce_mode
))
953 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
954 if (!is_submodule_populated_gently(path
.buf
, &err
))
957 found_submodules
= 1;
961 discard_index(&istate
);
962 strbuf_release(&path
);
964 if (found_submodules
)
965 die(_("working trees containing submodules cannot be moved or removed"));
968 static int move_worktree(int ac
, const char **av
, const char *prefix
)
971 struct option options
[] = {
973 N_("force move even if worktree is dirty or locked"),
974 PARSE_OPT_NOCOMPLETE
),
977 struct worktree
**worktrees
, *wt
;
978 struct strbuf dst
= STRBUF_INIT
;
979 struct strbuf errmsg
= STRBUF_INIT
;
980 const char *reason
= NULL
;
983 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
986 usage_with_options(git_worktree_move_usage
, options
);
988 path
= prefix_filename(prefix
, av
[1]);
989 strbuf_addstr(&dst
, path
);
992 worktrees
= get_worktrees();
993 wt
= find_worktree(worktrees
, prefix
, av
[0]);
995 die(_("'%s' is not a working tree"), av
[0]);
996 if (is_main_worktree(wt
))
997 die(_("'%s' is a main working tree"), av
[0]);
998 if (is_directory(dst
.buf
)) {
999 const char *sep
= find_last_dir_sep(wt
->path
);
1002 die(_("could not figure out destination name from '%s'"),
1004 strbuf_trim_trailing_dir_sep(&dst
);
1005 strbuf_addstr(&dst
, sep
);
1007 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1009 validate_no_submodules(wt
);
1012 reason
= worktree_lock_reason(wt
);
1015 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1017 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1019 if (validate_worktree(wt
, &errmsg
, 0))
1020 die(_("validation failed, cannot move working tree: %s"),
1022 strbuf_release(&errmsg
);
1024 if (rename(wt
->path
, dst
.buf
) == -1)
1025 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1027 update_worktree_location(wt
, dst
.buf
);
1029 strbuf_release(&dst
);
1030 free_worktrees(worktrees
);
1035 * Note, "git status --porcelain" is used to determine if it's safe to
1036 * delete a whole worktree. "git status" does not ignore user
1037 * configuration, so if a normal "git status" shows "clean" for the
1038 * user, then it's ok to remove it.
1040 * This assumption may be a bad one. We may want to ignore
1041 * (potentially bad) user settings and only delete a worktree when
1042 * it's absolutely safe to do so from _our_ point of view because we
1045 static void check_clean_worktree(struct worktree
*wt
,
1046 const char *original_path
)
1048 struct child_process cp
;
1053 * Until we sort this out, all submodules are "dirty" and
1054 * will abort this function.
1056 validate_no_submodules(wt
);
1058 child_process_init(&cp
);
1059 strvec_pushf(&cp
.env
, "%s=%s/.git",
1060 GIT_DIR_ENVIRONMENT
, wt
->path
);
1061 strvec_pushf(&cp
.env
, "%s=%s",
1062 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1063 strvec_pushl(&cp
.args
, "status",
1064 "--porcelain", "--ignore-submodules=none",
1069 ret
= start_command(&cp
);
1071 die_errno(_("failed to run 'git status' on '%s'"),
1073 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1075 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1078 ret
= finish_command(&cp
);
1080 die_errno(_("failed to run 'git status' on '%s', code %d"),
1081 original_path
, ret
);
1084 static int delete_git_work_tree(struct worktree
*wt
)
1086 struct strbuf sb
= STRBUF_INIT
;
1089 strbuf_addstr(&sb
, wt
->path
);
1090 if (remove_dir_recursively(&sb
, 0)) {
1091 error_errno(_("failed to delete '%s'"), sb
.buf
);
1094 strbuf_release(&sb
);
1098 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1101 struct option options
[] = {
1103 N_("force removal even if worktree is dirty or locked"),
1104 PARSE_OPT_NOCOMPLETE
),
1107 struct worktree
**worktrees
, *wt
;
1108 struct strbuf errmsg
= STRBUF_INIT
;
1109 const char *reason
= NULL
;
1112 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1114 usage_with_options(git_worktree_remove_usage
, options
);
1116 worktrees
= get_worktrees();
1117 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1119 die(_("'%s' is not a working tree"), av
[0]);
1120 if (is_main_worktree(wt
))
1121 die(_("'%s' is a main working tree"), av
[0]);
1123 reason
= worktree_lock_reason(wt
);
1126 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1128 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1130 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1131 die(_("validation failed, cannot remove working tree: %s"),
1133 strbuf_release(&errmsg
);
1135 if (file_exists(wt
->path
)) {
1137 check_clean_worktree(wt
, av
[0]);
1139 ret
|= delete_git_work_tree(wt
);
1142 * continue on even if ret is non-zero, there's no going back
1145 ret
|= delete_git_dir(wt
->id
);
1146 delete_worktrees_dir_if_empty();
1148 free_worktrees(worktrees
);
1152 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1155 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1157 int *exit_status
= (int *)cb_data
;
1158 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1163 static int repair(int ac
, const char **av
, const char *prefix
)
1166 const char *self
[] = { ".", NULL
};
1167 struct option options
[] = {
1172 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1173 p
= ac
> 0 ? av
: self
;
1175 repair_worktree_at_path(*p
, report_repair
, &rc
);
1176 repair_worktrees(report_repair
, &rc
);
1180 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1182 parse_opt_subcommand_fn
*fn
= NULL
;
1183 struct option options
[] = {
1184 OPT_SUBCOMMAND("add", &fn
, add
),
1185 OPT_SUBCOMMAND("prune", &fn
, prune
),
1186 OPT_SUBCOMMAND("list", &fn
, list
),
1187 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1188 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1189 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1190 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1191 OPT_SUBCOMMAND("repair", &fn
, repair
),
1195 git_config(git_worktree_config
, NULL
);
1200 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1201 return fn(ac
, av
, prefix
);