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