builtin/worktree.c: fix typo in "forgot fetch" msg
[git.git] / builtin / worktree.c
blob2901bfd936ad8ff155d8fca3ccb3291923edd6a6
1 #include "cache.h"
2 #include "abspath.h"
3 #include "advice.h"
4 #include "checkout.h"
5 #include "config.h"
6 #include "builtin.h"
7 #include "dir.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "parse-options.h"
12 #include "strvec.h"
13 #include "branch.h"
14 #include "refs.h"
15 #include "remote.h"
16 #include "run-command.h"
17 #include "hook.h"
18 #include "sigchain.h"
19 #include "submodule.h"
20 #include "utf8.h"
21 #include "worktree.h"
22 #include "wrapper.h"
23 #include "quote.h"
25 #define BUILTIN_WORKTREE_ADD_USAGE \
26 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
27 " [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
29 #define BUILTIN_WORKTREE_LIST_USAGE \
30 N_("git worktree list [-v | --porcelain [-z]]")
31 #define BUILTIN_WORKTREE_LOCK_USAGE \
32 N_("git worktree lock [--reason <string>] <worktree>")
33 #define BUILTIN_WORKTREE_MOVE_USAGE \
34 N_("git worktree move <worktree> <new-path>")
35 #define BUILTIN_WORKTREE_PRUNE_USAGE \
36 N_("git worktree prune [-n] [-v] [--expire <expire>]")
37 #define BUILTIN_WORKTREE_REMOVE_USAGE \
38 N_("git worktree remove [-f] <worktree>")
39 #define BUILTIN_WORKTREE_REPAIR_USAGE \
40 N_("git worktree repair [<path>...]")
41 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
42 N_("git worktree unlock <worktree>")
44 #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \
45 _("No possible source branch, inferring '--orphan'")
47 #define WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT \
48 _("If you meant to create a worktree containing a new orphan branch\n" \
49 "(branch with no commits) for this repository, you can do so\n" \
50 "using the --orphan flag:\n" \
51 "\n" \
52 " git worktree add --orphan -b %s %s\n")
54 #define WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT \
55 _("If you meant to create a worktree containing a new orphan branch\n" \
56 "(branch with no commits) for this repository, you can do so\n" \
57 "using the --orphan flag:\n" \
58 "\n" \
59 " git worktree add --orphan %s\n")
61 static const char * const git_worktree_usage[] = {
62 BUILTIN_WORKTREE_ADD_USAGE,
63 BUILTIN_WORKTREE_LIST_USAGE,
64 BUILTIN_WORKTREE_LOCK_USAGE,
65 BUILTIN_WORKTREE_MOVE_USAGE,
66 BUILTIN_WORKTREE_PRUNE_USAGE,
67 BUILTIN_WORKTREE_REMOVE_USAGE,
68 BUILTIN_WORKTREE_REPAIR_USAGE,
69 BUILTIN_WORKTREE_UNLOCK_USAGE,
70 NULL
73 static const char * const git_worktree_add_usage[] = {
74 BUILTIN_WORKTREE_ADD_USAGE,
75 NULL,
78 static const char * const git_worktree_list_usage[] = {
79 BUILTIN_WORKTREE_LIST_USAGE,
80 NULL
83 static const char * const git_worktree_lock_usage[] = {
84 BUILTIN_WORKTREE_LOCK_USAGE,
85 NULL
88 static const char * const git_worktree_move_usage[] = {
89 BUILTIN_WORKTREE_MOVE_USAGE,
90 NULL
93 static const char * const git_worktree_prune_usage[] = {
94 BUILTIN_WORKTREE_PRUNE_USAGE,
95 NULL
98 static const char * const git_worktree_remove_usage[] = {
99 BUILTIN_WORKTREE_REMOVE_USAGE,
100 NULL
103 static const char * const git_worktree_repair_usage[] = {
104 BUILTIN_WORKTREE_REPAIR_USAGE,
105 NULL
108 static const char * const git_worktree_unlock_usage[] = {
109 BUILTIN_WORKTREE_UNLOCK_USAGE,
110 NULL
113 struct add_opts {
114 int force;
115 int detach;
116 int quiet;
117 int checkout;
118 int orphan;
119 const char *keep_locked;
122 static int show_only;
123 static int verbose;
124 static int guess_remote;
125 static timestamp_t expire;
127 static int git_worktree_config(const char *var, const char *value, void *cb)
129 if (!strcmp(var, "worktree.guessremote")) {
130 guess_remote = git_config_bool(var, value);
131 return 0;
134 return git_default_config(var, value, cb);
137 static int delete_git_dir(const char *id)
139 struct strbuf sb = STRBUF_INIT;
140 int ret;
142 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
143 ret = remove_dir_recursively(&sb, 0);
144 if (ret < 0 && errno == ENOTDIR)
145 ret = unlink(sb.buf);
146 if (ret)
147 error_errno(_("failed to delete '%s'"), sb.buf);
148 strbuf_release(&sb);
149 return ret;
152 static void delete_worktrees_dir_if_empty(void)
154 rmdir(git_path("worktrees")); /* ignore failed removal */
157 static void prune_worktree(const char *id, const char *reason)
159 if (show_only || verbose)
160 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
161 if (!show_only)
162 delete_git_dir(id);
165 static int prune_cmp(const void *a, const void *b)
167 const struct string_list_item *x = a;
168 const struct string_list_item *y = b;
169 int c;
171 if ((c = fspathcmp(x->string, y->string)))
172 return c;
174 * paths same; prune_dupes() removes all but the first worktree entry
175 * having the same path, so sort main worktree ('util' is NULL) above
176 * linked worktrees ('util' not NULL) since main worktree can't be
177 * removed
179 if (!x->util)
180 return -1;
181 if (!y->util)
182 return 1;
183 /* paths same; sort by .git/worktrees/<id> */
184 return strcmp(x->util, y->util);
187 static void prune_dups(struct string_list *l)
189 int i;
191 QSORT(l->items, l->nr, prune_cmp);
192 for (i = 1; i < l->nr; i++) {
193 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
194 prune_worktree(l->items[i].util, "duplicate entry");
198 static void prune_worktrees(void)
200 struct strbuf reason = STRBUF_INIT;
201 struct strbuf main_path = STRBUF_INIT;
202 struct string_list kept = STRING_LIST_INIT_DUP;
203 DIR *dir = opendir(git_path("worktrees"));
204 struct dirent *d;
205 if (!dir)
206 return;
207 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
208 char *path;
209 strbuf_reset(&reason);
210 if (should_prune_worktree(d->d_name, &reason, &path, expire))
211 prune_worktree(d->d_name, reason.buf);
212 else if (path)
213 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
215 closedir(dir);
217 strbuf_add_absolute_path(&main_path, get_git_common_dir());
218 /* massage main worktree absolute path to match 'gitdir' content */
219 strbuf_strip_suffix(&main_path, "/.");
220 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
221 prune_dups(&kept);
222 string_list_clear(&kept, 1);
224 if (!show_only)
225 delete_worktrees_dir_if_empty();
226 strbuf_release(&reason);
229 static int prune(int ac, const char **av, const char *prefix)
231 struct option options[] = {
232 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
233 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
234 OPT_EXPIRY_DATE(0, "expire", &expire,
235 N_("expire working trees older than <time>")),
236 OPT_END()
239 expire = TIME_MAX;
240 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
242 if (ac)
243 usage_with_options(git_worktree_prune_usage, options);
244 prune_worktrees();
245 return 0;
248 static char *junk_work_tree;
249 static char *junk_git_dir;
250 static int is_junk;
251 static pid_t junk_pid;
253 static void remove_junk(void)
255 struct strbuf sb = STRBUF_INIT;
256 if (!is_junk || getpid() != junk_pid)
257 return;
258 if (junk_git_dir) {
259 strbuf_addstr(&sb, junk_git_dir);
260 remove_dir_recursively(&sb, 0);
261 strbuf_reset(&sb);
263 if (junk_work_tree) {
264 strbuf_addstr(&sb, junk_work_tree);
265 remove_dir_recursively(&sb, 0);
267 strbuf_release(&sb);
270 static void remove_junk_on_signal(int signo)
272 remove_junk();
273 sigchain_pop(signo);
274 raise(signo);
277 static const char *worktree_basename(const char *path, int *olen)
279 const char *name;
280 int len;
282 len = strlen(path);
283 while (len && is_dir_sep(path[len - 1]))
284 len--;
286 for (name = path + len - 1; name > path; name--)
287 if (is_dir_sep(*name)) {
288 name++;
289 break;
292 *olen = len;
293 return name;
296 /* check that path is viable location for worktree */
297 static void check_candidate_path(const char *path,
298 int force,
299 struct worktree **worktrees,
300 const char *cmd)
302 struct worktree *wt;
303 int locked;
305 if (file_exists(path) && !is_empty_dir(path))
306 die(_("'%s' already exists"), path);
308 wt = find_worktree_by_path(worktrees, path);
309 if (!wt)
310 return;
312 locked = !!worktree_lock_reason(wt);
313 if ((!locked && force) || (locked && force > 1)) {
314 if (delete_git_dir(wt->id))
315 die(_("unusable worktree destination '%s'"), path);
316 return;
319 if (locked)
320 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
321 else
322 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
325 static void copy_sparse_checkout(const char *worktree_git_dir)
327 char *from_file = git_pathdup("info/sparse-checkout");
328 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
330 if (file_exists(from_file)) {
331 if (safe_create_leading_directories(to_file) ||
332 copy_file(to_file, from_file, 0666))
333 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
334 from_file, to_file);
337 free(from_file);
338 free(to_file);
341 static void copy_filtered_worktree_config(const char *worktree_git_dir)
343 char *from_file = git_pathdup("config.worktree");
344 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
346 if (file_exists(from_file)) {
347 struct config_set cs = { { 0 } };
348 int bare;
350 if (safe_create_leading_directories(to_file) ||
351 copy_file(to_file, from_file, 0666)) {
352 error(_("failed to copy worktree config from '%s' to '%s'"),
353 from_file, to_file);
354 goto worktree_copy_cleanup;
357 git_configset_init(&cs);
358 git_configset_add_file(&cs, from_file);
360 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
361 bare &&
362 git_config_set_multivar_in_file_gently(
363 to_file, "core.bare", NULL, "true", 0))
364 error(_("failed to unset '%s' in '%s'"),
365 "core.bare", to_file);
366 if (!git_configset_get(&cs, "core.worktree") &&
367 git_config_set_in_file_gently(to_file,
368 "core.worktree", NULL))
369 error(_("failed to unset '%s' in '%s'"),
370 "core.worktree", to_file);
372 git_configset_clear(&cs);
375 worktree_copy_cleanup:
376 free(from_file);
377 free(to_file);
380 static int checkout_worktree(const struct add_opts *opts,
381 struct strvec *child_env)
383 struct child_process cp = CHILD_PROCESS_INIT;
384 cp.git_cmd = 1;
385 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
386 if (opts->quiet)
387 strvec_push(&cp.args, "--quiet");
388 strvec_pushv(&cp.env, child_env->v);
389 return run_command(&cp);
392 static int make_worktree_orphan(const char * ref, const struct add_opts *opts,
393 struct strvec *child_env)
395 struct strbuf symref = STRBUF_INIT;
396 struct child_process cp = CHILD_PROCESS_INIT;
398 validate_new_branchname(ref, &symref, 0);
399 strvec_pushl(&cp.args, "symbolic-ref", "HEAD", symref.buf, NULL);
400 if (opts->quiet)
401 strvec_push(&cp.args, "--quiet");
402 strvec_pushv(&cp.env, child_env->v);
403 strbuf_release(&symref);
404 cp.git_cmd = 1;
405 return run_command(&cp);
408 static int add_worktree(const char *path, const char *refname,
409 const struct add_opts *opts)
411 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
412 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
413 const char *name;
414 struct child_process cp = CHILD_PROCESS_INIT;
415 struct strvec child_env = STRVEC_INIT;
416 unsigned int counter = 0;
417 int len, ret;
418 struct strbuf symref = STRBUF_INIT;
419 struct commit *commit = NULL;
420 int is_branch = 0;
421 struct strbuf sb_name = STRBUF_INIT;
422 struct worktree **worktrees;
424 worktrees = get_worktrees();
425 check_candidate_path(path, opts->force, worktrees, "add");
426 free_worktrees(worktrees);
427 worktrees = NULL;
429 /* is 'refname' a branch or commit? */
430 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
431 ref_exists(symref.buf)) {
432 is_branch = 1;
433 if (!opts->force)
434 die_if_checked_out(symref.buf, 0);
436 commit = lookup_commit_reference_by_name(refname);
437 if (!commit && !opts->orphan)
438 die(_("invalid reference: %s"), refname);
440 name = worktree_basename(path, &len);
441 strbuf_add(&sb, name, path + len - name);
442 sanitize_refname_component(sb.buf, &sb_name);
443 if (!sb_name.len)
444 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
445 strbuf_reset(&sb);
446 name = sb_name.buf;
447 git_path_buf(&sb_repo, "worktrees/%s", name);
448 len = sb_repo.len;
449 if (safe_create_leading_directories_const(sb_repo.buf))
450 die_errno(_("could not create leading directories of '%s'"),
451 sb_repo.buf);
453 while (mkdir(sb_repo.buf, 0777)) {
454 counter++;
455 if ((errno != EEXIST) || !counter /* overflow */)
456 die_errno(_("could not create directory of '%s'"),
457 sb_repo.buf);
458 strbuf_setlen(&sb_repo, len);
459 strbuf_addf(&sb_repo, "%d", counter);
461 name = strrchr(sb_repo.buf, '/') + 1;
463 junk_pid = getpid();
464 atexit(remove_junk);
465 sigchain_push_common(remove_junk_on_signal);
467 junk_git_dir = xstrdup(sb_repo.buf);
468 is_junk = 1;
471 * lock the incomplete repo so prune won't delete it, unlock
472 * after the preparation is over.
474 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
475 if (opts->keep_locked)
476 write_file(sb.buf, "%s", opts->keep_locked);
477 else
478 write_file(sb.buf, _("initializing"));
480 strbuf_addf(&sb_git, "%s/.git", path);
481 if (safe_create_leading_directories_const(sb_git.buf))
482 die_errno(_("could not create leading directories of '%s'"),
483 sb_git.buf);
484 junk_work_tree = xstrdup(path);
486 strbuf_reset(&sb);
487 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
488 strbuf_realpath(&realpath, sb_git.buf, 1);
489 write_file(sb.buf, "%s", realpath.buf);
490 strbuf_realpath(&realpath, get_git_common_dir(), 1);
491 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
492 realpath.buf, name);
494 * This is to keep resolve_ref() happy. We need a valid HEAD
495 * or is_git_directory() will reject the directory. Any value which
496 * looks like an object ID will do since it will be immediately
497 * replaced by the symbolic-ref or update-ref invocation in the new
498 * worktree.
500 strbuf_reset(&sb);
501 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
502 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
503 strbuf_reset(&sb);
504 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
505 write_file(sb.buf, "../..");
508 * If the current worktree has sparse-checkout enabled, then copy
509 * the sparse-checkout patterns from the current worktree.
511 if (core_apply_sparse_checkout)
512 copy_sparse_checkout(sb_repo.buf);
515 * If we are using worktree config, then copy all current config
516 * values from the current worktree into the new one, that way the
517 * new worktree behaves the same as this one.
519 if (repository_format_worktree_config)
520 copy_filtered_worktree_config(sb_repo.buf);
522 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
523 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
524 cp.git_cmd = 1;
526 if (!is_branch && commit) {
527 strvec_pushl(&cp.args, "update-ref", "HEAD",
528 oid_to_hex(&commit->object.oid), NULL);
529 } else {
530 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
531 symref.buf, NULL);
532 if (opts->quiet)
533 strvec_push(&cp.args, "--quiet");
536 strvec_pushv(&cp.env, child_env.v);
537 ret = run_command(&cp);
538 if (ret)
539 goto done;
541 if (opts->orphan &&
542 (ret = make_worktree_orphan(refname, opts, &child_env)))
543 goto done;
545 if (opts->checkout &&
546 (ret = checkout_worktree(opts, &child_env)))
547 goto done;
549 is_junk = 0;
550 FREE_AND_NULL(junk_work_tree);
551 FREE_AND_NULL(junk_git_dir);
553 done:
554 if (ret || !opts->keep_locked) {
555 strbuf_reset(&sb);
556 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
557 unlink_or_warn(sb.buf);
561 * Hook failure does not warrant worktree deletion, so run hook after
562 * is_junk is cleared, but do return appropriate code when hook fails.
564 if (!ret && opts->checkout && !opts->orphan) {
565 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
567 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
568 strvec_pushl(&opt.args,
569 oid_to_hex(null_oid()),
570 oid_to_hex(&commit->object.oid),
571 "1",
572 NULL);
573 opt.dir = path;
575 ret = run_hooks_opt("post-checkout", &opt);
578 strvec_clear(&child_env);
579 strbuf_release(&sb);
580 strbuf_release(&symref);
581 strbuf_release(&sb_repo);
582 strbuf_release(&sb_git);
583 strbuf_release(&sb_name);
584 strbuf_release(&realpath);
585 return ret;
588 static void print_preparing_worktree_line(int detach,
589 const char *branch,
590 const char *new_branch,
591 int force_new_branch)
593 if (force_new_branch) {
594 struct commit *commit = lookup_commit_reference_by_name(new_branch);
595 if (!commit)
596 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
597 else
598 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
599 new_branch,
600 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
601 } else if (new_branch) {
602 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
603 } else {
604 struct strbuf s = STRBUF_INIT;
605 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
606 ref_exists(s.buf))
607 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
608 branch);
609 else {
610 struct commit *commit = lookup_commit_reference_by_name(branch);
611 if (!commit)
612 BUG(_("unreachable: invalid reference: %s"), branch);
613 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
614 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
616 strbuf_release(&s);
621 * Callback to short circuit iteration over refs on the first reference
622 * corresponding to a valid oid.
624 * Returns 0 on failure and non-zero on success.
626 static int first_valid_ref(const char *refname,
627 const struct object_id *oid,
628 int flags,
629 void *cb_data)
631 return 1;
635 * Verifies HEAD and determines whether there exist any valid local references.
637 * - Checks whether HEAD points to a valid reference.
639 * - Checks whether any valid local branches exist.
641 * - Emits a warning if there exist any valid branches but HEAD does not point
642 * to a valid reference.
644 * Returns 1 if any of the previous checks are true, otherwise returns 0.
646 static int can_use_local_refs(const struct add_opts *opts)
648 if (head_ref(first_valid_ref, NULL)) {
649 return 1;
650 } else if (for_each_branch_ref(first_valid_ref, NULL)) {
651 if (!opts->quiet) {
652 struct strbuf path = STRBUF_INIT;
653 struct strbuf contents = STRBUF_INIT;
655 strbuf_add_real_path(&path, get_worktree_git_dir(NULL));
656 strbuf_addstr(&path, "/HEAD");
657 strbuf_read_file(&contents, path.buf, 64);
658 strbuf_stripspace(&contents, 0);
659 strbuf_strip_suffix(&contents, "\n");
661 warning(_("HEAD points to an invalid (or orphaned) reference.\n"
662 "HEAD path: '%s'\n"
663 "HEAD contents: '%s'"),
664 path.buf, contents.buf);
665 strbuf_release(&path);
666 strbuf_release(&contents);
668 return 1;
670 return 0;
674 * Reports whether the necessary flags were set and whether the repository has
675 * remote references to attempt DWIM tracking of upstream branches.
677 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
679 * 2. Checks whether any valid remote branches exist.
681 * 3. Checks that there exists at least one remote and emits a warning/error
682 * if both checks 1. and 2. are false (can be bypassed with `--force`).
684 * Returns 1 if checks 1. and 2. are true, otherwise 0.
686 static int can_use_remote_refs(const struct add_opts *opts)
688 if (!guess_remote) {
689 return 0;
690 } else if (for_each_remote_ref(first_valid_ref, NULL)) {
691 return 1;
692 } else if (!opts->force && remote_get(NULL)) {
693 die(_("No local or remote refs exist despite at least one remote\n"
694 "present, stopping; use 'add -f' to override or fetch a remote first"));
696 return 0;
700 * Determines whether `--orphan` should be inferred in the evaluation of
701 * `worktree add path/` or `worktree add -b branch path/` and emits an error
702 * if the supplied arguments would produce an illegal combination when the
703 * `--orphan` flag is included.
705 * `opts` and `opt_track` contain the other options & flags supplied to the
706 * command.
708 * remote determines whether to check `can_use_remote_refs()` or not. This
709 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
711 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
712 * `--orphan` is inferred but doing so produces an illegal combination of
713 * options and flags. Additionally produces an error when remote refs are
714 * checked and the repo is in a state that looks like the user added a remote
715 * but forgot to fetch (and did not override the warning with -f).
717 static int dwim_orphan(const struct add_opts *opts, int opt_track, int remote)
719 if (can_use_local_refs(opts)) {
720 return 0;
721 } else if (remote && can_use_remote_refs(opts)) {
722 return 0;
723 } else if (!opts->quiet) {
724 fprintf_ln(stderr, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT);
727 if (opt_track) {
728 die(_("'%s' and '%s' cannot be used together"), "--orphan",
729 "--track");
730 } else if (!opts->checkout) {
731 die(_("'%s' and '%s' cannot be used together"), "--orphan",
732 "--no-checkout");
734 return 1;
737 static const char *dwim_branch(const char *path, const char **new_branch)
739 int n;
740 int branch_exists;
741 const char *s = worktree_basename(path, &n);
742 const char *branchname = xstrndup(s, n);
743 struct strbuf ref = STRBUF_INIT;
745 UNLEAK(branchname);
747 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
748 ref_exists(ref.buf);
749 strbuf_release(&ref);
750 if (branch_exists)
751 return branchname;
753 *new_branch = branchname;
754 if (guess_remote) {
755 struct object_id oid;
756 const char *remote =
757 unique_tracking_name(*new_branch, &oid, NULL);
758 return remote;
760 return NULL;
763 static int add(int ac, const char **av, const char *prefix)
765 struct add_opts opts;
766 const char *new_branch_force = NULL;
767 char *path;
768 const char *branch;
769 const char *new_branch = NULL;
770 const char *opt_track = NULL;
771 const char *lock_reason = NULL;
772 int keep_locked = 0;
773 int used_new_branch_options;
774 struct option options[] = {
775 OPT__FORCE(&opts.force,
776 N_("checkout <branch> even if already checked out in other worktree"),
777 PARSE_OPT_NOCOMPLETE),
778 OPT_STRING('b', NULL, &new_branch, N_("branch"),
779 N_("create a new branch")),
780 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
781 N_("create or reset a branch")),
782 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn/orphaned branch")),
783 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
784 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
785 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
786 OPT_STRING(0, "reason", &lock_reason, N_("string"),
787 N_("reason for locking")),
788 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
789 OPT_PASSTHRU(0, "track", &opt_track, NULL,
790 N_("set up tracking mode (see git-branch(1))"),
791 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
792 OPT_BOOL(0, "guess-remote", &guess_remote,
793 N_("try to match the new branch name with a remote-tracking branch")),
794 OPT_END()
796 int ret;
798 memset(&opts, 0, sizeof(opts));
799 opts.checkout = 1;
800 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
801 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
802 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
803 if (opts.detach && opts.orphan)
804 die(_("options '%s', and '%s' cannot be used together"),
805 "--orphan", "--detach");
806 if (opts.orphan && opt_track)
807 die(_("'%s' and '%s' cannot be used together"), "--orphan", "--track");
808 if (opts.orphan && !opts.checkout)
809 die(_("'%s' and '%s' cannot be used together"), "--orphan",
810 "--no-checkout");
811 if (opts.orphan && ac == 2)
812 die(_("'%s' and '%s' cannot be used together"), "--orphan",
813 _("<commit-ish>"));
814 if (lock_reason && !keep_locked)
815 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
816 if (lock_reason)
817 opts.keep_locked = lock_reason;
818 else if (keep_locked)
819 opts.keep_locked = _("added with --lock");
821 if (ac < 1 || ac > 2)
822 usage_with_options(git_worktree_add_usage, options);
824 path = prefix_filename(prefix, av[0]);
825 branch = ac < 2 ? "HEAD" : av[1];
826 used_new_branch_options = new_branch || new_branch_force;
828 if (!strcmp(branch, "-"))
829 branch = "@{-1}";
831 if (new_branch_force) {
832 struct strbuf symref = STRBUF_INIT;
834 new_branch = new_branch_force;
836 if (!opts.force &&
837 !strbuf_check_branch_ref(&symref, new_branch) &&
838 ref_exists(symref.buf))
839 die_if_checked_out(symref.buf, 0);
840 strbuf_release(&symref);
843 if (opts.orphan && !new_branch) {
844 int n;
845 const char *s = worktree_basename(path, &n);
846 new_branch = xstrndup(s, n);
847 } else if (opts.orphan) {
848 // No-op
849 } else if (opts.detach) {
850 // Check HEAD
851 if (!strcmp(branch, "HEAD"))
852 can_use_local_refs(&opts);
853 } else if (ac < 2 && new_branch) {
854 // DWIM: Infer --orphan when repo has no refs.
855 opts.orphan = dwim_orphan(&opts, !!opt_track, 0);
856 } else if (ac < 2) {
857 // DWIM: Guess branch name from path.
858 const char *s = dwim_branch(path, &new_branch);
859 if (s)
860 branch = s;
862 // DWIM: Infer --orphan when repo has no refs.
863 opts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);
864 } else if (ac == 2) {
865 struct object_id oid;
866 struct commit *commit;
867 const char *remote;
869 commit = lookup_commit_reference_by_name(branch);
870 if (!commit) {
871 remote = unique_tracking_name(branch, &oid, NULL);
872 if (remote) {
873 new_branch = branch;
874 branch = remote;
878 if (!strcmp(branch, "HEAD"))
879 can_use_local_refs(&opts);
883 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
884 int attempt_hint = !opts.quiet && (ac < 2);
885 if (attempt_hint && used_new_branch_options) {
886 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
887 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT,
888 new_branch, path);
889 } else if (attempt_hint) {
890 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
891 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT, path);
893 die(_("invalid reference: %s"), branch);
896 if (!opts.quiet)
897 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
899 if (opts.orphan) {
900 branch = new_branch;
901 } else if (new_branch) {
902 struct child_process cp = CHILD_PROCESS_INIT;
903 cp.git_cmd = 1;
904 strvec_push(&cp.args, "branch");
905 if (new_branch_force)
906 strvec_push(&cp.args, "--force");
907 if (opts.quiet)
908 strvec_push(&cp.args, "--quiet");
909 strvec_push(&cp.args, new_branch);
910 strvec_push(&cp.args, branch);
911 if (opt_track)
912 strvec_push(&cp.args, opt_track);
913 if (run_command(&cp))
914 return -1;
915 branch = new_branch;
916 } else if (opt_track) {
917 die(_("--[no-]track can only be used if a new branch is created"));
920 ret = add_worktree(path, branch, &opts);
921 free(path);
922 return ret;
925 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
927 const char *reason;
929 printf("worktree %s%c", wt->path, line_terminator);
930 if (wt->is_bare)
931 printf("bare%c", line_terminator);
932 else {
933 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
934 if (wt->is_detached)
935 printf("detached%c", line_terminator);
936 else if (wt->head_ref)
937 printf("branch %s%c", wt->head_ref, line_terminator);
940 reason = worktree_lock_reason(wt);
941 if (reason) {
942 fputs("locked", stdout);
943 if (*reason) {
944 fputc(' ', stdout);
945 write_name_quoted(reason, stdout, line_terminator);
946 } else {
947 fputc(line_terminator, stdout);
951 reason = worktree_prune_reason(wt, expire);
952 if (reason)
953 printf("prunable %s%c", reason, line_terminator);
955 fputc(line_terminator, stdout);
958 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
960 struct strbuf sb = STRBUF_INIT;
961 int cur_path_len = strlen(wt->path);
962 int path_adj = cur_path_len - utf8_strwidth(wt->path);
963 const char *reason;
965 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
966 if (wt->is_bare)
967 strbuf_addstr(&sb, "(bare)");
968 else {
969 strbuf_addf(&sb, "%-*s ", abbrev_len,
970 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
971 if (wt->is_detached)
972 strbuf_addstr(&sb, "(detached HEAD)");
973 else if (wt->head_ref) {
974 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
975 strbuf_addf(&sb, "[%s]", ref);
976 free(ref);
977 } else
978 strbuf_addstr(&sb, "(error)");
981 reason = worktree_lock_reason(wt);
982 if (verbose && reason && *reason)
983 strbuf_addf(&sb, "\n\tlocked: %s", reason);
984 else if (reason)
985 strbuf_addstr(&sb, " locked");
987 reason = worktree_prune_reason(wt, expire);
988 if (verbose && reason)
989 strbuf_addf(&sb, "\n\tprunable: %s", reason);
990 else if (reason)
991 strbuf_addstr(&sb, " prunable");
993 printf("%s\n", sb.buf);
994 strbuf_release(&sb);
997 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
999 int i;
1001 for (i = 0; wt[i]; i++) {
1002 int sha1_len;
1003 int path_len = strlen(wt[i]->path);
1005 if (path_len > *maxlen)
1006 *maxlen = path_len;
1007 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
1008 if (sha1_len > *abbrev)
1009 *abbrev = sha1_len;
1013 static int pathcmp(const void *a_, const void *b_)
1015 const struct worktree *const *a = a_;
1016 const struct worktree *const *b = b_;
1017 return fspathcmp((*a)->path, (*b)->path);
1020 static void pathsort(struct worktree **wt)
1022 int n = 0;
1023 struct worktree **p = wt;
1025 while (*p++)
1026 n++;
1027 QSORT(wt, n, pathcmp);
1030 static int list(int ac, const char **av, const char *prefix)
1032 int porcelain = 0;
1033 int line_terminator = '\n';
1035 struct option options[] = {
1036 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
1037 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
1038 OPT_EXPIRY_DATE(0, "expire", &expire,
1039 N_("add 'prunable' annotation to worktrees older than <time>")),
1040 OPT_SET_INT('z', NULL, &line_terminator,
1041 N_("terminate records with a NUL character"), '\0'),
1042 OPT_END()
1045 expire = TIME_MAX;
1046 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
1047 if (ac)
1048 usage_with_options(git_worktree_list_usage, options);
1049 else if (verbose && porcelain)
1050 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1051 else if (!line_terminator && !porcelain)
1052 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1053 else {
1054 struct worktree **worktrees = get_worktrees();
1055 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
1057 /* sort worktrees by path but keep main worktree at top */
1058 pathsort(worktrees + 1);
1060 if (!porcelain)
1061 measure_widths(worktrees, &abbrev, &path_maxlen);
1063 for (i = 0; worktrees[i]; i++) {
1064 if (porcelain)
1065 show_worktree_porcelain(worktrees[i],
1066 line_terminator);
1067 else
1068 show_worktree(worktrees[i], path_maxlen, abbrev);
1070 free_worktrees(worktrees);
1072 return 0;
1075 static int lock_worktree(int ac, const char **av, const char *prefix)
1077 const char *reason = "", *old_reason;
1078 struct option options[] = {
1079 OPT_STRING(0, "reason", &reason, N_("string"),
1080 N_("reason for locking")),
1081 OPT_END()
1083 struct worktree **worktrees, *wt;
1085 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
1086 if (ac != 1)
1087 usage_with_options(git_worktree_lock_usage, options);
1089 worktrees = get_worktrees();
1090 wt = find_worktree(worktrees, prefix, av[0]);
1091 if (!wt)
1092 die(_("'%s' is not a working tree"), av[0]);
1093 if (is_main_worktree(wt))
1094 die(_("The main working tree cannot be locked or unlocked"));
1096 old_reason = worktree_lock_reason(wt);
1097 if (old_reason) {
1098 if (*old_reason)
1099 die(_("'%s' is already locked, reason: %s"),
1100 av[0], old_reason);
1101 die(_("'%s' is already locked"), av[0]);
1104 write_file(git_common_path("worktrees/%s/locked", wt->id),
1105 "%s", reason);
1106 free_worktrees(worktrees);
1107 return 0;
1110 static int unlock_worktree(int ac, const char **av, const char *prefix)
1112 struct option options[] = {
1113 OPT_END()
1115 struct worktree **worktrees, *wt;
1116 int ret;
1118 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
1119 if (ac != 1)
1120 usage_with_options(git_worktree_unlock_usage, options);
1122 worktrees = get_worktrees();
1123 wt = find_worktree(worktrees, prefix, av[0]);
1124 if (!wt)
1125 die(_("'%s' is not a working tree"), av[0]);
1126 if (is_main_worktree(wt))
1127 die(_("The main working tree cannot be locked or unlocked"));
1128 if (!worktree_lock_reason(wt))
1129 die(_("'%s' is not locked"), av[0]);
1130 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
1131 free_worktrees(worktrees);
1132 return ret;
1135 static void validate_no_submodules(const struct worktree *wt)
1137 struct index_state istate = INDEX_STATE_INIT(the_repository);
1138 struct strbuf path = STRBUF_INIT;
1139 int i, found_submodules = 0;
1141 if (is_directory(worktree_git_path(wt, "modules"))) {
1143 * There could be false positives, e.g. the "modules"
1144 * directory exists but is empty. But it's a rare case and
1145 * this simpler check is probably good enough for now.
1147 found_submodules = 1;
1148 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1149 get_worktree_git_dir(wt)) > 0) {
1150 for (i = 0; i < istate.cache_nr; i++) {
1151 struct cache_entry *ce = istate.cache[i];
1152 int err;
1154 if (!S_ISGITLINK(ce->ce_mode))
1155 continue;
1157 strbuf_reset(&path);
1158 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
1159 if (!is_submodule_populated_gently(path.buf, &err))
1160 continue;
1162 found_submodules = 1;
1163 break;
1166 discard_index(&istate);
1167 strbuf_release(&path);
1169 if (found_submodules)
1170 die(_("working trees containing submodules cannot be moved or removed"));
1173 static int move_worktree(int ac, const char **av, const char *prefix)
1175 int force = 0;
1176 struct option options[] = {
1177 OPT__FORCE(&force,
1178 N_("force move even if worktree is dirty or locked"),
1179 PARSE_OPT_NOCOMPLETE),
1180 OPT_END()
1182 struct worktree **worktrees, *wt;
1183 struct strbuf dst = STRBUF_INIT;
1184 struct strbuf errmsg = STRBUF_INIT;
1185 const char *reason = NULL;
1186 char *path;
1188 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1190 if (ac != 2)
1191 usage_with_options(git_worktree_move_usage, options);
1193 path = prefix_filename(prefix, av[1]);
1194 strbuf_addstr(&dst, path);
1195 free(path);
1197 worktrees = get_worktrees();
1198 wt = find_worktree(worktrees, prefix, av[0]);
1199 if (!wt)
1200 die(_("'%s' is not a working tree"), av[0]);
1201 if (is_main_worktree(wt))
1202 die(_("'%s' is a main working tree"), av[0]);
1203 if (is_directory(dst.buf)) {
1204 const char *sep = find_last_dir_sep(wt->path);
1206 if (!sep)
1207 die(_("could not figure out destination name from '%s'"),
1208 wt->path);
1209 strbuf_trim_trailing_dir_sep(&dst);
1210 strbuf_addstr(&dst, sep);
1212 check_candidate_path(dst.buf, force, worktrees, "move");
1214 validate_no_submodules(wt);
1216 if (force < 2)
1217 reason = worktree_lock_reason(wt);
1218 if (reason) {
1219 if (*reason)
1220 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1221 reason);
1222 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1224 if (validate_worktree(wt, &errmsg, 0))
1225 die(_("validation failed, cannot move working tree: %s"),
1226 errmsg.buf);
1227 strbuf_release(&errmsg);
1229 if (rename(wt->path, dst.buf) == -1)
1230 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1232 update_worktree_location(wt, dst.buf);
1234 strbuf_release(&dst);
1235 free_worktrees(worktrees);
1236 return 0;
1240 * Note, "git status --porcelain" is used to determine if it's safe to
1241 * delete a whole worktree. "git status" does not ignore user
1242 * configuration, so if a normal "git status" shows "clean" for the
1243 * user, then it's ok to remove it.
1245 * This assumption may be a bad one. We may want to ignore
1246 * (potentially bad) user settings and only delete a worktree when
1247 * it's absolutely safe to do so from _our_ point of view because we
1248 * know better.
1250 static void check_clean_worktree(struct worktree *wt,
1251 const char *original_path)
1253 struct child_process cp;
1254 char buf[1];
1255 int ret;
1258 * Until we sort this out, all submodules are "dirty" and
1259 * will abort this function.
1261 validate_no_submodules(wt);
1263 child_process_init(&cp);
1264 strvec_pushf(&cp.env, "%s=%s/.git",
1265 GIT_DIR_ENVIRONMENT, wt->path);
1266 strvec_pushf(&cp.env, "%s=%s",
1267 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1268 strvec_pushl(&cp.args, "status",
1269 "--porcelain", "--ignore-submodules=none",
1270 NULL);
1271 cp.git_cmd = 1;
1272 cp.dir = wt->path;
1273 cp.out = -1;
1274 ret = start_command(&cp);
1275 if (ret)
1276 die_errno(_("failed to run 'git status' on '%s'"),
1277 original_path);
1278 ret = xread(cp.out, buf, sizeof(buf));
1279 if (ret)
1280 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1281 original_path);
1282 close(cp.out);
1283 ret = finish_command(&cp);
1284 if (ret)
1285 die_errno(_("failed to run 'git status' on '%s', code %d"),
1286 original_path, ret);
1289 static int delete_git_work_tree(struct worktree *wt)
1291 struct strbuf sb = STRBUF_INIT;
1292 int ret = 0;
1294 strbuf_addstr(&sb, wt->path);
1295 if (remove_dir_recursively(&sb, 0)) {
1296 error_errno(_("failed to delete '%s'"), sb.buf);
1297 ret = -1;
1299 strbuf_release(&sb);
1300 return ret;
1303 static int remove_worktree(int ac, const char **av, const char *prefix)
1305 int force = 0;
1306 struct option options[] = {
1307 OPT__FORCE(&force,
1308 N_("force removal even if worktree is dirty or locked"),
1309 PARSE_OPT_NOCOMPLETE),
1310 OPT_END()
1312 struct worktree **worktrees, *wt;
1313 struct strbuf errmsg = STRBUF_INIT;
1314 const char *reason = NULL;
1315 int ret = 0;
1317 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1318 if (ac != 1)
1319 usage_with_options(git_worktree_remove_usage, options);
1321 worktrees = get_worktrees();
1322 wt = find_worktree(worktrees, prefix, av[0]);
1323 if (!wt)
1324 die(_("'%s' is not a working tree"), av[0]);
1325 if (is_main_worktree(wt))
1326 die(_("'%s' is a main working tree"), av[0]);
1327 if (force < 2)
1328 reason = worktree_lock_reason(wt);
1329 if (reason) {
1330 if (*reason)
1331 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1332 reason);
1333 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1335 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1336 die(_("validation failed, cannot remove working tree: %s"),
1337 errmsg.buf);
1338 strbuf_release(&errmsg);
1340 if (file_exists(wt->path)) {
1341 if (!force)
1342 check_clean_worktree(wt, av[0]);
1344 ret |= delete_git_work_tree(wt);
1347 * continue on even if ret is non-zero, there's no going back
1348 * from here.
1350 ret |= delete_git_dir(wt->id);
1351 delete_worktrees_dir_if_empty();
1353 free_worktrees(worktrees);
1354 return ret;
1357 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1359 if (!iserr) {
1360 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1361 } else {
1362 int *exit_status = (int *)cb_data;
1363 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1364 *exit_status = 1;
1368 static int repair(int ac, const char **av, const char *prefix)
1370 const char **p;
1371 const char *self[] = { ".", NULL };
1372 struct option options[] = {
1373 OPT_END()
1375 int rc = 0;
1377 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1378 p = ac > 0 ? av : self;
1379 for (; *p; p++)
1380 repair_worktree_at_path(*p, report_repair, &rc);
1381 repair_worktrees(report_repair, &rc);
1382 return rc;
1385 int cmd_worktree(int ac, const char **av, const char *prefix)
1387 parse_opt_subcommand_fn *fn = NULL;
1388 struct option options[] = {
1389 OPT_SUBCOMMAND("add", &fn, add),
1390 OPT_SUBCOMMAND("prune", &fn, prune),
1391 OPT_SUBCOMMAND("list", &fn, list),
1392 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1393 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1394 OPT_SUBCOMMAND("move", &fn, move_worktree),
1395 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1396 OPT_SUBCOMMAND("repair", &fn, repair),
1397 OPT_END()
1400 git_config(git_worktree_config, NULL);
1402 if (!prefix)
1403 prefix = "";
1405 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1406 return fn(ac, av, prefix);