]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/worktree.c
worktree add: introduce "try --orphan" hint
[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"
fc56361f 15#include "run-command.h"
5e3aba33 16#include "hook.h"
b979d950 17#include "sigchain.h"
00a6d4d1 18#include "submodule.h"
bb9c03b8
MR
19#include "utf8.h"
20#include "worktree.h"
d5ebb50d 21#include "wrapper.h"
862c723d 22#include "quote.h"
df0b6cfb 23
0afd556b 24#define BUILTIN_WORKTREE_ADD_USAGE \
97f03a56 25 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
7ab89189
JA
26 " [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]")
27
0afd556b 28#define BUILTIN_WORKTREE_LIST_USAGE \
97f03a56 29 N_("git worktree list [-v | --porcelain [-z]]")
0afd556b 30#define BUILTIN_WORKTREE_LOCK_USAGE \
97f03a56 31 N_("git worktree lock [--reason <string>] <worktree>")
0afd556b
ÆAB
32#define BUILTIN_WORKTREE_MOVE_USAGE \
33 N_("git worktree move <worktree> <new-path>")
34#define BUILTIN_WORKTREE_PRUNE_USAGE \
97f03a56 35 N_("git worktree prune [-n] [-v] [--expire <expire>]")
0afd556b 36#define BUILTIN_WORKTREE_REMOVE_USAGE \
97f03a56 37 N_("git worktree remove [-f] <worktree>")
0afd556b
ÆAB
38#define BUILTIN_WORKTREE_REPAIR_USAGE \
39 N_("git worktree repair [<path>...]")
40#define BUILTIN_WORKTREE_UNLOCK_USAGE \
41 N_("git worktree unlock <worktree>")
42
35f0383c
JA
43#define WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT \
44 _("If you meant to create a worktree containing a new orphan branch\n" \
45 "(branch with no commits) for this repository, you can do so\n" \
46 "using the --orphan flag:\n" \
47 "\n" \
48 " git worktree add --orphan -b %s %s\n")
49
50#define WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT \
51 _("If you meant to create a worktree containing a new orphan branch\n" \
52 "(branch with no commits) for this repository, you can do so\n" \
53 "using the --orphan flag:\n" \
54 "\n" \
55 " git worktree add --orphan %s\n")
56
0afd556b
ÆAB
57static const char * const git_worktree_usage[] = {
58 BUILTIN_WORKTREE_ADD_USAGE,
59 BUILTIN_WORKTREE_LIST_USAGE,
60 BUILTIN_WORKTREE_LOCK_USAGE,
61 BUILTIN_WORKTREE_MOVE_USAGE,
62 BUILTIN_WORKTREE_PRUNE_USAGE,
63 BUILTIN_WORKTREE_REMOVE_USAGE,
64 BUILTIN_WORKTREE_REPAIR_USAGE,
65 BUILTIN_WORKTREE_UNLOCK_USAGE,
66 NULL
67};
68
69static const char * const git_worktree_add_usage[] = {
70 BUILTIN_WORKTREE_ADD_USAGE,
71 NULL,
72};
73
74static const char * const git_worktree_list_usage[] = {
75 BUILTIN_WORKTREE_LIST_USAGE,
76 NULL
77};
78
79static const char * const git_worktree_lock_usage[] = {
80 BUILTIN_WORKTREE_LOCK_USAGE,
81 NULL
82};
83
84static const char * const git_worktree_move_usage[] = {
85 BUILTIN_WORKTREE_MOVE_USAGE,
86 NULL
87};
88
89static const char * const git_worktree_prune_usage[] = {
90 BUILTIN_WORKTREE_PRUNE_USAGE,
91 NULL
92};
93
94static const char * const git_worktree_remove_usage[] = {
95 BUILTIN_WORKTREE_REMOVE_USAGE,
96 NULL
97};
98
99static const char * const git_worktree_repair_usage[] = {
100 BUILTIN_WORKTREE_REPAIR_USAGE,
101 NULL
102};
103
104static const char * const git_worktree_unlock_usage[] = {
105 BUILTIN_WORKTREE_UNLOCK_USAGE,
df0b6cfb
NTND
106 NULL
107};
108
5dd6e234
ES
109struct add_opts {
110 int force;
111 int detach;
371979c2 112 int quiet;
ef2a0ac9 113 int checkout;
7ab89189 114 int orphan;
0db4961c 115 const char *keep_locked;
5dd6e234
ES
116};
117
df0b6cfb
NTND
118static int show_only;
119static int verbose;
e92445a7 120static int guess_remote;
dddbad72 121static timestamp_t expire;
df0b6cfb 122
e92445a7
TG
123static int git_worktree_config(const char *var, const char *value, void *cb)
124{
125 if (!strcmp(var, "worktree.guessremote")) {
126 guess_remote = git_config_bool(var, value);
127 return 0;
128 }
129
130 return git_default_config(var, value, cb);
131}
132
602aaed0 133static int delete_git_dir(const char *id)
e5353bef
ES
134{
135 struct strbuf sb = STRBUF_INIT;
602aaed0 136 int ret;
e5353bef 137
602aaed0
ES
138 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
139 ret = remove_dir_recursively(&sb, 0);
140 if (ret < 0 && errno == ENOTDIR)
141 ret = unlink(sb.buf);
142 if (ret)
e5353bef 143 error_errno(_("failed to delete '%s'"), sb.buf);
e5353bef
ES
144 strbuf_release(&sb);
145 return ret;
146}
147
3a540433
ES
148static void delete_worktrees_dir_if_empty(void)
149{
150 rmdir(git_path("worktrees")); /* ignore failed removal */
151}
152
dd9609a1
ES
153static void prune_worktree(const char *id, const char *reason)
154{
155 if (show_only || verbose)
da8fb6be 156 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
dd9609a1
ES
157 if (!show_only)
158 delete_git_dir(id);
159}
160
4a3ce479
ES
161static int prune_cmp(const void *a, const void *b)
162{
163 const struct string_list_item *x = a;
164 const struct string_list_item *y = b;
165 int c;
166
167 if ((c = fspathcmp(x->string, y->string)))
168 return c;
916133ef
ES
169 /*
170 * paths same; prune_dupes() removes all but the first worktree entry
171 * having the same path, so sort main worktree ('util' is NULL) above
172 * linked worktrees ('util' not NULL) since main worktree can't be
173 * removed
174 */
175 if (!x->util)
176 return -1;
177 if (!y->util)
178 return 1;
4a3ce479
ES
179 /* paths same; sort by .git/worktrees/<id> */
180 return strcmp(x->util, y->util);
181}
182
183static void prune_dups(struct string_list *l)
184{
185 int i;
186
187 QSORT(l->items, l->nr, prune_cmp);
188 for (i = 1; i < l->nr; i++) {
189 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
190 prune_worktree(l->items[i].util, "duplicate entry");
191 }
192}
193
df0b6cfb
NTND
194static void prune_worktrees(void)
195{
196 struct strbuf reason = STRBUF_INIT;
916133ef 197 struct strbuf main_path = STRBUF_INIT;
9f24f3c7 198 struct string_list kept = STRING_LIST_INIT_DUP;
df0b6cfb
NTND
199 DIR *dir = opendir(git_path("worktrees"));
200 struct dirent *d;
df0b6cfb
NTND
201 if (!dir)
202 return;
b548f0f1 203 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
4a3ce479 204 char *path;
df0b6cfb 205 strbuf_reset(&reason);
a29a8b75 206 if (should_prune_worktree(d->d_name, &reason, &path, expire))
4a3ce479
ES
207 prune_worktree(d->d_name, reason.buf);
208 else if (path)
9f24f3c7 209 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
df0b6cfb
NTND
210 }
211 closedir(dir);
4a3ce479 212
916133ef
ES
213 strbuf_add_absolute_path(&main_path, get_git_common_dir());
214 /* massage main worktree absolute path to match 'gitdir' content */
215 strbuf_strip_suffix(&main_path, "/.");
9f24f3c7 216 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
4a3ce479
ES
217 prune_dups(&kept);
218 string_list_clear(&kept, 1);
219
df0b6cfb 220 if (!show_only)
3a540433 221 delete_worktrees_dir_if_empty();
df0b6cfb 222 strbuf_release(&reason);
df0b6cfb
NTND
223}
224
225static int prune(int ac, const char **av, const char *prefix)
226{
227 struct option options[] = {
228 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
2488dcab 229 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
df0b6cfb 230 OPT_EXPIRY_DATE(0, "expire", &expire,
2488dcab 231 N_("expire working trees older than <time>")),
df0b6cfb
NTND
232 OPT_END()
233 };
234
dddbad72 235 expire = TIME_MAX;
0afd556b
ÆAB
236 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
237 0);
df0b6cfb 238 if (ac)
0afd556b 239 usage_with_options(git_worktree_prune_usage, options);
df0b6cfb
NTND
240 prune_worktrees();
241 return 0;
242}
243
b979d950
ES
244static char *junk_work_tree;
245static char *junk_git_dir;
246static int is_junk;
247static pid_t junk_pid;
248
249static void remove_junk(void)
250{
251 struct strbuf sb = STRBUF_INIT;
252 if (!is_junk || getpid() != junk_pid)
253 return;
254 if (junk_git_dir) {
255 strbuf_addstr(&sb, junk_git_dir);
256 remove_dir_recursively(&sb, 0);
257 strbuf_reset(&sb);
258 }
259 if (junk_work_tree) {
260 strbuf_addstr(&sb, junk_work_tree);
261 remove_dir_recursively(&sb, 0);
262 }
263 strbuf_release(&sb);
264}
265
266static void remove_junk_on_signal(int signo)
267{
268 remove_junk();
269 sigchain_pop(signo);
270 raise(signo);
271}
272
f5682b2a
ES
273static const char *worktree_basename(const char *path, int *olen)
274{
275 const char *name;
276 int len;
277
278 len = strlen(path);
279 while (len && is_dir_sep(path[len - 1]))
280 len--;
281
282 for (name = path + len - 1; name > path; name--)
283 if (is_dir_sep(*name)) {
284 name++;
285 break;
286 }
287
288 *olen = len;
289 return name;
290}
291
d179af67
ES
292/* check that path is viable location for worktree */
293static void check_candidate_path(const char *path,
294 int force,
295 struct worktree **worktrees,
296 const char *cmd)
45059e64 297{
cb56f55c
ES
298 struct worktree *wt;
299 int locked;
300
45059e64
ES
301 if (file_exists(path) && !is_empty_dir(path))
302 die(_("'%s' already exists"), path);
cb56f55c 303
bb69b3b0 304 wt = find_worktree_by_path(worktrees, path);
cb56f55c 305 if (!wt)
d179af67 306 return;
cb56f55c 307
d236f12b 308 locked = !!worktree_lock_reason(wt);
d179af67 309 if ((!locked && force) || (locked && force > 1)) {
e19831c9 310 if (delete_git_dir(wt->id))
d179af67
ES
311 die(_("unusable worktree destination '%s'"), path);
312 return;
e19831c9
ES
313 }
314
cb56f55c 315 if (locked)
b86339b1 316 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 317 else
b86339b1 318 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
45059e64
ES
319}
320
ace5ac53
DS
321static void copy_sparse_checkout(const char *worktree_git_dir)
322{
323 char *from_file = git_pathdup("info/sparse-checkout");
324 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
325
326 if (file_exists(from_file)) {
327 if (safe_create_leading_directories(to_file) ||
328 copy_file(to_file, from_file, 0666))
329 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
330 from_file, to_file);
331 }
332
333 free(from_file);
334 free(to_file);
335}
336
86397053
DS
337static void copy_filtered_worktree_config(const char *worktree_git_dir)
338{
339 char *from_file = git_pathdup("config.worktree");
340 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
341
342 if (file_exists(from_file)) {
343 struct config_set cs = { { 0 } };
86397053
DS
344 int bare;
345
346 if (safe_create_leading_directories(to_file) ||
347 copy_file(to_file, from_file, 0666)) {
348 error(_("failed to copy worktree config from '%s' to '%s'"),
349 from_file, to_file);
350 goto worktree_copy_cleanup;
351 }
352
353 git_configset_init(&cs);
354 git_configset_add_file(&cs, from_file);
355
356 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
357 bare &&
358 git_config_set_multivar_in_file_gently(
359 to_file, "core.bare", NULL, "true", 0))
360 error(_("failed to unset '%s' in '%s'"),
361 "core.bare", to_file);
b83efcec 362 if (!git_configset_get(&cs, "core.worktree") &&
86397053
DS
363 git_config_set_in_file_gently(to_file,
364 "core.worktree", NULL))
365 error(_("failed to unset '%s' in '%s'"),
366 "core.worktree", to_file);
367
368 git_configset_clear(&cs);
369 }
370
371worktree_copy_cleanup:
372 free(from_file);
373 free(to_file);
374}
375
23f832e2
DS
376static int checkout_worktree(const struct add_opts *opts,
377 struct strvec *child_env)
378{
379 struct child_process cp = CHILD_PROCESS_INIT;
380 cp.git_cmd = 1;
381 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
382 if (opts->quiet)
383 strvec_push(&cp.args, "--quiet");
29fda24d 384 strvec_pushv(&cp.env, child_env->v);
23f832e2
DS
385 return run_command(&cp);
386}
387
7ab89189
JA
388static int make_worktree_orphan(const char * ref, const struct add_opts *opts,
389 struct strvec *child_env)
390{
391 struct strbuf symref = STRBUF_INIT;
392 struct child_process cp = CHILD_PROCESS_INIT;
393
394 validate_new_branchname(ref, &symref, 0);
395 strvec_pushl(&cp.args, "symbolic-ref", "HEAD", symref.buf, NULL);
396 if (opts->quiet)
397 strvec_push(&cp.args, "--quiet");
398 strvec_pushv(&cp.env, child_env->v);
399 strbuf_release(&symref);
400 cp.git_cmd = 1;
401 return run_command(&cp);
402}
403
80a0548f 404static int add_worktree(const char *path, const char *refname,
5dd6e234 405 const struct add_opts *opts)
b979d950
ES
406{
407 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
3d7747e3 408 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
b979d950 409 const char *name;
542aa25d 410 struct child_process cp = CHILD_PROCESS_INIT;
22f9b7f3 411 struct strvec child_env = STRVEC_INIT;
7af01f23
MS
412 unsigned int counter = 0;
413 int len, ret;
f7c9dac1
ES
414 struct strbuf symref = STRBUF_INIT;
415 struct commit *commit = NULL;
ade546be 416 int is_branch = 0;
1de16aec 417 struct strbuf sb_name = STRBUF_INIT;
d179af67 418 struct worktree **worktrees;
b979d950 419
03f2465b 420 worktrees = get_worktrees();
d179af67
ES
421 check_candidate_path(path, opts->force, worktrees, "add");
422 free_worktrees(worktrees);
423 worktrees = NULL;
b979d950 424
f7c9dac1 425 /* is 'refname' a branch or commit? */
0ebf4a2a 426 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
ade546be
ES
427 ref_exists(symref.buf)) {
428 is_branch = 1;
f7c9dac1 429 if (!opts->force)
8d9fdd70 430 die_if_checked_out(symref.buf, 0);
f7c9dac1 431 }
ade546be 432 commit = lookup_commit_reference_by_name(refname);
7ab89189 433 if (!commit && !opts->orphan)
ade546be 434 die(_("invalid reference: %s"), refname);
f7c9dac1 435
f5682b2a 436 name = worktree_basename(path, &len);
1de16aec
NTND
437 strbuf_add(&sb, name, path + len - name);
438 sanitize_refname_component(sb.buf, &sb_name);
439 if (!sb_name.len)
440 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
441 strbuf_reset(&sb);
442 name = sb_name.buf;
443 git_path_buf(&sb_repo, "worktrees/%s", name);
b979d950
ES
444 len = sb_repo.len;
445 if (safe_create_leading_directories_const(sb_repo.buf))
446 die_errno(_("could not create leading directories of '%s'"),
447 sb_repo.buf);
7af01f23
MS
448
449 while (mkdir(sb_repo.buf, 0777)) {
b979d950 450 counter++;
7af01f23
MS
451 if ((errno != EEXIST) || !counter /* overflow */)
452 die_errno(_("could not create directory of '%s'"),
453 sb_repo.buf);
b979d950
ES
454 strbuf_setlen(&sb_repo, len);
455 strbuf_addf(&sb_repo, "%d", counter);
456 }
457 name = strrchr(sb_repo.buf, '/') + 1;
458
459 junk_pid = getpid();
460 atexit(remove_junk);
461 sigchain_push_common(remove_junk_on_signal);
462
b979d950
ES
463 junk_git_dir = xstrdup(sb_repo.buf);
464 is_junk = 1;
465
466 /*
467 * lock the incomplete repo so prune won't delete it, unlock
468 * after the preparation is over.
469 */
470 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
0db4961c
SM
471 if (opts->keep_locked)
472 write_file(sb.buf, "%s", opts->keep_locked);
507e6e9e 473 else
0db4961c 474 write_file(sb.buf, _("initializing"));
b979d950
ES
475
476 strbuf_addf(&sb_git, "%s/.git", path);
477 if (safe_create_leading_directories_const(sb_git.buf))
478 die_errno(_("could not create leading directories of '%s'"),
479 sb_git.buf);
480 junk_work_tree = xstrdup(path);
481
482 strbuf_reset(&sb);
483 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
3d7747e3
AM
484 strbuf_realpath(&realpath, sb_git.buf, 1);
485 write_file(sb.buf, "%s", realpath.buf);
486 strbuf_realpath(&realpath, get_git_common_dir(), 1);
1f76a10b 487 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
3d7747e3 488 realpath.buf, name);
b979d950
ES
489 /*
490 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
491 * or is_git_directory() will reject the directory. Any value which
492 * looks like an object ID will do since it will be immediately
493 * replaced by the symbolic-ref or update-ref invocation in the new
494 * worktree.
b979d950 495 */
b979d950
ES
496 strbuf_reset(&sb);
497 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
14228447 498 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
b979d950
ES
499 strbuf_reset(&sb);
500 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 501 write_file(sb.buf, "../..");
b979d950 502
53255916
DS
503 /*
504 * If the current worktree has sparse-checkout enabled, then copy
505 * the sparse-checkout patterns from the current worktree.
506 */
ace5ac53
DS
507 if (core_apply_sparse_checkout)
508 copy_sparse_checkout(sb_repo.buf);
53255916
DS
509
510 /*
511 * If we are using worktree config, then copy all current config
512 * values from the current worktree into the new one, that way the
513 * new worktree behaves the same as this one.
514 */
86397053
DS
515 if (repository_format_worktree_config)
516 copy_filtered_worktree_config(sb_repo.buf);
53255916 517
22f9b7f3
JK
518 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
519 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950 520 cp.git_cmd = 1;
7f44e3d1 521
7ab89189 522 if (!is_branch && commit) {
22f9b7f3 523 strvec_pushl(&cp.args, "update-ref", "HEAD",
f6d8942b 524 oid_to_hex(&commit->object.oid), NULL);
7ab89189 525 } else {
22f9b7f3 526 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
f6d8942b 527 symref.buf, NULL);
371979c2 528 if (opts->quiet)
22f9b7f3 529 strvec_push(&cp.args, "--quiet");
371979c2
EP
530 }
531
29fda24d 532 strvec_pushv(&cp.env, child_env.v);
7f44e3d1
ES
533 ret = run_command(&cp);
534 if (ret)
535 goto done;
536
7ab89189
JA
537 if (opts->orphan &&
538 (ret = make_worktree_orphan(refname, opts, &child_env)))
539 goto done;
540
23f832e2
DS
541 if (opts->checkout &&
542 (ret = checkout_worktree(opts, &child_env)))
543 goto done;
ef2a0ac9
RZ
544
545 is_junk = 0;
88ce3ef6
ÆAB
546 FREE_AND_NULL(junk_work_tree);
547 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 548
7f44e3d1 549done:
507e6e9e
NTND
550 if (ret || !opts->keep_locked) {
551 strbuf_reset(&sb);
552 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
553 unlink_or_warn(sb.buf);
554 }
ade546be
ES
555
556 /*
557 * Hook failure does not warrant worktree deletion, so run hook after
558 * is_junk is cleared, but do return appropriate code when hook fails.
559 */
7ab89189 560 if (!ret && opts->checkout && !opts->orphan) {
1a3017d9
ES
561 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
562
563 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
564 strvec_pushl(&opt.args,
565 oid_to_hex(null_oid()),
566 oid_to_hex(&commit->object.oid),
567 "1",
568 NULL);
569 opt.dir = path;
570
571 ret = run_hooks_opt("post-checkout", &opt);
a4bf1e3c 572 }
ade546be 573
22f9b7f3 574 strvec_clear(&child_env);
b979d950 575 strbuf_release(&sb);
f7c9dac1 576 strbuf_release(&symref);
b979d950
ES
577 strbuf_release(&sb_repo);
578 strbuf_release(&sb_git);
1de16aec 579 strbuf_release(&sb_name);
3d7747e3 580 strbuf_release(&realpath);
b979d950
ES
581 return ret;
582}
583
2c27002a
TG
584static void print_preparing_worktree_line(int detach,
585 const char *branch,
586 const char *new_branch,
587 int force_new_branch)
588{
589 if (force_new_branch) {
590 struct commit *commit = lookup_commit_reference_by_name(new_branch);
591 if (!commit)
da8fb6be 592 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a 593 else
da8fb6be 594 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
2c27002a 595 new_branch,
d850b7a5 596 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a 597 } else if (new_branch) {
da8fb6be 598 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a
TG
599 } else {
600 struct strbuf s = STRBUF_INIT;
601 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
602 ref_exists(s.buf))
da8fb6be 603 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
2c27002a
TG
604 branch);
605 else {
606 struct commit *commit = lookup_commit_reference_by_name(branch);
607 if (!commit)
7ab89189 608 BUG(_("unreachable: invalid reference: %s"), branch);
da8fb6be 609 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
d850b7a5 610 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a
TG
611 }
612 strbuf_release(&s);
613 }
614}
615
6427f871
TG
616static const char *dwim_branch(const char *path, const char **new_branch)
617{
618 int n;
aa1b6397 619 int branch_exists;
6427f871 620 const char *s = worktree_basename(path, &n);
f60a7b76
TG
621 const char *branchname = xstrndup(s, n);
622 struct strbuf ref = STRBUF_INIT;
623
624 UNLEAK(branchname);
aa1b6397
AH
625
626 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
627 ref_exists(ref.buf);
628 strbuf_release(&ref);
629 if (branch_exists)
f60a7b76 630 return branchname;
f60a7b76
TG
631
632 *new_branch = branchname;
6427f871
TG
633 if (guess_remote) {
634 struct object_id oid;
635 const char *remote =
3c87aa94 636 unique_tracking_name(*new_branch, &oid, NULL);
6427f871
TG
637 return remote;
638 }
639 return NULL;
640}
641
fc56361f
ES
642static int add(int ac, const char **av, const char *prefix)
643{
5dd6e234
ES
644 struct add_opts opts;
645 const char *new_branch_force = NULL;
e4da43b1
JK
646 char *path;
647 const char *branch;
d861d34a 648 const char *new_branch = NULL;
e284e892 649 const char *opt_track = NULL;
0db4961c
SM
650 const char *lock_reason = NULL;
651 int keep_locked = 0;
35f0383c 652 int used_new_branch_options;
fc56361f 653 struct option options[] = {
1224781d
NTND
654 OPT__FORCE(&opts.force,
655 N_("checkout <branch> even if already checked out in other worktree"),
fc3d4e0c 656 PARSE_OPT_NOCOMPLETE),
d861d34a 657 OPT_STRING('b', NULL, &new_branch, N_("branch"),
cbdf60fa
ES
658 N_("create a new branch")),
659 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
660 N_("create or reset a branch")),
7ab89189 661 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn/orphaned branch")),
c670aa47 662 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 663 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
0db4961c
SM
664 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
665 OPT_STRING(0, "reason", &lock_reason, N_("string"),
666 N_("reason for locking")),
371979c2 667 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
e284e892
TG
668 OPT_PASSTHRU(0, "track", &opt_track, NULL,
669 N_("set up tracking mode (see git-branch(1))"),
670 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
71d6682d
TG
671 OPT_BOOL(0, "guess-remote", &guess_remote,
672 N_("try to match the new branch name with a remote-tracking branch")),
fc56361f
ES
673 OPT_END()
674 };
ac95f5d3 675 int ret;
fc56361f 676
5dd6e234 677 memset(&opts, 0, sizeof(opts));
ef2a0ac9 678 opts.checkout = 1;
0afd556b 679 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
d861d34a 680 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
c4881829 681 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
7ab89189
JA
682 if (opts.detach && opts.orphan)
683 die(_("options '%s', and '%s' cannot be used together"),
684 "--orphan", "--detach");
685 if (opts.orphan && opt_track)
686 die(_("'%s' and '%s' cannot be used together"), "--orphan", "--track");
687 if (opts.orphan && !opts.checkout)
688 die(_("'%s' and '%s' cannot be used together"), "--orphan",
689 "--no-checkout");
690 if (opts.orphan && ac == 2)
691 die(_("'%s' and '%s' cannot be used together"), "--orphan",
692 _("<commit-ish>"));
0db4961c 693 if (lock_reason && !keep_locked)
6fa00ee8 694 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
0db4961c
SM
695 if (lock_reason)
696 opts.keep_locked = lock_reason;
697 else if (keep_locked)
698 opts.keep_locked = _("added with --lock");
699
0f4af3b9 700 if (ac < 1 || ac > 2)
0afd556b 701 usage_with_options(git_worktree_add_usage, options);
fc56361f 702
116fb64e 703 path = prefix_filename(prefix, av[0]);
0f4af3b9 704 branch = ac < 2 ? "HEAD" : av[1];
35f0383c 705 used_new_branch_options = new_branch || new_branch_force;
fc56361f 706
1a450e2f
JDG
707 if (!strcmp(branch, "-"))
708 branch = "@{-1}";
709
d861d34a 710 if (new_branch_force) {
beb6f24b
NTND
711 struct strbuf symref = STRBUF_INIT;
712
d861d34a 713 new_branch = new_branch_force;
eef005dc 714
beb6f24b 715 if (!opts.force &&
d861d34a 716 !strbuf_check_branch_ref(&symref, new_branch) &&
beb6f24b 717 ref_exists(symref.buf))
8d9fdd70 718 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
719 strbuf_release(&symref);
720 }
721
7ab89189
JA
722 if (opts.orphan && !new_branch) {
723 int n;
724 const char *s = worktree_basename(path, &n);
725 new_branch = xstrndup(s, n);
726 } else if (new_branch || opts.detach || opts.orphan) {
727 // No-op
728 } else if (ac < 2) {
6427f871
TG
729 const char *s = dwim_branch(path, &new_branch);
730 if (s)
731 branch = s;
7ab89189 732 } else if (ac == 2) {
4e853331
TG
733 struct object_id oid;
734 struct commit *commit;
735 const char *remote;
736
737 commit = lookup_commit_reference_by_name(branch);
738 if (!commit) {
3c87aa94 739 remote = unique_tracking_name(branch, &oid, NULL);
4e853331 740 if (remote) {
d861d34a 741 new_branch = branch;
4e853331
TG
742 branch = remote;
743 }
744 }
745 }
7ab89189
JA
746
747 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
35f0383c
JA
748 int attempt_hint = !opts.quiet && (ac < 2);
749 if (attempt_hint && used_new_branch_options) {
750 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
751 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT,
752 new_branch, path);
753 } else if (attempt_hint) {
754 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
755 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT, path);
756 }
7ab89189
JA
757 die(_("invalid reference: %s"), branch);
758 }
759
371979c2
EP
760 if (!opts.quiet)
761 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
2c27002a 762
7ab89189
JA
763 if (opts.orphan) {
764 branch = new_branch;
765 } else if (new_branch) {
542aa25d 766 struct child_process cp = CHILD_PROCESS_INIT;
c2842439 767 cp.git_cmd = 1;
22f9b7f3 768 strvec_push(&cp.args, "branch");
d861d34a 769 if (new_branch_force)
22f9b7f3 770 strvec_push(&cp.args, "--force");
371979c2 771 if (opts.quiet)
22f9b7f3
JK
772 strvec_push(&cp.args, "--quiet");
773 strvec_push(&cp.args, new_branch);
774 strvec_push(&cp.args, branch);
e284e892 775 if (opt_track)
22f9b7f3 776 strvec_push(&cp.args, opt_track);
c2842439
ES
777 if (run_command(&cp))
778 return -1;
d861d34a 779 branch = new_branch;
e284e892
TG
780 } else if (opt_track) {
781 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
782 }
783
ac95f5d3
ÆAB
784 ret = add_worktree(path, branch, &opts);
785 free(path);
786 return ret;
fc56361f
ES
787}
788
d97eb302 789static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
bb9c03b8 790{
862c723d
RS
791 const char *reason;
792
d97eb302 793 printf("worktree %s%c", wt->path, line_terminator);
bb9c03b8 794 if (wt->is_bare)
d97eb302 795 printf("bare%c", line_terminator);
bb9c03b8 796 else {
d97eb302 797 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
bb9c03b8 798 if (wt->is_detached)
d97eb302 799 printf("detached%c", line_terminator);
a234563a 800 else if (wt->head_ref)
d97eb302 801 printf("branch %s%c", wt->head_ref, line_terminator);
bb9c03b8 802 }
862c723d
RS
803
804 reason = worktree_lock_reason(wt);
d97eb302
PW
805 if (reason) {
806 fputs("locked", stdout);
807 if (*reason) {
808 fputc(' ', stdout);
809 write_name_quoted(reason, stdout, line_terminator);
810 } else {
811 fputc(line_terminator, stdout);
812 }
813 }
862c723d 814
9b19a58f
RS
815 reason = worktree_prune_reason(wt, expire);
816 if (reason)
d97eb302 817 printf("prunable %s%c", reason, line_terminator);
9b19a58f 818
d97eb302 819 fputc(line_terminator, stdout);
bb9c03b8
MR
820}
821
822static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
823{
824 struct strbuf sb = STRBUF_INIT;
825 int cur_path_len = strlen(wt->path);
826 int path_adj = cur_path_len - utf8_strwidth(wt->path);
076b444a 827 const char *reason;
bb9c03b8
MR
828
829 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
830 if (wt->is_bare)
831 strbuf_addstr(&sb, "(bare)");
832 else {
833 strbuf_addf(&sb, "%-*s ", abbrev_len,
d850b7a5 834 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
96f09e2a 835 if (wt->is_detached)
bb9c03b8 836 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
837 else if (wt->head_ref) {
838 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
839 strbuf_addf(&sb, "[%s]", ref);
840 free(ref);
841 } else
a234563a 842 strbuf_addstr(&sb, "(error)");
bb9c03b8 843 }
bb9c03b8 844
076b444a
RS
845 reason = worktree_lock_reason(wt);
846 if (verbose && reason && *reason)
847 strbuf_addf(&sb, "\n\tlocked: %s", reason);
848 else if (reason)
c57b3367
RS
849 strbuf_addstr(&sb, " locked");
850
076b444a
RS
851 reason = worktree_prune_reason(wt, expire);
852 if (verbose && reason)
853 strbuf_addf(&sb, "\n\tprunable: %s", reason);
854 else if (reason)
9b19a58f
RS
855 strbuf_addstr(&sb, " prunable");
856
c57b3367 857 printf("%s\n", sb.buf);
bb9c03b8
MR
858 strbuf_release(&sb);
859}
860
861static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
862{
863 int i;
864
865 for (i = 0; wt[i]; i++) {
866 int sha1_len;
867 int path_len = strlen(wt[i]->path);
868
869 if (path_len > *maxlen)
870 *maxlen = path_len;
d850b7a5 871 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
bb9c03b8
MR
872 if (sha1_len > *abbrev)
873 *abbrev = sha1_len;
874 }
875}
876
d9c54c2b
ES
877static int pathcmp(const void *a_, const void *b_)
878{
879 const struct worktree *const *a = a_;
880 const struct worktree *const *b = b_;
881 return fspathcmp((*a)->path, (*b)->path);
882}
883
884static void pathsort(struct worktree **wt)
885{
886 int n = 0;
887 struct worktree **p = wt;
888
889 while (*p++)
890 n++;
891 QSORT(wt, n, pathcmp);
892}
893
bb9c03b8
MR
894static int list(int ac, const char **av, const char *prefix)
895{
896 int porcelain = 0;
d97eb302 897 int line_terminator = '\n';
bb9c03b8
MR
898
899 struct option options[] = {
900 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
076b444a 901 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
9b19a58f
RS
902 OPT_EXPIRY_DATE(0, "expire", &expire,
903 N_("add 'prunable' annotation to worktrees older than <time>")),
d97eb302
PW
904 OPT_SET_INT('z', NULL, &line_terminator,
905 N_("terminate records with a NUL character"), '\0'),
bb9c03b8
MR
906 OPT_END()
907 };
908
9b19a58f 909 expire = TIME_MAX;
0afd556b 910 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
bb9c03b8 911 if (ac)
0afd556b 912 usage_with_options(git_worktree_list_usage, options);
076b444a 913 else if (verbose && porcelain)
43ea635c 914 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
d97eb302
PW
915 else if (!line_terminator && !porcelain)
916 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
bb9c03b8 917 else {
03f2465b 918 struct worktree **worktrees = get_worktrees();
bb9c03b8
MR
919 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
920
d9c54c2b
ES
921 /* sort worktrees by path but keep main worktree at top */
922 pathsort(worktrees + 1);
923
bb9c03b8
MR
924 if (!porcelain)
925 measure_widths(worktrees, &abbrev, &path_maxlen);
926
927 for (i = 0; worktrees[i]; i++) {
928 if (porcelain)
d97eb302
PW
929 show_worktree_porcelain(worktrees[i],
930 line_terminator);
bb9c03b8
MR
931 else
932 show_worktree(worktrees[i], path_maxlen, abbrev);
933 }
934 free_worktrees(worktrees);
935 }
936 return 0;
937}
938
58142c09
NTND
939static int lock_worktree(int ac, const char **av, const char *prefix)
940{
941 const char *reason = "", *old_reason;
942 struct option options[] = {
943 OPT_STRING(0, "reason", &reason, N_("string"),
944 N_("reason for locking")),
945 OPT_END()
946 };
947 struct worktree **worktrees, *wt;
948
0afd556b 949 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
58142c09 950 if (ac != 1)
0afd556b 951 usage_with_options(git_worktree_lock_usage, options);
58142c09 952
03f2465b 953 worktrees = get_worktrees();
58142c09
NTND
954 wt = find_worktree(worktrees, prefix, av[0]);
955 if (!wt)
956 die(_("'%s' is not a working tree"), av[0]);
957 if (is_main_worktree(wt))
958 die(_("The main working tree cannot be locked or unlocked"));
959
d236f12b 960 old_reason = worktree_lock_reason(wt);
58142c09
NTND
961 if (old_reason) {
962 if (*old_reason)
963 die(_("'%s' is already locked, reason: %s"),
964 av[0], old_reason);
965 die(_("'%s' is already locked"), av[0]);
966 }
967
968 write_file(git_common_path("worktrees/%s/locked", wt->id),
969 "%s", reason);
970 free_worktrees(worktrees);
971 return 0;
972}
973
6d308627
NTND
974static int unlock_worktree(int ac, const char **av, const char *prefix)
975{
976 struct option options[] = {
977 OPT_END()
978 };
979 struct worktree **worktrees, *wt;
980 int ret;
981
0afd556b 982 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
6d308627 983 if (ac != 1)
0afd556b 984 usage_with_options(git_worktree_unlock_usage, options);
6d308627 985
03f2465b 986 worktrees = get_worktrees();
6d308627
NTND
987 wt = find_worktree(worktrees, prefix, av[0]);
988 if (!wt)
989 die(_("'%s' is not a working tree"), av[0]);
990 if (is_main_worktree(wt))
991 die(_("The main working tree cannot be locked or unlocked"));
d236f12b 992 if (!worktree_lock_reason(wt))
6d308627
NTND
993 die(_("'%s' is not locked"), av[0]);
994 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
995 free_worktrees(worktrees);
996 return ret;
997}
998
78d986b2
NTND
999static void validate_no_submodules(const struct worktree *wt)
1000{
6269f8ea 1001 struct index_state istate = INDEX_STATE_INIT(the_repository);
00a6d4d1 1002 struct strbuf path = STRBUF_INIT;
78d986b2
NTND
1003 int i, found_submodules = 0;
1004
00a6d4d1
NTND
1005 if (is_directory(worktree_git_path(wt, "modules"))) {
1006 /*
1007 * There could be false positives, e.g. the "modules"
1008 * directory exists but is empty. But it's a rare case and
1009 * this simpler check is probably good enough for now.
1010 */
1011 found_submodules = 1;
1012 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1013 get_worktree_git_dir(wt)) > 0) {
78d986b2
NTND
1014 for (i = 0; i < istate.cache_nr; i++) {
1015 struct cache_entry *ce = istate.cache[i];
00a6d4d1 1016 int err;
78d986b2 1017
00a6d4d1
NTND
1018 if (!S_ISGITLINK(ce->ce_mode))
1019 continue;
1020
1021 strbuf_reset(&path);
1022 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
1023 if (!is_submodule_populated_gently(path.buf, &err))
1024 continue;
1025
1026 found_submodules = 1;
1027 break;
78d986b2
NTND
1028 }
1029 }
1030 discard_index(&istate);
00a6d4d1 1031 strbuf_release(&path);
78d986b2
NTND
1032
1033 if (found_submodules)
cc73385c 1034 die(_("working trees containing submodules cannot be moved or removed"));
78d986b2
NTND
1035}
1036
9f792bb4
NTND
1037static int move_worktree(int ac, const char **av, const char *prefix)
1038{
68a6b3a1 1039 int force = 0;
9f792bb4 1040 struct option options[] = {
68a6b3a1
ES
1041 OPT__FORCE(&force,
1042 N_("force move even if worktree is dirty or locked"),
1043 PARSE_OPT_NOCOMPLETE),
9f792bb4
NTND
1044 OPT_END()
1045 };
1046 struct worktree **worktrees, *wt;
1047 struct strbuf dst = STRBUF_INIT;
1048 struct strbuf errmsg = STRBUF_INIT;
68a6b3a1 1049 const char *reason = NULL;
9f792bb4
NTND
1050 char *path;
1051
0afd556b
ÆAB
1052 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1053 0);
9f792bb4 1054 if (ac != 2)
0afd556b 1055 usage_with_options(git_worktree_move_usage, options);
9f792bb4
NTND
1056
1057 path = prefix_filename(prefix, av[1]);
1058 strbuf_addstr(&dst, path);
1059 free(path);
1060
03f2465b 1061 worktrees = get_worktrees();
9f792bb4
NTND
1062 wt = find_worktree(worktrees, prefix, av[0]);
1063 if (!wt)
1064 die(_("'%s' is not a working tree"), av[0]);
1065 if (is_main_worktree(wt))
1066 die(_("'%s' is a main working tree"), av[0]);
c64a8d20
NTND
1067 if (is_directory(dst.buf)) {
1068 const char *sep = find_last_dir_sep(wt->path);
1069
1070 if (!sep)
1071 die(_("could not figure out destination name from '%s'"),
1072 wt->path);
1073 strbuf_trim_trailing_dir_sep(&dst);
1074 strbuf_addstr(&dst, sep);
1075 }
810382ed 1076 check_candidate_path(dst.buf, force, worktrees, "move");
9f792bb4 1077
78d986b2
NTND
1078 validate_no_submodules(wt);
1079
68a6b3a1 1080 if (force < 2)
d236f12b 1081 reason = worktree_lock_reason(wt);
9f792bb4
NTND
1082 if (reason) {
1083 if (*reason)
68a6b3a1 1084 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
9f792bb4 1085 reason);
68a6b3a1 1086 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
9f792bb4 1087 }
ee6763af 1088 if (validate_worktree(wt, &errmsg, 0))
9f792bb4
NTND
1089 die(_("validation failed, cannot move working tree: %s"),
1090 errmsg.buf);
1091 strbuf_release(&errmsg);
1092
1093 if (rename(wt->path, dst.buf) == -1)
1094 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1095
1096 update_worktree_location(wt, dst.buf);
1097
1098 strbuf_release(&dst);
1099 free_worktrees(worktrees);
1100 return 0;
1101}
1102
cc73385c
NTND
1103/*
1104 * Note, "git status --porcelain" is used to determine if it's safe to
1105 * delete a whole worktree. "git status" does not ignore user
1106 * configuration, so if a normal "git status" shows "clean" for the
1107 * user, then it's ok to remove it.
1108 *
1109 * This assumption may be a bad one. We may want to ignore
1110 * (potentially bad) user settings and only delete a worktree when
1111 * it's absolutely safe to do so from _our_ point of view because we
1112 * know better.
1113 */
1114static void check_clean_worktree(struct worktree *wt,
1115 const char *original_path)
1116{
cc73385c
NTND
1117 struct child_process cp;
1118 char buf[1];
1119 int ret;
1120
1121 /*
1122 * Until we sort this out, all submodules are "dirty" and
1123 * will abort this function.
1124 */
1125 validate_no_submodules(wt);
1126
27ed6ccc 1127 child_process_init(&cp);
29fda24d 1128 strvec_pushf(&cp.env, "%s=%s/.git",
f6d8942b 1129 GIT_DIR_ENVIRONMENT, wt->path);
29fda24d 1130 strvec_pushf(&cp.env, "%s=%s",
f6d8942b 1131 GIT_WORK_TREE_ENVIRONMENT, wt->path);
22f9b7f3 1132 strvec_pushl(&cp.args, "status",
f6d8942b
JK
1133 "--porcelain", "--ignore-submodules=none",
1134 NULL);
cc73385c
NTND
1135 cp.git_cmd = 1;
1136 cp.dir = wt->path;
1137 cp.out = -1;
1138 ret = start_command(&cp);
1139 if (ret)
1140 die_errno(_("failed to run 'git status' on '%s'"),
1141 original_path);
1142 ret = xread(cp.out, buf, sizeof(buf));
1143 if (ret)
507e5470 1144 die(_("'%s' contains modified or untracked files, use --force to delete it"),
cc73385c
NTND
1145 original_path);
1146 close(cp.out);
1147 ret = finish_command(&cp);
1148 if (ret)
1149 die_errno(_("failed to run 'git status' on '%s', code %d"),
1150 original_path, ret);
1151}
1152
1153static int delete_git_work_tree(struct worktree *wt)
1154{
1155 struct strbuf sb = STRBUF_INIT;
1156 int ret = 0;
1157
1158 strbuf_addstr(&sb, wt->path);
1159 if (remove_dir_recursively(&sb, 0)) {
1160 error_errno(_("failed to delete '%s'"), sb.buf);
1161 ret = -1;
1162 }
1163 strbuf_release(&sb);
1164 return ret;
1165}
1166
cc73385c
NTND
1167static int remove_worktree(int ac, const char **av, const char *prefix)
1168{
1169 int force = 0;
1170 struct option options[] = {
d228eea5 1171 OPT__FORCE(&force,
f4143101 1172 N_("force removal even if worktree is dirty or locked"),
d228eea5 1173 PARSE_OPT_NOCOMPLETE),
cc73385c
NTND
1174 OPT_END()
1175 };
1176 struct worktree **worktrees, *wt;
1177 struct strbuf errmsg = STRBUF_INIT;
f4143101 1178 const char *reason = NULL;
cc73385c
NTND
1179 int ret = 0;
1180
0afd556b 1181 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
cc73385c 1182 if (ac != 1)
0afd556b 1183 usage_with_options(git_worktree_remove_usage, options);
cc73385c 1184
03f2465b 1185 worktrees = get_worktrees();
cc73385c
NTND
1186 wt = find_worktree(worktrees, prefix, av[0]);
1187 if (!wt)
1188 die(_("'%s' is not a working tree"), av[0]);
1189 if (is_main_worktree(wt))
1190 die(_("'%s' is a main working tree"), av[0]);
f4143101 1191 if (force < 2)
d236f12b 1192 reason = worktree_lock_reason(wt);
cc73385c
NTND
1193 if (reason) {
1194 if (*reason)
f4143101 1195 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
cc73385c 1196 reason);
f4143101 1197 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
cc73385c 1198 }
ee6763af 1199 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
cc73385c
NTND
1200 die(_("validation failed, cannot remove working tree: %s"),
1201 errmsg.buf);
1202 strbuf_release(&errmsg);
1203
ee6763af
NTND
1204 if (file_exists(wt->path)) {
1205 if (!force)
1206 check_clean_worktree(wt, av[0]);
cc73385c 1207
ee6763af
NTND
1208 ret |= delete_git_work_tree(wt);
1209 }
cc73385c
NTND
1210 /*
1211 * continue on even if ret is non-zero, there's no going back
1212 * from here.
1213 */
602aaed0 1214 ret |= delete_git_dir(wt->id);
3a540433 1215 delete_worktrees_dir_if_empty();
cc73385c
NTND
1216
1217 free_worktrees(worktrees);
1218 return ret;
1219}
1220
bdd1f3e4
ES
1221static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1222{
1223 if (!iserr) {
da8fb6be 1224 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
bdd1f3e4
ES
1225 } else {
1226 int *exit_status = (int *)cb_data;
1227 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1228 *exit_status = 1;
1229 }
1230}
1231
e8e1ff24
ES
1232static int repair(int ac, const char **av, const char *prefix)
1233{
b214ab5a
ES
1234 const char **p;
1235 const char *self[] = { ".", NULL };
e8e1ff24
ES
1236 struct option options[] = {
1237 OPT_END()
1238 };
1239 int rc = 0;
1240
0afd556b 1241 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
b214ab5a
ES
1242 p = ac > 0 ? av : self;
1243 for (; *p; p++)
1244 repair_worktree_at_path(*p, report_repair, &rc);
cf76baea 1245 repair_worktrees(report_repair, &rc);
e8e1ff24
ES
1246 return rc;
1247}
1248
df0b6cfb
NTND
1249int cmd_worktree(int ac, const char **av, const char *prefix)
1250{
398c4ff5 1251 parse_opt_subcommand_fn *fn = NULL;
df0b6cfb 1252 struct option options[] = {
398c4ff5
SG
1253 OPT_SUBCOMMAND("add", &fn, add),
1254 OPT_SUBCOMMAND("prune", &fn, prune),
1255 OPT_SUBCOMMAND("list", &fn, list),
1256 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1257 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1258 OPT_SUBCOMMAND("move", &fn, move_worktree),
1259 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1260 OPT_SUBCOMMAND("repair", &fn, repair),
df0b6cfb
NTND
1261 OPT_END()
1262 };
1263
e92445a7 1264 git_config(git_worktree_config, NULL);
d49028e6 1265
0409e0b6
NTND
1266 if (!prefix)
1267 prefix = "";
398c4ff5 1268
0afd556b 1269 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
398c4ff5 1270 return fn(ac, av, prefix);
df0b6cfb 1271}