MyFirstContribution: refrain from self-iterating too much
[git.git] / builtin / worktree.c
blob4a24d53be15c3a74d6632c68ccacb813c8aa989b
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 #define BUILTIN_WORKTREE_ADD_USAGE \
19 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
20 " [-b <new-branch>] <path> [<commit-ish>]")
21 #define BUILTIN_WORKTREE_LIST_USAGE \
22 N_("git worktree list [-v | --porcelain [-z]]")
23 #define BUILTIN_WORKTREE_LOCK_USAGE \
24 N_("git worktree lock [--reason <string>] <worktree>")
25 #define BUILTIN_WORKTREE_MOVE_USAGE \
26 N_("git worktree move <worktree> <new-path>")
27 #define BUILTIN_WORKTREE_PRUNE_USAGE \
28 N_("git worktree prune [-n] [-v] [--expire <expire>]")
29 #define BUILTIN_WORKTREE_REMOVE_USAGE \
30 N_("git worktree remove [-f] <worktree>")
31 #define BUILTIN_WORKTREE_REPAIR_USAGE \
32 N_("git worktree repair [<path>...]")
33 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
34 N_("git worktree unlock <worktree>")
36 static const char * const git_worktree_usage[] = {
37 BUILTIN_WORKTREE_ADD_USAGE,
38 BUILTIN_WORKTREE_LIST_USAGE,
39 BUILTIN_WORKTREE_LOCK_USAGE,
40 BUILTIN_WORKTREE_MOVE_USAGE,
41 BUILTIN_WORKTREE_PRUNE_USAGE,
42 BUILTIN_WORKTREE_REMOVE_USAGE,
43 BUILTIN_WORKTREE_REPAIR_USAGE,
44 BUILTIN_WORKTREE_UNLOCK_USAGE,
45 NULL
48 static const char * const git_worktree_add_usage[] = {
49 BUILTIN_WORKTREE_ADD_USAGE,
50 NULL,
53 static const char * const git_worktree_list_usage[] = {
54 BUILTIN_WORKTREE_LIST_USAGE,
55 NULL
58 static const char * const git_worktree_lock_usage[] = {
59 BUILTIN_WORKTREE_LOCK_USAGE,
60 NULL
63 static const char * const git_worktree_move_usage[] = {
64 BUILTIN_WORKTREE_MOVE_USAGE,
65 NULL
68 static const char * const git_worktree_prune_usage[] = {
69 BUILTIN_WORKTREE_PRUNE_USAGE,
70 NULL
73 static const char * const git_worktree_remove_usage[] = {
74 BUILTIN_WORKTREE_REMOVE_USAGE,
75 NULL
78 static const char * const git_worktree_repair_usage[] = {
79 BUILTIN_WORKTREE_REPAIR_USAGE,
80 NULL
83 static const char * const git_worktree_unlock_usage[] = {
84 BUILTIN_WORKTREE_UNLOCK_USAGE,
85 NULL
88 struct add_opts {
89 int force;
90 int detach;
91 int quiet;
92 int checkout;
93 const char *keep_locked;
96 static int show_only;
97 static int verbose;
98 static int guess_remote;
99 static timestamp_t expire;
101 static int git_worktree_config(const char *var, const char *value, void *cb)
103 if (!strcmp(var, "worktree.guessremote")) {
104 guess_remote = git_config_bool(var, value);
105 return 0;
108 return git_default_config(var, value, cb);
111 static int delete_git_dir(const char *id)
113 struct strbuf sb = STRBUF_INIT;
114 int ret;
116 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
117 ret = remove_dir_recursively(&sb, 0);
118 if (ret < 0 && errno == ENOTDIR)
119 ret = unlink(sb.buf);
120 if (ret)
121 error_errno(_("failed to delete '%s'"), sb.buf);
122 strbuf_release(&sb);
123 return ret;
126 static void delete_worktrees_dir_if_empty(void)
128 rmdir(git_path("worktrees")); /* ignore failed removal */
131 static void prune_worktree(const char *id, const char *reason)
133 if (show_only || verbose)
134 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
135 if (!show_only)
136 delete_git_dir(id);
139 static int prune_cmp(const void *a, const void *b)
141 const struct string_list_item *x = a;
142 const struct string_list_item *y = b;
143 int c;
145 if ((c = fspathcmp(x->string, y->string)))
146 return c;
148 * paths same; prune_dupes() removes all but the first worktree entry
149 * having the same path, so sort main worktree ('util' is NULL) above
150 * linked worktrees ('util' not NULL) since main worktree can't be
151 * removed
153 if (!x->util)
154 return -1;
155 if (!y->util)
156 return 1;
157 /* paths same; sort by .git/worktrees/<id> */
158 return strcmp(x->util, y->util);
161 static void prune_dups(struct string_list *l)
163 int i;
165 QSORT(l->items, l->nr, prune_cmp);
166 for (i = 1; i < l->nr; i++) {
167 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
168 prune_worktree(l->items[i].util, "duplicate entry");
172 static void prune_worktrees(void)
174 struct strbuf reason = STRBUF_INIT;
175 struct strbuf main_path = STRBUF_INIT;
176 struct string_list kept = STRING_LIST_INIT_NODUP;
177 DIR *dir = opendir(git_path("worktrees"));
178 struct dirent *d;
179 if (!dir)
180 return;
181 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
182 char *path;
183 strbuf_reset(&reason);
184 if (should_prune_worktree(d->d_name, &reason, &path, expire))
185 prune_worktree(d->d_name, reason.buf);
186 else if (path)
187 string_list_append(&kept, path)->util = xstrdup(d->d_name);
189 closedir(dir);
191 strbuf_add_absolute_path(&main_path, get_git_common_dir());
192 /* massage main worktree absolute path to match 'gitdir' content */
193 strbuf_strip_suffix(&main_path, "/.");
194 string_list_append(&kept, strbuf_detach(&main_path, NULL));
195 prune_dups(&kept);
196 string_list_clear(&kept, 1);
198 if (!show_only)
199 delete_worktrees_dir_if_empty();
200 strbuf_release(&reason);
203 static int prune(int ac, const char **av, const char *prefix)
205 struct option options[] = {
206 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
207 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
208 OPT_EXPIRY_DATE(0, "expire", &expire,
209 N_("expire working trees older than <time>")),
210 OPT_END()
213 expire = TIME_MAX;
214 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
216 if (ac)
217 usage_with_options(git_worktree_prune_usage, options);
218 prune_worktrees();
219 return 0;
222 static char *junk_work_tree;
223 static char *junk_git_dir;
224 static int is_junk;
225 static pid_t junk_pid;
227 static void remove_junk(void)
229 struct strbuf sb = STRBUF_INIT;
230 if (!is_junk || getpid() != junk_pid)
231 return;
232 if (junk_git_dir) {
233 strbuf_addstr(&sb, junk_git_dir);
234 remove_dir_recursively(&sb, 0);
235 strbuf_reset(&sb);
237 if (junk_work_tree) {
238 strbuf_addstr(&sb, junk_work_tree);
239 remove_dir_recursively(&sb, 0);
241 strbuf_release(&sb);
244 static void remove_junk_on_signal(int signo)
246 remove_junk();
247 sigchain_pop(signo);
248 raise(signo);
251 static const char *worktree_basename(const char *path, int *olen)
253 const char *name;
254 int len;
256 len = strlen(path);
257 while (len && is_dir_sep(path[len - 1]))
258 len--;
260 for (name = path + len - 1; name > path; name--)
261 if (is_dir_sep(*name)) {
262 name++;
263 break;
266 *olen = len;
267 return name;
270 /* check that path is viable location for worktree */
271 static void check_candidate_path(const char *path,
272 int force,
273 struct worktree **worktrees,
274 const char *cmd)
276 struct worktree *wt;
277 int locked;
279 if (file_exists(path) && !is_empty_dir(path))
280 die(_("'%s' already exists"), path);
282 wt = find_worktree_by_path(worktrees, path);
283 if (!wt)
284 return;
286 locked = !!worktree_lock_reason(wt);
287 if ((!locked && force) || (locked && force > 1)) {
288 if (delete_git_dir(wt->id))
289 die(_("unusable worktree destination '%s'"), path);
290 return;
293 if (locked)
294 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
295 else
296 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
299 static void copy_sparse_checkout(const char *worktree_git_dir)
301 char *from_file = git_pathdup("info/sparse-checkout");
302 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
304 if (file_exists(from_file)) {
305 if (safe_create_leading_directories(to_file) ||
306 copy_file(to_file, from_file, 0666))
307 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
308 from_file, to_file);
311 free(from_file);
312 free(to_file);
315 static void copy_filtered_worktree_config(const char *worktree_git_dir)
317 char *from_file = git_pathdup("config.worktree");
318 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
320 if (file_exists(from_file)) {
321 struct config_set cs = { { 0 } };
322 const char *core_worktree;
323 int bare;
325 if (safe_create_leading_directories(to_file) ||
326 copy_file(to_file, from_file, 0666)) {
327 error(_("failed to copy worktree config from '%s' to '%s'"),
328 from_file, to_file);
329 goto worktree_copy_cleanup;
332 git_configset_init(&cs);
333 git_configset_add_file(&cs, from_file);
335 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
336 bare &&
337 git_config_set_multivar_in_file_gently(
338 to_file, "core.bare", NULL, "true", 0))
339 error(_("failed to unset '%s' in '%s'"),
340 "core.bare", to_file);
341 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree) &&
342 git_config_set_in_file_gently(to_file,
343 "core.worktree", NULL))
344 error(_("failed to unset '%s' in '%s'"),
345 "core.worktree", to_file);
347 git_configset_clear(&cs);
350 worktree_copy_cleanup:
351 free(from_file);
352 free(to_file);
355 static int checkout_worktree(const struct add_opts *opts,
356 struct strvec *child_env)
358 struct child_process cp = CHILD_PROCESS_INIT;
359 cp.git_cmd = 1;
360 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
361 if (opts->quiet)
362 strvec_push(&cp.args, "--quiet");
363 strvec_pushv(&cp.env, child_env->v);
364 return run_command(&cp);
367 static int add_worktree(const char *path, const char *refname,
368 const struct add_opts *opts)
370 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
371 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
372 const char *name;
373 struct child_process cp = CHILD_PROCESS_INIT;
374 struct strvec child_env = STRVEC_INIT;
375 unsigned int counter = 0;
376 int len, ret;
377 struct strbuf symref = STRBUF_INIT;
378 struct commit *commit = NULL;
379 int is_branch = 0;
380 struct strbuf sb_name = STRBUF_INIT;
381 struct worktree **worktrees;
383 worktrees = get_worktrees();
384 check_candidate_path(path, opts->force, worktrees, "add");
385 free_worktrees(worktrees);
386 worktrees = NULL;
388 /* is 'refname' a branch or commit? */
389 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
390 ref_exists(symref.buf)) {
391 is_branch = 1;
392 if (!opts->force)
393 die_if_checked_out(symref.buf, 0);
395 commit = lookup_commit_reference_by_name(refname);
396 if (!commit)
397 die(_("invalid reference: %s"), refname);
399 name = worktree_basename(path, &len);
400 strbuf_add(&sb, name, path + len - name);
401 sanitize_refname_component(sb.buf, &sb_name);
402 if (!sb_name.len)
403 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
404 strbuf_reset(&sb);
405 name = sb_name.buf;
406 git_path_buf(&sb_repo, "worktrees/%s", name);
407 len = sb_repo.len;
408 if (safe_create_leading_directories_const(sb_repo.buf))
409 die_errno(_("could not create leading directories of '%s'"),
410 sb_repo.buf);
412 while (mkdir(sb_repo.buf, 0777)) {
413 counter++;
414 if ((errno != EEXIST) || !counter /* overflow */)
415 die_errno(_("could not create directory of '%s'"),
416 sb_repo.buf);
417 strbuf_setlen(&sb_repo, len);
418 strbuf_addf(&sb_repo, "%d", counter);
420 name = strrchr(sb_repo.buf, '/') + 1;
422 junk_pid = getpid();
423 atexit(remove_junk);
424 sigchain_push_common(remove_junk_on_signal);
426 junk_git_dir = xstrdup(sb_repo.buf);
427 is_junk = 1;
430 * lock the incomplete repo so prune won't delete it, unlock
431 * after the preparation is over.
433 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
434 if (opts->keep_locked)
435 write_file(sb.buf, "%s", opts->keep_locked);
436 else
437 write_file(sb.buf, _("initializing"));
439 strbuf_addf(&sb_git, "%s/.git", path);
440 if (safe_create_leading_directories_const(sb_git.buf))
441 die_errno(_("could not create leading directories of '%s'"),
442 sb_git.buf);
443 junk_work_tree = xstrdup(path);
445 strbuf_reset(&sb);
446 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
447 strbuf_realpath(&realpath, sb_git.buf, 1);
448 write_file(sb.buf, "%s", realpath.buf);
449 strbuf_realpath(&realpath, get_git_common_dir(), 1);
450 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
451 realpath.buf, name);
453 * This is to keep resolve_ref() happy. We need a valid HEAD
454 * or is_git_directory() will reject the directory. Any value which
455 * looks like an object ID will do since it will be immediately
456 * replaced by the symbolic-ref or update-ref invocation in the new
457 * worktree.
459 strbuf_reset(&sb);
460 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
461 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
462 strbuf_reset(&sb);
463 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
464 write_file(sb.buf, "../..");
467 * If the current worktree has sparse-checkout enabled, then copy
468 * the sparse-checkout patterns from the current worktree.
470 if (core_apply_sparse_checkout)
471 copy_sparse_checkout(sb_repo.buf);
474 * If we are using worktree config, then copy all current config
475 * values from the current worktree into the new one, that way the
476 * new worktree behaves the same as this one.
478 if (repository_format_worktree_config)
479 copy_filtered_worktree_config(sb_repo.buf);
481 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
482 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
483 cp.git_cmd = 1;
485 if (!is_branch)
486 strvec_pushl(&cp.args, "update-ref", "HEAD",
487 oid_to_hex(&commit->object.oid), NULL);
488 else {
489 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
490 symref.buf, NULL);
491 if (opts->quiet)
492 strvec_push(&cp.args, "--quiet");
495 strvec_pushv(&cp.env, child_env.v);
496 ret = run_command(&cp);
497 if (ret)
498 goto done;
500 if (opts->checkout &&
501 (ret = checkout_worktree(opts, &child_env)))
502 goto done;
504 is_junk = 0;
505 FREE_AND_NULL(junk_work_tree);
506 FREE_AND_NULL(junk_git_dir);
508 done:
509 if (ret || !opts->keep_locked) {
510 strbuf_reset(&sb);
511 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
512 unlink_or_warn(sb.buf);
516 * Hook failure does not warrant worktree deletion, so run hook after
517 * is_junk is cleared, but do return appropriate code when hook fails.
519 if (!ret && opts->checkout) {
520 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
522 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
523 strvec_pushl(&opt.args,
524 oid_to_hex(null_oid()),
525 oid_to_hex(&commit->object.oid),
526 "1",
527 NULL);
528 opt.dir = path;
530 ret = run_hooks_opt("post-checkout", &opt);
533 strvec_clear(&child_env);
534 strbuf_release(&sb);
535 strbuf_release(&symref);
536 strbuf_release(&sb_repo);
537 strbuf_release(&sb_git);
538 strbuf_release(&sb_name);
539 strbuf_release(&realpath);
540 return ret;
543 static void print_preparing_worktree_line(int detach,
544 const char *branch,
545 const char *new_branch,
546 int force_new_branch)
548 if (force_new_branch) {
549 struct commit *commit = lookup_commit_reference_by_name(new_branch);
550 if (!commit)
551 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
552 else
553 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
554 new_branch,
555 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
556 } else if (new_branch) {
557 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
558 } else {
559 struct strbuf s = STRBUF_INIT;
560 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
561 ref_exists(s.buf))
562 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
563 branch);
564 else {
565 struct commit *commit = lookup_commit_reference_by_name(branch);
566 if (!commit)
567 die(_("invalid reference: %s"), branch);
568 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
569 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
571 strbuf_release(&s);
575 static const char *dwim_branch(const char *path, const char **new_branch)
577 int n;
578 int branch_exists;
579 const char *s = worktree_basename(path, &n);
580 const char *branchname = xstrndup(s, n);
581 struct strbuf ref = STRBUF_INIT;
583 UNLEAK(branchname);
585 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
586 ref_exists(ref.buf);
587 strbuf_release(&ref);
588 if (branch_exists)
589 return branchname;
591 *new_branch = branchname;
592 if (guess_remote) {
593 struct object_id oid;
594 const char *remote =
595 unique_tracking_name(*new_branch, &oid, NULL);
596 return remote;
598 return NULL;
601 static int add(int ac, const char **av, const char *prefix)
603 struct add_opts opts;
604 const char *new_branch_force = NULL;
605 char *path;
606 const char *branch;
607 const char *new_branch = NULL;
608 const char *opt_track = NULL;
609 const char *lock_reason = NULL;
610 int keep_locked = 0;
611 struct option options[] = {
612 OPT__FORCE(&opts.force,
613 N_("checkout <branch> even if already checked out in other worktree"),
614 PARSE_OPT_NOCOMPLETE),
615 OPT_STRING('b', NULL, &new_branch, N_("branch"),
616 N_("create a new branch")),
617 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
618 N_("create or reset a branch")),
619 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
620 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
621 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
622 OPT_STRING(0, "reason", &lock_reason, N_("string"),
623 N_("reason for locking")),
624 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
625 OPT_PASSTHRU(0, "track", &opt_track, NULL,
626 N_("set up tracking mode (see git-branch(1))"),
627 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
628 OPT_BOOL(0, "guess-remote", &guess_remote,
629 N_("try to match the new branch name with a remote-tracking branch")),
630 OPT_END()
633 memset(&opts, 0, sizeof(opts));
634 opts.checkout = 1;
635 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
636 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
637 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
638 if (lock_reason && !keep_locked)
639 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
640 if (lock_reason)
641 opts.keep_locked = lock_reason;
642 else if (keep_locked)
643 opts.keep_locked = _("added with --lock");
645 if (ac < 1 || ac > 2)
646 usage_with_options(git_worktree_add_usage, options);
648 path = prefix_filename(prefix, av[0]);
649 branch = ac < 2 ? "HEAD" : av[1];
651 if (!strcmp(branch, "-"))
652 branch = "@{-1}";
654 if (new_branch_force) {
655 struct strbuf symref = STRBUF_INIT;
657 new_branch = new_branch_force;
659 if (!opts.force &&
660 !strbuf_check_branch_ref(&symref, new_branch) &&
661 ref_exists(symref.buf))
662 die_if_checked_out(symref.buf, 0);
663 strbuf_release(&symref);
666 if (ac < 2 && !new_branch && !opts.detach) {
667 const char *s = dwim_branch(path, &new_branch);
668 if (s)
669 branch = s;
672 if (ac == 2 && !new_branch && !opts.detach) {
673 struct object_id oid;
674 struct commit *commit;
675 const char *remote;
677 commit = lookup_commit_reference_by_name(branch);
678 if (!commit) {
679 remote = unique_tracking_name(branch, &oid, NULL);
680 if (remote) {
681 new_branch = branch;
682 branch = remote;
686 if (!opts.quiet)
687 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
689 if (new_branch) {
690 struct child_process cp = CHILD_PROCESS_INIT;
691 cp.git_cmd = 1;
692 strvec_push(&cp.args, "branch");
693 if (new_branch_force)
694 strvec_push(&cp.args, "--force");
695 if (opts.quiet)
696 strvec_push(&cp.args, "--quiet");
697 strvec_push(&cp.args, new_branch);
698 strvec_push(&cp.args, branch);
699 if (opt_track)
700 strvec_push(&cp.args, opt_track);
701 if (run_command(&cp))
702 return -1;
703 branch = new_branch;
704 } else if (opt_track) {
705 die(_("--[no-]track can only be used if a new branch is created"));
708 UNLEAK(path);
709 UNLEAK(opts);
710 return add_worktree(path, branch, &opts);
713 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
715 const char *reason;
717 printf("worktree %s%c", wt->path, line_terminator);
718 if (wt->is_bare)
719 printf("bare%c", line_terminator);
720 else {
721 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
722 if (wt->is_detached)
723 printf("detached%c", line_terminator);
724 else if (wt->head_ref)
725 printf("branch %s%c", wt->head_ref, line_terminator);
728 reason = worktree_lock_reason(wt);
729 if (reason) {
730 fputs("locked", stdout);
731 if (*reason) {
732 fputc(' ', stdout);
733 write_name_quoted(reason, stdout, line_terminator);
734 } else {
735 fputc(line_terminator, stdout);
739 reason = worktree_prune_reason(wt, expire);
740 if (reason)
741 printf("prunable %s%c", reason, line_terminator);
743 fputc(line_terminator, stdout);
746 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
748 struct strbuf sb = STRBUF_INIT;
749 int cur_path_len = strlen(wt->path);
750 int path_adj = cur_path_len - utf8_strwidth(wt->path);
751 const char *reason;
753 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
754 if (wt->is_bare)
755 strbuf_addstr(&sb, "(bare)");
756 else {
757 strbuf_addf(&sb, "%-*s ", abbrev_len,
758 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
759 if (wt->is_detached)
760 strbuf_addstr(&sb, "(detached HEAD)");
761 else if (wt->head_ref) {
762 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
763 strbuf_addf(&sb, "[%s]", ref);
764 free(ref);
765 } else
766 strbuf_addstr(&sb, "(error)");
769 reason = worktree_lock_reason(wt);
770 if (verbose && reason && *reason)
771 strbuf_addf(&sb, "\n\tlocked: %s", reason);
772 else if (reason)
773 strbuf_addstr(&sb, " locked");
775 reason = worktree_prune_reason(wt, expire);
776 if (verbose && reason)
777 strbuf_addf(&sb, "\n\tprunable: %s", reason);
778 else if (reason)
779 strbuf_addstr(&sb, " prunable");
781 printf("%s\n", sb.buf);
782 strbuf_release(&sb);
785 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
787 int i;
789 for (i = 0; wt[i]; i++) {
790 int sha1_len;
791 int path_len = strlen(wt[i]->path);
793 if (path_len > *maxlen)
794 *maxlen = path_len;
795 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
796 if (sha1_len > *abbrev)
797 *abbrev = sha1_len;
801 static int pathcmp(const void *a_, const void *b_)
803 const struct worktree *const *a = a_;
804 const struct worktree *const *b = b_;
805 return fspathcmp((*a)->path, (*b)->path);
808 static void pathsort(struct worktree **wt)
810 int n = 0;
811 struct worktree **p = wt;
813 while (*p++)
814 n++;
815 QSORT(wt, n, pathcmp);
818 static int list(int ac, const char **av, const char *prefix)
820 int porcelain = 0;
821 int line_terminator = '\n';
823 struct option options[] = {
824 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
825 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
826 OPT_EXPIRY_DATE(0, "expire", &expire,
827 N_("add 'prunable' annotation to worktrees older than <time>")),
828 OPT_SET_INT('z', NULL, &line_terminator,
829 N_("terminate records with a NUL character"), '\0'),
830 OPT_END()
833 expire = TIME_MAX;
834 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
835 if (ac)
836 usage_with_options(git_worktree_list_usage, options);
837 else if (verbose && porcelain)
838 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
839 else if (!line_terminator && !porcelain)
840 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
841 else {
842 struct worktree **worktrees = get_worktrees();
843 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
845 /* sort worktrees by path but keep main worktree at top */
846 pathsort(worktrees + 1);
848 if (!porcelain)
849 measure_widths(worktrees, &abbrev, &path_maxlen);
851 for (i = 0; worktrees[i]; i++) {
852 if (porcelain)
853 show_worktree_porcelain(worktrees[i],
854 line_terminator);
855 else
856 show_worktree(worktrees[i], path_maxlen, abbrev);
858 free_worktrees(worktrees);
860 return 0;
863 static int lock_worktree(int ac, const char **av, const char *prefix)
865 const char *reason = "", *old_reason;
866 struct option options[] = {
867 OPT_STRING(0, "reason", &reason, N_("string"),
868 N_("reason for locking")),
869 OPT_END()
871 struct worktree **worktrees, *wt;
873 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
874 if (ac != 1)
875 usage_with_options(git_worktree_lock_usage, options);
877 worktrees = get_worktrees();
878 wt = find_worktree(worktrees, prefix, av[0]);
879 if (!wt)
880 die(_("'%s' is not a working tree"), av[0]);
881 if (is_main_worktree(wt))
882 die(_("The main working tree cannot be locked or unlocked"));
884 old_reason = worktree_lock_reason(wt);
885 if (old_reason) {
886 if (*old_reason)
887 die(_("'%s' is already locked, reason: %s"),
888 av[0], old_reason);
889 die(_("'%s' is already locked"), av[0]);
892 write_file(git_common_path("worktrees/%s/locked", wt->id),
893 "%s", reason);
894 free_worktrees(worktrees);
895 return 0;
898 static int unlock_worktree(int ac, const char **av, const char *prefix)
900 struct option options[] = {
901 OPT_END()
903 struct worktree **worktrees, *wt;
904 int ret;
906 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
907 if (ac != 1)
908 usage_with_options(git_worktree_unlock_usage, options);
910 worktrees = get_worktrees();
911 wt = find_worktree(worktrees, prefix, av[0]);
912 if (!wt)
913 die(_("'%s' is not a working tree"), av[0]);
914 if (is_main_worktree(wt))
915 die(_("The main working tree cannot be locked or unlocked"));
916 if (!worktree_lock_reason(wt))
917 die(_("'%s' is not locked"), av[0]);
918 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
919 free_worktrees(worktrees);
920 return ret;
923 static void validate_no_submodules(const struct worktree *wt)
925 struct index_state istate = { NULL };
926 struct strbuf path = STRBUF_INIT;
927 int i, found_submodules = 0;
929 if (is_directory(worktree_git_path(wt, "modules"))) {
931 * There could be false positives, e.g. the "modules"
932 * directory exists but is empty. But it's a rare case and
933 * this simpler check is probably good enough for now.
935 found_submodules = 1;
936 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
937 get_worktree_git_dir(wt)) > 0) {
938 for (i = 0; i < istate.cache_nr; i++) {
939 struct cache_entry *ce = istate.cache[i];
940 int err;
942 if (!S_ISGITLINK(ce->ce_mode))
943 continue;
945 strbuf_reset(&path);
946 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
947 if (!is_submodule_populated_gently(path.buf, &err))
948 continue;
950 found_submodules = 1;
951 break;
954 discard_index(&istate);
955 strbuf_release(&path);
957 if (found_submodules)
958 die(_("working trees containing submodules cannot be moved or removed"));
961 static int move_worktree(int ac, const char **av, const char *prefix)
963 int force = 0;
964 struct option options[] = {
965 OPT__FORCE(&force,
966 N_("force move even if worktree is dirty or locked"),
967 PARSE_OPT_NOCOMPLETE),
968 OPT_END()
970 struct worktree **worktrees, *wt;
971 struct strbuf dst = STRBUF_INIT;
972 struct strbuf errmsg = STRBUF_INIT;
973 const char *reason = NULL;
974 char *path;
976 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
978 if (ac != 2)
979 usage_with_options(git_worktree_move_usage, options);
981 path = prefix_filename(prefix, av[1]);
982 strbuf_addstr(&dst, path);
983 free(path);
985 worktrees = get_worktrees();
986 wt = find_worktree(worktrees, prefix, av[0]);
987 if (!wt)
988 die(_("'%s' is not a working tree"), av[0]);
989 if (is_main_worktree(wt))
990 die(_("'%s' is a main working tree"), av[0]);
991 if (is_directory(dst.buf)) {
992 const char *sep = find_last_dir_sep(wt->path);
994 if (!sep)
995 die(_("could not figure out destination name from '%s'"),
996 wt->path);
997 strbuf_trim_trailing_dir_sep(&dst);
998 strbuf_addstr(&dst, sep);
1000 check_candidate_path(dst.buf, force, worktrees, "move");
1002 validate_no_submodules(wt);
1004 if (force < 2)
1005 reason = worktree_lock_reason(wt);
1006 if (reason) {
1007 if (*reason)
1008 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1009 reason);
1010 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1012 if (validate_worktree(wt, &errmsg, 0))
1013 die(_("validation failed, cannot move working tree: %s"),
1014 errmsg.buf);
1015 strbuf_release(&errmsg);
1017 if (rename(wt->path, dst.buf) == -1)
1018 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1020 update_worktree_location(wt, dst.buf);
1022 strbuf_release(&dst);
1023 free_worktrees(worktrees);
1024 return 0;
1028 * Note, "git status --porcelain" is used to determine if it's safe to
1029 * delete a whole worktree. "git status" does not ignore user
1030 * configuration, so if a normal "git status" shows "clean" for the
1031 * user, then it's ok to remove it.
1033 * This assumption may be a bad one. We may want to ignore
1034 * (potentially bad) user settings and only delete a worktree when
1035 * it's absolutely safe to do so from _our_ point of view because we
1036 * know better.
1038 static void check_clean_worktree(struct worktree *wt,
1039 const char *original_path)
1041 struct child_process cp;
1042 char buf[1];
1043 int ret;
1046 * Until we sort this out, all submodules are "dirty" and
1047 * will abort this function.
1049 validate_no_submodules(wt);
1051 child_process_init(&cp);
1052 strvec_pushf(&cp.env, "%s=%s/.git",
1053 GIT_DIR_ENVIRONMENT, wt->path);
1054 strvec_pushf(&cp.env, "%s=%s",
1055 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1056 strvec_pushl(&cp.args, "status",
1057 "--porcelain", "--ignore-submodules=none",
1058 NULL);
1059 cp.git_cmd = 1;
1060 cp.dir = wt->path;
1061 cp.out = -1;
1062 ret = start_command(&cp);
1063 if (ret)
1064 die_errno(_("failed to run 'git status' on '%s'"),
1065 original_path);
1066 ret = xread(cp.out, buf, sizeof(buf));
1067 if (ret)
1068 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1069 original_path);
1070 close(cp.out);
1071 ret = finish_command(&cp);
1072 if (ret)
1073 die_errno(_("failed to run 'git status' on '%s', code %d"),
1074 original_path, ret);
1077 static int delete_git_work_tree(struct worktree *wt)
1079 struct strbuf sb = STRBUF_INIT;
1080 int ret = 0;
1082 strbuf_addstr(&sb, wt->path);
1083 if (remove_dir_recursively(&sb, 0)) {
1084 error_errno(_("failed to delete '%s'"), sb.buf);
1085 ret = -1;
1087 strbuf_release(&sb);
1088 return ret;
1091 static int remove_worktree(int ac, const char **av, const char *prefix)
1093 int force = 0;
1094 struct option options[] = {
1095 OPT__FORCE(&force,
1096 N_("force removal even if worktree is dirty or locked"),
1097 PARSE_OPT_NOCOMPLETE),
1098 OPT_END()
1100 struct worktree **worktrees, *wt;
1101 struct strbuf errmsg = STRBUF_INIT;
1102 const char *reason = NULL;
1103 int ret = 0;
1105 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1106 if (ac != 1)
1107 usage_with_options(git_worktree_remove_usage, options);
1109 worktrees = get_worktrees();
1110 wt = find_worktree(worktrees, prefix, av[0]);
1111 if (!wt)
1112 die(_("'%s' is not a working tree"), av[0]);
1113 if (is_main_worktree(wt))
1114 die(_("'%s' is a main working tree"), av[0]);
1115 if (force < 2)
1116 reason = worktree_lock_reason(wt);
1117 if (reason) {
1118 if (*reason)
1119 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1120 reason);
1121 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1123 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1124 die(_("validation failed, cannot remove working tree: %s"),
1125 errmsg.buf);
1126 strbuf_release(&errmsg);
1128 if (file_exists(wt->path)) {
1129 if (!force)
1130 check_clean_worktree(wt, av[0]);
1132 ret |= delete_git_work_tree(wt);
1135 * continue on even if ret is non-zero, there's no going back
1136 * from here.
1138 ret |= delete_git_dir(wt->id);
1139 delete_worktrees_dir_if_empty();
1141 free_worktrees(worktrees);
1142 return ret;
1145 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1147 if (!iserr) {
1148 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1149 } else {
1150 int *exit_status = (int *)cb_data;
1151 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1152 *exit_status = 1;
1156 static int repair(int ac, const char **av, const char *prefix)
1158 const char **p;
1159 const char *self[] = { ".", NULL };
1160 struct option options[] = {
1161 OPT_END()
1163 int rc = 0;
1165 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1166 p = ac > 0 ? av : self;
1167 for (; *p; p++)
1168 repair_worktree_at_path(*p, report_repair, &rc);
1169 repair_worktrees(report_repair, &rc);
1170 return rc;
1173 int cmd_worktree(int ac, const char **av, const char *prefix)
1175 parse_opt_subcommand_fn *fn = NULL;
1176 struct option options[] = {
1177 OPT_SUBCOMMAND("add", &fn, add),
1178 OPT_SUBCOMMAND("prune", &fn, prune),
1179 OPT_SUBCOMMAND("list", &fn, list),
1180 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1181 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1182 OPT_SUBCOMMAND("move", &fn, move_worktree),
1183 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1184 OPT_SUBCOMMAND("repair", &fn, repair),
1185 OPT_END()
1188 git_config(git_worktree_config, NULL);
1190 if (!prefix)
1191 prefix = "";
1193 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1194 return fn(ac, av, prefix);