7 #include "environment.h"
10 #include "object-file.h"
11 #include "object-name.h"
12 #include "parse-options.h"
16 #include "run-command.h"
19 #include "submodule.h"
25 #define BUILTIN_WORKTREE_ADD_USAGE \
26 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
27 " [-b <new-branch>] <path> [<commit-ish>]")
28 #define BUILTIN_WORKTREE_LIST_USAGE \
29 N_("git worktree list [-v | --porcelain [-z]]")
30 #define BUILTIN_WORKTREE_LOCK_USAGE \
31 N_("git worktree lock [--reason <string>] <worktree>")
32 #define BUILTIN_WORKTREE_MOVE_USAGE \
33 N_("git worktree move <worktree> <new-path>")
34 #define BUILTIN_WORKTREE_PRUNE_USAGE \
35 N_("git worktree prune [-n] [-v] [--expire <expire>]")
36 #define BUILTIN_WORKTREE_REMOVE_USAGE \
37 N_("git worktree remove [-f] <worktree>")
38 #define BUILTIN_WORKTREE_REPAIR_USAGE \
39 N_("git worktree repair [<path>...]")
40 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
41 N_("git worktree unlock <worktree>")
43 static const char * const git_worktree_usage
[] = {
44 BUILTIN_WORKTREE_ADD_USAGE
,
45 BUILTIN_WORKTREE_LIST_USAGE
,
46 BUILTIN_WORKTREE_LOCK_USAGE
,
47 BUILTIN_WORKTREE_MOVE_USAGE
,
48 BUILTIN_WORKTREE_PRUNE_USAGE
,
49 BUILTIN_WORKTREE_REMOVE_USAGE
,
50 BUILTIN_WORKTREE_REPAIR_USAGE
,
51 BUILTIN_WORKTREE_UNLOCK_USAGE
,
55 static const char * const git_worktree_add_usage
[] = {
56 BUILTIN_WORKTREE_ADD_USAGE
,
60 static const char * const git_worktree_list_usage
[] = {
61 BUILTIN_WORKTREE_LIST_USAGE
,
65 static const char * const git_worktree_lock_usage
[] = {
66 BUILTIN_WORKTREE_LOCK_USAGE
,
70 static const char * const git_worktree_move_usage
[] = {
71 BUILTIN_WORKTREE_MOVE_USAGE
,
75 static const char * const git_worktree_prune_usage
[] = {
76 BUILTIN_WORKTREE_PRUNE_USAGE
,
80 static const char * const git_worktree_remove_usage
[] = {
81 BUILTIN_WORKTREE_REMOVE_USAGE
,
85 static const char * const git_worktree_repair_usage
[] = {
86 BUILTIN_WORKTREE_REPAIR_USAGE
,
90 static const char * const git_worktree_unlock_usage
[] = {
91 BUILTIN_WORKTREE_UNLOCK_USAGE
,
100 const char *keep_locked
;
103 static int show_only
;
105 static int guess_remote
;
106 static timestamp_t expire
;
108 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
110 if (!strcmp(var
, "worktree.guessremote")) {
111 guess_remote
= git_config_bool(var
, value
);
115 return git_default_config(var
, value
, cb
);
118 static int delete_git_dir(const char *id
)
120 struct strbuf sb
= STRBUF_INIT
;
123 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
124 ret
= remove_dir_recursively(&sb
, 0);
125 if (ret
< 0 && errno
== ENOTDIR
)
126 ret
= unlink(sb
.buf
);
128 error_errno(_("failed to delete '%s'"), sb
.buf
);
133 static void delete_worktrees_dir_if_empty(void)
135 rmdir(git_path("worktrees")); /* ignore failed removal */
138 static void prune_worktree(const char *id
, const char *reason
)
140 if (show_only
|| verbose
)
141 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
146 static int prune_cmp(const void *a
, const void *b
)
148 const struct string_list_item
*x
= a
;
149 const struct string_list_item
*y
= b
;
152 if ((c
= fspathcmp(x
->string
, y
->string
)))
155 * paths same; prune_dupes() removes all but the first worktree entry
156 * having the same path, so sort main worktree ('util' is NULL) above
157 * linked worktrees ('util' not NULL) since main worktree can't be
164 /* paths same; sort by .git/worktrees/<id> */
165 return strcmp(x
->util
, y
->util
);
168 static void prune_dups(struct string_list
*l
)
172 QSORT(l
->items
, l
->nr
, prune_cmp
);
173 for (i
= 1; i
< l
->nr
; i
++) {
174 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
175 prune_worktree(l
->items
[i
].util
, "duplicate entry");
179 static void prune_worktrees(void)
181 struct strbuf reason
= STRBUF_INIT
;
182 struct strbuf main_path
= STRBUF_INIT
;
183 struct string_list kept
= STRING_LIST_INIT_DUP
;
184 DIR *dir
= opendir(git_path("worktrees"));
188 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
190 strbuf_reset(&reason
);
191 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
192 prune_worktree(d
->d_name
, reason
.buf
);
194 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
198 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
199 /* massage main worktree absolute path to match 'gitdir' content */
200 strbuf_strip_suffix(&main_path
, "/.");
201 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
203 string_list_clear(&kept
, 1);
206 delete_worktrees_dir_if_empty();
207 strbuf_release(&reason
);
210 static int prune(int ac
, const char **av
, const char *prefix
)
212 struct option options
[] = {
213 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
214 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
215 OPT_EXPIRY_DATE(0, "expire", &expire
,
216 N_("expire working trees older than <time>")),
221 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
224 usage_with_options(git_worktree_prune_usage
, options
);
229 static char *junk_work_tree
;
230 static char *junk_git_dir
;
232 static pid_t junk_pid
;
234 static void remove_junk(void)
236 struct strbuf sb
= STRBUF_INIT
;
237 if (!is_junk
|| getpid() != junk_pid
)
240 strbuf_addstr(&sb
, junk_git_dir
);
241 remove_dir_recursively(&sb
, 0);
244 if (junk_work_tree
) {
245 strbuf_addstr(&sb
, junk_work_tree
);
246 remove_dir_recursively(&sb
, 0);
251 static void remove_junk_on_signal(int signo
)
258 static const char *worktree_basename(const char *path
, int *olen
)
264 while (len
&& is_dir_sep(path
[len
- 1]))
267 for (name
= path
+ len
- 1; name
> path
; name
--)
268 if (is_dir_sep(*name
)) {
277 /* check that path is viable location for worktree */
278 static void check_candidate_path(const char *path
,
280 struct worktree
**worktrees
,
286 if (file_exists(path
) && !is_empty_dir(path
))
287 die(_("'%s' already exists"), path
);
289 wt
= find_worktree_by_path(worktrees
, path
);
293 locked
= !!worktree_lock_reason(wt
);
294 if ((!locked
&& force
) || (locked
&& force
> 1)) {
295 if (delete_git_dir(wt
->id
))
296 die(_("unusable worktree destination '%s'"), path
);
301 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
303 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
306 static void copy_sparse_checkout(const char *worktree_git_dir
)
308 char *from_file
= git_pathdup("info/sparse-checkout");
309 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
311 if (file_exists(from_file
)) {
312 if (safe_create_leading_directories(to_file
) ||
313 copy_file(to_file
, from_file
, 0666))
314 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
322 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
324 char *from_file
= git_pathdup("config.worktree");
325 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
327 if (file_exists(from_file
)) {
328 struct config_set cs
= { { 0 } };
329 const char *core_worktree
;
332 if (safe_create_leading_directories(to_file
) ||
333 copy_file(to_file
, from_file
, 0666)) {
334 error(_("failed to copy worktree config from '%s' to '%s'"),
336 goto worktree_copy_cleanup
;
339 git_configset_init(&cs
);
340 git_configset_add_file(&cs
, from_file
);
342 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
344 git_config_set_multivar_in_file_gently(
345 to_file
, "core.bare", NULL
, "true", 0))
346 error(_("failed to unset '%s' in '%s'"),
347 "core.bare", to_file
);
348 if (!git_configset_get_value(&cs
, "core.worktree", &core_worktree
) &&
349 git_config_set_in_file_gently(to_file
,
350 "core.worktree", NULL
))
351 error(_("failed to unset '%s' in '%s'"),
352 "core.worktree", to_file
);
354 git_configset_clear(&cs
);
357 worktree_copy_cleanup
:
362 static int checkout_worktree(const struct add_opts
*opts
,
363 struct strvec
*child_env
)
365 struct child_process cp
= CHILD_PROCESS_INIT
;
367 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
369 strvec_push(&cp
.args
, "--quiet");
370 strvec_pushv(&cp
.env
, child_env
->v
);
371 return run_command(&cp
);
374 static int add_worktree(const char *path
, const char *refname
,
375 const struct add_opts
*opts
)
377 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
378 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_INIT
;
380 struct child_process cp
= CHILD_PROCESS_INIT
;
381 struct strvec child_env
= STRVEC_INIT
;
382 unsigned int counter
= 0;
384 struct strbuf symref
= STRBUF_INIT
;
385 struct commit
*commit
= NULL
;
387 struct strbuf sb_name
= STRBUF_INIT
;
388 struct worktree
**worktrees
;
390 worktrees
= get_worktrees();
391 check_candidate_path(path
, opts
->force
, worktrees
, "add");
392 free_worktrees(worktrees
);
395 /* is 'refname' a branch or commit? */
396 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
397 ref_exists(symref
.buf
)) {
400 die_if_checked_out(symref
.buf
, 0);
402 commit
= lookup_commit_reference_by_name(refname
);
404 die(_("invalid reference: %s"), refname
);
406 name
= worktree_basename(path
, &len
);
407 strbuf_add(&sb
, name
, path
+ len
- name
);
408 sanitize_refname_component(sb
.buf
, &sb_name
);
410 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
413 git_path_buf(&sb_repo
, "worktrees/%s", name
);
415 if (safe_create_leading_directories_const(sb_repo
.buf
))
416 die_errno(_("could not create leading directories of '%s'"),
419 while (mkdir(sb_repo
.buf
, 0777)) {
421 if ((errno
!= EEXIST
) || !counter
/* overflow */)
422 die_errno(_("could not create directory of '%s'"),
424 strbuf_setlen(&sb_repo
, len
);
425 strbuf_addf(&sb_repo
, "%d", counter
);
427 name
= strrchr(sb_repo
.buf
, '/') + 1;
431 sigchain_push_common(remove_junk_on_signal
);
433 junk_git_dir
= xstrdup(sb_repo
.buf
);
437 * lock the incomplete repo so prune won't delete it, unlock
438 * after the preparation is over.
440 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
441 if (opts
->keep_locked
)
442 write_file(sb
.buf
, "%s", opts
->keep_locked
);
444 write_file(sb
.buf
, _("initializing"));
446 strbuf_addf(&sb_git
, "%s/.git", path
);
447 if (safe_create_leading_directories_const(sb_git
.buf
))
448 die_errno(_("could not create leading directories of '%s'"),
450 junk_work_tree
= xstrdup(path
);
453 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
454 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
455 write_file(sb
.buf
, "%s", realpath
.buf
);
456 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
457 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
460 * This is to keep resolve_ref() happy. We need a valid HEAD
461 * or is_git_directory() will reject the directory. Any value which
462 * looks like an object ID will do since it will be immediately
463 * replaced by the symbolic-ref or update-ref invocation in the new
467 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
468 write_file(sb
.buf
, "%s", oid_to_hex(null_oid()));
470 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
471 write_file(sb
.buf
, "../..");
474 * If the current worktree has sparse-checkout enabled, then copy
475 * the sparse-checkout patterns from the current worktree.
477 if (core_apply_sparse_checkout
)
478 copy_sparse_checkout(sb_repo
.buf
);
481 * If we are using worktree config, then copy all current config
482 * values from the current worktree into the new one, that way the
483 * new worktree behaves the same as this one.
485 if (repository_format_worktree_config
)
486 copy_filtered_worktree_config(sb_repo
.buf
);
488 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
489 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
493 strvec_pushl(&cp
.args
, "update-ref", "HEAD",
494 oid_to_hex(&commit
->object
.oid
), NULL
);
496 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD",
499 strvec_push(&cp
.args
, "--quiet");
502 strvec_pushv(&cp
.env
, child_env
.v
);
503 ret
= run_command(&cp
);
507 if (opts
->checkout
&&
508 (ret
= checkout_worktree(opts
, &child_env
)))
512 FREE_AND_NULL(junk_work_tree
);
513 FREE_AND_NULL(junk_git_dir
);
516 if (ret
|| !opts
->keep_locked
) {
518 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
519 unlink_or_warn(sb
.buf
);
523 * Hook failure does not warrant worktree deletion, so run hook after
524 * is_junk is cleared, but do return appropriate code when hook fails.
526 if (!ret
&& opts
->checkout
) {
527 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
529 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
530 strvec_pushl(&opt
.args
,
531 oid_to_hex(null_oid()),
532 oid_to_hex(&commit
->object
.oid
),
537 ret
= run_hooks_opt("post-checkout", &opt
);
540 strvec_clear(&child_env
);
542 strbuf_release(&symref
);
543 strbuf_release(&sb_repo
);
544 strbuf_release(&sb_git
);
545 strbuf_release(&sb_name
);
546 strbuf_release(&realpath
);
550 static void print_preparing_worktree_line(int detach
,
552 const char *new_branch
,
553 int force_new_branch
)
555 if (force_new_branch
) {
556 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
558 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
560 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
562 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
563 } else if (new_branch
) {
564 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
566 struct strbuf s
= STRBUF_INIT
;
567 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
569 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
572 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
574 die(_("invalid reference: %s"), branch
);
575 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
576 repo_find_unique_abbrev(the_repository
, &commit
->object
.oid
, DEFAULT_ABBREV
));
582 static const char *dwim_branch(const char *path
, const char **new_branch
)
586 const char *s
= worktree_basename(path
, &n
);
587 const char *branchname
= xstrndup(s
, n
);
588 struct strbuf ref
= STRBUF_INIT
;
592 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
594 strbuf_release(&ref
);
598 *new_branch
= branchname
;
600 struct object_id oid
;
602 unique_tracking_name(*new_branch
, &oid
, NULL
);
608 static int add(int ac
, const char **av
, const char *prefix
)
610 struct add_opts opts
;
611 const char *new_branch_force
= NULL
;
614 const char *new_branch
= NULL
;
615 const char *opt_track
= NULL
;
616 const char *lock_reason
= NULL
;
618 struct option options
[] = {
619 OPT__FORCE(&opts
.force
,
620 N_("checkout <branch> even if already checked out in other worktree"),
621 PARSE_OPT_NOCOMPLETE
),
622 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
623 N_("create a new branch")),
624 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
625 N_("create or reset a branch")),
626 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
627 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
628 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
629 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
630 N_("reason for locking")),
631 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
632 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
633 N_("set up tracking mode (see git-branch(1))"),
634 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
635 OPT_BOOL(0, "guess-remote", &guess_remote
,
636 N_("try to match the new branch name with a remote-tracking branch")),
641 memset(&opts
, 0, sizeof(opts
));
643 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
644 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
645 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
646 if (lock_reason
&& !keep_locked
)
647 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
649 opts
.keep_locked
= lock_reason
;
650 else if (keep_locked
)
651 opts
.keep_locked
= _("added with --lock");
653 if (ac
< 1 || ac
> 2)
654 usage_with_options(git_worktree_add_usage
, options
);
656 path
= prefix_filename(prefix
, av
[0]);
657 branch
= ac
< 2 ? "HEAD" : av
[1];
659 if (!strcmp(branch
, "-"))
662 if (new_branch_force
) {
663 struct strbuf symref
= STRBUF_INIT
;
665 new_branch
= new_branch_force
;
668 !strbuf_check_branch_ref(&symref
, new_branch
) &&
669 ref_exists(symref
.buf
))
670 die_if_checked_out(symref
.buf
, 0);
671 strbuf_release(&symref
);
674 if (ac
< 2 && !new_branch
&& !opts
.detach
) {
675 const char *s
= dwim_branch(path
, &new_branch
);
680 if (ac
== 2 && !new_branch
&& !opts
.detach
) {
681 struct object_id oid
;
682 struct commit
*commit
;
685 commit
= lookup_commit_reference_by_name(branch
);
687 remote
= unique_tracking_name(branch
, &oid
, NULL
);
695 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
698 struct child_process cp
= CHILD_PROCESS_INIT
;
700 strvec_push(&cp
.args
, "branch");
701 if (new_branch_force
)
702 strvec_push(&cp
.args
, "--force");
704 strvec_push(&cp
.args
, "--quiet");
705 strvec_push(&cp
.args
, new_branch
);
706 strvec_push(&cp
.args
, branch
);
708 strvec_push(&cp
.args
, opt_track
);
709 if (run_command(&cp
))
712 } else if (opt_track
) {
713 die(_("--[no-]track can only be used if a new branch is created"));
716 ret
= add_worktree(path
, branch
, &opts
);
721 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
725 printf("worktree %s%c", wt
->path
, line_terminator
);
727 printf("bare%c", line_terminator
);
729 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
731 printf("detached%c", line_terminator
);
732 else if (wt
->head_ref
)
733 printf("branch %s%c", wt
->head_ref
, line_terminator
);
736 reason
= worktree_lock_reason(wt
);
738 fputs("locked", stdout
);
741 write_name_quoted(reason
, stdout
, line_terminator
);
743 fputc(line_terminator
, stdout
);
747 reason
= worktree_prune_reason(wt
, expire
);
749 printf("prunable %s%c", reason
, line_terminator
);
751 fputc(line_terminator
, stdout
);
754 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
756 struct strbuf sb
= STRBUF_INIT
;
757 int cur_path_len
= strlen(wt
->path
);
758 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
761 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
763 strbuf_addstr(&sb
, "(bare)");
765 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
766 repo_find_unique_abbrev(the_repository
, &wt
->head_oid
, DEFAULT_ABBREV
));
768 strbuf_addstr(&sb
, "(detached HEAD)");
769 else if (wt
->head_ref
) {
770 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
771 strbuf_addf(&sb
, "[%s]", ref
);
774 strbuf_addstr(&sb
, "(error)");
777 reason
= worktree_lock_reason(wt
);
778 if (verbose
&& reason
&& *reason
)
779 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
781 strbuf_addstr(&sb
, " locked");
783 reason
= worktree_prune_reason(wt
, expire
);
784 if (verbose
&& reason
)
785 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
787 strbuf_addstr(&sb
, " prunable");
789 printf("%s\n", sb
.buf
);
793 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
797 for (i
= 0; wt
[i
]; i
++) {
799 int path_len
= strlen(wt
[i
]->path
);
801 if (path_len
> *maxlen
)
803 sha1_len
= strlen(repo_find_unique_abbrev(the_repository
, &wt
[i
]->head_oid
, *abbrev
));
804 if (sha1_len
> *abbrev
)
809 static int pathcmp(const void *a_
, const void *b_
)
811 const struct worktree
*const *a
= a_
;
812 const struct worktree
*const *b
= b_
;
813 return fspathcmp((*a
)->path
, (*b
)->path
);
816 static void pathsort(struct worktree
**wt
)
819 struct worktree
**p
= wt
;
823 QSORT(wt
, n
, pathcmp
);
826 static int list(int ac
, const char **av
, const char *prefix
)
829 int line_terminator
= '\n';
831 struct option options
[] = {
832 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
833 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
834 OPT_EXPIRY_DATE(0, "expire", &expire
,
835 N_("add 'prunable' annotation to worktrees older than <time>")),
836 OPT_SET_INT('z', NULL
, &line_terminator
,
837 N_("terminate records with a NUL character"), '\0'),
842 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
844 usage_with_options(git_worktree_list_usage
, options
);
845 else if (verbose
&& porcelain
)
846 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
847 else if (!line_terminator
&& !porcelain
)
848 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
850 struct worktree
**worktrees
= get_worktrees();
851 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
853 /* sort worktrees by path but keep main worktree at top */
854 pathsort(worktrees
+ 1);
857 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
859 for (i
= 0; worktrees
[i
]; i
++) {
861 show_worktree_porcelain(worktrees
[i
],
864 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
866 free_worktrees(worktrees
);
871 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
873 const char *reason
= "", *old_reason
;
874 struct option options
[] = {
875 OPT_STRING(0, "reason", &reason
, N_("string"),
876 N_("reason for locking")),
879 struct worktree
**worktrees
, *wt
;
881 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
883 usage_with_options(git_worktree_lock_usage
, options
);
885 worktrees
= get_worktrees();
886 wt
= find_worktree(worktrees
, prefix
, av
[0]);
888 die(_("'%s' is not a working tree"), av
[0]);
889 if (is_main_worktree(wt
))
890 die(_("The main working tree cannot be locked or unlocked"));
892 old_reason
= worktree_lock_reason(wt
);
895 die(_("'%s' is already locked, reason: %s"),
897 die(_("'%s' is already locked"), av
[0]);
900 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
902 free_worktrees(worktrees
);
906 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
908 struct option options
[] = {
911 struct worktree
**worktrees
, *wt
;
914 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
916 usage_with_options(git_worktree_unlock_usage
, options
);
918 worktrees
= get_worktrees();
919 wt
= find_worktree(worktrees
, prefix
, av
[0]);
921 die(_("'%s' is not a working tree"), av
[0]);
922 if (is_main_worktree(wt
))
923 die(_("The main working tree cannot be locked or unlocked"));
924 if (!worktree_lock_reason(wt
))
925 die(_("'%s' is not locked"), av
[0]);
926 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
927 free_worktrees(worktrees
);
931 static void validate_no_submodules(const struct worktree
*wt
)
933 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
934 struct strbuf path
= STRBUF_INIT
;
935 int i
, found_submodules
= 0;
937 if (is_directory(worktree_git_path(wt
, "modules"))) {
939 * There could be false positives, e.g. the "modules"
940 * directory exists but is empty. But it's a rare case and
941 * this simpler check is probably good enough for now.
943 found_submodules
= 1;
944 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
945 get_worktree_git_dir(wt
)) > 0) {
946 for (i
= 0; i
< istate
.cache_nr
; i
++) {
947 struct cache_entry
*ce
= istate
.cache
[i
];
950 if (!S_ISGITLINK(ce
->ce_mode
))
954 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
955 if (!is_submodule_populated_gently(path
.buf
, &err
))
958 found_submodules
= 1;
962 discard_index(&istate
);
963 strbuf_release(&path
);
965 if (found_submodules
)
966 die(_("working trees containing submodules cannot be moved or removed"));
969 static int move_worktree(int ac
, const char **av
, const char *prefix
)
972 struct option options
[] = {
974 N_("force move even if worktree is dirty or locked"),
975 PARSE_OPT_NOCOMPLETE
),
978 struct worktree
**worktrees
, *wt
;
979 struct strbuf dst
= STRBUF_INIT
;
980 struct strbuf errmsg
= STRBUF_INIT
;
981 const char *reason
= NULL
;
984 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
987 usage_with_options(git_worktree_move_usage
, options
);
989 path
= prefix_filename(prefix
, av
[1]);
990 strbuf_addstr(&dst
, path
);
993 worktrees
= get_worktrees();
994 wt
= find_worktree(worktrees
, prefix
, av
[0]);
996 die(_("'%s' is not a working tree"), av
[0]);
997 if (is_main_worktree(wt
))
998 die(_("'%s' is a main working tree"), av
[0]);
999 if (is_directory(dst
.buf
)) {
1000 const char *sep
= find_last_dir_sep(wt
->path
);
1003 die(_("could not figure out destination name from '%s'"),
1005 strbuf_trim_trailing_dir_sep(&dst
);
1006 strbuf_addstr(&dst
, sep
);
1008 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1010 validate_no_submodules(wt
);
1013 reason
= worktree_lock_reason(wt
);
1016 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1018 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1020 if (validate_worktree(wt
, &errmsg
, 0))
1021 die(_("validation failed, cannot move working tree: %s"),
1023 strbuf_release(&errmsg
);
1025 if (rename(wt
->path
, dst
.buf
) == -1)
1026 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1028 update_worktree_location(wt
, dst
.buf
);
1030 strbuf_release(&dst
);
1031 free_worktrees(worktrees
);
1036 * Note, "git status --porcelain" is used to determine if it's safe to
1037 * delete a whole worktree. "git status" does not ignore user
1038 * configuration, so if a normal "git status" shows "clean" for the
1039 * user, then it's ok to remove it.
1041 * This assumption may be a bad one. We may want to ignore
1042 * (potentially bad) user settings and only delete a worktree when
1043 * it's absolutely safe to do so from _our_ point of view because we
1046 static void check_clean_worktree(struct worktree
*wt
,
1047 const char *original_path
)
1049 struct child_process cp
;
1054 * Until we sort this out, all submodules are "dirty" and
1055 * will abort this function.
1057 validate_no_submodules(wt
);
1059 child_process_init(&cp
);
1060 strvec_pushf(&cp
.env
, "%s=%s/.git",
1061 GIT_DIR_ENVIRONMENT
, wt
->path
);
1062 strvec_pushf(&cp
.env
, "%s=%s",
1063 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1064 strvec_pushl(&cp
.args
, "status",
1065 "--porcelain", "--ignore-submodules=none",
1070 ret
= start_command(&cp
);
1072 die_errno(_("failed to run 'git status' on '%s'"),
1074 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1076 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1079 ret
= finish_command(&cp
);
1081 die_errno(_("failed to run 'git status' on '%s', code %d"),
1082 original_path
, ret
);
1085 static int delete_git_work_tree(struct worktree
*wt
)
1087 struct strbuf sb
= STRBUF_INIT
;
1090 strbuf_addstr(&sb
, wt
->path
);
1091 if (remove_dir_recursively(&sb
, 0)) {
1092 error_errno(_("failed to delete '%s'"), sb
.buf
);
1095 strbuf_release(&sb
);
1099 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1102 struct option options
[] = {
1104 N_("force removal even if worktree is dirty or locked"),
1105 PARSE_OPT_NOCOMPLETE
),
1108 struct worktree
**worktrees
, *wt
;
1109 struct strbuf errmsg
= STRBUF_INIT
;
1110 const char *reason
= NULL
;
1113 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1115 usage_with_options(git_worktree_remove_usage
, options
);
1117 worktrees
= get_worktrees();
1118 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1120 die(_("'%s' is not a working tree"), av
[0]);
1121 if (is_main_worktree(wt
))
1122 die(_("'%s' is a main working tree"), av
[0]);
1124 reason
= worktree_lock_reason(wt
);
1127 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1129 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1131 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1132 die(_("validation failed, cannot remove working tree: %s"),
1134 strbuf_release(&errmsg
);
1136 if (file_exists(wt
->path
)) {
1138 check_clean_worktree(wt
, av
[0]);
1140 ret
|= delete_git_work_tree(wt
);
1143 * continue on even if ret is non-zero, there's no going back
1146 ret
|= delete_git_dir(wt
->id
);
1147 delete_worktrees_dir_if_empty();
1149 free_worktrees(worktrees
);
1153 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1156 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1158 int *exit_status
= (int *)cb_data
;
1159 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1164 static int repair(int ac
, const char **av
, const char *prefix
)
1167 const char *self
[] = { ".", NULL
};
1168 struct option options
[] = {
1173 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1174 p
= ac
> 0 ? av
: self
;
1176 repair_worktree_at_path(*p
, report_repair
, &rc
);
1177 repair_worktrees(report_repair
, &rc
);
1181 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1183 parse_opt_subcommand_fn
*fn
= NULL
;
1184 struct option options
[] = {
1185 OPT_SUBCOMMAND("add", &fn
, add
),
1186 OPT_SUBCOMMAND("prune", &fn
, prune
),
1187 OPT_SUBCOMMAND("list", &fn
, list
),
1188 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1189 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1190 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1191 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1192 OPT_SUBCOMMAND("repair", &fn
, repair
),
1196 git_config(git_worktree_config
, NULL
);
1201 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1202 return fn(ac
, av
, prefix
);