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