]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/worktree.c
config: add --comment option to add a comment
[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 51#define WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT \
d44b5171 52 _("If you meant to create a worktree containing a new unborn branch\n" \
35f0383c
JA
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 \
d44b5171 59 _("If you meant to create a worktree containing a new unborn branch\n" \
35f0383c
JA
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(
42d5c033 368 to_file, "core.bare", NULL, "true", NULL, 0))
86397053
DS
369 error(_("failed to unset '%s' in '%s'"),
370 "core.bare", to_file);
b83efcec 371 if (!git_configset_get(&cs, "core.worktree") &&
86397053 372 git_config_set_in_file_gently(to_file,
42d5c033 373 "core.worktree", NULL, NULL))
86397053
DS
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;
22f9b7f3 419 struct strvec child_env = STRVEC_INIT;
7af01f23
MS
420 unsigned int counter = 0;
421 int len, ret;
f7c9dac1
ES
422 struct strbuf symref = STRBUF_INIT;
423 struct commit *commit = NULL;
ade546be 424 int is_branch = 0;
1de16aec 425 struct strbuf sb_name = STRBUF_INIT;
8f4c00de
PS
426 struct worktree **worktrees, *wt = NULL;
427 struct ref_store *wt_refs;
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 strbuf_reset(&sb);
499 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 500 write_file(sb.buf, "../..");
b979d950 501
b979d950 502 /*
8f4c00de 503 * Set up the ref store of the worktree and create the HEAD reference.
b979d950 504 */
8f4c00de
PS
505 wt = get_linked_worktree(name, 1);
506 if (!wt) {
507 ret = error(_("could not find created worktree '%s'"), name);
508 goto done;
509 }
510 wt_refs = get_worktree_ref_store(wt);
511
512 ret = refs_init_db(wt_refs, REFS_INIT_DB_IS_WORKTREE, &sb);
513 if (ret)
514 goto done;
515
516 if (!is_branch && commit)
517 ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
518 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
519 else
520 ret = refs_create_symref(wt_refs, "HEAD", symref.buf, NULL);
521 if (ret)
522 goto done;
b979d950 523
53255916
DS
524 /*
525 * If the current worktree has sparse-checkout enabled, then copy
526 * the sparse-checkout patterns from the current worktree.
527 */
ace5ac53
DS
528 if (core_apply_sparse_checkout)
529 copy_sparse_checkout(sb_repo.buf);
53255916
DS
530
531 /*
532 * If we are using worktree config, then copy all current config
533 * values from the current worktree into the new one, that way the
534 * new worktree behaves the same as this one.
535 */
3867f6d6 536 if (the_repository->repository_format_worktree_config)
86397053 537 copy_filtered_worktree_config(sb_repo.buf);
53255916 538
22f9b7f3
JK
539 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
540 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
7f44e3d1 541
7ab89189
JA
542 if (opts->orphan &&
543 (ret = make_worktree_orphan(refname, opts, &child_env)))
544 goto done;
545
23f832e2
DS
546 if (opts->checkout &&
547 (ret = checkout_worktree(opts, &child_env)))
548 goto done;
ef2a0ac9
RZ
549
550 is_junk = 0;
88ce3ef6
ÆAB
551 FREE_AND_NULL(junk_work_tree);
552 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 553
7f44e3d1 554done:
507e6e9e
NTND
555 if (ret || !opts->keep_locked) {
556 strbuf_reset(&sb);
557 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
558 unlink_or_warn(sb.buf);
559 }
ade546be
ES
560
561 /*
562 * Hook failure does not warrant worktree deletion, so run hook after
563 * is_junk is cleared, but do return appropriate code when hook fails.
564 */
7ab89189 565 if (!ret && opts->checkout && !opts->orphan) {
1a3017d9
ES
566 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
567
568 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
569 strvec_pushl(&opt.args,
570 oid_to_hex(null_oid()),
571 oid_to_hex(&commit->object.oid),
572 "1",
573 NULL);
574 opt.dir = path;
575
576 ret = run_hooks_opt("post-checkout", &opt);
a4bf1e3c 577 }
ade546be 578
22f9b7f3 579 strvec_clear(&child_env);
b979d950 580 strbuf_release(&sb);
f7c9dac1 581 strbuf_release(&symref);
b979d950
ES
582 strbuf_release(&sb_repo);
583 strbuf_release(&sb_git);
1de16aec 584 strbuf_release(&sb_name);
3d7747e3 585 strbuf_release(&realpath);
8f4c00de 586 free_worktree(wt);
b979d950
ES
587 return ret;
588}
589
2c27002a
TG
590static void print_preparing_worktree_line(int detach,
591 const char *branch,
592 const char *new_branch,
593 int force_new_branch)
594{
595 if (force_new_branch) {
596 struct commit *commit = lookup_commit_reference_by_name(new_branch);
597 if (!commit)
da8fb6be 598 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a 599 else
da8fb6be 600 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
2c27002a 601 new_branch,
d850b7a5 602 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a 603 } else if (new_branch) {
da8fb6be 604 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
2c27002a
TG
605 } else {
606 struct strbuf s = STRBUF_INIT;
607 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
608 ref_exists(s.buf))
da8fb6be 609 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
2c27002a
TG
610 branch);
611 else {
612 struct commit *commit = lookup_commit_reference_by_name(branch);
613 if (!commit)
7ab89189 614 BUG(_("unreachable: invalid reference: %s"), branch);
da8fb6be 615 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
d850b7a5 616 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
2c27002a
TG
617 }
618 strbuf_release(&s);
619 }
620}
621
128e5496
JA
622/**
623 * Callback to short circuit iteration over refs on the first reference
624 * corresponding to a valid oid.
625 *
626 * Returns 0 on failure and non-zero on success.
627 */
bbfc4f53
JK
628static int first_valid_ref(const char *refname UNUSED,
629 const struct object_id *oid UNUSED,
630 int flags UNUSED,
631 void *cb_data UNUSED)
128e5496
JA
632{
633 return 1;
634}
635
636/**
637 * Verifies HEAD and determines whether there exist any valid local references.
638 *
639 * - Checks whether HEAD points to a valid reference.
640 *
641 * - Checks whether any valid local branches exist.
642 *
926c40d0
JA
643 * - Emits a warning if there exist any valid branches but HEAD does not point
644 * to a valid reference.
645 *
128e5496
JA
646 * Returns 1 if any of the previous checks are true, otherwise returns 0.
647 */
648static int can_use_local_refs(const struct add_opts *opts)
649{
650 if (head_ref(first_valid_ref, NULL)) {
651 return 1;
652 } else if (for_each_branch_ref(first_valid_ref, NULL)) {
926c40d0
JA
653 if (!opts->quiet) {
654 struct strbuf path = STRBUF_INIT;
655 struct strbuf contents = STRBUF_INIT;
656
657 strbuf_add_real_path(&path, get_worktree_git_dir(NULL));
658 strbuf_addstr(&path, "/HEAD");
659 strbuf_read_file(&contents, path.buf, 64);
660 strbuf_stripspace(&contents, 0);
661 strbuf_strip_suffix(&contents, "\n");
662
663 warning(_("HEAD points to an invalid (or orphaned) reference.\n"
664 "HEAD path: '%s'\n"
665 "HEAD contents: '%s'"),
666 path.buf, contents.buf);
667 strbuf_release(&path);
668 strbuf_release(&contents);
669 }
128e5496
JA
670 return 1;
671 }
672 return 0;
673}
674
675/**
676 * Reports whether the necessary flags were set and whether the repository has
677 * remote references to attempt DWIM tracking of upstream branches.
678 *
679 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
680 *
681 * 2. Checks whether any valid remote branches exist.
682 *
683 * 3. Checks that there exists at least one remote and emits a warning/error
684 * if both checks 1. and 2. are false (can be bypassed with `--force`).
685 *
686 * Returns 1 if checks 1. and 2. are true, otherwise 0.
687 */
688static int can_use_remote_refs(const struct add_opts *opts)
689{
690 if (!guess_remote) {
128e5496
JA
691 return 0;
692 } else if (for_each_remote_ref(first_valid_ref, NULL)) {
693 return 1;
694 } else if (!opts->force && remote_get(NULL)) {
695 die(_("No local or remote refs exist despite at least one remote\n"
fdc9914c 696 "present, stopping; use 'add -f' to override or fetch a remote first"));
128e5496
JA
697 }
698 return 0;
699}
700
701/**
702 * Determines whether `--orphan` should be inferred in the evaluation of
703 * `worktree add path/` or `worktree add -b branch path/` and emits an error
704 * if the supplied arguments would produce an illegal combination when the
705 * `--orphan` flag is included.
706 *
707 * `opts` and `opt_track` contain the other options & flags supplied to the
708 * command.
709 *
710 * remote determines whether to check `can_use_remote_refs()` or not. This
711 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
712 *
713 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
714 * `--orphan` is inferred but doing so produces an illegal combination of
715 * options and flags. Additionally produces an error when remote refs are
716 * checked and the repo is in a state that looks like the user added a remote
717 * but forgot to fetch (and did not override the warning with -f).
718 */
719static int dwim_orphan(const struct add_opts *opts, int opt_track, int remote)
720{
721 if (can_use_local_refs(opts)) {
722 return 0;
723 } else if (remote && can_use_remote_refs(opts)) {
724 return 0;
725 } else if (!opts->quiet) {
726 fprintf_ln(stderr, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT);
727 }
728
729 if (opt_track) {
62bc6dd3
RS
730 die(_("options '%s' and '%s' cannot be used together"),
731 "--orphan", "--track");
128e5496 732 } else if (!opts->checkout) {
62bc6dd3
RS
733 die(_("options '%s' and '%s' cannot be used together"),
734 "--orphan", "--no-checkout");
128e5496
JA
735 }
736 return 1;
737}
738
6427f871
TG
739static const char *dwim_branch(const char *path, const char **new_branch)
740{
741 int n;
aa1b6397 742 int branch_exists;
6427f871 743 const char *s = worktree_basename(path, &n);
f60a7b76
TG
744 const char *branchname = xstrndup(s, n);
745 struct strbuf ref = STRBUF_INIT;
746
747 UNLEAK(branchname);
aa1b6397
AH
748
749 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
750 ref_exists(ref.buf);
751 strbuf_release(&ref);
752 if (branch_exists)
f60a7b76 753 return branchname;
f60a7b76
TG
754
755 *new_branch = branchname;
6427f871
TG
756 if (guess_remote) {
757 struct object_id oid;
758 const char *remote =
3c87aa94 759 unique_tracking_name(*new_branch, &oid, NULL);
6427f871
TG
760 return remote;
761 }
762 return NULL;
763}
764
fc56361f
ES
765static int add(int ac, const char **av, const char *prefix)
766{
5dd6e234
ES
767 struct add_opts opts;
768 const char *new_branch_force = NULL;
e4da43b1
JK
769 char *path;
770 const char *branch;
d861d34a 771 const char *new_branch = NULL;
e284e892 772 const char *opt_track = NULL;
0db4961c
SM
773 const char *lock_reason = NULL;
774 int keep_locked = 0;
35f0383c 775 int used_new_branch_options;
fc56361f 776 struct option options[] = {
1224781d
NTND
777 OPT__FORCE(&opts.force,
778 N_("checkout <branch> even if already checked out in other worktree"),
fc3d4e0c 779 PARSE_OPT_NOCOMPLETE),
d861d34a 780 OPT_STRING('b', NULL, &new_branch, N_("branch"),
cbdf60fa
ES
781 N_("create a new branch")),
782 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
783 N_("create or reset a branch")),
d44b5171 784 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn branch")),
c670aa47 785 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 786 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
0db4961c
SM
787 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
788 OPT_STRING(0, "reason", &lock_reason, N_("string"),
789 N_("reason for locking")),
371979c2 790 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
e284e892
TG
791 OPT_PASSTHRU(0, "track", &opt_track, NULL,
792 N_("set up tracking mode (see git-branch(1))"),
793 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
71d6682d
TG
794 OPT_BOOL(0, "guess-remote", &guess_remote,
795 N_("try to match the new branch name with a remote-tracking branch")),
fc56361f
ES
796 OPT_END()
797 };
ac95f5d3 798 int ret;
fc56361f 799
5dd6e234 800 memset(&opts, 0, sizeof(opts));
ef2a0ac9 801 opts.checkout = 1;
0afd556b 802 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
d861d34a 803 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
c4881829 804 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
7ab89189 805 if (opts.detach && opts.orphan)
62bc6dd3 806 die(_("options '%s' and '%s' cannot be used together"),
7ab89189
JA
807 "--orphan", "--detach");
808 if (opts.orphan && opt_track)
62bc6dd3
RS
809 die(_("options '%s' and '%s' cannot be used together"),
810 "--orphan", "--track");
7ab89189 811 if (opts.orphan && !opts.checkout)
62bc6dd3
RS
812 die(_("options '%s' and '%s' cannot be used together"),
813 "--orphan", "--no-checkout");
7ab89189 814 if (opts.orphan && ac == 2)
792b8628
RS
815 die(_("option '%s' and commit-ish cannot be used together"),
816 "--orphan");
0db4961c 817 if (lock_reason && !keep_locked)
6fa00ee8 818 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
0db4961c
SM
819 if (lock_reason)
820 opts.keep_locked = lock_reason;
821 else if (keep_locked)
822 opts.keep_locked = _("added with --lock");
823
0f4af3b9 824 if (ac < 1 || ac > 2)
0afd556b 825 usage_with_options(git_worktree_add_usage, options);
fc56361f 826
116fb64e 827 path = prefix_filename(prefix, av[0]);
0f4af3b9 828 branch = ac < 2 ? "HEAD" : av[1];
35f0383c 829 used_new_branch_options = new_branch || new_branch_force;
fc56361f 830
1a450e2f
JDG
831 if (!strcmp(branch, "-"))
832 branch = "@{-1}";
833
d861d34a 834 if (new_branch_force) {
beb6f24b
NTND
835 struct strbuf symref = STRBUF_INIT;
836
d861d34a 837 new_branch = new_branch_force;
eef005dc 838
beb6f24b 839 if (!opts.force &&
d861d34a 840 !strbuf_check_branch_ref(&symref, new_branch) &&
beb6f24b 841 ref_exists(symref.buf))
8d9fdd70 842 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
843 strbuf_release(&symref);
844 }
845
7ab89189
JA
846 if (opts.orphan && !new_branch) {
847 int n;
848 const char *s = worktree_basename(path, &n);
849 new_branch = xstrndup(s, n);
926c40d0 850 } else if (opts.orphan) {
777f7838 851 ; /* no-op */
926c40d0 852 } else if (opts.detach) {
777f7838 853 /* Check HEAD */
926c40d0
JA
854 if (!strcmp(branch, "HEAD"))
855 can_use_local_refs(&opts);
128e5496 856 } else if (ac < 2 && new_branch) {
777f7838 857 /* DWIM: Infer --orphan when repo has no refs. */
128e5496 858 opts.orphan = dwim_orphan(&opts, !!opt_track, 0);
7ab89189 859 } else if (ac < 2) {
777f7838 860 /* DWIM: Guess branch name from path. */
6427f871
TG
861 const char *s = dwim_branch(path, &new_branch);
862 if (s)
863 branch = s;
1eb07d82 864
777f7838 865 /* DWIM: Infer --orphan when repo has no refs. */
128e5496 866 opts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);
7ab89189 867 } else if (ac == 2) {
4e853331
TG
868 struct object_id oid;
869 struct commit *commit;
870 const char *remote;
871
872 commit = lookup_commit_reference_by_name(branch);
873 if (!commit) {
3c87aa94 874 remote = unique_tracking_name(branch, &oid, NULL);
4e853331 875 if (remote) {
d861d34a 876 new_branch = branch;
4e853331
TG
877 branch = remote;
878 }
879 }
926c40d0
JA
880
881 if (!strcmp(branch, "HEAD"))
882 can_use_local_refs(&opts);
883
4e853331 884 }
7ab89189
JA
885
886 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
35f0383c
JA
887 int attempt_hint = !opts.quiet && (ac < 2);
888 if (attempt_hint && used_new_branch_options) {
889 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
890 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT,
891 new_branch, path);
892 } else if (attempt_hint) {
893 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
894 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT, path);
895 }
7ab89189
JA
896 die(_("invalid reference: %s"), branch);
897 }
898
371979c2
EP
899 if (!opts.quiet)
900 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
2c27002a 901
7ab89189
JA
902 if (opts.orphan) {
903 branch = new_branch;
904 } else if (new_branch) {
542aa25d 905 struct child_process cp = CHILD_PROCESS_INIT;
c2842439 906 cp.git_cmd = 1;
22f9b7f3 907 strvec_push(&cp.args, "branch");
d861d34a 908 if (new_branch_force)
22f9b7f3 909 strvec_push(&cp.args, "--force");
371979c2 910 if (opts.quiet)
22f9b7f3
JK
911 strvec_push(&cp.args, "--quiet");
912 strvec_push(&cp.args, new_branch);
913 strvec_push(&cp.args, branch);
e284e892 914 if (opt_track)
22f9b7f3 915 strvec_push(&cp.args, opt_track);
c2842439
ES
916 if (run_command(&cp))
917 return -1;
d861d34a 918 branch = new_branch;
e284e892
TG
919 } else if (opt_track) {
920 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
921 }
922
ac95f5d3
ÆAB
923 ret = add_worktree(path, branch, &opts);
924 free(path);
925 return ret;
fc56361f
ES
926}
927
d97eb302 928static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
bb9c03b8 929{
862c723d
RS
930 const char *reason;
931
d97eb302 932 printf("worktree %s%c", wt->path, line_terminator);
bb9c03b8 933 if (wt->is_bare)
d97eb302 934 printf("bare%c", line_terminator);
bb9c03b8 935 else {
d97eb302 936 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
bb9c03b8 937 if (wt->is_detached)
d97eb302 938 printf("detached%c", line_terminator);
a234563a 939 else if (wt->head_ref)
d97eb302 940 printf("branch %s%c", wt->head_ref, line_terminator);
bb9c03b8 941 }
862c723d
RS
942
943 reason = worktree_lock_reason(wt);
d97eb302
PW
944 if (reason) {
945 fputs("locked", stdout);
946 if (*reason) {
947 fputc(' ', stdout);
948 write_name_quoted(reason, stdout, line_terminator);
949 } else {
950 fputc(line_terminator, stdout);
951 }
952 }
862c723d 953
9b19a58f
RS
954 reason = worktree_prune_reason(wt, expire);
955 if (reason)
d97eb302 956 printf("prunable %s%c", reason, line_terminator);
9b19a58f 957
d97eb302 958 fputc(line_terminator, stdout);
bb9c03b8
MR
959}
960
961static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
962{
963 struct strbuf sb = STRBUF_INIT;
964 int cur_path_len = strlen(wt->path);
965 int path_adj = cur_path_len - utf8_strwidth(wt->path);
076b444a 966 const char *reason;
bb9c03b8
MR
967
968 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
969 if (wt->is_bare)
970 strbuf_addstr(&sb, "(bare)");
971 else {
972 strbuf_addf(&sb, "%-*s ", abbrev_len,
d850b7a5 973 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
96f09e2a 974 if (wt->is_detached)
bb9c03b8 975 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
976 else if (wt->head_ref) {
977 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
978 strbuf_addf(&sb, "[%s]", ref);
979 free(ref);
980 } else
a234563a 981 strbuf_addstr(&sb, "(error)");
bb9c03b8 982 }
bb9c03b8 983
076b444a
RS
984 reason = worktree_lock_reason(wt);
985 if (verbose && reason && *reason)
986 strbuf_addf(&sb, "\n\tlocked: %s", reason);
987 else if (reason)
c57b3367
RS
988 strbuf_addstr(&sb, " locked");
989
076b444a
RS
990 reason = worktree_prune_reason(wt, expire);
991 if (verbose && reason)
992 strbuf_addf(&sb, "\n\tprunable: %s", reason);
993 else if (reason)
9b19a58f
RS
994 strbuf_addstr(&sb, " prunable");
995
c57b3367 996 printf("%s\n", sb.buf);
bb9c03b8
MR
997 strbuf_release(&sb);
998}
999
1000static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
1001{
1002 int i;
1003
1004 for (i = 0; wt[i]; i++) {
1005 int sha1_len;
1006 int path_len = strlen(wt[i]->path);
1007
1008 if (path_len > *maxlen)
1009 *maxlen = path_len;
d850b7a5 1010 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
bb9c03b8
MR
1011 if (sha1_len > *abbrev)
1012 *abbrev = sha1_len;
1013 }
1014}
1015
d9c54c2b
ES
1016static int pathcmp(const void *a_, const void *b_)
1017{
1018 const struct worktree *const *a = a_;
1019 const struct worktree *const *b = b_;
1020 return fspathcmp((*a)->path, (*b)->path);
1021}
1022
1023static void pathsort(struct worktree **wt)
1024{
1025 int n = 0;
1026 struct worktree **p = wt;
1027
1028 while (*p++)
1029 n++;
1030 QSORT(wt, n, pathcmp);
1031}
1032
bb9c03b8
MR
1033static int list(int ac, const char **av, const char *prefix)
1034{
1035 int porcelain = 0;
d97eb302 1036 int line_terminator = '\n';
bb9c03b8
MR
1037
1038 struct option options[] = {
1039 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
076b444a 1040 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
9b19a58f
RS
1041 OPT_EXPIRY_DATE(0, "expire", &expire,
1042 N_("add 'prunable' annotation to worktrees older than <time>")),
d97eb302
PW
1043 OPT_SET_INT('z', NULL, &line_terminator,
1044 N_("terminate records with a NUL character"), '\0'),
bb9c03b8
MR
1045 OPT_END()
1046 };
1047
9b19a58f 1048 expire = TIME_MAX;
0afd556b 1049 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
bb9c03b8 1050 if (ac)
0afd556b 1051 usage_with_options(git_worktree_list_usage, options);
076b444a 1052 else if (verbose && porcelain)
43ea635c 1053 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
d97eb302
PW
1054 else if (!line_terminator && !porcelain)
1055 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
bb9c03b8 1056 else {
03f2465b 1057 struct worktree **worktrees = get_worktrees();
bb9c03b8
MR
1058 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
1059
d9c54c2b
ES
1060 /* sort worktrees by path but keep main worktree at top */
1061 pathsort(worktrees + 1);
1062
bb9c03b8
MR
1063 if (!porcelain)
1064 measure_widths(worktrees, &abbrev, &path_maxlen);
1065
1066 for (i = 0; worktrees[i]; i++) {
1067 if (porcelain)
d97eb302
PW
1068 show_worktree_porcelain(worktrees[i],
1069 line_terminator);
bb9c03b8
MR
1070 else
1071 show_worktree(worktrees[i], path_maxlen, abbrev);
1072 }
1073 free_worktrees(worktrees);
1074 }
1075 return 0;
1076}
1077
58142c09
NTND
1078static int lock_worktree(int ac, const char **av, const char *prefix)
1079{
1080 const char *reason = "", *old_reason;
1081 struct option options[] = {
1082 OPT_STRING(0, "reason", &reason, N_("string"),
1083 N_("reason for locking")),
1084 OPT_END()
1085 };
1086 struct worktree **worktrees, *wt;
1087
0afd556b 1088 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
58142c09 1089 if (ac != 1)
0afd556b 1090 usage_with_options(git_worktree_lock_usage, options);
58142c09 1091
03f2465b 1092 worktrees = get_worktrees();
58142c09
NTND
1093 wt = find_worktree(worktrees, prefix, av[0]);
1094 if (!wt)
1095 die(_("'%s' is not a working tree"), av[0]);
1096 if (is_main_worktree(wt))
1097 die(_("The main working tree cannot be locked or unlocked"));
1098
d236f12b 1099 old_reason = worktree_lock_reason(wt);
58142c09
NTND
1100 if (old_reason) {
1101 if (*old_reason)
1102 die(_("'%s' is already locked, reason: %s"),
1103 av[0], old_reason);
1104 die(_("'%s' is already locked"), av[0]);
1105 }
1106
1107 write_file(git_common_path("worktrees/%s/locked", wt->id),
1108 "%s", reason);
1109 free_worktrees(worktrees);
1110 return 0;
1111}
1112
6d308627
NTND
1113static int unlock_worktree(int ac, const char **av, const char *prefix)
1114{
1115 struct option options[] = {
1116 OPT_END()
1117 };
1118 struct worktree **worktrees, *wt;
1119 int ret;
1120
0afd556b 1121 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
6d308627 1122 if (ac != 1)
0afd556b 1123 usage_with_options(git_worktree_unlock_usage, options);
6d308627 1124
03f2465b 1125 worktrees = get_worktrees();
6d308627
NTND
1126 wt = find_worktree(worktrees, prefix, av[0]);
1127 if (!wt)
1128 die(_("'%s' is not a working tree"), av[0]);
1129 if (is_main_worktree(wt))
1130 die(_("The main working tree cannot be locked or unlocked"));
d236f12b 1131 if (!worktree_lock_reason(wt))
6d308627
NTND
1132 die(_("'%s' is not locked"), av[0]);
1133 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
1134 free_worktrees(worktrees);
1135 return ret;
1136}
1137
78d986b2
NTND
1138static void validate_no_submodules(const struct worktree *wt)
1139{
6269f8ea 1140 struct index_state istate = INDEX_STATE_INIT(the_repository);
00a6d4d1 1141 struct strbuf path = STRBUF_INIT;
78d986b2
NTND
1142 int i, found_submodules = 0;
1143
00a6d4d1
NTND
1144 if (is_directory(worktree_git_path(wt, "modules"))) {
1145 /*
1146 * There could be false positives, e.g. the "modules"
1147 * directory exists but is empty. But it's a rare case and
1148 * this simpler check is probably good enough for now.
1149 */
1150 found_submodules = 1;
1151 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1152 get_worktree_git_dir(wt)) > 0) {
78d986b2
NTND
1153 for (i = 0; i < istate.cache_nr; i++) {
1154 struct cache_entry *ce = istate.cache[i];
00a6d4d1 1155 int err;
78d986b2 1156
00a6d4d1
NTND
1157 if (!S_ISGITLINK(ce->ce_mode))
1158 continue;
1159
1160 strbuf_reset(&path);
1161 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
1162 if (!is_submodule_populated_gently(path.buf, &err))
1163 continue;
1164
1165 found_submodules = 1;
1166 break;
78d986b2
NTND
1167 }
1168 }
1169 discard_index(&istate);
00a6d4d1 1170 strbuf_release(&path);
78d986b2
NTND
1171
1172 if (found_submodules)
cc73385c 1173 die(_("working trees containing submodules cannot be moved or removed"));
78d986b2
NTND
1174}
1175
9f792bb4
NTND
1176static int move_worktree(int ac, const char **av, const char *prefix)
1177{
68a6b3a1 1178 int force = 0;
9f792bb4 1179 struct option options[] = {
68a6b3a1
ES
1180 OPT__FORCE(&force,
1181 N_("force move even if worktree is dirty or locked"),
1182 PARSE_OPT_NOCOMPLETE),
9f792bb4
NTND
1183 OPT_END()
1184 };
1185 struct worktree **worktrees, *wt;
1186 struct strbuf dst = STRBUF_INIT;
1187 struct strbuf errmsg = STRBUF_INIT;
68a6b3a1 1188 const char *reason = NULL;
9f792bb4
NTND
1189 char *path;
1190
0afd556b
ÆAB
1191 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1192 0);
9f792bb4 1193 if (ac != 2)
0afd556b 1194 usage_with_options(git_worktree_move_usage, options);
9f792bb4
NTND
1195
1196 path = prefix_filename(prefix, av[1]);
1197 strbuf_addstr(&dst, path);
1198 free(path);
1199
03f2465b 1200 worktrees = get_worktrees();
9f792bb4
NTND
1201 wt = find_worktree(worktrees, prefix, av[0]);
1202 if (!wt)
1203 die(_("'%s' is not a working tree"), av[0]);
1204 if (is_main_worktree(wt))
1205 die(_("'%s' is a main working tree"), av[0]);
c64a8d20
NTND
1206 if (is_directory(dst.buf)) {
1207 const char *sep = find_last_dir_sep(wt->path);
1208
1209 if (!sep)
1210 die(_("could not figure out destination name from '%s'"),
1211 wt->path);
1212 strbuf_trim_trailing_dir_sep(&dst);
1213 strbuf_addstr(&dst, sep);
1214 }
810382ed 1215 check_candidate_path(dst.buf, force, worktrees, "move");
9f792bb4 1216
78d986b2
NTND
1217 validate_no_submodules(wt);
1218
68a6b3a1 1219 if (force < 2)
d236f12b 1220 reason = worktree_lock_reason(wt);
9f792bb4
NTND
1221 if (reason) {
1222 if (*reason)
68a6b3a1 1223 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
9f792bb4 1224 reason);
68a6b3a1 1225 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
9f792bb4 1226 }
ee6763af 1227 if (validate_worktree(wt, &errmsg, 0))
9f792bb4
NTND
1228 die(_("validation failed, cannot move working tree: %s"),
1229 errmsg.buf);
1230 strbuf_release(&errmsg);
1231
1232 if (rename(wt->path, dst.buf) == -1)
1233 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1234
1235 update_worktree_location(wt, dst.buf);
1236
1237 strbuf_release(&dst);
1238 free_worktrees(worktrees);
1239 return 0;
1240}
1241
cc73385c
NTND
1242/*
1243 * Note, "git status --porcelain" is used to determine if it's safe to
1244 * delete a whole worktree. "git status" does not ignore user
1245 * configuration, so if a normal "git status" shows "clean" for the
1246 * user, then it's ok to remove it.
1247 *
1248 * This assumption may be a bad one. We may want to ignore
1249 * (potentially bad) user settings and only delete a worktree when
1250 * it's absolutely safe to do so from _our_ point of view because we
1251 * know better.
1252 */
1253static void check_clean_worktree(struct worktree *wt,
1254 const char *original_path)
1255{
cc73385c
NTND
1256 struct child_process cp;
1257 char buf[1];
1258 int ret;
1259
1260 /*
1261 * Until we sort this out, all submodules are "dirty" and
1262 * will abort this function.
1263 */
1264 validate_no_submodules(wt);
1265
27ed6ccc 1266 child_process_init(&cp);
29fda24d 1267 strvec_pushf(&cp.env, "%s=%s/.git",
f6d8942b 1268 GIT_DIR_ENVIRONMENT, wt->path);
29fda24d 1269 strvec_pushf(&cp.env, "%s=%s",
f6d8942b 1270 GIT_WORK_TREE_ENVIRONMENT, wt->path);
22f9b7f3 1271 strvec_pushl(&cp.args, "status",
f6d8942b
JK
1272 "--porcelain", "--ignore-submodules=none",
1273 NULL);
cc73385c
NTND
1274 cp.git_cmd = 1;
1275 cp.dir = wt->path;
1276 cp.out = -1;
1277 ret = start_command(&cp);
1278 if (ret)
1279 die_errno(_("failed to run 'git status' on '%s'"),
1280 original_path);
1281 ret = xread(cp.out, buf, sizeof(buf));
1282 if (ret)
507e5470 1283 die(_("'%s' contains modified or untracked files, use --force to delete it"),
cc73385c
NTND
1284 original_path);
1285 close(cp.out);
1286 ret = finish_command(&cp);
1287 if (ret)
1288 die_errno(_("failed to run 'git status' on '%s', code %d"),
1289 original_path, ret);
1290}
1291
1292static int delete_git_work_tree(struct worktree *wt)
1293{
1294 struct strbuf sb = STRBUF_INIT;
1295 int ret = 0;
1296
1297 strbuf_addstr(&sb, wt->path);
1298 if (remove_dir_recursively(&sb, 0)) {
1299 error_errno(_("failed to delete '%s'"), sb.buf);
1300 ret = -1;
1301 }
1302 strbuf_release(&sb);
1303 return ret;
1304}
1305
cc73385c
NTND
1306static int remove_worktree(int ac, const char **av, const char *prefix)
1307{
1308 int force = 0;
1309 struct option options[] = {
d228eea5 1310 OPT__FORCE(&force,
f4143101 1311 N_("force removal even if worktree is dirty or locked"),
d228eea5 1312 PARSE_OPT_NOCOMPLETE),
cc73385c
NTND
1313 OPT_END()
1314 };
1315 struct worktree **worktrees, *wt;
1316 struct strbuf errmsg = STRBUF_INIT;
f4143101 1317 const char *reason = NULL;
cc73385c
NTND
1318 int ret = 0;
1319
0afd556b 1320 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
cc73385c 1321 if (ac != 1)
0afd556b 1322 usage_with_options(git_worktree_remove_usage, options);
cc73385c 1323
03f2465b 1324 worktrees = get_worktrees();
cc73385c
NTND
1325 wt = find_worktree(worktrees, prefix, av[0]);
1326 if (!wt)
1327 die(_("'%s' is not a working tree"), av[0]);
1328 if (is_main_worktree(wt))
1329 die(_("'%s' is a main working tree"), av[0]);
f4143101 1330 if (force < 2)
d236f12b 1331 reason = worktree_lock_reason(wt);
cc73385c
NTND
1332 if (reason) {
1333 if (*reason)
f4143101 1334 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
cc73385c 1335 reason);
f4143101 1336 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
cc73385c 1337 }
ee6763af 1338 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
cc73385c
NTND
1339 die(_("validation failed, cannot remove working tree: %s"),
1340 errmsg.buf);
1341 strbuf_release(&errmsg);
1342
ee6763af
NTND
1343 if (file_exists(wt->path)) {
1344 if (!force)
1345 check_clean_worktree(wt, av[0]);
cc73385c 1346
ee6763af
NTND
1347 ret |= delete_git_work_tree(wt);
1348 }
cc73385c
NTND
1349 /*
1350 * continue on even if ret is non-zero, there's no going back
1351 * from here.
1352 */
602aaed0 1353 ret |= delete_git_dir(wt->id);
3a540433 1354 delete_worktrees_dir_if_empty();
cc73385c
NTND
1355
1356 free_worktrees(worktrees);
1357 return ret;
1358}
1359
bdd1f3e4
ES
1360static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1361{
1362 if (!iserr) {
da8fb6be 1363 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
bdd1f3e4
ES
1364 } else {
1365 int *exit_status = (int *)cb_data;
1366 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1367 *exit_status = 1;
1368 }
1369}
1370
e8e1ff24
ES
1371static int repair(int ac, const char **av, const char *prefix)
1372{
b214ab5a
ES
1373 const char **p;
1374 const char *self[] = { ".", NULL };
e8e1ff24
ES
1375 struct option options[] = {
1376 OPT_END()
1377 };
1378 int rc = 0;
1379
0afd556b 1380 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
b214ab5a
ES
1381 p = ac > 0 ? av : self;
1382 for (; *p; p++)
1383 repair_worktree_at_path(*p, report_repair, &rc);
cf76baea 1384 repair_worktrees(report_repair, &rc);
e8e1ff24
ES
1385 return rc;
1386}
1387
df0b6cfb
NTND
1388int cmd_worktree(int ac, const char **av, const char *prefix)
1389{
398c4ff5 1390 parse_opt_subcommand_fn *fn = NULL;
df0b6cfb 1391 struct option options[] = {
398c4ff5
SG
1392 OPT_SUBCOMMAND("add", &fn, add),
1393 OPT_SUBCOMMAND("prune", &fn, prune),
1394 OPT_SUBCOMMAND("list", &fn, list),
1395 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1396 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1397 OPT_SUBCOMMAND("move", &fn, move_worktree),
1398 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1399 OPT_SUBCOMMAND("repair", &fn, repair),
df0b6cfb
NTND
1400 OPT_END()
1401 };
1402
e92445a7 1403 git_config(git_worktree_config, NULL);
d49028e6 1404
0409e0b6
NTND
1405 if (!prefix)
1406 prefix = "";
398c4ff5 1407
0afd556b 1408 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
8fac776f
SL
1409
1410 prepare_repo_settings(the_repository);
1411 the_repository->settings.command_requires_full_index = 0;
1412
398c4ff5 1413 return fn(ac, av, prefix);
df0b6cfb 1414}