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