]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/worktree.c
worktree add: emit warn when there is a bad HEAD
[thirdparty/git.git] / builtin / worktree.c
CommitLineData
df0b6cfb 1#include "cache.h"
0b027f6c 2#include "abspath.h"
35f0383c 3#include "advice.h"
4e853331 4#include "checkout.h"
b2141fc1 5#include "config.h"
df0b6cfb
NTND
6#include "builtin.h"
7#include "dir.h"
32a8f510 8#include "environment.h"
f394e093 9#include "gettext.h"
41771fa4 10#include "hex.h"
df0b6cfb 11#include "parse-options.h"
dbbcd44f 12#include "strvec.h"
f7c9dac1
ES
13#include "branch.h"
14#include "refs.h"
128e5496 15#include "remote.h"
fc56361f 16#include "run-command.h"
5e3aba33 17#include "hook.h"
b979d950 18#include "sigchain.h"
00a6d4d1 19#include "submodule.h"
bb9c03b8
MR
20#include "utf8.h"
21#include "worktree.h"
d5ebb50d 22#include "wrapper.h"
862c723d 23#include "quote.h"
df0b6cfb 24
0afd556b 25#define BUILTIN_WORKTREE_ADD_USAGE \
97f03a56 26 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
7ab89189
JA
27 " [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
28
0afd556b 29#define BUILTIN_WORKTREE_LIST_USAGE \
97f03a56 30 N_("git worktree list [-v | --porcelain [-z]]")
0afd556b 31#define BUILTIN_WORKTREE_LOCK_USAGE \
97f03a56 32 N_("git worktree lock [--reason <string>] <worktree>")
0afd556b
ÆAB
33#define BUILTIN_WORKTREE_MOVE_USAGE \
34 N_("git worktree move <worktree> <new-path>")
35#define BUILTIN_WORKTREE_PRUNE_USAGE \
97f03a56 36 N_("git worktree prune [-n] [-v] [--expire <expire>]")
0afd556b 37#define BUILTIN_WORKTREE_REMOVE_USAGE \
97f03a56 38 N_("git worktree remove [-f] <worktree>")
0afd556b
ÆAB
39#define BUILTIN_WORKTREE_REPAIR_USAGE \
40 N_("git worktree repair [<path>...]")
41#define BUILTIN_WORKTREE_UNLOCK_USAGE \
42 N_("git worktree unlock <worktree>")
43
128e5496
JA
44#define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \
45 _("No possible source branch, inferring '--orphan'")
46
35f0383c
JA
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")
53
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")
60
0afd556b
ÆAB
61static 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
71};
72
73static const char * const git_worktree_add_usage[] = {
74 BUILTIN_WORKTREE_ADD_USAGE,
75 NULL,
76};
77
78static const char * const git_worktree_list_usage[] = {
79 BUILTIN_WORKTREE_LIST_USAGE,
80 NULL
81};
82
83static const char * const git_worktree_lock_usage[] = {
84 BUILTIN_WORKTREE_LOCK_USAGE,
85 NULL
86};
87
88static const char * const git_worktree_move_usage[] = {
89 BUILTIN_WORKTREE_MOVE_USAGE,
90 NULL
91};
92
93static const char * const git_worktree_prune_usage[] = {
94 BUILTIN_WORKTREE_PRUNE_USAGE,
95 NULL
96};
97
98static const char * const git_worktree_remove_usage[] = {
99 BUILTIN_WORKTREE_REMOVE_USAGE,
100 NULL
101};
102
103static const char * const git_worktree_repair_usage[] = {
104 BUILTIN_WORKTREE_REPAIR_USAGE,
105 NULL
106};
107
108static const char * const git_worktree_unlock_usage[] = {
109 BUILTIN_WORKTREE_UNLOCK_USAGE,
df0b6cfb
NTND
110 NULL
111};
112
5dd6e234
ES
113struct add_opts {
114 int force;
115 int detach;
371979c2 116 int quiet;
ef2a0ac9 117 int checkout;
7ab89189 118 int orphan;
0db4961c 119 const char *keep_locked;
5dd6e234
ES
120};
121
df0b6cfb
NTND
122static int show_only;
123static int verbose;
e92445a7 124static int guess_remote;
dddbad72 125static timestamp_t expire;
df0b6cfb 126
e92445a7
TG
127static int git_worktree_config(const char *var, const char *value, void *cb)
128{
129 if (!strcmp(var, "worktree.guessremote")) {
130 guess_remote = git_config_bool(var, value);
131 return 0;
132 }
133
134 return git_default_config(var, value, cb);
135}
136
602aaed0 137static int delete_git_dir(const char *id)
e5353bef
ES
138{
139 struct strbuf sb = STRBUF_INIT;
602aaed0 140 int ret;
e5353bef 141
602aaed0
ES
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)
e5353bef 147 error_errno(_("failed to delete '%s'"), sb.buf);
e5353bef
ES
148 strbuf_release(&sb);
149 return ret;
150}
151
3a540433
ES
152static void delete_worktrees_dir_if_empty(void)
153{
154 rmdir(git_path("worktrees")); /* ignore failed removal */
155}
156
dd9609a1
ES
157static void prune_worktree(const char *id, const char *reason)
158{
159 if (show_only || verbose)
da8fb6be 160 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
dd9609a1
ES
161 if (!show_only)
162 delete_git_dir(id);
163}
164
4a3ce479
ES
165static int prune_cmp(const void *a, const void *b)
166{
167 const struct string_list_item *x = a;
168 const struct string_list_item *y = b;
169 int c;
170
171 if ((c = fspathcmp(x->string, y->string)))
172 return c;
916133ef
ES
173 /*
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
178 */
179 if (!x->util)
180 return -1;
181 if (!y->util)
182 return 1;
4a3ce479
ES
183 /* paths same; sort by .git/worktrees/<id> */
184 return strcmp(x->util, y->util);
185}
186
187static void prune_dups(struct string_list *l)
188{
189 int i;
190
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");
195 }
196}
197
df0b6cfb
NTND
198static void prune_worktrees(void)
199{
200 struct strbuf reason = STRBUF_INIT;
916133ef 201 struct strbuf main_path = STRBUF_INIT;
9f24f3c7 202 struct string_list kept = STRING_LIST_INIT_DUP;
df0b6cfb
NTND
203 DIR *dir = opendir(git_path("worktrees"));
204 struct dirent *d;
df0b6cfb
NTND
205 if (!dir)
206 return;
b548f0f1 207 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
4a3ce479 208 char *path;
df0b6cfb 209 strbuf_reset(&reason);
a29a8b75 210 if (should_prune_worktree(d->d_name, &reason, &path, expire))
4a3ce479
ES
211 prune_worktree(d->d_name, reason.buf);
212 else if (path)
9f24f3c7 213 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
df0b6cfb
NTND
214 }
215 closedir(dir);
4a3ce479 216
916133ef
ES
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, "/.");
9f24f3c7 220 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
4a3ce479
ES
221 prune_dups(&kept);
222 string_list_clear(&kept, 1);
223
df0b6cfb 224 if (!show_only)
3a540433 225 delete_worktrees_dir_if_empty();
df0b6cfb 226 strbuf_release(&reason);
df0b6cfb
NTND
227}
228
229static int prune(int ac, const char **av, const char *prefix)
230{
231 struct option options[] = {
232 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
2488dcab 233 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
df0b6cfb 234 OPT_EXPIRY_DATE(0, "expire", &expire,
2488dcab 235 N_("expire working trees older than <time>")),
df0b6cfb
NTND
236 OPT_END()
237 };
238
dddbad72 239 expire = TIME_MAX;
0afd556b
ÆAB
240 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
241 0);
df0b6cfb 242 if (ac)
0afd556b 243 usage_with_options(git_worktree_prune_usage, options);
df0b6cfb
NTND
244 prune_worktrees();
245 return 0;
246}
247
b979d950
ES
248static char *junk_work_tree;
249static char *junk_git_dir;
250static int is_junk;
251static pid_t junk_pid;
252
253static void remove_junk(void)
254{
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);
262 }
263 if (junk_work_tree) {
264 strbuf_addstr(&sb, junk_work_tree);
265 remove_dir_recursively(&sb, 0);
266 }
267 strbuf_release(&sb);
268}
269
270static void remove_junk_on_signal(int signo)
271{
272 remove_junk();
273 sigchain_pop(signo);
274 raise(signo);
275}
276
f5682b2a
ES
277static const char *worktree_basename(const char *path, int *olen)
278{
279 const char *name;
280 int len;
281
282 len = strlen(path);
283 while (len && is_dir_sep(path[len - 1]))
284 len--;
285
286 for (name = path + len - 1; name > path; name--)
287 if (is_dir_sep(*name)) {
288 name++;
289 break;
290 }
291
292 *olen = len;
293 return name;
294}
295
d179af67
ES
296/* check that path is viable location for worktree */
297static void check_candidate_path(const char *path,
298 int force,
299 struct worktree **worktrees,
300 const char *cmd)
45059e64 301{
cb56f55c
ES
302 struct worktree *wt;
303 int locked;
304
45059e64
ES
305 if (file_exists(path) && !is_empty_dir(path))
306 die(_("'%s' already exists"), path);
cb56f55c 307
bb69b3b0 308 wt = find_worktree_by_path(worktrees, path);
cb56f55c 309 if (!wt)
d179af67 310 return;
cb56f55c 311
d236f12b 312 locked = !!worktree_lock_reason(wt);
d179af67 313 if ((!locked && force) || (locked && force > 1)) {
e19831c9 314 if (delete_git_dir(wt->id))
d179af67
ES
315 die(_("unusable worktree destination '%s'"), path);
316 return;
e19831c9
ES
317 }
318
cb56f55c 319 if (locked)
b86339b1 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);
cb56f55c 321 else
b86339b1 322 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
45059e64
ES
323}
324
ace5ac53
DS
325static void copy_sparse_checkout(const char *worktree_git_dir)
326{
327 char *from_file = git_pathdup("info/sparse-checkout");
328 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
329
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);
335 }
336
337 free(from_file);
338 free(to_file);
339}
340
86397053
DS
341static void copy_filtered_worktree_config(const char *worktree_git_dir)
342{
343 char *from_file = git_pathdup("config.worktree");
344 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
345
346 if (file_exists(from_file)) {
347 struct config_set cs = { { 0 } };
86397053
DS
348 int bare;
349
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;
355 }
356
357 git_configset_init(&cs);
358 git_configset_add_file(&cs, from_file);
359
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);
b83efcec 366 if (!git_configset_get(&cs, "core.worktree") &&
86397053
DS
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);
371
372 git_configset_clear(&cs);
373 }
374
375worktree_copy_cleanup:
376 free(from_file);
377 free(to_file);
378}
379
23f832e2
DS
380static int checkout_worktree(const struct add_opts *opts,
381 struct strvec *child_env)
382{
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");
29fda24d 388 strvec_pushv(&cp.env, child_env->v);
23f832e2
DS
389 return run_command(&cp);
390}
391
7ab89189
JA
392static int make_worktree_orphan(const char * ref, const struct add_opts *opts,
393 struct strvec *child_env)
394{
395 struct strbuf symref = STRBUF_INIT;
396 struct child_process cp = CHILD_PROCESS_INIT;
397
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);
406}
407
80a0548f 408static int add_worktree(const char *path, const char *refname,
5dd6e234 409 const struct add_opts *opts)
b979d950
ES
410{
411 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
3d7747e3 412 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
b979d950 413 const char *name;
542aa25d 414 struct child_process cp = CHILD_PROCESS_INIT;
22f9b7f3 415 struct strvec child_env = STRVEC_INIT;
7af01f23
MS
416 unsigned int counter = 0;
417 int len, ret;
f7c9dac1
ES
418 struct strbuf symref = STRBUF_INIT;
419 struct commit *commit = NULL;
ade546be 420 int is_branch = 0;
1de16aec 421 struct strbuf sb_name = STRBUF_INIT;
d179af67 422 struct worktree **worktrees;
b979d950 423
03f2465b 424 worktrees = get_worktrees();
d179af67
ES
425 check_candidate_path(path, opts->force, worktrees, "add");
426 free_worktrees(worktrees);
427 worktrees = NULL;
b979d950 428
f7c9dac1 429 /* is 'refname' a branch or commit? */
0ebf4a2a 430 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
ade546be
ES
431 ref_exists(symref.buf)) {
432 is_branch = 1;
f7c9dac1 433 if (!opts->force)
8d9fdd70 434 die_if_checked_out(symref.buf, 0);
f7c9dac1 435 }
ade546be 436 commit = lookup_commit_reference_by_name(refname);
7ab89189 437 if (!commit && !opts->orphan)
ade546be 438 die(_("invalid reference: %s"), refname);
f7c9dac1 439
f5682b2a 440 name = worktree_basename(path, &len);
1de16aec
NTND
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);
b979d950
ES
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);
7af01f23
MS
452
453 while (mkdir(sb_repo.buf, 0777)) {
b979d950 454 counter++;
7af01f23
MS
455 if ((errno != EEXIST) || !counter /* overflow */)
456 die_errno(_("could not create directory of '%s'"),
457 sb_repo.buf);
b979d950
ES
458 strbuf_setlen(&sb_repo, len);
459 strbuf_addf(&sb_repo, "%d", counter);
460 }
461 name = strrchr(sb_repo.buf, '/') + 1;
462
463 junk_pid = getpid();
464 atexit(remove_junk);
465 sigchain_push_common(remove_junk_on_signal);
466
b979d950
ES
467 junk_git_dir = xstrdup(sb_repo.buf);
468 is_junk = 1;
469
470 /*
471 * lock the incomplete repo so prune won't delete it, unlock
472 * after the preparation is over.
473 */
474 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
0db4961c
SM
475 if (opts->keep_locked)
476 write_file(sb.buf, "%s", opts->keep_locked);
507e6e9e 477 else
0db4961c 478 write_file(sb.buf, _("initializing"));
b979d950
ES
479
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);
485
486 strbuf_reset(&sb);
487 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
3d7747e3
AM
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);
1f76a10b 491 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
3d7747e3 492 realpath.buf, name);
b979d950
ES
493 /*
494 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
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.
b979d950 499 */
b979d950
ES
500 strbuf_reset(&sb);
501 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
14228447 502 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
b979d950
ES
503 strbuf_reset(&sb);
504 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 505 write_file(sb.buf, "../..");
b979d950 506
53255916
DS
507 /*
508 * If the current worktree has sparse-checkout enabled, then copy
509 * the sparse-checkout patterns from the current worktree.
510 */
ace5ac53
DS
511 if (core_apply_sparse_checkout)
512 copy_sparse_checkout(sb_repo.buf);
53255916
DS
513
514 /*
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.
518 */
86397053
DS
519 if (repository_format_worktree_config)
520 copy_filtered_worktree_config(sb_repo.buf);
53255916 521
22f9b7f3
JK
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);
b979d950 524 cp.git_cmd = 1;
7f44e3d1 525
7ab89189 526 if (!is_branch && commit) {
22f9b7f3 527 strvec_pushl(&cp.args, "update-ref", "HEAD",
f6d8942b 528 oid_to_hex(&commit->object.oid), NULL);
7ab89189 529 } else {
22f9b7f3 530 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
f6d8942b 531 symref.buf, NULL);
371979c2 532 if (opts->quiet)
22f9b7f3 533 strvec_push(&cp.args, "--quiet");
371979c2
EP
534 }
535
29fda24d 536 strvec_pushv(&cp.env, child_env.v);
7f44e3d1
ES
537 ret = run_command(&cp);
538 if (ret)
539 goto done;
540
7ab89189
JA
541 if (opts->orphan &&
542 (ret = make_worktree_orphan(refname, opts, &child_env)))
543 goto done;
544
23f832e2
DS
545 if (opts->checkout &&
546 (ret = checkout_worktree(opts, &child_env)))
547 goto done;
ef2a0ac9
RZ
548
549 is_junk = 0;
88ce3ef6
ÆAB
550 FREE_AND_NULL(junk_work_tree);
551 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 552
7f44e3d1 553done:
507e6e9e
NTND
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);
558 }
ade546be
ES
559
560 /*
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.
563 */
7ab89189 564 if (!ret && opts->checkout && !opts->orphan) {
1a3017d9
ES
565 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
566
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;
574
575 ret = run_hooks_opt("post-checkout", &opt);
a4bf1e3c 576 }
ade546be 577
22f9b7f3 578 strvec_clear(&child_env);
b979d950 579 strbuf_release(&sb);
f7c9dac1 580 strbuf_release(&symref);
b979d950
ES
581 strbuf_release(&sb_repo);
582 strbuf_release(&sb_git);
1de16aec 583 strbuf_release(&sb_name);
3d7747e3 584 strbuf_release(&realpath);
b979d950
ES
585 return ret;
586}
587
2c27002a
TG
588static void print_preparing_worktree_line(int detach,
589 const char *branch,
590 const char *new_branch,
591 int force_new_branch)
592{
593 if (force_new_branch) {
594 struct commit *commit = lookup_commit_reference_by_name(new_branch);
595 if (!commit)
da8fb6be 596 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a 597 else
da8fb6be 598 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
2c27002a 599 new_branch,
d850b7a5 600 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a 601 } else if (new_branch) {
da8fb6be 602 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a
TG
603 } else {
604 struct strbuf s = STRBUF_INIT;
605 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
606 ref_exists(s.buf))
da8fb6be 607 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
2c27002a
TG
608 branch);
609 else {
610 struct commit *commit = lookup_commit_reference_by_name(branch);
611 if (!commit)
7ab89189 612 BUG(_("unreachable: invalid reference: %s"), branch);
da8fb6be 613 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
d850b7a5 614 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a
TG
615 }
616 strbuf_release(&s);
617 }
618}
619
128e5496
JA
620/**
621 * Callback to short circuit iteration over refs on the first reference
622 * corresponding to a valid oid.
623 *
624 * Returns 0 on failure and non-zero on success.
625 */
626static int first_valid_ref(const char *refname,
627 const struct object_id *oid,
628 int flags,
629 void *cb_data)
630{
631 return 1;
632}
633
634/**
635 * Verifies HEAD and determines whether there exist any valid local references.
636 *
637 * - Checks whether HEAD points to a valid reference.
638 *
639 * - Checks whether any valid local branches exist.
640 *
926c40d0
JA
641 * - Emits a warning if there exist any valid branches but HEAD does not point
642 * to a valid reference.
643 *
128e5496
JA
644 * Returns 1 if any of the previous checks are true, otherwise returns 0.
645 */
646static int can_use_local_refs(const struct add_opts *opts)
647{
648 if (head_ref(first_valid_ref, NULL)) {
649 return 1;
650 } else if (for_each_branch_ref(first_valid_ref, NULL)) {
926c40d0
JA
651 if (!opts->quiet) {
652 struct strbuf path = STRBUF_INIT;
653 struct strbuf contents = STRBUF_INIT;
654
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");
660
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);
667 }
128e5496
JA
668 return 1;
669 }
670 return 0;
671}
672
673/**
674 * Reports whether the necessary flags were set and whether the repository has
675 * remote references to attempt DWIM tracking of upstream branches.
676 *
677 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
678 *
679 * 2. Checks whether any valid remote branches exist.
680 *
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`).
683 *
684 * Returns 1 if checks 1. and 2. are true, otherwise 0.
685 */
686static int can_use_remote_refs(const struct add_opts *opts)
687{
688 if (!guess_remote) {
128e5496
JA
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 overide or fetch a remote first"));
128e5496
JA
695 }
696 return 0;
697}
698
699/**
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.
704 *
705 * `opts` and `opt_track` contain the other options & flags supplied to the
706 * command.
707 *
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`.
710 *
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).
716 */
717static int dwim_orphan(const struct add_opts *opts, int opt_track, int remote)
718{
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);
725 }
726
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");
733 }
734 return 1;
735}
736
6427f871
TG
737static const char *dwim_branch(const char *path, const char **new_branch)
738{
739 int n;
aa1b6397 740 int branch_exists;
6427f871 741 const char *s = worktree_basename(path, &n);
f60a7b76
TG
742 const char *branchname = xstrndup(s, n);
743 struct strbuf ref = STRBUF_INIT;
744
745 UNLEAK(branchname);
aa1b6397
AH
746
747 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
748 ref_exists(ref.buf);
749 strbuf_release(&ref);
750 if (branch_exists)
f60a7b76 751 return branchname;
f60a7b76
TG
752
753 *new_branch = branchname;
6427f871
TG
754 if (guess_remote) {
755 struct object_id oid;
756 const char *remote =
3c87aa94 757 unique_tracking_name(*new_branch, &oid, NULL);
6427f871
TG
758 return remote;
759 }
760 return NULL;
761}
762
fc56361f
ES
763static int add(int ac, const char **av, const char *prefix)
764{
5dd6e234
ES
765 struct add_opts opts;
766 const char *new_branch_force = NULL;
e4da43b1
JK
767 char *path;
768 const char *branch;
d861d34a 769 const char *new_branch = NULL;
e284e892 770 const char *opt_track = NULL;
0db4961c
SM
771 const char *lock_reason = NULL;
772 int keep_locked = 0;
35f0383c 773 int used_new_branch_options;
fc56361f 774 struct option options[] = {
1224781d
NTND
775 OPT__FORCE(&opts.force,
776 N_("checkout <branch> even if already checked out in other worktree"),
fc3d4e0c 777 PARSE_OPT_NOCOMPLETE),
d861d34a 778 OPT_STRING('b', NULL, &new_branch, N_("branch"),
cbdf60fa
ES
779 N_("create a new branch")),
780 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
781 N_("create or reset a branch")),
7ab89189 782 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn/orphaned branch")),
c670aa47 783 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 784 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
0db4961c
SM
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")),
371979c2 788 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
e284e892
TG
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),
71d6682d
TG
792 OPT_BOOL(0, "guess-remote", &guess_remote,
793 N_("try to match the new branch name with a remote-tracking branch")),
fc56361f
ES
794 OPT_END()
795 };
ac95f5d3 796 int ret;
fc56361f 797
5dd6e234 798 memset(&opts, 0, sizeof(opts));
ef2a0ac9 799 opts.checkout = 1;
0afd556b 800 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
d861d34a 801 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
c4881829 802 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
7ab89189
JA
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>"));
0db4961c 814 if (lock_reason && !keep_locked)
6fa00ee8 815 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
0db4961c
SM
816 if (lock_reason)
817 opts.keep_locked = lock_reason;
818 else if (keep_locked)
819 opts.keep_locked = _("added with --lock");
820
0f4af3b9 821 if (ac < 1 || ac > 2)
0afd556b 822 usage_with_options(git_worktree_add_usage, options);
fc56361f 823
116fb64e 824 path = prefix_filename(prefix, av[0]);
0f4af3b9 825 branch = ac < 2 ? "HEAD" : av[1];
35f0383c 826 used_new_branch_options = new_branch || new_branch_force;
fc56361f 827
1a450e2f
JDG
828 if (!strcmp(branch, "-"))
829 branch = "@{-1}";
830
d861d34a 831 if (new_branch_force) {
beb6f24b
NTND
832 struct strbuf symref = STRBUF_INIT;
833
d861d34a 834 new_branch = new_branch_force;
eef005dc 835
beb6f24b 836 if (!opts.force &&
d861d34a 837 !strbuf_check_branch_ref(&symref, new_branch) &&
beb6f24b 838 ref_exists(symref.buf))
8d9fdd70 839 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
840 strbuf_release(&symref);
841 }
842
7ab89189
JA
843 if (opts.orphan && !new_branch) {
844 int n;
845 const char *s = worktree_basename(path, &n);
846 new_branch = xstrndup(s, n);
926c40d0 847 } else if (opts.orphan) {
7ab89189 848 // No-op
926c40d0
JA
849 } else if (opts.detach) {
850 // Check HEAD
851 if (!strcmp(branch, "HEAD"))
852 can_use_local_refs(&opts);
128e5496
JA
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);
7ab89189 856 } else if (ac < 2) {
128e5496 857 // DWIM: Guess branch name from path.
6427f871
TG
858 const char *s = dwim_branch(path, &new_branch);
859 if (s)
860 branch = s;
128e5496
JA
861
862 // DWIM: Infer --orphan when repo has no refs.
863 opts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);
7ab89189 864 } else if (ac == 2) {
4e853331
TG
865 struct object_id oid;
866 struct commit *commit;
867 const char *remote;
868
869 commit = lookup_commit_reference_by_name(branch);
870 if (!commit) {
3c87aa94 871 remote = unique_tracking_name(branch, &oid, NULL);
4e853331 872 if (remote) {
d861d34a 873 new_branch = branch;
4e853331
TG
874 branch = remote;
875 }
876 }
926c40d0
JA
877
878 if (!strcmp(branch, "HEAD"))
879 can_use_local_refs(&opts);
880
4e853331 881 }
7ab89189
JA
882
883 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
35f0383c
JA
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);
892 }
7ab89189
JA
893 die(_("invalid reference: %s"), branch);
894 }
895
371979c2
EP
896 if (!opts.quiet)
897 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
2c27002a 898
7ab89189
JA
899 if (opts.orphan) {
900 branch = new_branch;
901 } else if (new_branch) {
542aa25d 902 struct child_process cp = CHILD_PROCESS_INIT;
c2842439 903 cp.git_cmd = 1;
22f9b7f3 904 strvec_push(&cp.args, "branch");
d861d34a 905 if (new_branch_force)
22f9b7f3 906 strvec_push(&cp.args, "--force");
371979c2 907 if (opts.quiet)
22f9b7f3
JK
908 strvec_push(&cp.args, "--quiet");
909 strvec_push(&cp.args, new_branch);
910 strvec_push(&cp.args, branch);
e284e892 911 if (opt_track)
22f9b7f3 912 strvec_push(&cp.args, opt_track);
c2842439
ES
913 if (run_command(&cp))
914 return -1;
d861d34a 915 branch = new_branch;
e284e892
TG
916 } else if (opt_track) {
917 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
918 }
919
ac95f5d3
ÆAB
920 ret = add_worktree(path, branch, &opts);
921 free(path);
922 return ret;
fc56361f
ES
923}
924
d97eb302 925static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
bb9c03b8 926{
862c723d
RS
927 const char *reason;
928
d97eb302 929 printf("worktree %s%c", wt->path, line_terminator);
bb9c03b8 930 if (wt->is_bare)
d97eb302 931 printf("bare%c", line_terminator);
bb9c03b8 932 else {
d97eb302 933 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
bb9c03b8 934 if (wt->is_detached)
d97eb302 935 printf("detached%c", line_terminator);
a234563a 936 else if (wt->head_ref)
d97eb302 937 printf("branch %s%c", wt->head_ref, line_terminator);
bb9c03b8 938 }
862c723d
RS
939
940 reason = worktree_lock_reason(wt);
d97eb302
PW
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);
948 }
949 }
862c723d 950
9b19a58f
RS
951 reason = worktree_prune_reason(wt, expire);
952 if (reason)
d97eb302 953 printf("prunable %s%c", reason, line_terminator);
9b19a58f 954
d97eb302 955 fputc(line_terminator, stdout);
bb9c03b8
MR
956}
957
958static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
959{
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);
076b444a 963 const char *reason;
bb9c03b8
MR
964
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,
d850b7a5 970 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
96f09e2a 971 if (wt->is_detached)
bb9c03b8 972 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
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
a234563a 978 strbuf_addstr(&sb, "(error)");
bb9c03b8 979 }
bb9c03b8 980
076b444a
RS
981 reason = worktree_lock_reason(wt);
982 if (verbose && reason && *reason)
983 strbuf_addf(&sb, "\n\tlocked: %s", reason);
984 else if (reason)
c57b3367
RS
985 strbuf_addstr(&sb, " locked");
986
076b444a
RS
987 reason = worktree_prune_reason(wt, expire);
988 if (verbose && reason)
989 strbuf_addf(&sb, "\n\tprunable: %s", reason);
990 else if (reason)
9b19a58f
RS
991 strbuf_addstr(&sb, " prunable");
992
c57b3367 993 printf("%s\n", sb.buf);
bb9c03b8
MR
994 strbuf_release(&sb);
995}
996
997static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
998{
999 int i;
1000
1001 for (i = 0; wt[i]; i++) {
1002 int sha1_len;
1003 int path_len = strlen(wt[i]->path);
1004
1005 if (path_len > *maxlen)
1006 *maxlen = path_len;
d850b7a5 1007 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
bb9c03b8
MR
1008 if (sha1_len > *abbrev)
1009 *abbrev = sha1_len;
1010 }
1011}
1012
d9c54c2b
ES
1013static int pathcmp(const void *a_, const void *b_)
1014{
1015 const struct worktree *const *a = a_;
1016 const struct worktree *const *b = b_;
1017 return fspathcmp((*a)->path, (*b)->path);
1018}
1019
1020static void pathsort(struct worktree **wt)
1021{
1022 int n = 0;
1023 struct worktree **p = wt;
1024
1025 while (*p++)
1026 n++;
1027 QSORT(wt, n, pathcmp);
1028}
1029
bb9c03b8
MR
1030static int list(int ac, const char **av, const char *prefix)
1031{
1032 int porcelain = 0;
d97eb302 1033 int line_terminator = '\n';
bb9c03b8
MR
1034
1035 struct option options[] = {
1036 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
076b444a 1037 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
9b19a58f
RS
1038 OPT_EXPIRY_DATE(0, "expire", &expire,
1039 N_("add 'prunable' annotation to worktrees older than <time>")),
d97eb302
PW
1040 OPT_SET_INT('z', NULL, &line_terminator,
1041 N_("terminate records with a NUL character"), '\0'),
bb9c03b8
MR
1042 OPT_END()
1043 };
1044
9b19a58f 1045 expire = TIME_MAX;
0afd556b 1046 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
bb9c03b8 1047 if (ac)
0afd556b 1048 usage_with_options(git_worktree_list_usage, options);
076b444a 1049 else if (verbose && porcelain)
43ea635c 1050 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
d97eb302
PW
1051 else if (!line_terminator && !porcelain)
1052 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
bb9c03b8 1053 else {
03f2465b 1054 struct worktree **worktrees = get_worktrees();
bb9c03b8
MR
1055 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
1056
d9c54c2b
ES
1057 /* sort worktrees by path but keep main worktree at top */
1058 pathsort(worktrees + 1);
1059
bb9c03b8
MR
1060 if (!porcelain)
1061 measure_widths(worktrees, &abbrev, &path_maxlen);
1062
1063 for (i = 0; worktrees[i]; i++) {
1064 if (porcelain)
d97eb302
PW
1065 show_worktree_porcelain(worktrees[i],
1066 line_terminator);
bb9c03b8
MR
1067 else
1068 show_worktree(worktrees[i], path_maxlen, abbrev);
1069 }
1070 free_worktrees(worktrees);
1071 }
1072 return 0;
1073}
1074
58142c09
NTND
1075static int lock_worktree(int ac, const char **av, const char *prefix)
1076{
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()
1082 };
1083 struct worktree **worktrees, *wt;
1084
0afd556b 1085 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
58142c09 1086 if (ac != 1)
0afd556b 1087 usage_with_options(git_worktree_lock_usage, options);
58142c09 1088
03f2465b 1089 worktrees = get_worktrees();
58142c09
NTND
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"));
1095
d236f12b 1096 old_reason = worktree_lock_reason(wt);
58142c09
NTND
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]);
1102 }
1103
1104 write_file(git_common_path("worktrees/%s/locked", wt->id),
1105 "%s", reason);
1106 free_worktrees(worktrees);
1107 return 0;
1108}
1109
6d308627
NTND
1110static int unlock_worktree(int ac, const char **av, const char *prefix)
1111{
1112 struct option options[] = {
1113 OPT_END()
1114 };
1115 struct worktree **worktrees, *wt;
1116 int ret;
1117
0afd556b 1118 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
6d308627 1119 if (ac != 1)
0afd556b 1120 usage_with_options(git_worktree_unlock_usage, options);
6d308627 1121
03f2465b 1122 worktrees = get_worktrees();
6d308627
NTND
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"));
d236f12b 1128 if (!worktree_lock_reason(wt))
6d308627
NTND
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;
1133}
1134
78d986b2
NTND
1135static void validate_no_submodules(const struct worktree *wt)
1136{
6269f8ea 1137 struct index_state istate = INDEX_STATE_INIT(the_repository);
00a6d4d1 1138 struct strbuf path = STRBUF_INIT;
78d986b2
NTND
1139 int i, found_submodules = 0;
1140
00a6d4d1
NTND
1141 if (is_directory(worktree_git_path(wt, "modules"))) {
1142 /*
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.
1146 */
1147 found_submodules = 1;
1148 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1149 get_worktree_git_dir(wt)) > 0) {
78d986b2
NTND
1150 for (i = 0; i < istate.cache_nr; i++) {
1151 struct cache_entry *ce = istate.cache[i];
00a6d4d1 1152 int err;
78d986b2 1153
00a6d4d1
NTND
1154 if (!S_ISGITLINK(ce->ce_mode))
1155 continue;
1156
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;
1161
1162 found_submodules = 1;
1163 break;
78d986b2
NTND
1164 }
1165 }
1166 discard_index(&istate);
00a6d4d1 1167 strbuf_release(&path);
78d986b2
NTND
1168
1169 if (found_submodules)
cc73385c 1170 die(_("working trees containing submodules cannot be moved or removed"));
78d986b2
NTND
1171}
1172
9f792bb4
NTND
1173static int move_worktree(int ac, const char **av, const char *prefix)
1174{
68a6b3a1 1175 int force = 0;
9f792bb4 1176 struct option options[] = {
68a6b3a1
ES
1177 OPT__FORCE(&force,
1178 N_("force move even if worktree is dirty or locked"),
1179 PARSE_OPT_NOCOMPLETE),
9f792bb4
NTND
1180 OPT_END()
1181 };
1182 struct worktree **worktrees, *wt;
1183 struct strbuf dst = STRBUF_INIT;
1184 struct strbuf errmsg = STRBUF_INIT;
68a6b3a1 1185 const char *reason = NULL;
9f792bb4
NTND
1186 char *path;
1187
0afd556b
ÆAB
1188 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1189 0);
9f792bb4 1190 if (ac != 2)
0afd556b 1191 usage_with_options(git_worktree_move_usage, options);
9f792bb4
NTND
1192
1193 path = prefix_filename(prefix, av[1]);
1194 strbuf_addstr(&dst, path);
1195 free(path);
1196
03f2465b 1197 worktrees = get_worktrees();
9f792bb4
NTND
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]);
c64a8d20
NTND
1203 if (is_directory(dst.buf)) {
1204 const char *sep = find_last_dir_sep(wt->path);
1205
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);
1211 }
810382ed 1212 check_candidate_path(dst.buf, force, worktrees, "move");
9f792bb4 1213
78d986b2
NTND
1214 validate_no_submodules(wt);
1215
68a6b3a1 1216 if (force < 2)
d236f12b 1217 reason = worktree_lock_reason(wt);
9f792bb4
NTND
1218 if (reason) {
1219 if (*reason)
68a6b3a1 1220 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
9f792bb4 1221 reason);
68a6b3a1 1222 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
9f792bb4 1223 }
ee6763af 1224 if (validate_worktree(wt, &errmsg, 0))
9f792bb4
NTND
1225 die(_("validation failed, cannot move working tree: %s"),
1226 errmsg.buf);
1227 strbuf_release(&errmsg);
1228
1229 if (rename(wt->path, dst.buf) == -1)
1230 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1231
1232 update_worktree_location(wt, dst.buf);
1233
1234 strbuf_release(&dst);
1235 free_worktrees(worktrees);
1236 return 0;
1237}
1238
cc73385c
NTND
1239/*
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.
1244 *
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.
1249 */
1250static void check_clean_worktree(struct worktree *wt,
1251 const char *original_path)
1252{
cc73385c
NTND
1253 struct child_process cp;
1254 char buf[1];
1255 int ret;
1256
1257 /*
1258 * Until we sort this out, all submodules are "dirty" and
1259 * will abort this function.
1260 */
1261 validate_no_submodules(wt);
1262
27ed6ccc 1263 child_process_init(&cp);
29fda24d 1264 strvec_pushf(&cp.env, "%s=%s/.git",
f6d8942b 1265 GIT_DIR_ENVIRONMENT, wt->path);
29fda24d 1266 strvec_pushf(&cp.env, "%s=%s",
f6d8942b 1267 GIT_WORK_TREE_ENVIRONMENT, wt->path);
22f9b7f3 1268 strvec_pushl(&cp.args, "status",
f6d8942b
JK
1269 "--porcelain", "--ignore-submodules=none",
1270 NULL);
cc73385c
NTND
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)
507e5470 1280 die(_("'%s' contains modified or untracked files, use --force to delete it"),
cc73385c
NTND
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);
1287}
1288
1289static int delete_git_work_tree(struct worktree *wt)
1290{
1291 struct strbuf sb = STRBUF_INIT;
1292 int ret = 0;
1293
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;
1298 }
1299 strbuf_release(&sb);
1300 return ret;
1301}
1302
cc73385c
NTND
1303static int remove_worktree(int ac, const char **av, const char *prefix)
1304{
1305 int force = 0;
1306 struct option options[] = {
d228eea5 1307 OPT__FORCE(&force,
f4143101 1308 N_("force removal even if worktree is dirty or locked"),
d228eea5 1309 PARSE_OPT_NOCOMPLETE),
cc73385c
NTND
1310 OPT_END()
1311 };
1312 struct worktree **worktrees, *wt;
1313 struct strbuf errmsg = STRBUF_INIT;
f4143101 1314 const char *reason = NULL;
cc73385c
NTND
1315 int ret = 0;
1316
0afd556b 1317 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
cc73385c 1318 if (ac != 1)
0afd556b 1319 usage_with_options(git_worktree_remove_usage, options);
cc73385c 1320
03f2465b 1321 worktrees = get_worktrees();
cc73385c
NTND
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]);
f4143101 1327 if (force < 2)
d236f12b 1328 reason = worktree_lock_reason(wt);
cc73385c
NTND
1329 if (reason) {
1330 if (*reason)
f4143101 1331 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
cc73385c 1332 reason);
f4143101 1333 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
cc73385c 1334 }
ee6763af 1335 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
cc73385c
NTND
1336 die(_("validation failed, cannot remove working tree: %s"),
1337 errmsg.buf);
1338 strbuf_release(&errmsg);
1339
ee6763af
NTND
1340 if (file_exists(wt->path)) {
1341 if (!force)
1342 check_clean_worktree(wt, av[0]);
cc73385c 1343
ee6763af
NTND
1344 ret |= delete_git_work_tree(wt);
1345 }
cc73385c
NTND
1346 /*
1347 * continue on even if ret is non-zero, there's no going back
1348 * from here.
1349 */
602aaed0 1350 ret |= delete_git_dir(wt->id);
3a540433 1351 delete_worktrees_dir_if_empty();
cc73385c
NTND
1352
1353 free_worktrees(worktrees);
1354 return ret;
1355}
1356
bdd1f3e4
ES
1357static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1358{
1359 if (!iserr) {
da8fb6be 1360 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
bdd1f3e4
ES
1361 } else {
1362 int *exit_status = (int *)cb_data;
1363 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1364 *exit_status = 1;
1365 }
1366}
1367
e8e1ff24
ES
1368static int repair(int ac, const char **av, const char *prefix)
1369{
b214ab5a
ES
1370 const char **p;
1371 const char *self[] = { ".", NULL };
e8e1ff24
ES
1372 struct option options[] = {
1373 OPT_END()
1374 };
1375 int rc = 0;
1376
0afd556b 1377 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
b214ab5a
ES
1378 p = ac > 0 ? av : self;
1379 for (; *p; p++)
1380 repair_worktree_at_path(*p, report_repair, &rc);
cf76baea 1381 repair_worktrees(report_repair, &rc);
e8e1ff24
ES
1382 return rc;
1383}
1384
df0b6cfb
NTND
1385int cmd_worktree(int ac, const char **av, const char *prefix)
1386{
398c4ff5 1387 parse_opt_subcommand_fn *fn = NULL;
df0b6cfb 1388 struct option options[] = {
398c4ff5
SG
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),
df0b6cfb
NTND
1397 OPT_END()
1398 };
1399
e92445a7 1400 git_config(git_worktree_config, NULL);
d49028e6 1401
0409e0b6
NTND
1402 if (!prefix)
1403 prefix = "";
398c4ff5 1404
0afd556b 1405 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
398c4ff5 1406 return fn(ac, av, prefix);
df0b6cfb 1407}