at commit 997c1daf

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