at commit 2e8a9d94

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