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