Git 2.32.1
[git/debian.git] / builtin / worktree.c
blob976bf8ed063f1db6d2ab6582b0ed7faea4c31a42
1 #include "cache.h"
2 #include "checkout.h"
3 #include "config.h"
4 #include "builtin.h"
5 #include "dir.h"
6 #include "parse-options.h"
7 #include "strvec.h"
8 #include "branch.h"
9 #include "refs.h"
10 #include "run-command.h"
11 #include "sigchain.h"
12 #include "submodule.h"
13 #include "utf8.h"
14 #include "worktree.h"
15 #include "quote.h"
17 static const char * const worktree_usage[] = {
18 N_("git worktree add [<options>] <path> [<commit-ish>]"),
19 N_("git worktree list [<options>]"),
20 N_("git worktree lock [<options>] <path>"),
21 N_("git worktree move <worktree> <new-path>"),
22 N_("git worktree prune [<options>]"),
23 N_("git worktree remove [<options>] <worktree>"),
24 N_("git worktree unlock <path>"),
25 NULL
28 struct add_opts {
29 int force;
30 int detach;
31 int quiet;
32 int checkout;
33 int keep_locked;
36 static int show_only;
37 static int verbose;
38 static int guess_remote;
39 static timestamp_t expire;
41 static int git_worktree_config(const char *var, const char *value, void *cb)
43 if (!strcmp(var, "worktree.guessremote")) {
44 guess_remote = git_config_bool(var, value);
45 return 0;
48 return git_default_config(var, value, cb);
51 static int delete_git_dir(const char *id)
53 struct strbuf sb = STRBUF_INIT;
54 int ret;
56 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
57 ret = remove_dir_recursively(&sb, 0);
58 if (ret < 0 && errno == ENOTDIR)
59 ret = unlink(sb.buf);
60 if (ret)
61 error_errno(_("failed to delete '%s'"), sb.buf);
62 strbuf_release(&sb);
63 return ret;
66 static void delete_worktrees_dir_if_empty(void)
68 rmdir(git_path("worktrees")); /* ignore failed removal */
71 static void prune_worktree(const char *id, const char *reason)
73 if (show_only || verbose)
74 printf_ln(_("Removing %s/%s: %s"), "worktrees", id, reason);
75 if (!show_only)
76 delete_git_dir(id);
79 static int prune_cmp(const void *a, const void *b)
81 const struct string_list_item *x = a;
82 const struct string_list_item *y = b;
83 int c;
85 if ((c = fspathcmp(x->string, y->string)))
86 return c;
88 * paths same; prune_dupes() removes all but the first worktree entry
89 * having the same path, so sort main worktree ('util' is NULL) above
90 * linked worktrees ('util' not NULL) since main worktree can't be
91 * removed
93 if (!x->util)
94 return -1;
95 if (!y->util)
96 return 1;
97 /* paths same; sort by .git/worktrees/<id> */
98 return strcmp(x->util, y->util);
101 static void prune_dups(struct string_list *l)
103 int i;
105 QSORT(l->items, l->nr, prune_cmp);
106 for (i = 1; i < l->nr; i++) {
107 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
108 prune_worktree(l->items[i].util, "duplicate entry");
112 static void prune_worktrees(void)
114 struct strbuf reason = STRBUF_INIT;
115 struct strbuf main_path = STRBUF_INIT;
116 struct string_list kept = STRING_LIST_INIT_NODUP;
117 DIR *dir = opendir(git_path("worktrees"));
118 struct dirent *d;
119 if (!dir)
120 return;
121 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
122 char *path;
123 strbuf_reset(&reason);
124 if (should_prune_worktree(d->d_name, &reason, &path, expire))
125 prune_worktree(d->d_name, reason.buf);
126 else if (path)
127 string_list_append(&kept, path)->util = xstrdup(d->d_name);
129 closedir(dir);
131 strbuf_add_absolute_path(&main_path, get_git_common_dir());
132 /* massage main worktree absolute path to match 'gitdir' content */
133 strbuf_strip_suffix(&main_path, "/.");
134 string_list_append(&kept, strbuf_detach(&main_path, NULL));
135 prune_dups(&kept);
136 string_list_clear(&kept, 1);
138 if (!show_only)
139 delete_worktrees_dir_if_empty();
140 strbuf_release(&reason);
143 static int prune(int ac, const char **av, const char *prefix)
145 struct option options[] = {
146 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
147 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
148 OPT_EXPIRY_DATE(0, "expire", &expire,
149 N_("expire working trees older than <time>")),
150 OPT_END()
153 expire = TIME_MAX;
154 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
155 if (ac)
156 usage_with_options(worktree_usage, options);
157 prune_worktrees();
158 return 0;
161 static char *junk_work_tree;
162 static char *junk_git_dir;
163 static int is_junk;
164 static pid_t junk_pid;
166 static void remove_junk(void)
168 struct strbuf sb = STRBUF_INIT;
169 if (!is_junk || getpid() != junk_pid)
170 return;
171 if (junk_git_dir) {
172 strbuf_addstr(&sb, junk_git_dir);
173 remove_dir_recursively(&sb, 0);
174 strbuf_reset(&sb);
176 if (junk_work_tree) {
177 strbuf_addstr(&sb, junk_work_tree);
178 remove_dir_recursively(&sb, 0);
180 strbuf_release(&sb);
183 static void remove_junk_on_signal(int signo)
185 remove_junk();
186 sigchain_pop(signo);
187 raise(signo);
190 static const char *worktree_basename(const char *path, int *olen)
192 const char *name;
193 int len;
195 len = strlen(path);
196 while (len && is_dir_sep(path[len - 1]))
197 len--;
199 for (name = path + len - 1; name > path; name--)
200 if (is_dir_sep(*name)) {
201 name++;
202 break;
205 *olen = len;
206 return name;
209 /* check that path is viable location for worktree */
210 static void check_candidate_path(const char *path,
211 int force,
212 struct worktree **worktrees,
213 const char *cmd)
215 struct worktree *wt;
216 int locked;
218 if (file_exists(path) && !is_empty_dir(path))
219 die(_("'%s' already exists"), path);
221 wt = find_worktree_by_path(worktrees, path);
222 if (!wt)
223 return;
225 locked = !!worktree_lock_reason(wt);
226 if ((!locked && force) || (locked && force > 1)) {
227 if (delete_git_dir(wt->id))
228 die(_("unusable worktree destination '%s'"), path);
229 return;
232 if (locked)
233 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
234 else
235 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
238 static int add_worktree(const char *path, const char *refname,
239 const struct add_opts *opts)
241 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
242 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
243 const char *name;
244 struct child_process cp = CHILD_PROCESS_INIT;
245 struct strvec child_env = STRVEC_INIT;
246 unsigned int counter = 0;
247 int len, ret;
248 struct strbuf symref = STRBUF_INIT;
249 struct commit *commit = NULL;
250 int is_branch = 0;
251 struct strbuf sb_name = STRBUF_INIT;
252 struct worktree **worktrees;
254 worktrees = get_worktrees();
255 check_candidate_path(path, opts->force, worktrees, "add");
256 free_worktrees(worktrees);
257 worktrees = NULL;
259 /* is 'refname' a branch or commit? */
260 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
261 ref_exists(symref.buf)) {
262 is_branch = 1;
263 if (!opts->force)
264 die_if_checked_out(symref.buf, 0);
266 commit = lookup_commit_reference_by_name(refname);
267 if (!commit)
268 die(_("invalid reference: %s"), refname);
270 name = worktree_basename(path, &len);
271 strbuf_add(&sb, name, path + len - name);
272 sanitize_refname_component(sb.buf, &sb_name);
273 if (!sb_name.len)
274 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
275 strbuf_reset(&sb);
276 name = sb_name.buf;
277 git_path_buf(&sb_repo, "worktrees/%s", name);
278 len = sb_repo.len;
279 if (safe_create_leading_directories_const(sb_repo.buf))
280 die_errno(_("could not create leading directories of '%s'"),
281 sb_repo.buf);
283 while (mkdir(sb_repo.buf, 0777)) {
284 counter++;
285 if ((errno != EEXIST) || !counter /* overflow */)
286 die_errno(_("could not create directory of '%s'"),
287 sb_repo.buf);
288 strbuf_setlen(&sb_repo, len);
289 strbuf_addf(&sb_repo, "%d", counter);
291 name = strrchr(sb_repo.buf, '/') + 1;
293 junk_pid = getpid();
294 atexit(remove_junk);
295 sigchain_push_common(remove_junk_on_signal);
297 junk_git_dir = xstrdup(sb_repo.buf);
298 is_junk = 1;
301 * lock the incomplete repo so prune won't delete it, unlock
302 * after the preparation is over.
304 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
305 if (!opts->keep_locked)
306 write_file(sb.buf, "initializing");
307 else
308 write_file(sb.buf, "added with --lock");
310 strbuf_addf(&sb_git, "%s/.git", path);
311 if (safe_create_leading_directories_const(sb_git.buf))
312 die_errno(_("could not create leading directories of '%s'"),
313 sb_git.buf);
314 junk_work_tree = xstrdup(path);
316 strbuf_reset(&sb);
317 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
318 strbuf_realpath(&realpath, sb_git.buf, 1);
319 write_file(sb.buf, "%s", realpath.buf);
320 strbuf_realpath(&realpath, get_git_common_dir(), 1);
321 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
322 realpath.buf, name);
324 * This is to keep resolve_ref() happy. We need a valid HEAD
325 * or is_git_directory() will reject the directory. Any value which
326 * looks like an object ID will do since it will be immediately
327 * replaced by the symbolic-ref or update-ref invocation in the new
328 * worktree.
330 strbuf_reset(&sb);
331 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
332 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
333 strbuf_reset(&sb);
334 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
335 write_file(sb.buf, "../..");
337 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
338 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
339 cp.git_cmd = 1;
341 if (!is_branch)
342 strvec_pushl(&cp.args, "update-ref", "HEAD",
343 oid_to_hex(&commit->object.oid), NULL);
344 else {
345 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
346 symref.buf, NULL);
347 if (opts->quiet)
348 strvec_push(&cp.args, "--quiet");
351 cp.env = child_env.v;
352 ret = run_command(&cp);
353 if (ret)
354 goto done;
356 if (opts->checkout) {
357 cp.argv = NULL;
358 strvec_clear(&cp.args);
359 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
360 if (opts->quiet)
361 strvec_push(&cp.args, "--quiet");
362 cp.env = child_env.v;
363 ret = run_command(&cp);
364 if (ret)
365 goto done;
368 is_junk = 0;
369 FREE_AND_NULL(junk_work_tree);
370 FREE_AND_NULL(junk_git_dir);
372 done:
373 if (ret || !opts->keep_locked) {
374 strbuf_reset(&sb);
375 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
376 unlink_or_warn(sb.buf);
380 * Hook failure does not warrant worktree deletion, so run hook after
381 * is_junk is cleared, but do return appropriate code when hook fails.
383 if (!ret && opts->checkout) {
384 const char *hook = find_hook("post-checkout");
385 if (hook) {
386 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
387 cp.git_cmd = 0;
388 cp.no_stdin = 1;
389 cp.stdout_to_stderr = 1;
390 cp.dir = path;
391 cp.env = env;
392 cp.argv = NULL;
393 cp.trace2_hook_name = "post-checkout";
394 strvec_pushl(&cp.args, absolute_path(hook),
395 oid_to_hex(null_oid()),
396 oid_to_hex(&commit->object.oid),
397 "1", NULL);
398 ret = run_command(&cp);
402 strvec_clear(&child_env);
403 strbuf_release(&sb);
404 strbuf_release(&symref);
405 strbuf_release(&sb_repo);
406 strbuf_release(&sb_git);
407 strbuf_release(&sb_name);
408 strbuf_release(&realpath);
409 return ret;
412 static void print_preparing_worktree_line(int detach,
413 const char *branch,
414 const char *new_branch,
415 int force_new_branch)
417 if (force_new_branch) {
418 struct commit *commit = lookup_commit_reference_by_name(new_branch);
419 if (!commit)
420 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
421 else
422 printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
423 new_branch,
424 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
425 } else if (new_branch) {
426 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
427 } else {
428 struct strbuf s = STRBUF_INIT;
429 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
430 ref_exists(s.buf))
431 printf_ln(_("Preparing worktree (checking out '%s')"),
432 branch);
433 else {
434 struct commit *commit = lookup_commit_reference_by_name(branch);
435 if (!commit)
436 die(_("invalid reference: %s"), branch);
437 printf_ln(_("Preparing worktree (detached HEAD %s)"),
438 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
440 strbuf_release(&s);
444 static const char *dwim_branch(const char *path, const char **new_branch)
446 int n;
447 int branch_exists;
448 const char *s = worktree_basename(path, &n);
449 const char *branchname = xstrndup(s, n);
450 struct strbuf ref = STRBUF_INIT;
452 UNLEAK(branchname);
454 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
455 ref_exists(ref.buf);
456 strbuf_release(&ref);
457 if (branch_exists)
458 return branchname;
460 *new_branch = branchname;
461 if (guess_remote) {
462 struct object_id oid;
463 const char *remote =
464 unique_tracking_name(*new_branch, &oid, NULL);
465 return remote;
467 return NULL;
470 static int add(int ac, const char **av, const char *prefix)
472 struct add_opts opts;
473 const char *new_branch_force = NULL;
474 char *path;
475 const char *branch;
476 const char *new_branch = NULL;
477 const char *opt_track = NULL;
478 struct option options[] = {
479 OPT__FORCE(&opts.force,
480 N_("checkout <branch> even if already checked out in other worktree"),
481 PARSE_OPT_NOCOMPLETE),
482 OPT_STRING('b', NULL, &new_branch, N_("branch"),
483 N_("create a new branch")),
484 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
485 N_("create or reset a branch")),
486 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
487 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
488 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
489 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
490 OPT_PASSTHRU(0, "track", &opt_track, NULL,
491 N_("set up tracking mode (see git-branch(1))"),
492 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
493 OPT_BOOL(0, "guess-remote", &guess_remote,
494 N_("try to match the new branch name with a remote-tracking branch")),
495 OPT_END()
498 memset(&opts, 0, sizeof(opts));
499 opts.checkout = 1;
500 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
501 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
502 die(_("-b, -B, and --detach are mutually exclusive"));
503 if (ac < 1 || ac > 2)
504 usage_with_options(worktree_usage, options);
506 path = prefix_filename(prefix, av[0]);
507 branch = ac < 2 ? "HEAD" : av[1];
509 if (!strcmp(branch, "-"))
510 branch = "@{-1}";
512 if (new_branch_force) {
513 struct strbuf symref = STRBUF_INIT;
515 new_branch = new_branch_force;
517 if (!opts.force &&
518 !strbuf_check_branch_ref(&symref, new_branch) &&
519 ref_exists(symref.buf))
520 die_if_checked_out(symref.buf, 0);
521 strbuf_release(&symref);
524 if (ac < 2 && !new_branch && !opts.detach) {
525 const char *s = dwim_branch(path, &new_branch);
526 if (s)
527 branch = s;
530 if (ac == 2 && !new_branch && !opts.detach) {
531 struct object_id oid;
532 struct commit *commit;
533 const char *remote;
535 commit = lookup_commit_reference_by_name(branch);
536 if (!commit) {
537 remote = unique_tracking_name(branch, &oid, NULL);
538 if (remote) {
539 new_branch = branch;
540 branch = remote;
544 if (!opts.quiet)
545 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
547 if (new_branch) {
548 struct child_process cp = CHILD_PROCESS_INIT;
549 cp.git_cmd = 1;
550 strvec_push(&cp.args, "branch");
551 if (new_branch_force)
552 strvec_push(&cp.args, "--force");
553 if (opts.quiet)
554 strvec_push(&cp.args, "--quiet");
555 strvec_push(&cp.args, new_branch);
556 strvec_push(&cp.args, branch);
557 if (opt_track)
558 strvec_push(&cp.args, opt_track);
559 if (run_command(&cp))
560 return -1;
561 branch = new_branch;
562 } else if (opt_track) {
563 die(_("--[no-]track can only be used if a new branch is created"));
566 UNLEAK(path);
567 UNLEAK(opts);
568 return add_worktree(path, branch, &opts);
571 static void show_worktree_porcelain(struct worktree *wt)
573 const char *reason;
575 printf("worktree %s\n", wt->path);
576 if (wt->is_bare)
577 printf("bare\n");
578 else {
579 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
580 if (wt->is_detached)
581 printf("detached\n");
582 else if (wt->head_ref)
583 printf("branch %s\n", wt->head_ref);
586 reason = worktree_lock_reason(wt);
587 if (reason && *reason) {
588 struct strbuf sb = STRBUF_INIT;
589 quote_c_style(reason, &sb, NULL, 0);
590 printf("locked %s\n", sb.buf);
591 strbuf_release(&sb);
592 } else if (reason)
593 printf("locked\n");
595 reason = worktree_prune_reason(wt, expire);
596 if (reason)
597 printf("prunable %s\n", reason);
599 printf("\n");
602 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
604 struct strbuf sb = STRBUF_INIT;
605 int cur_path_len = strlen(wt->path);
606 int path_adj = cur_path_len - utf8_strwidth(wt->path);
607 const char *reason;
609 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
610 if (wt->is_bare)
611 strbuf_addstr(&sb, "(bare)");
612 else {
613 strbuf_addf(&sb, "%-*s ", abbrev_len,
614 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
615 if (wt->is_detached)
616 strbuf_addstr(&sb, "(detached HEAD)");
617 else if (wt->head_ref) {
618 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
619 strbuf_addf(&sb, "[%s]", ref);
620 free(ref);
621 } else
622 strbuf_addstr(&sb, "(error)");
625 reason = worktree_lock_reason(wt);
626 if (verbose && reason && *reason)
627 strbuf_addf(&sb, "\n\tlocked: %s", reason);
628 else if (reason)
629 strbuf_addstr(&sb, " locked");
631 reason = worktree_prune_reason(wt, expire);
632 if (verbose && reason)
633 strbuf_addf(&sb, "\n\tprunable: %s", reason);
634 else if (reason)
635 strbuf_addstr(&sb, " prunable");
637 printf("%s\n", sb.buf);
638 strbuf_release(&sb);
641 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
643 int i;
645 for (i = 0; wt[i]; i++) {
646 int sha1_len;
647 int path_len = strlen(wt[i]->path);
649 if (path_len > *maxlen)
650 *maxlen = path_len;
651 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
652 if (sha1_len > *abbrev)
653 *abbrev = sha1_len;
657 static int pathcmp(const void *a_, const void *b_)
659 const struct worktree *const *a = a_;
660 const struct worktree *const *b = b_;
661 return fspathcmp((*a)->path, (*b)->path);
664 static void pathsort(struct worktree **wt)
666 int n = 0;
667 struct worktree **p = wt;
669 while (*p++)
670 n++;
671 QSORT(wt, n, pathcmp);
674 static int list(int ac, const char **av, const char *prefix)
676 int porcelain = 0;
678 struct option options[] = {
679 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
680 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
681 OPT_EXPIRY_DATE(0, "expire", &expire,
682 N_("add 'prunable' annotation to worktrees older than <time>")),
683 OPT_END()
686 expire = TIME_MAX;
687 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
688 if (ac)
689 usage_with_options(worktree_usage, options);
690 else if (verbose && porcelain)
691 die(_("--verbose and --porcelain are mutually exclusive"));
692 else {
693 struct worktree **worktrees = get_worktrees();
694 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
696 /* sort worktrees by path but keep main worktree at top */
697 pathsort(worktrees + 1);
699 if (!porcelain)
700 measure_widths(worktrees, &abbrev, &path_maxlen);
702 for (i = 0; worktrees[i]; i++) {
703 if (porcelain)
704 show_worktree_porcelain(worktrees[i]);
705 else
706 show_worktree(worktrees[i], path_maxlen, abbrev);
708 free_worktrees(worktrees);
710 return 0;
713 static int lock_worktree(int ac, const char **av, const char *prefix)
715 const char *reason = "", *old_reason;
716 struct option options[] = {
717 OPT_STRING(0, "reason", &reason, N_("string"),
718 N_("reason for locking")),
719 OPT_END()
721 struct worktree **worktrees, *wt;
723 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
724 if (ac != 1)
725 usage_with_options(worktree_usage, options);
727 worktrees = get_worktrees();
728 wt = find_worktree(worktrees, prefix, av[0]);
729 if (!wt)
730 die(_("'%s' is not a working tree"), av[0]);
731 if (is_main_worktree(wt))
732 die(_("The main working tree cannot be locked or unlocked"));
734 old_reason = worktree_lock_reason(wt);
735 if (old_reason) {
736 if (*old_reason)
737 die(_("'%s' is already locked, reason: %s"),
738 av[0], old_reason);
739 die(_("'%s' is already locked"), av[0]);
742 write_file(git_common_path("worktrees/%s/locked", wt->id),
743 "%s", reason);
744 free_worktrees(worktrees);
745 return 0;
748 static int unlock_worktree(int ac, const char **av, const char *prefix)
750 struct option options[] = {
751 OPT_END()
753 struct worktree **worktrees, *wt;
754 int ret;
756 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
757 if (ac != 1)
758 usage_with_options(worktree_usage, options);
760 worktrees = get_worktrees();
761 wt = find_worktree(worktrees, prefix, av[0]);
762 if (!wt)
763 die(_("'%s' is not a working tree"), av[0]);
764 if (is_main_worktree(wt))
765 die(_("The main working tree cannot be locked or unlocked"));
766 if (!worktree_lock_reason(wt))
767 die(_("'%s' is not locked"), av[0]);
768 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
769 free_worktrees(worktrees);
770 return ret;
773 static void validate_no_submodules(const struct worktree *wt)
775 struct index_state istate = { NULL };
776 struct strbuf path = STRBUF_INIT;
777 int i, found_submodules = 0;
779 if (is_directory(worktree_git_path(wt, "modules"))) {
781 * There could be false positives, e.g. the "modules"
782 * directory exists but is empty. But it's a rare case and
783 * this simpler check is probably good enough for now.
785 found_submodules = 1;
786 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
787 get_worktree_git_dir(wt)) > 0) {
788 for (i = 0; i < istate.cache_nr; i++) {
789 struct cache_entry *ce = istate.cache[i];
790 int err;
792 if (!S_ISGITLINK(ce->ce_mode))
793 continue;
795 strbuf_reset(&path);
796 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
797 if (!is_submodule_populated_gently(path.buf, &err))
798 continue;
800 found_submodules = 1;
801 break;
804 discard_index(&istate);
805 strbuf_release(&path);
807 if (found_submodules)
808 die(_("working trees containing submodules cannot be moved or removed"));
811 static int move_worktree(int ac, const char **av, const char *prefix)
813 int force = 0;
814 struct option options[] = {
815 OPT__FORCE(&force,
816 N_("force move even if worktree is dirty or locked"),
817 PARSE_OPT_NOCOMPLETE),
818 OPT_END()
820 struct worktree **worktrees, *wt;
821 struct strbuf dst = STRBUF_INIT;
822 struct strbuf errmsg = STRBUF_INIT;
823 const char *reason = NULL;
824 char *path;
826 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
827 if (ac != 2)
828 usage_with_options(worktree_usage, options);
830 path = prefix_filename(prefix, av[1]);
831 strbuf_addstr(&dst, path);
832 free(path);
834 worktrees = get_worktrees();
835 wt = find_worktree(worktrees, prefix, av[0]);
836 if (!wt)
837 die(_("'%s' is not a working tree"), av[0]);
838 if (is_main_worktree(wt))
839 die(_("'%s' is a main working tree"), av[0]);
840 if (is_directory(dst.buf)) {
841 const char *sep = find_last_dir_sep(wt->path);
843 if (!sep)
844 die(_("could not figure out destination name from '%s'"),
845 wt->path);
846 strbuf_trim_trailing_dir_sep(&dst);
847 strbuf_addstr(&dst, sep);
849 check_candidate_path(dst.buf, force, worktrees, "move");
851 validate_no_submodules(wt);
853 if (force < 2)
854 reason = worktree_lock_reason(wt);
855 if (reason) {
856 if (*reason)
857 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
858 reason);
859 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
861 if (validate_worktree(wt, &errmsg, 0))
862 die(_("validation failed, cannot move working tree: %s"),
863 errmsg.buf);
864 strbuf_release(&errmsg);
866 if (rename(wt->path, dst.buf) == -1)
867 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
869 update_worktree_location(wt, dst.buf);
871 strbuf_release(&dst);
872 free_worktrees(worktrees);
873 return 0;
877 * Note, "git status --porcelain" is used to determine if it's safe to
878 * delete a whole worktree. "git status" does not ignore user
879 * configuration, so if a normal "git status" shows "clean" for the
880 * user, then it's ok to remove it.
882 * This assumption may be a bad one. We may want to ignore
883 * (potentially bad) user settings and only delete a worktree when
884 * it's absolutely safe to do so from _our_ point of view because we
885 * know better.
887 static void check_clean_worktree(struct worktree *wt,
888 const char *original_path)
890 struct child_process cp;
891 char buf[1];
892 int ret;
895 * Until we sort this out, all submodules are "dirty" and
896 * will abort this function.
898 validate_no_submodules(wt);
900 child_process_init(&cp);
901 strvec_pushf(&cp.env_array, "%s=%s/.git",
902 GIT_DIR_ENVIRONMENT, wt->path);
903 strvec_pushf(&cp.env_array, "%s=%s",
904 GIT_WORK_TREE_ENVIRONMENT, wt->path);
905 strvec_pushl(&cp.args, "status",
906 "--porcelain", "--ignore-submodules=none",
907 NULL);
908 cp.git_cmd = 1;
909 cp.dir = wt->path;
910 cp.out = -1;
911 ret = start_command(&cp);
912 if (ret)
913 die_errno(_("failed to run 'git status' on '%s'"),
914 original_path);
915 ret = xread(cp.out, buf, sizeof(buf));
916 if (ret)
917 die(_("'%s' contains modified or untracked files, use --force to delete it"),
918 original_path);
919 close(cp.out);
920 ret = finish_command(&cp);
921 if (ret)
922 die_errno(_("failed to run 'git status' on '%s', code %d"),
923 original_path, ret);
926 static int delete_git_work_tree(struct worktree *wt)
928 struct strbuf sb = STRBUF_INIT;
929 int ret = 0;
931 strbuf_addstr(&sb, wt->path);
932 if (remove_dir_recursively(&sb, 0)) {
933 error_errno(_("failed to delete '%s'"), sb.buf);
934 ret = -1;
936 strbuf_release(&sb);
937 return ret;
940 static int remove_worktree(int ac, const char **av, const char *prefix)
942 int force = 0;
943 struct option options[] = {
944 OPT__FORCE(&force,
945 N_("force removal even if worktree is dirty or locked"),
946 PARSE_OPT_NOCOMPLETE),
947 OPT_END()
949 struct worktree **worktrees, *wt;
950 struct strbuf errmsg = STRBUF_INIT;
951 const char *reason = NULL;
952 int ret = 0;
954 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
955 if (ac != 1)
956 usage_with_options(worktree_usage, options);
958 worktrees = get_worktrees();
959 wt = find_worktree(worktrees, prefix, av[0]);
960 if (!wt)
961 die(_("'%s' is not a working tree"), av[0]);
962 if (is_main_worktree(wt))
963 die(_("'%s' is a main working tree"), av[0]);
964 if (force < 2)
965 reason = worktree_lock_reason(wt);
966 if (reason) {
967 if (*reason)
968 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
969 reason);
970 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
972 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
973 die(_("validation failed, cannot remove working tree: %s"),
974 errmsg.buf);
975 strbuf_release(&errmsg);
977 if (file_exists(wt->path)) {
978 if (!force)
979 check_clean_worktree(wt, av[0]);
981 ret |= delete_git_work_tree(wt);
984 * continue on even if ret is non-zero, there's no going back
985 * from here.
987 ret |= delete_git_dir(wt->id);
988 delete_worktrees_dir_if_empty();
990 free_worktrees(worktrees);
991 return ret;
994 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
996 if (!iserr) {
997 printf_ln(_("repair: %s: %s"), msg, path);
998 } else {
999 int *exit_status = (int *)cb_data;
1000 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1001 *exit_status = 1;
1005 static int repair(int ac, const char **av, const char *prefix)
1007 const char **p;
1008 const char *self[] = { ".", NULL };
1009 struct option options[] = {
1010 OPT_END()
1012 int rc = 0;
1014 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
1015 p = ac > 0 ? av : self;
1016 for (; *p; p++)
1017 repair_worktree_at_path(*p, report_repair, &rc);
1018 repair_worktrees(report_repair, &rc);
1019 return rc;
1022 int cmd_worktree(int ac, const char **av, const char *prefix)
1024 struct option options[] = {
1025 OPT_END()
1028 git_config(git_worktree_config, NULL);
1030 if (ac < 2)
1031 usage_with_options(worktree_usage, options);
1032 if (!prefix)
1033 prefix = "";
1034 if (!strcmp(av[1], "add"))
1035 return add(ac - 1, av + 1, prefix);
1036 if (!strcmp(av[1], "prune"))
1037 return prune(ac - 1, av + 1, prefix);
1038 if (!strcmp(av[1], "list"))
1039 return list(ac - 1, av + 1, prefix);
1040 if (!strcmp(av[1], "lock"))
1041 return lock_worktree(ac - 1, av + 1, prefix);
1042 if (!strcmp(av[1], "unlock"))
1043 return unlock_worktree(ac - 1, av + 1, prefix);
1044 if (!strcmp(av[1], "move"))
1045 return move_worktree(ac - 1, av + 1, prefix);
1046 if (!strcmp(av[1], "remove"))
1047 return remove_worktree(ac - 1, av + 1, prefix);
1048 if (!strcmp(av[1], "repair"))
1049 return repair(ac - 1, av + 1, prefix);
1050 usage_with_options(worktree_usage, options);