7 #include "parse-options.h"
11 #include "run-command.h"
14 #include "submodule.h"
19 #define BUILTIN_WORKTREE_ADD_USAGE \
20 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
21 " [-b <new-branch>] <path> [<commit-ish>]")
22 #define BUILTIN_WORKTREE_LIST_USAGE \
23 N_("git worktree list [-v | --porcelain [-z]]")
24 #define BUILTIN_WORKTREE_LOCK_USAGE \
25 N_("git worktree lock [--reason <string>] <worktree>")
26 #define BUILTIN_WORKTREE_MOVE_USAGE \
27 N_("git worktree move <worktree> <new-path>")
28 #define BUILTIN_WORKTREE_PRUNE_USAGE \
29 N_("git worktree prune [-n] [-v] [--expire <expire>]")
30 #define BUILTIN_WORKTREE_REMOVE_USAGE \
31 N_("git worktree remove [-f] <worktree>")
32 #define BUILTIN_WORKTREE_REPAIR_USAGE \
33 N_("git worktree repair [<path>...]")
34 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
35 N_("git worktree unlock <worktree>")
37 static const char * const git_worktree_usage
[] = {
38 BUILTIN_WORKTREE_ADD_USAGE
,
39 BUILTIN_WORKTREE_LIST_USAGE
,
40 BUILTIN_WORKTREE_LOCK_USAGE
,
41 BUILTIN_WORKTREE_MOVE_USAGE
,
42 BUILTIN_WORKTREE_PRUNE_USAGE
,
43 BUILTIN_WORKTREE_REMOVE_USAGE
,
44 BUILTIN_WORKTREE_REPAIR_USAGE
,
45 BUILTIN_WORKTREE_UNLOCK_USAGE
,
49 static const char * const git_worktree_add_usage
[] = {
50 BUILTIN_WORKTREE_ADD_USAGE
,
54 static const char * const git_worktree_list_usage
[] = {
55 BUILTIN_WORKTREE_LIST_USAGE
,
59 static const char * const git_worktree_lock_usage
[] = {
60 BUILTIN_WORKTREE_LOCK_USAGE
,
64 static const char * const git_worktree_move_usage
[] = {
65 BUILTIN_WORKTREE_MOVE_USAGE
,
69 static const char * const git_worktree_prune_usage
[] = {
70 BUILTIN_WORKTREE_PRUNE_USAGE
,
74 static const char * const git_worktree_remove_usage
[] = {
75 BUILTIN_WORKTREE_REMOVE_USAGE
,
79 static const char * const git_worktree_repair_usage
[] = {
80 BUILTIN_WORKTREE_REPAIR_USAGE
,
84 static const char * const git_worktree_unlock_usage
[] = {
85 BUILTIN_WORKTREE_UNLOCK_USAGE
,
94 const char *keep_locked
;
99 static int guess_remote
;
100 static timestamp_t expire
;
102 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
104 if (!strcmp(var
, "worktree.guessremote")) {
105 guess_remote
= git_config_bool(var
, value
);
109 return git_default_config(var
, value
, cb
);
112 static int delete_git_dir(const char *id
)
114 struct strbuf sb
= STRBUF_INIT
;
117 strbuf_addstr(&sb
, git_common_path("worktrees/%s", id
));
118 ret
= remove_dir_recursively(&sb
, 0);
119 if (ret
< 0 && errno
== ENOTDIR
)
120 ret
= unlink(sb
.buf
);
122 error_errno(_("failed to delete '%s'"), sb
.buf
);
127 static void delete_worktrees_dir_if_empty(void)
129 rmdir(git_path("worktrees")); /* ignore failed removal */
132 static void prune_worktree(const char *id
, const char *reason
)
134 if (show_only
|| verbose
)
135 fprintf_ln(stderr
, _("Removing %s/%s: %s"), "worktrees", id
, reason
);
140 static int prune_cmp(const void *a
, const void *b
)
142 const struct string_list_item
*x
= a
;
143 const struct string_list_item
*y
= b
;
146 if ((c
= fspathcmp(x
->string
, y
->string
)))
149 * paths same; prune_dupes() removes all but the first worktree entry
150 * having the same path, so sort main worktree ('util' is NULL) above
151 * linked worktrees ('util' not NULL) since main worktree can't be
158 /* paths same; sort by .git/worktrees/<id> */
159 return strcmp(x
->util
, y
->util
);
162 static void prune_dups(struct string_list
*l
)
166 QSORT(l
->items
, l
->nr
, prune_cmp
);
167 for (i
= 1; i
< l
->nr
; i
++) {
168 if (!fspathcmp(l
->items
[i
].string
, l
->items
[i
- 1].string
))
169 prune_worktree(l
->items
[i
].util
, "duplicate entry");
173 static void prune_worktrees(void)
175 struct strbuf reason
= STRBUF_INIT
;
176 struct strbuf main_path
= STRBUF_INIT
;
177 struct string_list kept
= STRING_LIST_INIT_DUP
;
178 DIR *dir
= opendir(git_path("worktrees"));
182 while ((d
= readdir_skip_dot_and_dotdot(dir
)) != NULL
) {
184 strbuf_reset(&reason
);
185 if (should_prune_worktree(d
->d_name
, &reason
, &path
, expire
))
186 prune_worktree(d
->d_name
, reason
.buf
);
188 string_list_append_nodup(&kept
, path
)->util
= xstrdup(d
->d_name
);
192 strbuf_add_absolute_path(&main_path
, get_git_common_dir());
193 /* massage main worktree absolute path to match 'gitdir' content */
194 strbuf_strip_suffix(&main_path
, "/.");
195 string_list_append_nodup(&kept
, strbuf_detach(&main_path
, NULL
));
197 string_list_clear(&kept
, 1);
200 delete_worktrees_dir_if_empty();
201 strbuf_release(&reason
);
204 static int prune(int ac
, const char **av
, const char *prefix
)
206 struct option options
[] = {
207 OPT__DRY_RUN(&show_only
, N_("do not remove, show only")),
208 OPT__VERBOSE(&verbose
, N_("report pruned working trees")),
209 OPT_EXPIRY_DATE(0, "expire", &expire
,
210 N_("expire working trees older than <time>")),
215 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_prune_usage
,
218 usage_with_options(git_worktree_prune_usage
, options
);
223 static char *junk_work_tree
;
224 static char *junk_git_dir
;
226 static pid_t junk_pid
;
228 static void remove_junk(void)
230 struct strbuf sb
= STRBUF_INIT
;
231 if (!is_junk
|| getpid() != junk_pid
)
234 strbuf_addstr(&sb
, junk_git_dir
);
235 remove_dir_recursively(&sb
, 0);
238 if (junk_work_tree
) {
239 strbuf_addstr(&sb
, junk_work_tree
);
240 remove_dir_recursively(&sb
, 0);
245 static void remove_junk_on_signal(int signo
)
252 static const char *worktree_basename(const char *path
, int *olen
)
258 while (len
&& is_dir_sep(path
[len
- 1]))
261 for (name
= path
+ len
- 1; name
> path
; name
--)
262 if (is_dir_sep(*name
)) {
271 /* check that path is viable location for worktree */
272 static void check_candidate_path(const char *path
,
274 struct worktree
**worktrees
,
280 if (file_exists(path
) && !is_empty_dir(path
))
281 die(_("'%s' already exists"), path
);
283 wt
= find_worktree_by_path(worktrees
, path
);
287 locked
= !!worktree_lock_reason(wt
);
288 if ((!locked
&& force
) || (locked
&& force
> 1)) {
289 if (delete_git_dir(wt
->id
))
290 die(_("unusable worktree destination '%s'"), path
);
295 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path
, cmd
);
297 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path
, cmd
);
300 static void copy_sparse_checkout(const char *worktree_git_dir
)
302 char *from_file
= git_pathdup("info/sparse-checkout");
303 char *to_file
= xstrfmt("%s/info/sparse-checkout", worktree_git_dir
);
305 if (file_exists(from_file
)) {
306 if (safe_create_leading_directories(to_file
) ||
307 copy_file(to_file
, from_file
, 0666))
308 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
316 static void copy_filtered_worktree_config(const char *worktree_git_dir
)
318 char *from_file
= git_pathdup("config.worktree");
319 char *to_file
= xstrfmt("%s/config.worktree", worktree_git_dir
);
321 if (file_exists(from_file
)) {
322 struct config_set cs
= { { 0 } };
323 const char *core_worktree
;
326 if (safe_create_leading_directories(to_file
) ||
327 copy_file(to_file
, from_file
, 0666)) {
328 error(_("failed to copy worktree config from '%s' to '%s'"),
330 goto worktree_copy_cleanup
;
333 git_configset_init(&cs
);
334 git_configset_add_file(&cs
, from_file
);
336 if (!git_configset_get_bool(&cs
, "core.bare", &bare
) &&
338 git_config_set_multivar_in_file_gently(
339 to_file
, "core.bare", NULL
, "true", 0))
340 error(_("failed to unset '%s' in '%s'"),
341 "core.bare", to_file
);
342 if (!git_configset_get_value(&cs
, "core.worktree", &core_worktree
) &&
343 git_config_set_in_file_gently(to_file
,
344 "core.worktree", NULL
))
345 error(_("failed to unset '%s' in '%s'"),
346 "core.worktree", to_file
);
348 git_configset_clear(&cs
);
351 worktree_copy_cleanup
:
356 static int checkout_worktree(const struct add_opts
*opts
,
357 struct strvec
*child_env
)
359 struct child_process cp
= CHILD_PROCESS_INIT
;
361 strvec_pushl(&cp
.args
, "reset", "--hard", "--no-recurse-submodules", NULL
);
363 strvec_push(&cp
.args
, "--quiet");
364 strvec_pushv(&cp
.env
, child_env
->v
);
365 return run_command(&cp
);
368 static int add_worktree(const char *path
, const char *refname
,
369 const struct add_opts
*opts
)
371 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
372 struct strbuf sb
= STRBUF_INIT
, realpath
= STRBUF_INIT
;
374 struct child_process cp
= CHILD_PROCESS_INIT
;
375 struct strvec child_env
= STRVEC_INIT
;
376 unsigned int counter
= 0;
378 struct strbuf symref
= STRBUF_INIT
;
379 struct commit
*commit
= NULL
;
381 struct strbuf sb_name
= STRBUF_INIT
;
382 struct worktree
**worktrees
;
384 worktrees
= get_worktrees();
385 check_candidate_path(path
, opts
->force
, worktrees
, "add");
386 free_worktrees(worktrees
);
389 /* is 'refname' a branch or commit? */
390 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
391 ref_exists(symref
.buf
)) {
394 die_if_checked_out(symref
.buf
, 0);
396 commit
= lookup_commit_reference_by_name(refname
);
398 die(_("invalid reference: %s"), refname
);
400 name
= worktree_basename(path
, &len
);
401 strbuf_add(&sb
, name
, path
+ len
- name
);
402 sanitize_refname_component(sb
.buf
, &sb_name
);
404 BUG("How come '%s' becomes empty after sanitization?", sb
.buf
);
407 git_path_buf(&sb_repo
, "worktrees/%s", name
);
409 if (safe_create_leading_directories_const(sb_repo
.buf
))
410 die_errno(_("could not create leading directories of '%s'"),
413 while (mkdir(sb_repo
.buf
, 0777)) {
415 if ((errno
!= EEXIST
) || !counter
/* overflow */)
416 die_errno(_("could not create directory of '%s'"),
418 strbuf_setlen(&sb_repo
, len
);
419 strbuf_addf(&sb_repo
, "%d", counter
);
421 name
= strrchr(sb_repo
.buf
, '/') + 1;
425 sigchain_push_common(remove_junk_on_signal
);
427 junk_git_dir
= xstrdup(sb_repo
.buf
);
431 * lock the incomplete repo so prune won't delete it, unlock
432 * after the preparation is over.
434 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
435 if (opts
->keep_locked
)
436 write_file(sb
.buf
, "%s", opts
->keep_locked
);
438 write_file(sb
.buf
, _("initializing"));
440 strbuf_addf(&sb_git
, "%s/.git", path
);
441 if (safe_create_leading_directories_const(sb_git
.buf
))
442 die_errno(_("could not create leading directories of '%s'"),
444 junk_work_tree
= xstrdup(path
);
447 strbuf_addf(&sb
, "%s/gitdir", sb_repo
.buf
);
448 strbuf_realpath(&realpath
, sb_git
.buf
, 1);
449 write_file(sb
.buf
, "%s", realpath
.buf
);
450 strbuf_realpath(&realpath
, get_git_common_dir(), 1);
451 write_file(sb_git
.buf
, "gitdir: %s/worktrees/%s",
454 * This is to keep resolve_ref() happy. We need a valid HEAD
455 * or is_git_directory() will reject the directory. Any value which
456 * looks like an object ID will do since it will be immediately
457 * replaced by the symbolic-ref or update-ref invocation in the new
461 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
462 write_file(sb
.buf
, "%s", oid_to_hex(null_oid()));
464 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
465 write_file(sb
.buf
, "../..");
468 * If the current worktree has sparse-checkout enabled, then copy
469 * the sparse-checkout patterns from the current worktree.
471 if (core_apply_sparse_checkout
)
472 copy_sparse_checkout(sb_repo
.buf
);
475 * If we are using worktree config, then copy all current config
476 * values from the current worktree into the new one, that way the
477 * new worktree behaves the same as this one.
479 if (repository_format_worktree_config
)
480 copy_filtered_worktree_config(sb_repo
.buf
);
482 strvec_pushf(&child_env
, "%s=%s", GIT_DIR_ENVIRONMENT
, sb_git
.buf
);
483 strvec_pushf(&child_env
, "%s=%s", GIT_WORK_TREE_ENVIRONMENT
, path
);
487 strvec_pushl(&cp
.args
, "update-ref", "HEAD",
488 oid_to_hex(&commit
->object
.oid
), NULL
);
490 strvec_pushl(&cp
.args
, "symbolic-ref", "HEAD",
493 strvec_push(&cp
.args
, "--quiet");
496 strvec_pushv(&cp
.env
, child_env
.v
);
497 ret
= run_command(&cp
);
501 if (opts
->checkout
&&
502 (ret
= checkout_worktree(opts
, &child_env
)))
506 FREE_AND_NULL(junk_work_tree
);
507 FREE_AND_NULL(junk_git_dir
);
510 if (ret
|| !opts
->keep_locked
) {
512 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
513 unlink_or_warn(sb
.buf
);
517 * Hook failure does not warrant worktree deletion, so run hook after
518 * is_junk is cleared, but do return appropriate code when hook fails.
520 if (!ret
&& opts
->checkout
) {
521 struct run_hooks_opt opt
= RUN_HOOKS_OPT_INIT
;
523 strvec_pushl(&opt
.env
, "GIT_DIR", "GIT_WORK_TREE", NULL
);
524 strvec_pushl(&opt
.args
,
525 oid_to_hex(null_oid()),
526 oid_to_hex(&commit
->object
.oid
),
531 ret
= run_hooks_opt("post-checkout", &opt
);
534 strvec_clear(&child_env
);
536 strbuf_release(&symref
);
537 strbuf_release(&sb_repo
);
538 strbuf_release(&sb_git
);
539 strbuf_release(&sb_name
);
540 strbuf_release(&realpath
);
544 static void print_preparing_worktree_line(int detach
,
546 const char *new_branch
,
547 int force_new_branch
)
549 if (force_new_branch
) {
550 struct commit
*commit
= lookup_commit_reference_by_name(new_branch
);
552 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
554 fprintf_ln(stderr
, _("Preparing worktree (resetting branch '%s'; was at %s)"),
556 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
557 } else if (new_branch
) {
558 fprintf_ln(stderr
, _("Preparing worktree (new branch '%s')"), new_branch
);
560 struct strbuf s
= STRBUF_INIT
;
561 if (!detach
&& !strbuf_check_branch_ref(&s
, branch
) &&
563 fprintf_ln(stderr
, _("Preparing worktree (checking out '%s')"),
566 struct commit
*commit
= lookup_commit_reference_by_name(branch
);
568 die(_("invalid reference: %s"), branch
);
569 fprintf_ln(stderr
, _("Preparing worktree (detached HEAD %s)"),
570 find_unique_abbrev(&commit
->object
.oid
, DEFAULT_ABBREV
));
576 static const char *dwim_branch(const char *path
, const char **new_branch
)
580 const char *s
= worktree_basename(path
, &n
);
581 const char *branchname
= xstrndup(s
, n
);
582 struct strbuf ref
= STRBUF_INIT
;
586 branch_exists
= !strbuf_check_branch_ref(&ref
, branchname
) &&
588 strbuf_release(&ref
);
592 *new_branch
= branchname
;
594 struct object_id oid
;
596 unique_tracking_name(*new_branch
, &oid
, NULL
);
602 static int add(int ac
, const char **av
, const char *prefix
)
604 struct add_opts opts
;
605 const char *new_branch_force
= NULL
;
608 const char *new_branch
= NULL
;
609 const char *opt_track
= NULL
;
610 const char *lock_reason
= NULL
;
612 struct option options
[] = {
613 OPT__FORCE(&opts
.force
,
614 N_("checkout <branch> even if already checked out in other worktree"),
615 PARSE_OPT_NOCOMPLETE
),
616 OPT_STRING('b', NULL
, &new_branch
, N_("branch"),
617 N_("create a new branch")),
618 OPT_STRING('B', NULL
, &new_branch_force
, N_("branch"),
619 N_("create or reset a branch")),
620 OPT_BOOL('d', "detach", &opts
.detach
, N_("detach HEAD at named commit")),
621 OPT_BOOL(0, "checkout", &opts
.checkout
, N_("populate the new working tree")),
622 OPT_BOOL(0, "lock", &keep_locked
, N_("keep the new working tree locked")),
623 OPT_STRING(0, "reason", &lock_reason
, N_("string"),
624 N_("reason for locking")),
625 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
626 OPT_PASSTHRU(0, "track", &opt_track
, NULL
,
627 N_("set up tracking mode (see git-branch(1))"),
628 PARSE_OPT_NOARG
| PARSE_OPT_OPTARG
),
629 OPT_BOOL(0, "guess-remote", &guess_remote
,
630 N_("try to match the new branch name with a remote-tracking branch")),
635 memset(&opts
, 0, sizeof(opts
));
637 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_add_usage
, 0);
638 if (!!opts
.detach
+ !!new_branch
+ !!new_branch_force
> 1)
639 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
640 if (lock_reason
&& !keep_locked
)
641 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
643 opts
.keep_locked
= lock_reason
;
644 else if (keep_locked
)
645 opts
.keep_locked
= _("added with --lock");
647 if (ac
< 1 || ac
> 2)
648 usage_with_options(git_worktree_add_usage
, options
);
650 path
= prefix_filename(prefix
, av
[0]);
651 branch
= ac
< 2 ? "HEAD" : av
[1];
653 if (!strcmp(branch
, "-"))
656 if (new_branch_force
) {
657 struct strbuf symref
= STRBUF_INIT
;
659 new_branch
= new_branch_force
;
662 !strbuf_check_branch_ref(&symref
, new_branch
) &&
663 ref_exists(symref
.buf
))
664 die_if_checked_out(symref
.buf
, 0);
665 strbuf_release(&symref
);
668 if (ac
< 2 && !new_branch
&& !opts
.detach
) {
669 const char *s
= dwim_branch(path
, &new_branch
);
674 if (ac
== 2 && !new_branch
&& !opts
.detach
) {
675 struct object_id oid
;
676 struct commit
*commit
;
679 commit
= lookup_commit_reference_by_name(branch
);
681 remote
= unique_tracking_name(branch
, &oid
, NULL
);
689 print_preparing_worktree_line(opts
.detach
, branch
, new_branch
, !!new_branch_force
);
692 struct child_process cp
= CHILD_PROCESS_INIT
;
694 strvec_push(&cp
.args
, "branch");
695 if (new_branch_force
)
696 strvec_push(&cp
.args
, "--force");
698 strvec_push(&cp
.args
, "--quiet");
699 strvec_push(&cp
.args
, new_branch
);
700 strvec_push(&cp
.args
, branch
);
702 strvec_push(&cp
.args
, opt_track
);
703 if (run_command(&cp
))
706 } else if (opt_track
) {
707 die(_("--[no-]track can only be used if a new branch is created"));
710 ret
= add_worktree(path
, branch
, &opts
);
715 static void show_worktree_porcelain(struct worktree
*wt
, int line_terminator
)
719 printf("worktree %s%c", wt
->path
, line_terminator
);
721 printf("bare%c", line_terminator
);
723 printf("HEAD %s%c", oid_to_hex(&wt
->head_oid
), line_terminator
);
725 printf("detached%c", line_terminator
);
726 else if (wt
->head_ref
)
727 printf("branch %s%c", wt
->head_ref
, line_terminator
);
730 reason
= worktree_lock_reason(wt
);
732 fputs("locked", stdout
);
735 write_name_quoted(reason
, stdout
, line_terminator
);
737 fputc(line_terminator
, stdout
);
741 reason
= worktree_prune_reason(wt
, expire
);
743 printf("prunable %s%c", reason
, line_terminator
);
745 fputc(line_terminator
, stdout
);
748 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
750 struct strbuf sb
= STRBUF_INIT
;
751 int cur_path_len
= strlen(wt
->path
);
752 int path_adj
= cur_path_len
- utf8_strwidth(wt
->path
);
755 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
757 strbuf_addstr(&sb
, "(bare)");
759 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
760 find_unique_abbrev(&wt
->head_oid
, DEFAULT_ABBREV
));
762 strbuf_addstr(&sb
, "(detached HEAD)");
763 else if (wt
->head_ref
) {
764 char *ref
= shorten_unambiguous_ref(wt
->head_ref
, 0);
765 strbuf_addf(&sb
, "[%s]", ref
);
768 strbuf_addstr(&sb
, "(error)");
771 reason
= worktree_lock_reason(wt
);
772 if (verbose
&& reason
&& *reason
)
773 strbuf_addf(&sb
, "\n\tlocked: %s", reason
);
775 strbuf_addstr(&sb
, " locked");
777 reason
= worktree_prune_reason(wt
, expire
);
778 if (verbose
&& reason
)
779 strbuf_addf(&sb
, "\n\tprunable: %s", reason
);
781 strbuf_addstr(&sb
, " prunable");
783 printf("%s\n", sb
.buf
);
787 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
791 for (i
= 0; wt
[i
]; i
++) {
793 int path_len
= strlen(wt
[i
]->path
);
795 if (path_len
> *maxlen
)
797 sha1_len
= strlen(find_unique_abbrev(&wt
[i
]->head_oid
, *abbrev
));
798 if (sha1_len
> *abbrev
)
803 static int pathcmp(const void *a_
, const void *b_
)
805 const struct worktree
*const *a
= a_
;
806 const struct worktree
*const *b
= b_
;
807 return fspathcmp((*a
)->path
, (*b
)->path
);
810 static void pathsort(struct worktree
**wt
)
813 struct worktree
**p
= wt
;
817 QSORT(wt
, n
, pathcmp
);
820 static int list(int ac
, const char **av
, const char *prefix
)
823 int line_terminator
= '\n';
825 struct option options
[] = {
826 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
827 OPT__VERBOSE(&verbose
, N_("show extended annotations and reasons, if available")),
828 OPT_EXPIRY_DATE(0, "expire", &expire
,
829 N_("add 'prunable' annotation to worktrees older than <time>")),
830 OPT_SET_INT('z', NULL
, &line_terminator
,
831 N_("terminate records with a NUL character"), '\0'),
836 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_list_usage
, 0);
838 usage_with_options(git_worktree_list_usage
, options
);
839 else if (verbose
&& porcelain
)
840 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
841 else if (!line_terminator
&& !porcelain
)
842 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
844 struct worktree
**worktrees
= get_worktrees();
845 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
847 /* sort worktrees by path but keep main worktree at top */
848 pathsort(worktrees
+ 1);
851 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
853 for (i
= 0; worktrees
[i
]; i
++) {
855 show_worktree_porcelain(worktrees
[i
],
858 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
860 free_worktrees(worktrees
);
865 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
867 const char *reason
= "", *old_reason
;
868 struct option options
[] = {
869 OPT_STRING(0, "reason", &reason
, N_("string"),
870 N_("reason for locking")),
873 struct worktree
**worktrees
, *wt
;
875 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_lock_usage
, 0);
877 usage_with_options(git_worktree_lock_usage
, options
);
879 worktrees
= get_worktrees();
880 wt
= find_worktree(worktrees
, prefix
, av
[0]);
882 die(_("'%s' is not a working tree"), av
[0]);
883 if (is_main_worktree(wt
))
884 die(_("The main working tree cannot be locked or unlocked"));
886 old_reason
= worktree_lock_reason(wt
);
889 die(_("'%s' is already locked, reason: %s"),
891 die(_("'%s' is already locked"), av
[0]);
894 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
896 free_worktrees(worktrees
);
900 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
902 struct option options
[] = {
905 struct worktree
**worktrees
, *wt
;
908 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_unlock_usage
, 0);
910 usage_with_options(git_worktree_unlock_usage
, options
);
912 worktrees
= get_worktrees();
913 wt
= find_worktree(worktrees
, prefix
, av
[0]);
915 die(_("'%s' is not a working tree"), av
[0]);
916 if (is_main_worktree(wt
))
917 die(_("The main working tree cannot be locked or unlocked"));
918 if (!worktree_lock_reason(wt
))
919 die(_("'%s' is not locked"), av
[0]);
920 ret
= unlink_or_warn(git_common_path("worktrees/%s/locked", wt
->id
));
921 free_worktrees(worktrees
);
925 static void validate_no_submodules(const struct worktree
*wt
)
927 struct index_state istate
= INDEX_STATE_INIT(the_repository
);
928 struct strbuf path
= STRBUF_INIT
;
929 int i
, found_submodules
= 0;
931 if (is_directory(worktree_git_path(wt
, "modules"))) {
933 * There could be false positives, e.g. the "modules"
934 * directory exists but is empty. But it's a rare case and
935 * this simpler check is probably good enough for now.
937 found_submodules
= 1;
938 } else if (read_index_from(&istate
, worktree_git_path(wt
, "index"),
939 get_worktree_git_dir(wt
)) > 0) {
940 for (i
= 0; i
< istate
.cache_nr
; i
++) {
941 struct cache_entry
*ce
= istate
.cache
[i
];
944 if (!S_ISGITLINK(ce
->ce_mode
))
948 strbuf_addf(&path
, "%s/%s", wt
->path
, ce
->name
);
949 if (!is_submodule_populated_gently(path
.buf
, &err
))
952 found_submodules
= 1;
956 discard_index(&istate
);
957 strbuf_release(&path
);
959 if (found_submodules
)
960 die(_("working trees containing submodules cannot be moved or removed"));
963 static int move_worktree(int ac
, const char **av
, const char *prefix
)
966 struct option options
[] = {
968 N_("force move even if worktree is dirty or locked"),
969 PARSE_OPT_NOCOMPLETE
),
972 struct worktree
**worktrees
, *wt
;
973 struct strbuf dst
= STRBUF_INIT
;
974 struct strbuf errmsg
= STRBUF_INIT
;
975 const char *reason
= NULL
;
978 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_move_usage
,
981 usage_with_options(git_worktree_move_usage
, options
);
983 path
= prefix_filename(prefix
, av
[1]);
984 strbuf_addstr(&dst
, path
);
987 worktrees
= get_worktrees();
988 wt
= find_worktree(worktrees
, prefix
, av
[0]);
990 die(_("'%s' is not a working tree"), av
[0]);
991 if (is_main_worktree(wt
))
992 die(_("'%s' is a main working tree"), av
[0]);
993 if (is_directory(dst
.buf
)) {
994 const char *sep
= find_last_dir_sep(wt
->path
);
997 die(_("could not figure out destination name from '%s'"),
999 strbuf_trim_trailing_dir_sep(&dst
);
1000 strbuf_addstr(&dst
, sep
);
1002 check_candidate_path(dst
.buf
, force
, worktrees
, "move");
1004 validate_no_submodules(wt
);
1007 reason
= worktree_lock_reason(wt
);
1010 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1012 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1014 if (validate_worktree(wt
, &errmsg
, 0))
1015 die(_("validation failed, cannot move working tree: %s"),
1017 strbuf_release(&errmsg
);
1019 if (rename(wt
->path
, dst
.buf
) == -1)
1020 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
1022 update_worktree_location(wt
, dst
.buf
);
1024 strbuf_release(&dst
);
1025 free_worktrees(worktrees
);
1030 * Note, "git status --porcelain" is used to determine if it's safe to
1031 * delete a whole worktree. "git status" does not ignore user
1032 * configuration, so if a normal "git status" shows "clean" for the
1033 * user, then it's ok to remove it.
1035 * This assumption may be a bad one. We may want to ignore
1036 * (potentially bad) user settings and only delete a worktree when
1037 * it's absolutely safe to do so from _our_ point of view because we
1040 static void check_clean_worktree(struct worktree
*wt
,
1041 const char *original_path
)
1043 struct child_process cp
;
1048 * Until we sort this out, all submodules are "dirty" and
1049 * will abort this function.
1051 validate_no_submodules(wt
);
1053 child_process_init(&cp
);
1054 strvec_pushf(&cp
.env
, "%s=%s/.git",
1055 GIT_DIR_ENVIRONMENT
, wt
->path
);
1056 strvec_pushf(&cp
.env
, "%s=%s",
1057 GIT_WORK_TREE_ENVIRONMENT
, wt
->path
);
1058 strvec_pushl(&cp
.args
, "status",
1059 "--porcelain", "--ignore-submodules=none",
1064 ret
= start_command(&cp
);
1066 die_errno(_("failed to run 'git status' on '%s'"),
1068 ret
= xread(cp
.out
, buf
, sizeof(buf
));
1070 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1073 ret
= finish_command(&cp
);
1075 die_errno(_("failed to run 'git status' on '%s', code %d"),
1076 original_path
, ret
);
1079 static int delete_git_work_tree(struct worktree
*wt
)
1081 struct strbuf sb
= STRBUF_INIT
;
1084 strbuf_addstr(&sb
, wt
->path
);
1085 if (remove_dir_recursively(&sb
, 0)) {
1086 error_errno(_("failed to delete '%s'"), sb
.buf
);
1089 strbuf_release(&sb
);
1093 static int remove_worktree(int ac
, const char **av
, const char *prefix
)
1096 struct option options
[] = {
1098 N_("force removal even if worktree is dirty or locked"),
1099 PARSE_OPT_NOCOMPLETE
),
1102 struct worktree
**worktrees
, *wt
;
1103 struct strbuf errmsg
= STRBUF_INIT
;
1104 const char *reason
= NULL
;
1107 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_remove_usage
, 0);
1109 usage_with_options(git_worktree_remove_usage
, options
);
1111 worktrees
= get_worktrees();
1112 wt
= find_worktree(worktrees
, prefix
, av
[0]);
1114 die(_("'%s' is not a working tree"), av
[0]);
1115 if (is_main_worktree(wt
))
1116 die(_("'%s' is a main working tree"), av
[0]);
1118 reason
= worktree_lock_reason(wt
);
1121 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1123 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1125 if (validate_worktree(wt
, &errmsg
, WT_VALIDATE_WORKTREE_MISSING_OK
))
1126 die(_("validation failed, cannot remove working tree: %s"),
1128 strbuf_release(&errmsg
);
1130 if (file_exists(wt
->path
)) {
1132 check_clean_worktree(wt
, av
[0]);
1134 ret
|= delete_git_work_tree(wt
);
1137 * continue on even if ret is non-zero, there's no going back
1140 ret
|= delete_git_dir(wt
->id
);
1141 delete_worktrees_dir_if_empty();
1143 free_worktrees(worktrees
);
1147 static void report_repair(int iserr
, const char *path
, const char *msg
, void *cb_data
)
1150 fprintf_ln(stderr
, _("repair: %s: %s"), msg
, path
);
1152 int *exit_status
= (int *)cb_data
;
1153 fprintf_ln(stderr
, _("error: %s: %s"), msg
, path
);
1158 static int repair(int ac
, const char **av
, const char *prefix
)
1161 const char *self
[] = { ".", NULL
};
1162 struct option options
[] = {
1167 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_repair_usage
, 0);
1168 p
= ac
> 0 ? av
: self
;
1170 repair_worktree_at_path(*p
, report_repair
, &rc
);
1171 repair_worktrees(report_repair
, &rc
);
1175 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
1177 parse_opt_subcommand_fn
*fn
= NULL
;
1178 struct option options
[] = {
1179 OPT_SUBCOMMAND("add", &fn
, add
),
1180 OPT_SUBCOMMAND("prune", &fn
, prune
),
1181 OPT_SUBCOMMAND("list", &fn
, list
),
1182 OPT_SUBCOMMAND("lock", &fn
, lock_worktree
),
1183 OPT_SUBCOMMAND("unlock", &fn
, unlock_worktree
),
1184 OPT_SUBCOMMAND("move", &fn
, move_worktree
),
1185 OPT_SUBCOMMAND("remove", &fn
, remove_worktree
),
1186 OPT_SUBCOMMAND("repair", &fn
, repair
),
1190 git_config(git_worktree_config
, NULL
);
1195 ac
= parse_options(ac
, av
, prefix
, options
, git_worktree_usage
, 0);
1196 return fn(ac
, av
, prefix
);