Merge branch 'jt/reset-grafts-when-resetting-shallow'
[alt-git.git] / builtin / worktree.c
blob4eaba2a8fd0a0835e1eee02d46697ca20d97688b
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 "hook.h"
12 #include "sigchain.h"
13 #include "submodule.h"
14 #include "utf8.h"
15 #include "worktree.h"
16 #include "quote.h"
18 static const char * const worktree_usage[] = {
19 N_("git worktree add [<options>] <path> [<commit-ish>]"),
20 N_("git worktree list [<options>]"),
21 N_("git worktree lock [<options>] <path>"),
22 N_("git worktree move <worktree> <new-path>"),
23 N_("git worktree prune [<options>]"),
24 N_("git worktree remove [<options>] <worktree>"),
25 N_("git worktree unlock <path>"),
26 NULL
29 struct add_opts {
30 int force;
31 int detach;
32 int quiet;
33 int checkout;
34 const char *keep_locked;
37 static int show_only;
38 static int verbose;
39 static int guess_remote;
40 static timestamp_t expire;
42 static int git_worktree_config(const char *var, const char *value, void *cb)
44 if (!strcmp(var, "worktree.guessremote")) {
45 guess_remote = git_config_bool(var, value);
46 return 0;
49 return git_default_config(var, value, cb);
52 static int delete_git_dir(const char *id)
54 struct strbuf sb = STRBUF_INIT;
55 int ret;
57 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
58 ret = remove_dir_recursively(&sb, 0);
59 if (ret < 0 && errno == ENOTDIR)
60 ret = unlink(sb.buf);
61 if (ret)
62 error_errno(_("failed to delete '%s'"), sb.buf);
63 strbuf_release(&sb);
64 return ret;
67 static void delete_worktrees_dir_if_empty(void)
69 rmdir(git_path("worktrees")); /* ignore failed removal */
72 static void prune_worktree(const char *id, const char *reason)
74 if (show_only || verbose)
75 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
76 if (!show_only)
77 delete_git_dir(id);
80 static int prune_cmp(const void *a, const void *b)
82 const struct string_list_item *x = a;
83 const struct string_list_item *y = b;
84 int c;
86 if ((c = fspathcmp(x->string, y->string)))
87 return c;
89 * paths same; prune_dupes() removes all but the first worktree entry
90 * having the same path, so sort main worktree ('util' is NULL) above
91 * linked worktrees ('util' not NULL) since main worktree can't be
92 * removed
94 if (!x->util)
95 return -1;
96 if (!y->util)
97 return 1;
98 /* paths same; sort by .git/worktrees/<id> */
99 return strcmp(x->util, y->util);
102 static void prune_dups(struct string_list *l)
104 int i;
106 QSORT(l->items, l->nr, prune_cmp);
107 for (i = 1; i < l->nr; i++) {
108 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
109 prune_worktree(l->items[i].util, "duplicate entry");
113 static void prune_worktrees(void)
115 struct strbuf reason = STRBUF_INIT;
116 struct strbuf main_path = STRBUF_INIT;
117 struct string_list kept = STRING_LIST_INIT_NODUP;
118 DIR *dir = opendir(git_path("worktrees"));
119 struct dirent *d;
120 if (!dir)
121 return;
122 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
123 char *path;
124 strbuf_reset(&reason);
125 if (should_prune_worktree(d->d_name, &reason, &path, expire))
126 prune_worktree(d->d_name, reason.buf);
127 else if (path)
128 string_list_append(&kept, path)->util = xstrdup(d->d_name);
130 closedir(dir);
132 strbuf_add_absolute_path(&main_path, get_git_common_dir());
133 /* massage main worktree absolute path to match 'gitdir' content */
134 strbuf_strip_suffix(&main_path, "/.");
135 string_list_append(&kept, strbuf_detach(&main_path, NULL));
136 prune_dups(&kept);
137 string_list_clear(&kept, 1);
139 if (!show_only)
140 delete_worktrees_dir_if_empty();
141 strbuf_release(&reason);
144 static int prune(int ac, const char **av, const char *prefix)
146 struct option options[] = {
147 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
148 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
149 OPT_EXPIRY_DATE(0, "expire", &expire,
150 N_("expire working trees older than <time>")),
151 OPT_END()
154 expire = TIME_MAX;
155 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
156 if (ac)
157 usage_with_options(worktree_usage, options);
158 prune_worktrees();
159 return 0;
162 static char *junk_work_tree;
163 static char *junk_git_dir;
164 static int is_junk;
165 static pid_t junk_pid;
167 static void remove_junk(void)
169 struct strbuf sb = STRBUF_INIT;
170 if (!is_junk || getpid() != junk_pid)
171 return;
172 if (junk_git_dir) {
173 strbuf_addstr(&sb, junk_git_dir);
174 remove_dir_recursively(&sb, 0);
175 strbuf_reset(&sb);
177 if (junk_work_tree) {
178 strbuf_addstr(&sb, junk_work_tree);
179 remove_dir_recursively(&sb, 0);
181 strbuf_release(&sb);
184 static void remove_junk_on_signal(int signo)
186 remove_junk();
187 sigchain_pop(signo);
188 raise(signo);
191 static const char *worktree_basename(const char *path, int *olen)
193 const char *name;
194 int len;
196 len = strlen(path);
197 while (len && is_dir_sep(path[len - 1]))
198 len--;
200 for (name = path + len - 1; name > path; name--)
201 if (is_dir_sep(*name)) {
202 name++;
203 break;
206 *olen = len;
207 return name;
210 /* check that path is viable location for worktree */
211 static void check_candidate_path(const char *path,
212 int force,
213 struct worktree **worktrees,
214 const char *cmd)
216 struct worktree *wt;
217 int locked;
219 if (file_exists(path) && !is_empty_dir(path))
220 die(_("'%s' already exists"), path);
222 wt = find_worktree_by_path(worktrees, path);
223 if (!wt)
224 return;
226 locked = !!worktree_lock_reason(wt);
227 if ((!locked && force) || (locked && force > 1)) {
228 if (delete_git_dir(wt->id))
229 die(_("unusable worktree destination '%s'"), path);
230 return;
233 if (locked)
234 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
235 else
236 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
239 static void copy_sparse_checkout(const char *worktree_git_dir)
241 char *from_file = git_pathdup("info/sparse-checkout");
242 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
244 if (file_exists(from_file)) {
245 if (safe_create_leading_directories(to_file) ||
246 copy_file(to_file, from_file, 0666))
247 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
248 from_file, to_file);
251 free(from_file);
252 free(to_file);
255 static void copy_filtered_worktree_config(const char *worktree_git_dir)
257 char *from_file = git_pathdup("config.worktree");
258 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
260 if (file_exists(from_file)) {
261 struct config_set cs = { { 0 } };
262 const char *core_worktree;
263 int bare;
265 if (safe_create_leading_directories(to_file) ||
266 copy_file(to_file, from_file, 0666)) {
267 error(_("failed to copy worktree config from '%s' to '%s'"),
268 from_file, to_file);
269 goto worktree_copy_cleanup;
272 git_configset_init(&cs);
273 git_configset_add_file(&cs, from_file);
275 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
276 bare &&
277 git_config_set_multivar_in_file_gently(
278 to_file, "core.bare", NULL, "true", 0))
279 error(_("failed to unset '%s' in '%s'"),
280 "core.bare", to_file);
281 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree) &&
282 git_config_set_in_file_gently(to_file,
283 "core.worktree", NULL))
284 error(_("failed to unset '%s' in '%s'"),
285 "core.worktree", to_file);
287 git_configset_clear(&cs);
290 worktree_copy_cleanup:
291 free(from_file);
292 free(to_file);
295 static int checkout_worktree(const struct add_opts *opts,
296 struct strvec *child_env)
298 struct child_process cp = CHILD_PROCESS_INIT;
299 cp.git_cmd = 1;
300 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
301 if (opts->quiet)
302 strvec_push(&cp.args, "--quiet");
303 strvec_pushv(&cp.env_array, child_env->v);
304 return run_command(&cp);
307 static int add_worktree(const char *path, const char *refname,
308 const struct add_opts *opts)
310 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
311 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
312 const char *name;
313 struct child_process cp = CHILD_PROCESS_INIT;
314 struct strvec child_env = STRVEC_INIT;
315 unsigned int counter = 0;
316 int len, ret;
317 struct strbuf symref = STRBUF_INIT;
318 struct commit *commit = NULL;
319 int is_branch = 0;
320 struct strbuf sb_name = STRBUF_INIT;
321 struct worktree **worktrees;
323 worktrees = get_worktrees();
324 check_candidate_path(path, opts->force, worktrees, "add");
325 free_worktrees(worktrees);
326 worktrees = NULL;
328 /* is 'refname' a branch or commit? */
329 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
330 ref_exists(symref.buf)) {
331 is_branch = 1;
332 if (!opts->force)
333 die_if_checked_out(symref.buf, 0);
335 commit = lookup_commit_reference_by_name(refname);
336 if (!commit)
337 die(_("invalid reference: %s"), refname);
339 name = worktree_basename(path, &len);
340 strbuf_add(&sb, name, path + len - name);
341 sanitize_refname_component(sb.buf, &sb_name);
342 if (!sb_name.len)
343 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
344 strbuf_reset(&sb);
345 name = sb_name.buf;
346 git_path_buf(&sb_repo, "worktrees/%s", name);
347 len = sb_repo.len;
348 if (safe_create_leading_directories_const(sb_repo.buf))
349 die_errno(_("could not create leading directories of '%s'"),
350 sb_repo.buf);
352 while (mkdir(sb_repo.buf, 0777)) {
353 counter++;
354 if ((errno != EEXIST) || !counter /* overflow */)
355 die_errno(_("could not create directory of '%s'"),
356 sb_repo.buf);
357 strbuf_setlen(&sb_repo, len);
358 strbuf_addf(&sb_repo, "%d", counter);
360 name = strrchr(sb_repo.buf, '/') + 1;
362 junk_pid = getpid();
363 atexit(remove_junk);
364 sigchain_push_common(remove_junk_on_signal);
366 junk_git_dir = xstrdup(sb_repo.buf);
367 is_junk = 1;
370 * lock the incomplete repo so prune won't delete it, unlock
371 * after the preparation is over.
373 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
374 if (opts->keep_locked)
375 write_file(sb.buf, "%s", opts->keep_locked);
376 else
377 write_file(sb.buf, _("initializing"));
379 strbuf_addf(&sb_git, "%s/.git", path);
380 if (safe_create_leading_directories_const(sb_git.buf))
381 die_errno(_("could not create leading directories of '%s'"),
382 sb_git.buf);
383 junk_work_tree = xstrdup(path);
385 strbuf_reset(&sb);
386 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
387 strbuf_realpath(&realpath, sb_git.buf, 1);
388 write_file(sb.buf, "%s", realpath.buf);
389 strbuf_realpath(&realpath, get_git_common_dir(), 1);
390 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
391 realpath.buf, name);
393 * This is to keep resolve_ref() happy. We need a valid HEAD
394 * or is_git_directory() will reject the directory. Any value which
395 * looks like an object ID will do since it will be immediately
396 * replaced by the symbolic-ref or update-ref invocation in the new
397 * worktree.
399 strbuf_reset(&sb);
400 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
401 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
402 strbuf_reset(&sb);
403 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
404 write_file(sb.buf, "../..");
407 * If the current worktree has sparse-checkout enabled, then copy
408 * the sparse-checkout patterns from the current worktree.
410 if (core_apply_sparse_checkout)
411 copy_sparse_checkout(sb_repo.buf);
414 * If we are using worktree config, then copy all current config
415 * values from the current worktree into the new one, that way the
416 * new worktree behaves the same as this one.
418 if (repository_format_worktree_config)
419 copy_filtered_worktree_config(sb_repo.buf);
421 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
422 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
423 cp.git_cmd = 1;
425 if (!is_branch)
426 strvec_pushl(&cp.args, "update-ref", "HEAD",
427 oid_to_hex(&commit->object.oid), NULL);
428 else {
429 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
430 symref.buf, NULL);
431 if (opts->quiet)
432 strvec_push(&cp.args, "--quiet");
435 strvec_pushv(&cp.env_array, child_env.v);
436 ret = run_command(&cp);
437 if (ret)
438 goto done;
440 if (opts->checkout &&
441 (ret = checkout_worktree(opts, &child_env)))
442 goto done;
444 is_junk = 0;
445 FREE_AND_NULL(junk_work_tree);
446 FREE_AND_NULL(junk_git_dir);
448 done:
449 if (ret || !opts->keep_locked) {
450 strbuf_reset(&sb);
451 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
452 unlink_or_warn(sb.buf);
456 * Hook failure does not warrant worktree deletion, so run hook after
457 * is_junk is cleared, but do return appropriate code when hook fails.
459 if (!ret && opts->checkout) {
460 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
462 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
463 strvec_pushl(&opt.args,
464 oid_to_hex(null_oid()),
465 oid_to_hex(&commit->object.oid),
466 "1",
467 NULL);
468 opt.dir = path;
470 ret = run_hooks_opt("post-checkout", &opt);
473 strvec_clear(&child_env);
474 strbuf_release(&sb);
475 strbuf_release(&symref);
476 strbuf_release(&sb_repo);
477 strbuf_release(&sb_git);
478 strbuf_release(&sb_name);
479 strbuf_release(&realpath);
480 return ret;
483 static void print_preparing_worktree_line(int detach,
484 const char *branch,
485 const char *new_branch,
486 int force_new_branch)
488 if (force_new_branch) {
489 struct commit *commit = lookup_commit_reference_by_name(new_branch);
490 if (!commit)
491 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
492 else
493 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
494 new_branch,
495 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
496 } else if (new_branch) {
497 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
498 } else {
499 struct strbuf s = STRBUF_INIT;
500 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
501 ref_exists(s.buf))
502 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
503 branch);
504 else {
505 struct commit *commit = lookup_commit_reference_by_name(branch);
506 if (!commit)
507 die(_("invalid reference: %s"), branch);
508 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
509 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
511 strbuf_release(&s);
515 static const char *dwim_branch(const char *path, const char **new_branch)
517 int n;
518 int branch_exists;
519 const char *s = worktree_basename(path, &n);
520 const char *branchname = xstrndup(s, n);
521 struct strbuf ref = STRBUF_INIT;
523 UNLEAK(branchname);
525 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
526 ref_exists(ref.buf);
527 strbuf_release(&ref);
528 if (branch_exists)
529 return branchname;
531 *new_branch = branchname;
532 if (guess_remote) {
533 struct object_id oid;
534 const char *remote =
535 unique_tracking_name(*new_branch, &oid, NULL);
536 return remote;
538 return NULL;
541 static int add(int ac, const char **av, const char *prefix)
543 struct add_opts opts;
544 const char *new_branch_force = NULL;
545 char *path;
546 const char *branch;
547 const char *new_branch = NULL;
548 const char *opt_track = NULL;
549 const char *lock_reason = NULL;
550 int keep_locked = 0;
551 struct option options[] = {
552 OPT__FORCE(&opts.force,
553 N_("checkout <branch> even if already checked out in other worktree"),
554 PARSE_OPT_NOCOMPLETE),
555 OPT_STRING('b', NULL, &new_branch, N_("branch"),
556 N_("create a new branch")),
557 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
558 N_("create or reset a branch")),
559 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
560 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
561 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
562 OPT_STRING(0, "reason", &lock_reason, N_("string"),
563 N_("reason for locking")),
564 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
565 OPT_PASSTHRU(0, "track", &opt_track, NULL,
566 N_("set up tracking mode (see git-branch(1))"),
567 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
568 OPT_BOOL(0, "guess-remote", &guess_remote,
569 N_("try to match the new branch name with a remote-tracking branch")),
570 OPT_END()
573 memset(&opts, 0, sizeof(opts));
574 opts.checkout = 1;
575 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
576 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
577 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
578 if (lock_reason && !keep_locked)
579 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
580 if (lock_reason)
581 opts.keep_locked = lock_reason;
582 else if (keep_locked)
583 opts.keep_locked = _("added with --lock");
585 if (ac < 1 || ac > 2)
586 usage_with_options(worktree_usage, options);
588 path = prefix_filename(prefix, av[0]);
589 branch = ac < 2 ? "HEAD" : av[1];
591 if (!strcmp(branch, "-"))
592 branch = "@{-1}";
594 if (new_branch_force) {
595 struct strbuf symref = STRBUF_INIT;
597 new_branch = new_branch_force;
599 if (!opts.force &&
600 !strbuf_check_branch_ref(&symref, new_branch) &&
601 ref_exists(symref.buf))
602 die_if_checked_out(symref.buf, 0);
603 strbuf_release(&symref);
606 if (ac < 2 && !new_branch && !opts.detach) {
607 const char *s = dwim_branch(path, &new_branch);
608 if (s)
609 branch = s;
612 if (ac == 2 && !new_branch && !opts.detach) {
613 struct object_id oid;
614 struct commit *commit;
615 const char *remote;
617 commit = lookup_commit_reference_by_name(branch);
618 if (!commit) {
619 remote = unique_tracking_name(branch, &oid, NULL);
620 if (remote) {
621 new_branch = branch;
622 branch = remote;
626 if (!opts.quiet)
627 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
629 if (new_branch) {
630 struct child_process cp = CHILD_PROCESS_INIT;
631 cp.git_cmd = 1;
632 strvec_push(&cp.args, "branch");
633 if (new_branch_force)
634 strvec_push(&cp.args, "--force");
635 if (opts.quiet)
636 strvec_push(&cp.args, "--quiet");
637 strvec_push(&cp.args, new_branch);
638 strvec_push(&cp.args, branch);
639 if (opt_track)
640 strvec_push(&cp.args, opt_track);
641 if (run_command(&cp))
642 return -1;
643 branch = new_branch;
644 } else if (opt_track) {
645 die(_("--[no-]track can only be used if a new branch is created"));
648 UNLEAK(path);
649 UNLEAK(opts);
650 return add_worktree(path, branch, &opts);
653 static void show_worktree_porcelain(struct worktree *wt)
655 const char *reason;
657 printf("worktree %s\n", wt->path);
658 if (wt->is_bare)
659 printf("bare\n");
660 else {
661 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
662 if (wt->is_detached)
663 printf("detached\n");
664 else if (wt->head_ref)
665 printf("branch %s\n", wt->head_ref);
668 reason = worktree_lock_reason(wt);
669 if (reason && *reason) {
670 struct strbuf sb = STRBUF_INIT;
671 quote_c_style(reason, &sb, NULL, 0);
672 printf("locked %s\n", sb.buf);
673 strbuf_release(&sb);
674 } else if (reason)
675 printf("locked\n");
677 reason = worktree_prune_reason(wt, expire);
678 if (reason)
679 printf("prunable %s\n", reason);
681 printf("\n");
684 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
686 struct strbuf sb = STRBUF_INIT;
687 int cur_path_len = strlen(wt->path);
688 int path_adj = cur_path_len - utf8_strwidth(wt->path);
689 const char *reason;
691 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
692 if (wt->is_bare)
693 strbuf_addstr(&sb, "(bare)");
694 else {
695 strbuf_addf(&sb, "%-*s ", abbrev_len,
696 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
697 if (wt->is_detached)
698 strbuf_addstr(&sb, "(detached HEAD)");
699 else if (wt->head_ref) {
700 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
701 strbuf_addf(&sb, "[%s]", ref);
702 free(ref);
703 } else
704 strbuf_addstr(&sb, "(error)");
707 reason = worktree_lock_reason(wt);
708 if (verbose && reason && *reason)
709 strbuf_addf(&sb, "\n\tlocked: %s", reason);
710 else if (reason)
711 strbuf_addstr(&sb, " locked");
713 reason = worktree_prune_reason(wt, expire);
714 if (verbose && reason)
715 strbuf_addf(&sb, "\n\tprunable: %s", reason);
716 else if (reason)
717 strbuf_addstr(&sb, " prunable");
719 printf("%s\n", sb.buf);
720 strbuf_release(&sb);
723 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
725 int i;
727 for (i = 0; wt[i]; i++) {
728 int sha1_len;
729 int path_len = strlen(wt[i]->path);
731 if (path_len > *maxlen)
732 *maxlen = path_len;
733 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
734 if (sha1_len > *abbrev)
735 *abbrev = sha1_len;
739 static int pathcmp(const void *a_, const void *b_)
741 const struct worktree *const *a = a_;
742 const struct worktree *const *b = b_;
743 return fspathcmp((*a)->path, (*b)->path);
746 static void pathsort(struct worktree **wt)
748 int n = 0;
749 struct worktree **p = wt;
751 while (*p++)
752 n++;
753 QSORT(wt, n, pathcmp);
756 static int list(int ac, const char **av, const char *prefix)
758 int porcelain = 0;
760 struct option options[] = {
761 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
762 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
763 OPT_EXPIRY_DATE(0, "expire", &expire,
764 N_("add 'prunable' annotation to worktrees older than <time>")),
765 OPT_END()
768 expire = TIME_MAX;
769 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
770 if (ac)
771 usage_with_options(worktree_usage, options);
772 else if (verbose && porcelain)
773 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
774 else {
775 struct worktree **worktrees = get_worktrees();
776 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
778 /* sort worktrees by path but keep main worktree at top */
779 pathsort(worktrees + 1);
781 if (!porcelain)
782 measure_widths(worktrees, &abbrev, &path_maxlen);
784 for (i = 0; worktrees[i]; i++) {
785 if (porcelain)
786 show_worktree_porcelain(worktrees[i]);
787 else
788 show_worktree(worktrees[i], path_maxlen, abbrev);
790 free_worktrees(worktrees);
792 return 0;
795 static int lock_worktree(int ac, const char **av, const char *prefix)
797 const char *reason = "", *old_reason;
798 struct option options[] = {
799 OPT_STRING(0, "reason", &reason, N_("string"),
800 N_("reason for locking")),
801 OPT_END()
803 struct worktree **worktrees, *wt;
805 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
806 if (ac != 1)
807 usage_with_options(worktree_usage, options);
809 worktrees = get_worktrees();
810 wt = find_worktree(worktrees, prefix, av[0]);
811 if (!wt)
812 die(_("'%s' is not a working tree"), av[0]);
813 if (is_main_worktree(wt))
814 die(_("The main working tree cannot be locked or unlocked"));
816 old_reason = worktree_lock_reason(wt);
817 if (old_reason) {
818 if (*old_reason)
819 die(_("'%s' is already locked, reason: %s"),
820 av[0], old_reason);
821 die(_("'%s' is already locked"), av[0]);
824 write_file(git_common_path("worktrees/%s/locked", wt->id),
825 "%s", reason);
826 free_worktrees(worktrees);
827 return 0;
830 static int unlock_worktree(int ac, const char **av, const char *prefix)
832 struct option options[] = {
833 OPT_END()
835 struct worktree **worktrees, *wt;
836 int ret;
838 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
839 if (ac != 1)
840 usage_with_options(worktree_usage, options);
842 worktrees = get_worktrees();
843 wt = find_worktree(worktrees, prefix, av[0]);
844 if (!wt)
845 die(_("'%s' is not a working tree"), av[0]);
846 if (is_main_worktree(wt))
847 die(_("The main working tree cannot be locked or unlocked"));
848 if (!worktree_lock_reason(wt))
849 die(_("'%s' is not locked"), av[0]);
850 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
851 free_worktrees(worktrees);
852 return ret;
855 static void validate_no_submodules(const struct worktree *wt)
857 struct index_state istate = { NULL };
858 struct strbuf path = STRBUF_INIT;
859 int i, found_submodules = 0;
861 if (is_directory(worktree_git_path(wt, "modules"))) {
863 * There could be false positives, e.g. the "modules"
864 * directory exists but is empty. But it's a rare case and
865 * this simpler check is probably good enough for now.
867 found_submodules = 1;
868 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
869 get_worktree_git_dir(wt)) > 0) {
870 for (i = 0; i < istate.cache_nr; i++) {
871 struct cache_entry *ce = istate.cache[i];
872 int err;
874 if (!S_ISGITLINK(ce->ce_mode))
875 continue;
877 strbuf_reset(&path);
878 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
879 if (!is_submodule_populated_gently(path.buf, &err))
880 continue;
882 found_submodules = 1;
883 break;
886 discard_index(&istate);
887 strbuf_release(&path);
889 if (found_submodules)
890 die(_("working trees containing submodules cannot be moved or removed"));
893 static int move_worktree(int ac, const char **av, const char *prefix)
895 int force = 0;
896 struct option options[] = {
897 OPT__FORCE(&force,
898 N_("force move even if worktree is dirty or locked"),
899 PARSE_OPT_NOCOMPLETE),
900 OPT_END()
902 struct worktree **worktrees, *wt;
903 struct strbuf dst = STRBUF_INIT;
904 struct strbuf errmsg = STRBUF_INIT;
905 const char *reason = NULL;
906 char *path;
908 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
909 if (ac != 2)
910 usage_with_options(worktree_usage, options);
912 path = prefix_filename(prefix, av[1]);
913 strbuf_addstr(&dst, path);
914 free(path);
916 worktrees = get_worktrees();
917 wt = find_worktree(worktrees, prefix, av[0]);
918 if (!wt)
919 die(_("'%s' is not a working tree"), av[0]);
920 if (is_main_worktree(wt))
921 die(_("'%s' is a main working tree"), av[0]);
922 if (is_directory(dst.buf)) {
923 const char *sep = find_last_dir_sep(wt->path);
925 if (!sep)
926 die(_("could not figure out destination name from '%s'"),
927 wt->path);
928 strbuf_trim_trailing_dir_sep(&dst);
929 strbuf_addstr(&dst, sep);
931 check_candidate_path(dst.buf, force, worktrees, "move");
933 validate_no_submodules(wt);
935 if (force < 2)
936 reason = worktree_lock_reason(wt);
937 if (reason) {
938 if (*reason)
939 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
940 reason);
941 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
943 if (validate_worktree(wt, &errmsg, 0))
944 die(_("validation failed, cannot move working tree: %s"),
945 errmsg.buf);
946 strbuf_release(&errmsg);
948 if (rename(wt->path, dst.buf) == -1)
949 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
951 update_worktree_location(wt, dst.buf);
953 strbuf_release(&dst);
954 free_worktrees(worktrees);
955 return 0;
959 * Note, "git status --porcelain" is used to determine if it's safe to
960 * delete a whole worktree. "git status" does not ignore user
961 * configuration, so if a normal "git status" shows "clean" for the
962 * user, then it's ok to remove it.
964 * This assumption may be a bad one. We may want to ignore
965 * (potentially bad) user settings and only delete a worktree when
966 * it's absolutely safe to do so from _our_ point of view because we
967 * know better.
969 static void check_clean_worktree(struct worktree *wt,
970 const char *original_path)
972 struct child_process cp;
973 char buf[1];
974 int ret;
977 * Until we sort this out, all submodules are "dirty" and
978 * will abort this function.
980 validate_no_submodules(wt);
982 child_process_init(&cp);
983 strvec_pushf(&cp.env_array, "%s=%s/.git",
984 GIT_DIR_ENVIRONMENT, wt->path);
985 strvec_pushf(&cp.env_array, "%s=%s",
986 GIT_WORK_TREE_ENVIRONMENT, wt->path);
987 strvec_pushl(&cp.args, "status",
988 "--porcelain", "--ignore-submodules=none",
989 NULL);
990 cp.git_cmd = 1;
991 cp.dir = wt->path;
992 cp.out = -1;
993 ret = start_command(&cp);
994 if (ret)
995 die_errno(_("failed to run 'git status' on '%s'"),
996 original_path);
997 ret = xread(cp.out, buf, sizeof(buf));
998 if (ret)
999 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1000 original_path);
1001 close(cp.out);
1002 ret = finish_command(&cp);
1003 if (ret)
1004 die_errno(_("failed to run 'git status' on '%s', code %d"),
1005 original_path, ret);
1008 static int delete_git_work_tree(struct worktree *wt)
1010 struct strbuf sb = STRBUF_INIT;
1011 int ret = 0;
1013 strbuf_addstr(&sb, wt->path);
1014 if (remove_dir_recursively(&sb, 0)) {
1015 error_errno(_("failed to delete '%s'"), sb.buf);
1016 ret = -1;
1018 strbuf_release(&sb);
1019 return ret;
1022 static int remove_worktree(int ac, const char **av, const char *prefix)
1024 int force = 0;
1025 struct option options[] = {
1026 OPT__FORCE(&force,
1027 N_("force removal even if worktree is dirty or locked"),
1028 PARSE_OPT_NOCOMPLETE),
1029 OPT_END()
1031 struct worktree **worktrees, *wt;
1032 struct strbuf errmsg = STRBUF_INIT;
1033 const char *reason = NULL;
1034 int ret = 0;
1036 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
1037 if (ac != 1)
1038 usage_with_options(worktree_usage, options);
1040 worktrees = get_worktrees();
1041 wt = find_worktree(worktrees, prefix, av[0]);
1042 if (!wt)
1043 die(_("'%s' is not a working tree"), av[0]);
1044 if (is_main_worktree(wt))
1045 die(_("'%s' is a main working tree"), av[0]);
1046 if (force < 2)
1047 reason = worktree_lock_reason(wt);
1048 if (reason) {
1049 if (*reason)
1050 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1051 reason);
1052 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1054 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1055 die(_("validation failed, cannot remove working tree: %s"),
1056 errmsg.buf);
1057 strbuf_release(&errmsg);
1059 if (file_exists(wt->path)) {
1060 if (!force)
1061 check_clean_worktree(wt, av[0]);
1063 ret |= delete_git_work_tree(wt);
1066 * continue on even if ret is non-zero, there's no going back
1067 * from here.
1069 ret |= delete_git_dir(wt->id);
1070 delete_worktrees_dir_if_empty();
1072 free_worktrees(worktrees);
1073 return ret;
1076 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1078 if (!iserr) {
1079 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1080 } else {
1081 int *exit_status = (int *)cb_data;
1082 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1083 *exit_status = 1;
1087 static int repair(int ac, const char **av, const char *prefix)
1089 const char **p;
1090 const char *self[] = { ".", NULL };
1091 struct option options[] = {
1092 OPT_END()
1094 int rc = 0;
1096 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
1097 p = ac > 0 ? av : self;
1098 for (; *p; p++)
1099 repair_worktree_at_path(*p, report_repair, &rc);
1100 repair_worktrees(report_repair, &rc);
1101 return rc;
1104 int cmd_worktree(int ac, const char **av, const char *prefix)
1106 struct option options[] = {
1107 OPT_END()
1110 git_config(git_worktree_config, NULL);
1112 if (ac < 2)
1113 usage_with_options(worktree_usage, options);
1114 if (!prefix)
1115 prefix = "";
1116 if (!strcmp(av[1], "add"))
1117 return add(ac - 1, av + 1, prefix);
1118 if (!strcmp(av[1], "prune"))
1119 return prune(ac - 1, av + 1, prefix);
1120 if (!strcmp(av[1], "list"))
1121 return list(ac - 1, av + 1, prefix);
1122 if (!strcmp(av[1], "lock"))
1123 return lock_worktree(ac - 1, av + 1, prefix);
1124 if (!strcmp(av[1], "unlock"))
1125 return unlock_worktree(ac - 1, av + 1, prefix);
1126 if (!strcmp(av[1], "move"))
1127 return move_worktree(ac - 1, av + 1, prefix);
1128 if (!strcmp(av[1], "remove"))
1129 return remove_worktree(ac - 1, av + 1, prefix);
1130 if (!strcmp(av[1], "repair"))
1131 return repair(ac - 1, av + 1, prefix);
1132 usage_with_options(worktree_usage, options);