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