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