pager.h: move declarations for pager.c functions from cache.h
[git.git] / builtin / worktree.c
blob0621f6f708e93bdb8cde70eded330c84755a1e4f
1 #include "cache.h"
2 #include "abspath.h"
3 #include "checkout.h"
4 #include "config.h"
5 #include "builtin.h"
6 #include "dir.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "object-file.h"
11 #include "object-name.h"
12 #include "parse-options.h"
13 #include "strvec.h"
14 #include "branch.h"
15 #include "refs.h"
16 #include "run-command.h"
17 #include "hook.h"
18 #include "sigchain.h"
19 #include "submodule.h"
20 #include "utf8.h"
21 #include "worktree.h"
22 #include "wrapper.h"
23 #include "quote.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,
52 NULL
55 static const char * const git_worktree_add_usage[] = {
56 BUILTIN_WORKTREE_ADD_USAGE,
57 NULL,
60 static const char * const git_worktree_list_usage[] = {
61 BUILTIN_WORKTREE_LIST_USAGE,
62 NULL
65 static const char * const git_worktree_lock_usage[] = {
66 BUILTIN_WORKTREE_LOCK_USAGE,
67 NULL
70 static const char * const git_worktree_move_usage[] = {
71 BUILTIN_WORKTREE_MOVE_USAGE,
72 NULL
75 static const char * const git_worktree_prune_usage[] = {
76 BUILTIN_WORKTREE_PRUNE_USAGE,
77 NULL
80 static const char * const git_worktree_remove_usage[] = {
81 BUILTIN_WORKTREE_REMOVE_USAGE,
82 NULL
85 static const char * const git_worktree_repair_usage[] = {
86 BUILTIN_WORKTREE_REPAIR_USAGE,
87 NULL
90 static const char * const git_worktree_unlock_usage[] = {
91 BUILTIN_WORKTREE_UNLOCK_USAGE,
92 NULL
95 struct add_opts {
96 int force;
97 int detach;
98 int quiet;
99 int checkout;
100 const char *keep_locked;
103 static int show_only;
104 static int verbose;
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);
112 return 0;
115 return git_default_config(var, value, cb);
118 static int delete_git_dir(const char *id)
120 struct strbuf sb = STRBUF_INIT;
121 int ret;
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);
127 if (ret)
128 error_errno(_("failed to delete '%s'"), sb.buf);
129 strbuf_release(&sb);
130 return ret;
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);
142 if (!show_only)
143 delete_git_dir(id);
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;
150 int c;
152 if ((c = fspathcmp(x->string, y->string)))
153 return c;
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
158 * removed
160 if (!x->util)
161 return -1;
162 if (!y->util)
163 return 1;
164 /* paths same; sort by .git/worktrees/<id> */
165 return strcmp(x->util, y->util);
168 static void prune_dups(struct string_list *l)
170 int i;
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"));
185 struct dirent *d;
186 if (!dir)
187 return;
188 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
189 char *path;
190 strbuf_reset(&reason);
191 if (should_prune_worktree(d->d_name, &reason, &path, expire))
192 prune_worktree(d->d_name, reason.buf);
193 else if (path)
194 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
196 closedir(dir);
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));
202 prune_dups(&kept);
203 string_list_clear(&kept, 1);
205 if (!show_only)
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>")),
217 OPT_END()
220 expire = TIME_MAX;
221 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
223 if (ac)
224 usage_with_options(git_worktree_prune_usage, options);
225 prune_worktrees();
226 return 0;
229 static char *junk_work_tree;
230 static char *junk_git_dir;
231 static int is_junk;
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)
238 return;
239 if (junk_git_dir) {
240 strbuf_addstr(&sb, junk_git_dir);
241 remove_dir_recursively(&sb, 0);
242 strbuf_reset(&sb);
244 if (junk_work_tree) {
245 strbuf_addstr(&sb, junk_work_tree);
246 remove_dir_recursively(&sb, 0);
248 strbuf_release(&sb);
251 static void remove_junk_on_signal(int signo)
253 remove_junk();
254 sigchain_pop(signo);
255 raise(signo);
258 static const char *worktree_basename(const char *path, int *olen)
260 const char *name;
261 int len;
263 len = strlen(path);
264 while (len && is_dir_sep(path[len - 1]))
265 len--;
267 for (name = path + len - 1; name > path; name--)
268 if (is_dir_sep(*name)) {
269 name++;
270 break;
273 *olen = len;
274 return name;
277 /* check that path is viable location for worktree */
278 static void check_candidate_path(const char *path,
279 int force,
280 struct worktree **worktrees,
281 const char *cmd)
283 struct worktree *wt;
284 int locked;
286 if (file_exists(path) && !is_empty_dir(path))
287 die(_("'%s' already exists"), path);
289 wt = find_worktree_by_path(worktrees, path);
290 if (!wt)
291 return;
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);
297 return;
300 if (locked)
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);
302 else
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"),
315 from_file, to_file);
318 free(from_file);
319 free(to_file);
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;
330 int bare;
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'"),
335 from_file, to_file);
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) &&
343 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:
358 free(from_file);
359 free(to_file);
362 static int checkout_worktree(const struct add_opts *opts,
363 struct strvec *child_env)
365 struct child_process cp = CHILD_PROCESS_INIT;
366 cp.git_cmd = 1;
367 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
368 if (opts->quiet)
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;
379 const char *name;
380 struct child_process cp = CHILD_PROCESS_INIT;
381 struct strvec child_env = STRVEC_INIT;
382 unsigned int counter = 0;
383 int len, ret;
384 struct strbuf symref = STRBUF_INIT;
385 struct commit *commit = NULL;
386 int is_branch = 0;
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);
393 worktrees = NULL;
395 /* is 'refname' a branch or commit? */
396 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
397 ref_exists(symref.buf)) {
398 is_branch = 1;
399 if (!opts->force)
400 die_if_checked_out(symref.buf, 0);
402 commit = lookup_commit_reference_by_name(refname);
403 if (!commit)
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);
409 if (!sb_name.len)
410 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
411 strbuf_reset(&sb);
412 name = sb_name.buf;
413 git_path_buf(&sb_repo, "worktrees/%s", name);
414 len = sb_repo.len;
415 if (safe_create_leading_directories_const(sb_repo.buf))
416 die_errno(_("could not create leading directories of '%s'"),
417 sb_repo.buf);
419 while (mkdir(sb_repo.buf, 0777)) {
420 counter++;
421 if ((errno != EEXIST) || !counter /* overflow */)
422 die_errno(_("could not create directory of '%s'"),
423 sb_repo.buf);
424 strbuf_setlen(&sb_repo, len);
425 strbuf_addf(&sb_repo, "%d", counter);
427 name = strrchr(sb_repo.buf, '/') + 1;
429 junk_pid = getpid();
430 atexit(remove_junk);
431 sigchain_push_common(remove_junk_on_signal);
433 junk_git_dir = xstrdup(sb_repo.buf);
434 is_junk = 1;
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);
443 else
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'"),
449 sb_git.buf);
450 junk_work_tree = xstrdup(path);
452 strbuf_reset(&sb);
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",
458 realpath.buf, name);
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
464 * worktree.
466 strbuf_reset(&sb);
467 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
468 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
469 strbuf_reset(&sb);
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);
490 cp.git_cmd = 1;
492 if (!is_branch)
493 strvec_pushl(&cp.args, "update-ref", "HEAD",
494 oid_to_hex(&commit->object.oid), NULL);
495 else {
496 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
497 symref.buf, NULL);
498 if (opts->quiet)
499 strvec_push(&cp.args, "--quiet");
502 strvec_pushv(&cp.env, child_env.v);
503 ret = run_command(&cp);
504 if (ret)
505 goto done;
507 if (opts->checkout &&
508 (ret = checkout_worktree(opts, &child_env)))
509 goto done;
511 is_junk = 0;
512 FREE_AND_NULL(junk_work_tree);
513 FREE_AND_NULL(junk_git_dir);
515 done:
516 if (ret || !opts->keep_locked) {
517 strbuf_reset(&sb);
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),
533 "1",
534 NULL);
535 opt.dir = path;
537 ret = run_hooks_opt("post-checkout", &opt);
540 strvec_clear(&child_env);
541 strbuf_release(&sb);
542 strbuf_release(&symref);
543 strbuf_release(&sb_repo);
544 strbuf_release(&sb_git);
545 strbuf_release(&sb_name);
546 strbuf_release(&realpath);
547 return ret;
550 static void print_preparing_worktree_line(int detach,
551 const char *branch,
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);
557 if (!commit)
558 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
559 else
560 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
561 new_branch,
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);
565 } else {
566 struct strbuf s = STRBUF_INIT;
567 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
568 ref_exists(s.buf))
569 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
570 branch);
571 else {
572 struct commit *commit = lookup_commit_reference_by_name(branch);
573 if (!commit)
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));
578 strbuf_release(&s);
582 static const char *dwim_branch(const char *path, const char **new_branch)
584 int n;
585 int branch_exists;
586 const char *s = worktree_basename(path, &n);
587 const char *branchname = xstrndup(s, n);
588 struct strbuf ref = STRBUF_INIT;
590 UNLEAK(branchname);
592 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
593 ref_exists(ref.buf);
594 strbuf_release(&ref);
595 if (branch_exists)
596 return branchname;
598 *new_branch = branchname;
599 if (guess_remote) {
600 struct object_id oid;
601 const char *remote =
602 unique_tracking_name(*new_branch, &oid, NULL);
603 return remote;
605 return 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;
612 char *path;
613 const char *branch;
614 const char *new_branch = NULL;
615 const char *opt_track = NULL;
616 const char *lock_reason = NULL;
617 int keep_locked = 0;
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")),
637 OPT_END()
639 int ret;
641 memset(&opts, 0, sizeof(opts));
642 opts.checkout = 1;
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");
648 if (lock_reason)
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, "-"))
660 branch = "@{-1}";
662 if (new_branch_force) {
663 struct strbuf symref = STRBUF_INIT;
665 new_branch = new_branch_force;
667 if (!opts.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);
676 if (s)
677 branch = s;
680 if (ac == 2 && !new_branch && !opts.detach) {
681 struct object_id oid;
682 struct commit *commit;
683 const char *remote;
685 commit = lookup_commit_reference_by_name(branch);
686 if (!commit) {
687 remote = unique_tracking_name(branch, &oid, NULL);
688 if (remote) {
689 new_branch = branch;
690 branch = remote;
694 if (!opts.quiet)
695 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
697 if (new_branch) {
698 struct child_process cp = CHILD_PROCESS_INIT;
699 cp.git_cmd = 1;
700 strvec_push(&cp.args, "branch");
701 if (new_branch_force)
702 strvec_push(&cp.args, "--force");
703 if (opts.quiet)
704 strvec_push(&cp.args, "--quiet");
705 strvec_push(&cp.args, new_branch);
706 strvec_push(&cp.args, branch);
707 if (opt_track)
708 strvec_push(&cp.args, opt_track);
709 if (run_command(&cp))
710 return -1;
711 branch = new_branch;
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);
717 free(path);
718 return ret;
721 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
723 const char *reason;
725 printf("worktree %s%c", wt->path, line_terminator);
726 if (wt->is_bare)
727 printf("bare%c", line_terminator);
728 else {
729 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
730 if (wt->is_detached)
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);
737 if (reason) {
738 fputs("locked", stdout);
739 if (*reason) {
740 fputc(' ', stdout);
741 write_name_quoted(reason, stdout, line_terminator);
742 } else {
743 fputc(line_terminator, stdout);
747 reason = worktree_prune_reason(wt, expire);
748 if (reason)
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);
759 const char *reason;
761 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
762 if (wt->is_bare)
763 strbuf_addstr(&sb, "(bare)");
764 else {
765 strbuf_addf(&sb, "%-*s ", abbrev_len,
766 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
767 if (wt->is_detached)
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);
772 free(ref);
773 } else
774 strbuf_addstr(&sb, "(error)");
777 reason = worktree_lock_reason(wt);
778 if (verbose && reason && *reason)
779 strbuf_addf(&sb, "\n\tlocked: %s", reason);
780 else if (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);
786 else if (reason)
787 strbuf_addstr(&sb, " prunable");
789 printf("%s\n", sb.buf);
790 strbuf_release(&sb);
793 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
795 int i;
797 for (i = 0; wt[i]; i++) {
798 int sha1_len;
799 int path_len = strlen(wt[i]->path);
801 if (path_len > *maxlen)
802 *maxlen = path_len;
803 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
804 if (sha1_len > *abbrev)
805 *abbrev = sha1_len;
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)
818 int n = 0;
819 struct worktree **p = wt;
821 while (*p++)
822 n++;
823 QSORT(wt, n, pathcmp);
826 static int list(int ac, const char **av, const char *prefix)
828 int porcelain = 0;
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'),
838 OPT_END()
841 expire = TIME_MAX;
842 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
843 if (ac)
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");
849 else {
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);
856 if (!porcelain)
857 measure_widths(worktrees, &abbrev, &path_maxlen);
859 for (i = 0; worktrees[i]; i++) {
860 if (porcelain)
861 show_worktree_porcelain(worktrees[i],
862 line_terminator);
863 else
864 show_worktree(worktrees[i], path_maxlen, abbrev);
866 free_worktrees(worktrees);
868 return 0;
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")),
877 OPT_END()
879 struct worktree **worktrees, *wt;
881 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
882 if (ac != 1)
883 usage_with_options(git_worktree_lock_usage, options);
885 worktrees = get_worktrees();
886 wt = find_worktree(worktrees, prefix, av[0]);
887 if (!wt)
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);
893 if (old_reason) {
894 if (*old_reason)
895 die(_("'%s' is already locked, reason: %s"),
896 av[0], old_reason);
897 die(_("'%s' is already locked"), av[0]);
900 write_file(git_common_path("worktrees/%s/locked", wt->id),
901 "%s", reason);
902 free_worktrees(worktrees);
903 return 0;
906 static int unlock_worktree(int ac, const char **av, const char *prefix)
908 struct option options[] = {
909 OPT_END()
911 struct worktree **worktrees, *wt;
912 int ret;
914 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
915 if (ac != 1)
916 usage_with_options(git_worktree_unlock_usage, options);
918 worktrees = get_worktrees();
919 wt = find_worktree(worktrees, prefix, av[0]);
920 if (!wt)
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);
928 return ret;
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];
948 int err;
950 if (!S_ISGITLINK(ce->ce_mode))
951 continue;
953 strbuf_reset(&path);
954 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
955 if (!is_submodule_populated_gently(path.buf, &err))
956 continue;
958 found_submodules = 1;
959 break;
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)
971 int force = 0;
972 struct option options[] = {
973 OPT__FORCE(&force,
974 N_("force move even if worktree is dirty or locked"),
975 PARSE_OPT_NOCOMPLETE),
976 OPT_END()
978 struct worktree **worktrees, *wt;
979 struct strbuf dst = STRBUF_INIT;
980 struct strbuf errmsg = STRBUF_INIT;
981 const char *reason = NULL;
982 char *path;
984 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
986 if (ac != 2)
987 usage_with_options(git_worktree_move_usage, options);
989 path = prefix_filename(prefix, av[1]);
990 strbuf_addstr(&dst, path);
991 free(path);
993 worktrees = get_worktrees();
994 wt = find_worktree(worktrees, prefix, av[0]);
995 if (!wt)
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);
1002 if (!sep)
1003 die(_("could not figure out destination name from '%s'"),
1004 wt->path);
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);
1012 if (force < 2)
1013 reason = worktree_lock_reason(wt);
1014 if (reason) {
1015 if (*reason)
1016 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1017 reason);
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"),
1022 errmsg.buf);
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);
1032 return 0;
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
1044 * know better.
1046 static void check_clean_worktree(struct worktree *wt,
1047 const char *original_path)
1049 struct child_process cp;
1050 char buf[1];
1051 int ret;
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",
1066 NULL);
1067 cp.git_cmd = 1;
1068 cp.dir = wt->path;
1069 cp.out = -1;
1070 ret = start_command(&cp);
1071 if (ret)
1072 die_errno(_("failed to run 'git status' on '%s'"),
1073 original_path);
1074 ret = xread(cp.out, buf, sizeof(buf));
1075 if (ret)
1076 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1077 original_path);
1078 close(cp.out);
1079 ret = finish_command(&cp);
1080 if (ret)
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;
1088 int ret = 0;
1090 strbuf_addstr(&sb, wt->path);
1091 if (remove_dir_recursively(&sb, 0)) {
1092 error_errno(_("failed to delete '%s'"), sb.buf);
1093 ret = -1;
1095 strbuf_release(&sb);
1096 return ret;
1099 static int remove_worktree(int ac, const char **av, const char *prefix)
1101 int force = 0;
1102 struct option options[] = {
1103 OPT__FORCE(&force,
1104 N_("force removal even if worktree is dirty or locked"),
1105 PARSE_OPT_NOCOMPLETE),
1106 OPT_END()
1108 struct worktree **worktrees, *wt;
1109 struct strbuf errmsg = STRBUF_INIT;
1110 const char *reason = NULL;
1111 int ret = 0;
1113 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1114 if (ac != 1)
1115 usage_with_options(git_worktree_remove_usage, options);
1117 worktrees = get_worktrees();
1118 wt = find_worktree(worktrees, prefix, av[0]);
1119 if (!wt)
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]);
1123 if (force < 2)
1124 reason = worktree_lock_reason(wt);
1125 if (reason) {
1126 if (*reason)
1127 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1128 reason);
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"),
1133 errmsg.buf);
1134 strbuf_release(&errmsg);
1136 if (file_exists(wt->path)) {
1137 if (!force)
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
1144 * from here.
1146 ret |= delete_git_dir(wt->id);
1147 delete_worktrees_dir_if_empty();
1149 free_worktrees(worktrees);
1150 return ret;
1153 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1155 if (!iserr) {
1156 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1157 } else {
1158 int *exit_status = (int *)cb_data;
1159 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1160 *exit_status = 1;
1164 static int repair(int ac, const char **av, const char *prefix)
1166 const char **p;
1167 const char *self[] = { ".", NULL };
1168 struct option options[] = {
1169 OPT_END()
1171 int rc = 0;
1173 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1174 p = ac > 0 ? av : self;
1175 for (; *p; p++)
1176 repair_worktree_at_path(*p, report_repair, &rc);
1177 repair_worktrees(report_repair, &rc);
1178 return 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),
1193 OPT_END()
1196 git_config(git_worktree_config, NULL);
1198 if (!prefix)
1199 prefix = "";
1201 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1202 return fn(ac, av, prefix);