Sync with 2.40.2
[git.git] / builtin / worktree.c
blobf3180463be2a9801bb941eafcdf651181ac800fa
1 #include "cache.h"
2 #include "abspath.h"
3 #include "checkout.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "builtin.h"
7 #include "dir.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "object-file.h"
12 #include "object-name.h"
13 #include "parse-options.h"
14 #include "strvec.h"
15 #include "branch.h"
16 #include "refs.h"
17 #include "repository.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "sigchain.h"
21 #include "submodule.h"
22 #include "utf8.h"
23 #include "worktree.h"
24 #include "wrapper.h"
25 #include "quote.h"
27 #define BUILTIN_WORKTREE_ADD_USAGE \
28 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
29 " [-b <new-branch>] <path> [<commit-ish>]")
30 #define BUILTIN_WORKTREE_LIST_USAGE \
31 N_("git worktree list [-v | --porcelain [-z]]")
32 #define BUILTIN_WORKTREE_LOCK_USAGE \
33 N_("git worktree lock [--reason <string>] <worktree>")
34 #define BUILTIN_WORKTREE_MOVE_USAGE \
35 N_("git worktree move <worktree> <new-path>")
36 #define BUILTIN_WORKTREE_PRUNE_USAGE \
37 N_("git worktree prune [-n] [-v] [--expire <expire>]")
38 #define BUILTIN_WORKTREE_REMOVE_USAGE \
39 N_("git worktree remove [-f] <worktree>")
40 #define BUILTIN_WORKTREE_REPAIR_USAGE \
41 N_("git worktree repair [<path>...]")
42 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
43 N_("git worktree unlock <worktree>")
45 static const char * const git_worktree_usage[] = {
46 BUILTIN_WORKTREE_ADD_USAGE,
47 BUILTIN_WORKTREE_LIST_USAGE,
48 BUILTIN_WORKTREE_LOCK_USAGE,
49 BUILTIN_WORKTREE_MOVE_USAGE,
50 BUILTIN_WORKTREE_PRUNE_USAGE,
51 BUILTIN_WORKTREE_REMOVE_USAGE,
52 BUILTIN_WORKTREE_REPAIR_USAGE,
53 BUILTIN_WORKTREE_UNLOCK_USAGE,
54 NULL
57 static const char * const git_worktree_add_usage[] = {
58 BUILTIN_WORKTREE_ADD_USAGE,
59 NULL,
62 static const char * const git_worktree_list_usage[] = {
63 BUILTIN_WORKTREE_LIST_USAGE,
64 NULL
67 static const char * const git_worktree_lock_usage[] = {
68 BUILTIN_WORKTREE_LOCK_USAGE,
69 NULL
72 static const char * const git_worktree_move_usage[] = {
73 BUILTIN_WORKTREE_MOVE_USAGE,
74 NULL
77 static const char * const git_worktree_prune_usage[] = {
78 BUILTIN_WORKTREE_PRUNE_USAGE,
79 NULL
82 static const char * const git_worktree_remove_usage[] = {
83 BUILTIN_WORKTREE_REMOVE_USAGE,
84 NULL
87 static const char * const git_worktree_repair_usage[] = {
88 BUILTIN_WORKTREE_REPAIR_USAGE,
89 NULL
92 static const char * const git_worktree_unlock_usage[] = {
93 BUILTIN_WORKTREE_UNLOCK_USAGE,
94 NULL
97 struct add_opts {
98 int force;
99 int detach;
100 int quiet;
101 int checkout;
102 const char *keep_locked;
105 static int show_only;
106 static int verbose;
107 static int guess_remote;
108 static timestamp_t expire;
110 static int git_worktree_config(const char *var, const char *value, void *cb)
112 if (!strcmp(var, "worktree.guessremote")) {
113 guess_remote = git_config_bool(var, value);
114 return 0;
117 return git_default_config(var, value, cb);
120 static int delete_git_dir(const char *id)
122 struct strbuf sb = STRBUF_INIT;
123 int ret;
125 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
126 ret = remove_dir_recursively(&sb, 0);
127 if (ret < 0 && errno == ENOTDIR)
128 ret = unlink(sb.buf);
129 if (ret)
130 error_errno(_("failed to delete '%s'"), sb.buf);
131 strbuf_release(&sb);
132 return ret;
135 static void delete_worktrees_dir_if_empty(void)
137 rmdir(git_path("worktrees")); /* ignore failed removal */
140 static void prune_worktree(const char *id, const char *reason)
142 if (show_only || verbose)
143 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
144 if (!show_only)
145 delete_git_dir(id);
148 static int prune_cmp(const void *a, const void *b)
150 const struct string_list_item *x = a;
151 const struct string_list_item *y = b;
152 int c;
154 if ((c = fspathcmp(x->string, y->string)))
155 return c;
157 * paths same; prune_dupes() removes all but the first worktree entry
158 * having the same path, so sort main worktree ('util' is NULL) above
159 * linked worktrees ('util' not NULL) since main worktree can't be
160 * removed
162 if (!x->util)
163 return -1;
164 if (!y->util)
165 return 1;
166 /* paths same; sort by .git/worktrees/<id> */
167 return strcmp(x->util, y->util);
170 static void prune_dups(struct string_list *l)
172 int i;
174 QSORT(l->items, l->nr, prune_cmp);
175 for (i = 1; i < l->nr; i++) {
176 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
177 prune_worktree(l->items[i].util, "duplicate entry");
181 static void prune_worktrees(void)
183 struct strbuf reason = STRBUF_INIT;
184 struct strbuf main_path = STRBUF_INIT;
185 struct string_list kept = STRING_LIST_INIT_DUP;
186 DIR *dir = opendir(git_path("worktrees"));
187 struct dirent *d;
188 if (!dir)
189 return;
190 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
191 char *path;
192 strbuf_reset(&reason);
193 if (should_prune_worktree(d->d_name, &reason, &path, expire))
194 prune_worktree(d->d_name, reason.buf);
195 else if (path)
196 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
198 closedir(dir);
200 strbuf_add_absolute_path(&main_path, get_git_common_dir());
201 /* massage main worktree absolute path to match 'gitdir' content */
202 strbuf_strip_suffix(&main_path, "/.");
203 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
204 prune_dups(&kept);
205 string_list_clear(&kept, 1);
207 if (!show_only)
208 delete_worktrees_dir_if_empty();
209 strbuf_release(&reason);
212 static int prune(int ac, const char **av, const char *prefix)
214 struct option options[] = {
215 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
216 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
217 OPT_EXPIRY_DATE(0, "expire", &expire,
218 N_("expire working trees older than <time>")),
219 OPT_END()
222 expire = TIME_MAX;
223 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
225 if (ac)
226 usage_with_options(git_worktree_prune_usage, options);
227 prune_worktrees();
228 return 0;
231 static char *junk_work_tree;
232 static char *junk_git_dir;
233 static int is_junk;
234 static pid_t junk_pid;
236 static void remove_junk(void)
238 struct strbuf sb = STRBUF_INIT;
239 if (!is_junk || getpid() != junk_pid)
240 return;
241 if (junk_git_dir) {
242 strbuf_addstr(&sb, junk_git_dir);
243 remove_dir_recursively(&sb, 0);
244 strbuf_reset(&sb);
246 if (junk_work_tree) {
247 strbuf_addstr(&sb, junk_work_tree);
248 remove_dir_recursively(&sb, 0);
250 strbuf_release(&sb);
253 static void remove_junk_on_signal(int signo)
255 remove_junk();
256 sigchain_pop(signo);
257 raise(signo);
260 static const char *worktree_basename(const char *path, int *olen)
262 const char *name;
263 int len;
265 len = strlen(path);
266 while (len && is_dir_sep(path[len - 1]))
267 len--;
269 for (name = path + len - 1; name > path; name--)
270 if (is_dir_sep(*name)) {
271 name++;
272 break;
275 *olen = len;
276 return name;
279 /* check that path is viable location for worktree */
280 static void check_candidate_path(const char *path,
281 int force,
282 struct worktree **worktrees,
283 const char *cmd)
285 struct worktree *wt;
286 int locked;
288 if (file_exists(path) && !is_empty_dir(path))
289 die(_("'%s' already exists"), path);
291 wt = find_worktree_by_path(worktrees, path);
292 if (!wt)
293 return;
295 locked = !!worktree_lock_reason(wt);
296 if ((!locked && force) || (locked && force > 1)) {
297 if (delete_git_dir(wt->id))
298 die(_("unusable worktree destination '%s'"), path);
299 return;
302 if (locked)
303 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
304 else
305 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
308 static void copy_sparse_checkout(const char *worktree_git_dir)
310 char *from_file = git_pathdup("info/sparse-checkout");
311 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
313 if (file_exists(from_file)) {
314 if (safe_create_leading_directories(to_file) ||
315 copy_file(to_file, from_file, 0666))
316 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
317 from_file, to_file);
320 free(from_file);
321 free(to_file);
324 static void copy_filtered_worktree_config(const char *worktree_git_dir)
326 char *from_file = git_pathdup("config.worktree");
327 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
329 if (file_exists(from_file)) {
330 struct config_set cs = { { 0 } };
331 int bare;
333 if (safe_create_leading_directories(to_file) ||
334 copy_file(to_file, from_file, 0666)) {
335 error(_("failed to copy worktree config from '%s' to '%s'"),
336 from_file, to_file);
337 goto worktree_copy_cleanup;
340 git_configset_init(&cs);
341 git_configset_add_file(&cs, from_file);
343 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
344 bare &&
345 git_config_set_multivar_in_file_gently(
346 to_file, "core.bare", NULL, "true", 0))
347 error(_("failed to unset '%s' in '%s'"),
348 "core.bare", to_file);
349 if (!git_configset_get(&cs, "core.worktree") &&
350 git_config_set_in_file_gently(to_file,
351 "core.worktree", NULL))
352 error(_("failed to unset '%s' in '%s'"),
353 "core.worktree", to_file);
355 git_configset_clear(&cs);
358 worktree_copy_cleanup:
359 free(from_file);
360 free(to_file);
363 static int checkout_worktree(const struct add_opts *opts,
364 struct strvec *child_env)
366 struct child_process cp = CHILD_PROCESS_INIT;
367 cp.git_cmd = 1;
368 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
369 if (opts->quiet)
370 strvec_push(&cp.args, "--quiet");
371 strvec_pushv(&cp.env, child_env->v);
372 return run_command(&cp);
375 static int add_worktree(const char *path, const char *refname,
376 const struct add_opts *opts)
378 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
379 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
380 const char *name;
381 struct child_process cp = CHILD_PROCESS_INIT;
382 struct strvec child_env = STRVEC_INIT;
383 unsigned int counter = 0;
384 int len, ret;
385 struct strbuf symref = STRBUF_INIT;
386 struct commit *commit = NULL;
387 int is_branch = 0;
388 struct strbuf sb_name = STRBUF_INIT;
389 struct worktree **worktrees;
391 worktrees = get_worktrees();
392 check_candidate_path(path, opts->force, worktrees, "add");
393 free_worktrees(worktrees);
394 worktrees = NULL;
396 /* is 'refname' a branch or commit? */
397 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
398 ref_exists(symref.buf)) {
399 is_branch = 1;
400 if (!opts->force)
401 die_if_checked_out(symref.buf, 0);
403 commit = lookup_commit_reference_by_name(refname);
404 if (!commit)
405 die(_("invalid reference: %s"), refname);
407 name = worktree_basename(path, &len);
408 strbuf_add(&sb, name, path + len - name);
409 sanitize_refname_component(sb.buf, &sb_name);
410 if (!sb_name.len)
411 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
412 strbuf_reset(&sb);
413 name = sb_name.buf;
414 git_path_buf(&sb_repo, "worktrees/%s", name);
415 len = sb_repo.len;
416 if (safe_create_leading_directories_const(sb_repo.buf))
417 die_errno(_("could not create leading directories of '%s'"),
418 sb_repo.buf);
420 while (mkdir(sb_repo.buf, 0777)) {
421 counter++;
422 if ((errno != EEXIST) || !counter /* overflow */)
423 die_errno(_("could not create directory of '%s'"),
424 sb_repo.buf);
425 strbuf_setlen(&sb_repo, len);
426 strbuf_addf(&sb_repo, "%d", counter);
428 name = strrchr(sb_repo.buf, '/') + 1;
430 junk_pid = getpid();
431 atexit(remove_junk);
432 sigchain_push_common(remove_junk_on_signal);
434 junk_git_dir = xstrdup(sb_repo.buf);
435 is_junk = 1;
438 * lock the incomplete repo so prune won't delete it, unlock
439 * after the preparation is over.
441 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
442 if (opts->keep_locked)
443 write_file(sb.buf, "%s", opts->keep_locked);
444 else
445 write_file(sb.buf, _("initializing"));
447 strbuf_addf(&sb_git, "%s/.git", path);
448 if (safe_create_leading_directories_const(sb_git.buf))
449 die_errno(_("could not create leading directories of '%s'"),
450 sb_git.buf);
451 junk_work_tree = xstrdup(path);
453 strbuf_reset(&sb);
454 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
455 strbuf_realpath(&realpath, sb_git.buf, 1);
456 write_file(sb.buf, "%s", realpath.buf);
457 strbuf_realpath(&realpath, get_git_common_dir(), 1);
458 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
459 realpath.buf, name);
461 * This is to keep resolve_ref() happy. We need a valid HEAD
462 * or is_git_directory() will reject the directory. Any value which
463 * looks like an object ID will do since it will be immediately
464 * replaced by the symbolic-ref or update-ref invocation in the new
465 * worktree.
467 strbuf_reset(&sb);
468 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
469 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
470 strbuf_reset(&sb);
471 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
472 write_file(sb.buf, "../..");
475 * If the current worktree has sparse-checkout enabled, then copy
476 * the sparse-checkout patterns from the current worktree.
478 if (core_apply_sparse_checkout)
479 copy_sparse_checkout(sb_repo.buf);
482 * If we are using worktree config, then copy all current config
483 * values from the current worktree into the new one, that way the
484 * new worktree behaves the same as this one.
486 if (repository_format_worktree_config)
487 copy_filtered_worktree_config(sb_repo.buf);
489 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
490 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
491 cp.git_cmd = 1;
493 if (!is_branch)
494 strvec_pushl(&cp.args, "update-ref", "HEAD",
495 oid_to_hex(&commit->object.oid), NULL);
496 else {
497 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
498 symref.buf, NULL);
499 if (opts->quiet)
500 strvec_push(&cp.args, "--quiet");
503 strvec_pushv(&cp.env, child_env.v);
504 ret = run_command(&cp);
505 if (ret)
506 goto done;
508 if (opts->checkout &&
509 (ret = checkout_worktree(opts, &child_env)))
510 goto done;
512 is_junk = 0;
513 FREE_AND_NULL(junk_work_tree);
514 FREE_AND_NULL(junk_git_dir);
516 done:
517 if (ret || !opts->keep_locked) {
518 strbuf_reset(&sb);
519 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
520 unlink_or_warn(sb.buf);
524 * Hook failure does not warrant worktree deletion, so run hook after
525 * is_junk is cleared, but do return appropriate code when hook fails.
527 if (!ret && opts->checkout) {
528 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
530 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
531 strvec_pushl(&opt.args,
532 oid_to_hex(null_oid()),
533 oid_to_hex(&commit->object.oid),
534 "1",
535 NULL);
536 opt.dir = path;
538 ret = run_hooks_opt("post-checkout", &opt);
541 strvec_clear(&child_env);
542 strbuf_release(&sb);
543 strbuf_release(&symref);
544 strbuf_release(&sb_repo);
545 strbuf_release(&sb_git);
546 strbuf_release(&sb_name);
547 strbuf_release(&realpath);
548 return ret;
551 static void print_preparing_worktree_line(int detach,
552 const char *branch,
553 const char *new_branch,
554 int force_new_branch)
556 if (force_new_branch) {
557 struct commit *commit = lookup_commit_reference_by_name(new_branch);
558 if (!commit)
559 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
560 else
561 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
562 new_branch,
563 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
564 } else if (new_branch) {
565 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
566 } else {
567 struct strbuf s = STRBUF_INIT;
568 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
569 ref_exists(s.buf))
570 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
571 branch);
572 else {
573 struct commit *commit = lookup_commit_reference_by_name(branch);
574 if (!commit)
575 die(_("invalid reference: %s"), branch);
576 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
577 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
579 strbuf_release(&s);
583 static const char *dwim_branch(const char *path, const char **new_branch)
585 int n;
586 int branch_exists;
587 const char *s = worktree_basename(path, &n);
588 const char *branchname = xstrndup(s, n);
589 struct strbuf ref = STRBUF_INIT;
591 UNLEAK(branchname);
593 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
594 ref_exists(ref.buf);
595 strbuf_release(&ref);
596 if (branch_exists)
597 return branchname;
599 *new_branch = branchname;
600 if (guess_remote) {
601 struct object_id oid;
602 const char *remote =
603 unique_tracking_name(*new_branch, &oid, NULL);
604 return remote;
606 return NULL;
609 static int add(int ac, const char **av, const char *prefix)
611 struct add_opts opts;
612 const char *new_branch_force = NULL;
613 char *path;
614 const char *branch;
615 const char *new_branch = NULL;
616 const char *opt_track = NULL;
617 const char *lock_reason = NULL;
618 int keep_locked = 0;
619 struct option options[] = {
620 OPT__FORCE(&opts.force,
621 N_("checkout <branch> even if already checked out in other worktree"),
622 PARSE_OPT_NOCOMPLETE),
623 OPT_STRING('b', NULL, &new_branch, N_("branch"),
624 N_("create a new branch")),
625 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
626 N_("create or reset a branch")),
627 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
628 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
629 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
630 OPT_STRING(0, "reason", &lock_reason, N_("string"),
631 N_("reason for locking")),
632 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
633 OPT_PASSTHRU(0, "track", &opt_track, NULL,
634 N_("set up tracking mode (see git-branch(1))"),
635 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
636 OPT_BOOL(0, "guess-remote", &guess_remote,
637 N_("try to match the new branch name with a remote-tracking branch")),
638 OPT_END()
640 int ret;
642 memset(&opts, 0, sizeof(opts));
643 opts.checkout = 1;
644 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
645 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
646 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
647 if (lock_reason && !keep_locked)
648 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
649 if (lock_reason)
650 opts.keep_locked = lock_reason;
651 else if (keep_locked)
652 opts.keep_locked = _("added with --lock");
654 if (ac < 1 || ac > 2)
655 usage_with_options(git_worktree_add_usage, options);
657 path = prefix_filename(prefix, av[0]);
658 branch = ac < 2 ? "HEAD" : av[1];
660 if (!strcmp(branch, "-"))
661 branch = "@{-1}";
663 if (new_branch_force) {
664 struct strbuf symref = STRBUF_INIT;
666 new_branch = new_branch_force;
668 if (!opts.force &&
669 !strbuf_check_branch_ref(&symref, new_branch) &&
670 ref_exists(symref.buf))
671 die_if_checked_out(symref.buf, 0);
672 strbuf_release(&symref);
675 if (ac < 2 && !new_branch && !opts.detach) {
676 const char *s = dwim_branch(path, &new_branch);
677 if (s)
678 branch = s;
681 if (ac == 2 && !new_branch && !opts.detach) {
682 struct object_id oid;
683 struct commit *commit;
684 const char *remote;
686 commit = lookup_commit_reference_by_name(branch);
687 if (!commit) {
688 remote = unique_tracking_name(branch, &oid, NULL);
689 if (remote) {
690 new_branch = branch;
691 branch = remote;
695 if (!opts.quiet)
696 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
698 if (new_branch) {
699 struct child_process cp = CHILD_PROCESS_INIT;
700 cp.git_cmd = 1;
701 strvec_push(&cp.args, "branch");
702 if (new_branch_force)
703 strvec_push(&cp.args, "--force");
704 if (opts.quiet)
705 strvec_push(&cp.args, "--quiet");
706 strvec_push(&cp.args, new_branch);
707 strvec_push(&cp.args, branch);
708 if (opt_track)
709 strvec_push(&cp.args, opt_track);
710 if (run_command(&cp))
711 return -1;
712 branch = new_branch;
713 } else if (opt_track) {
714 die(_("--[no-]track can only be used if a new branch is created"));
717 ret = add_worktree(path, branch, &opts);
718 free(path);
719 return ret;
722 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
724 const char *reason;
726 printf("worktree %s%c", wt->path, line_terminator);
727 if (wt->is_bare)
728 printf("bare%c", line_terminator);
729 else {
730 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
731 if (wt->is_detached)
732 printf("detached%c", line_terminator);
733 else if (wt->head_ref)
734 printf("branch %s%c", wt->head_ref, line_terminator);
737 reason = worktree_lock_reason(wt);
738 if (reason) {
739 fputs("locked", stdout);
740 if (*reason) {
741 fputc(' ', stdout);
742 write_name_quoted(reason, stdout, line_terminator);
743 } else {
744 fputc(line_terminator, stdout);
748 reason = worktree_prune_reason(wt, expire);
749 if (reason)
750 printf("prunable %s%c", reason, line_terminator);
752 fputc(line_terminator, stdout);
755 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
757 struct strbuf sb = STRBUF_INIT;
758 int cur_path_len = strlen(wt->path);
759 int path_adj = cur_path_len - utf8_strwidth(wt->path);
760 const char *reason;
762 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
763 if (wt->is_bare)
764 strbuf_addstr(&sb, "(bare)");
765 else {
766 strbuf_addf(&sb, "%-*s ", abbrev_len,
767 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
768 if (wt->is_detached)
769 strbuf_addstr(&sb, "(detached HEAD)");
770 else if (wt->head_ref) {
771 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
772 strbuf_addf(&sb, "[%s]", ref);
773 free(ref);
774 } else
775 strbuf_addstr(&sb, "(error)");
778 reason = worktree_lock_reason(wt);
779 if (verbose && reason && *reason)
780 strbuf_addf(&sb, "\n\tlocked: %s", reason);
781 else if (reason)
782 strbuf_addstr(&sb, " locked");
784 reason = worktree_prune_reason(wt, expire);
785 if (verbose && reason)
786 strbuf_addf(&sb, "\n\tprunable: %s", reason);
787 else if (reason)
788 strbuf_addstr(&sb, " prunable");
790 printf("%s\n", sb.buf);
791 strbuf_release(&sb);
794 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
796 int i;
798 for (i = 0; wt[i]; i++) {
799 int sha1_len;
800 int path_len = strlen(wt[i]->path);
802 if (path_len > *maxlen)
803 *maxlen = path_len;
804 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
805 if (sha1_len > *abbrev)
806 *abbrev = sha1_len;
810 static int pathcmp(const void *a_, const void *b_)
812 const struct worktree *const *a = a_;
813 const struct worktree *const *b = b_;
814 return fspathcmp((*a)->path, (*b)->path);
817 static void pathsort(struct worktree **wt)
819 int n = 0;
820 struct worktree **p = wt;
822 while (*p++)
823 n++;
824 QSORT(wt, n, pathcmp);
827 static int list(int ac, const char **av, const char *prefix)
829 int porcelain = 0;
830 int line_terminator = '\n';
832 struct option options[] = {
833 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
834 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
835 OPT_EXPIRY_DATE(0, "expire", &expire,
836 N_("add 'prunable' annotation to worktrees older than <time>")),
837 OPT_SET_INT('z', NULL, &line_terminator,
838 N_("terminate records with a NUL character"), '\0'),
839 OPT_END()
842 expire = TIME_MAX;
843 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
844 if (ac)
845 usage_with_options(git_worktree_list_usage, options);
846 else if (verbose && porcelain)
847 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
848 else if (!line_terminator && !porcelain)
849 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
850 else {
851 struct worktree **worktrees = get_worktrees();
852 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
854 /* sort worktrees by path but keep main worktree at top */
855 pathsort(worktrees + 1);
857 if (!porcelain)
858 measure_widths(worktrees, &abbrev, &path_maxlen);
860 for (i = 0; worktrees[i]; i++) {
861 if (porcelain)
862 show_worktree_porcelain(worktrees[i],
863 line_terminator);
864 else
865 show_worktree(worktrees[i], path_maxlen, abbrev);
867 free_worktrees(worktrees);
869 return 0;
872 static int lock_worktree(int ac, const char **av, const char *prefix)
874 const char *reason = "", *old_reason;
875 struct option options[] = {
876 OPT_STRING(0, "reason", &reason, N_("string"),
877 N_("reason for locking")),
878 OPT_END()
880 struct worktree **worktrees, *wt;
882 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
883 if (ac != 1)
884 usage_with_options(git_worktree_lock_usage, options);
886 worktrees = get_worktrees();
887 wt = find_worktree(worktrees, prefix, av[0]);
888 if (!wt)
889 die(_("'%s' is not a working tree"), av[0]);
890 if (is_main_worktree(wt))
891 die(_("The main working tree cannot be locked or unlocked"));
893 old_reason = worktree_lock_reason(wt);
894 if (old_reason) {
895 if (*old_reason)
896 die(_("'%s' is already locked, reason: %s"),
897 av[0], old_reason);
898 die(_("'%s' is already locked"), av[0]);
901 write_file(git_common_path("worktrees/%s/locked", wt->id),
902 "%s", reason);
903 free_worktrees(worktrees);
904 return 0;
907 static int unlock_worktree(int ac, const char **av, const char *prefix)
909 struct option options[] = {
910 OPT_END()
912 struct worktree **worktrees, *wt;
913 int ret;
915 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
916 if (ac != 1)
917 usage_with_options(git_worktree_unlock_usage, options);
919 worktrees = get_worktrees();
920 wt = find_worktree(worktrees, prefix, av[0]);
921 if (!wt)
922 die(_("'%s' is not a working tree"), av[0]);
923 if (is_main_worktree(wt))
924 die(_("The main working tree cannot be locked or unlocked"));
925 if (!worktree_lock_reason(wt))
926 die(_("'%s' is not locked"), av[0]);
927 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
928 free_worktrees(worktrees);
929 return ret;
932 static void validate_no_submodules(const struct worktree *wt)
934 struct index_state istate = INDEX_STATE_INIT(the_repository);
935 struct strbuf path = STRBUF_INIT;
936 int i, found_submodules = 0;
938 if (is_directory(worktree_git_path(wt, "modules"))) {
940 * There could be false positives, e.g. the "modules"
941 * directory exists but is empty. But it's a rare case and
942 * this simpler check is probably good enough for now.
944 found_submodules = 1;
945 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
946 get_worktree_git_dir(wt)) > 0) {
947 for (i = 0; i < istate.cache_nr; i++) {
948 struct cache_entry *ce = istate.cache[i];
949 int err;
951 if (!S_ISGITLINK(ce->ce_mode))
952 continue;
954 strbuf_reset(&path);
955 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
956 if (!is_submodule_populated_gently(path.buf, &err))
957 continue;
959 found_submodules = 1;
960 break;
963 discard_index(&istate);
964 strbuf_release(&path);
966 if (found_submodules)
967 die(_("working trees containing submodules cannot be moved or removed"));
970 static int move_worktree(int ac, const char **av, const char *prefix)
972 int force = 0;
973 struct option options[] = {
974 OPT__FORCE(&force,
975 N_("force move even if worktree is dirty or locked"),
976 PARSE_OPT_NOCOMPLETE),
977 OPT_END()
979 struct worktree **worktrees, *wt;
980 struct strbuf dst = STRBUF_INIT;
981 struct strbuf errmsg = STRBUF_INIT;
982 const char *reason = NULL;
983 char *path;
985 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
987 if (ac != 2)
988 usage_with_options(git_worktree_move_usage, options);
990 path = prefix_filename(prefix, av[1]);
991 strbuf_addstr(&dst, path);
992 free(path);
994 worktrees = get_worktrees();
995 wt = find_worktree(worktrees, prefix, av[0]);
996 if (!wt)
997 die(_("'%s' is not a working tree"), av[0]);
998 if (is_main_worktree(wt))
999 die(_("'%s' is a main working tree"), av[0]);
1000 if (is_directory(dst.buf)) {
1001 const char *sep = find_last_dir_sep(wt->path);
1003 if (!sep)
1004 die(_("could not figure out destination name from '%s'"),
1005 wt->path);
1006 strbuf_trim_trailing_dir_sep(&dst);
1007 strbuf_addstr(&dst, sep);
1009 check_candidate_path(dst.buf, force, worktrees, "move");
1011 validate_no_submodules(wt);
1013 if (force < 2)
1014 reason = worktree_lock_reason(wt);
1015 if (reason) {
1016 if (*reason)
1017 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1018 reason);
1019 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1021 if (validate_worktree(wt, &errmsg, 0))
1022 die(_("validation failed, cannot move working tree: %s"),
1023 errmsg.buf);
1024 strbuf_release(&errmsg);
1026 if (rename(wt->path, dst.buf) == -1)
1027 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1029 update_worktree_location(wt, dst.buf);
1031 strbuf_release(&dst);
1032 free_worktrees(worktrees);
1033 return 0;
1037 * Note, "git status --porcelain" is used to determine if it's safe to
1038 * delete a whole worktree. "git status" does not ignore user
1039 * configuration, so if a normal "git status" shows "clean" for the
1040 * user, then it's ok to remove it.
1042 * This assumption may be a bad one. We may want to ignore
1043 * (potentially bad) user settings and only delete a worktree when
1044 * it's absolutely safe to do so from _our_ point of view because we
1045 * know better.
1047 static void check_clean_worktree(struct worktree *wt,
1048 const char *original_path)
1050 struct child_process cp;
1051 char buf[1];
1052 int ret;
1055 * Until we sort this out, all submodules are "dirty" and
1056 * will abort this function.
1058 validate_no_submodules(wt);
1060 child_process_init(&cp);
1061 strvec_pushf(&cp.env, "%s=%s/.git",
1062 GIT_DIR_ENVIRONMENT, wt->path);
1063 strvec_pushf(&cp.env, "%s=%s",
1064 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1065 strvec_pushl(&cp.args, "status",
1066 "--porcelain", "--ignore-submodules=none",
1067 NULL);
1068 cp.git_cmd = 1;
1069 cp.dir = wt->path;
1070 cp.out = -1;
1071 ret = start_command(&cp);
1072 if (ret)
1073 die_errno(_("failed to run 'git status' on '%s'"),
1074 original_path);
1075 ret = xread(cp.out, buf, sizeof(buf));
1076 if (ret)
1077 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1078 original_path);
1079 close(cp.out);
1080 ret = finish_command(&cp);
1081 if (ret)
1082 die_errno(_("failed to run 'git status' on '%s', code %d"),
1083 original_path, ret);
1086 static int delete_git_work_tree(struct worktree *wt)
1088 struct strbuf sb = STRBUF_INIT;
1089 int ret = 0;
1091 strbuf_addstr(&sb, wt->path);
1092 if (remove_dir_recursively(&sb, 0)) {
1093 error_errno(_("failed to delete '%s'"), sb.buf);
1094 ret = -1;
1096 strbuf_release(&sb);
1097 return ret;
1100 static int remove_worktree(int ac, const char **av, const char *prefix)
1102 int force = 0;
1103 struct option options[] = {
1104 OPT__FORCE(&force,
1105 N_("force removal even if worktree is dirty or locked"),
1106 PARSE_OPT_NOCOMPLETE),
1107 OPT_END()
1109 struct worktree **worktrees, *wt;
1110 struct strbuf errmsg = STRBUF_INIT;
1111 const char *reason = NULL;
1112 int ret = 0;
1114 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1115 if (ac != 1)
1116 usage_with_options(git_worktree_remove_usage, options);
1118 worktrees = get_worktrees();
1119 wt = find_worktree(worktrees, prefix, av[0]);
1120 if (!wt)
1121 die(_("'%s' is not a working tree"), av[0]);
1122 if (is_main_worktree(wt))
1123 die(_("'%s' is a main working tree"), av[0]);
1124 if (force < 2)
1125 reason = worktree_lock_reason(wt);
1126 if (reason) {
1127 if (*reason)
1128 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1129 reason);
1130 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1132 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1133 die(_("validation failed, cannot remove working tree: %s"),
1134 errmsg.buf);
1135 strbuf_release(&errmsg);
1137 if (file_exists(wt->path)) {
1138 if (!force)
1139 check_clean_worktree(wt, av[0]);
1141 ret |= delete_git_work_tree(wt);
1144 * continue on even if ret is non-zero, there's no going back
1145 * from here.
1147 ret |= delete_git_dir(wt->id);
1148 delete_worktrees_dir_if_empty();
1150 free_worktrees(worktrees);
1151 return ret;
1154 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1156 if (!iserr) {
1157 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1158 } else {
1159 int *exit_status = (int *)cb_data;
1160 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1161 *exit_status = 1;
1165 static int repair(int ac, const char **av, const char *prefix)
1167 const char **p;
1168 const char *self[] = { ".", NULL };
1169 struct option options[] = {
1170 OPT_END()
1172 int rc = 0;
1174 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1175 p = ac > 0 ? av : self;
1176 for (; *p; p++)
1177 repair_worktree_at_path(*p, report_repair, &rc);
1178 repair_worktrees(report_repair, &rc);
1179 return rc;
1182 int cmd_worktree(int ac, const char **av, const char *prefix)
1184 parse_opt_subcommand_fn *fn = NULL;
1185 struct option options[] = {
1186 OPT_SUBCOMMAND("add", &fn, add),
1187 OPT_SUBCOMMAND("prune", &fn, prune),
1188 OPT_SUBCOMMAND("list", &fn, list),
1189 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1190 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1191 OPT_SUBCOMMAND("move", &fn, move_worktree),
1192 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1193 OPT_SUBCOMMAND("repair", &fn, repair),
1194 OPT_END()
1197 git_config(git_worktree_config, NULL);
1199 if (!prefix)
1200 prefix = "";
1202 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1203 return fn(ac, av, prefix);