at commit b70101c2

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 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(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(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();
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(&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(sb_git.buf, sb.buf, opts->relative_paths);
543 strbuf_reset(&sb);
544 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
545 write_file(sb.buf, "../..");
546
547 /*
548 * Set up the ref store of the worktree and create the HEAD reference.
549 */
550 wt = get_linked_worktree(name, 1);
551 if (!wt) {
552 ret = error(_("could not find created worktree '%s'"), name);
553 goto done;
554 }
555 setup_alternate_ref_dir(wt, sb_repo.buf);
556 wt_refs = get_worktree_ref_store(wt);
557
558 ret = ref_store_create_on_disk(wt_refs, REF_STORE_CREATE_ON_DISK_IS_WORKTREE, &sb);
559 if (ret)
560 goto done;
561
562 if (!is_branch && commit)
563 ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
564 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
565 else
566 ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
567 if (ret)
568 goto done;
569
570 /*
571 * If the current worktree has sparse-checkout enabled, then copy
572 * the sparse-checkout patterns from the current worktree.
573 */
574 if (cfg->apply_sparse_checkout)
575 copy_sparse_checkout(sb_repo.buf);
576
577 /*
578 * If we are using worktree config, then copy all current config
579 * values from the current worktree into the new one, that way the
580 * new worktree behaves the same as this one.
581 */
582 if (the_repository->repository_format_worktree_config)
583 copy_filtered_worktree_config(sb_repo.buf);
584
585 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
586 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
587
588 if (opts->orphan &&
589 (ret = make_worktree_orphan(refname, opts, &child_env)))
590 goto done;
591
592 if (opts->checkout &&
593 (ret = checkout_worktree(opts, &child_env)))
594 goto done;
595
596 is_junk = 0;
597 FREE_AND_NULL(junk_work_tree);
598 FREE_AND_NULL(junk_git_dir);
599
600 done:
601 if (ret || !opts->keep_locked) {
602 strbuf_reset(&sb);
603 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
604 unlink_or_warn(sb.buf);
605 }
606
607 /*
608 * Hook failure does not warrant worktree deletion, so run hook after
609 * is_junk is cleared, but do return appropriate code when hook fails.
610 */
611 if (!ret && opts->checkout && !opts->orphan) {
612 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT_FORCE_SERIAL;
613
614 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
615 strvec_pushl(&opt.args,
616 oid_to_hex(null_oid(the_hash_algo)),
617 oid_to_hex(&commit->object.oid),
618 "1",
619 NULL);
620 opt.dir = path;
621
622 ret = run_hooks_opt(the_repository, "post-checkout", &opt);
623 }
624
625 strvec_clear(&child_env);
626 strbuf_release(&sb);
627 strbuf_release(&symref);
628 strbuf_release(&sb_repo);
629 strbuf_release(&sb_git);
630 strbuf_release(&sb_name);
631 free_worktree(wt);
632 return ret;
633 }
634
635 static void print_preparing_worktree_line(int detach,
636 const char *branch,
637 const char *new_branch,
638 int force_new_branch)
639 {
640 if (force_new_branch) {
641 struct commit *commit = lookup_commit_reference_by_name(new_branch);
642 if (!commit)
643 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
644 else
645 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
646 new_branch,
647 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
648 } else if (new_branch) {
649 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
650 } else {
651 struct strbuf s = STRBUF_INIT;
652 if (!detach && !check_branch_ref(&s, branch) &&
653 refs_ref_exists(get_main_ref_store(the_repository), s.buf))
654 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
655 branch);
656 else {
657 struct commit *commit = lookup_commit_reference_by_name(branch);
658 if (!commit)
659 BUG("unreachable: invalid reference: %s", branch);
660 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
661 repo_find_unique_abbrev(the_repository, &commit->object.oid, DEFAULT_ABBREV));
662 }
663 strbuf_release(&s);
664 }
665 }
666
667 /**
668 * Callback to short circuit iteration over refs on the first reference
669 * corresponding to a valid oid.
670 *
671 * Returns 0 on failure and non-zero on success.
672 */
673 static int first_valid_ref(const struct reference *ref UNUSED, void *cb_data UNUSED)
674 {
675 return 1;
676 }
677
678 /**
679 * Verifies HEAD and determines whether there exist any valid local references.
680 *
681 * - Checks whether HEAD points to a valid reference.
682 *
683 * - Checks whether any valid local branches exist.
684 *
685 * - Emits a warning if there exist any valid branches but HEAD does not point
686 * to a valid reference.
687 *
688 * Returns 1 if any of the previous checks are true, otherwise returns 0.
689 */
690 static int can_use_local_refs(const struct add_opts *opts)
691 {
692 if (refs_head_ref(get_main_ref_store(the_repository), first_valid_ref, NULL)) {
693 return 1;
694 } else if (refs_for_each_branch_ref(get_main_ref_store(the_repository), first_valid_ref, NULL)) {
695 if (!opts->quiet)
696 warning(_("HEAD points to an invalid (or orphaned) reference.\n"));
697 return 1;
698 }
699 return 0;
700 }
701
702 /**
703 * Reports whether the necessary flags were set and whether the repository has
704 * remote references to attempt DWIM tracking of upstream branches.
705 *
706 * 1. Checks that `--guess-remote` was used or `worktree.guessRemote = true`.
707 *
708 * 2. Checks whether any valid remote branches exist.
709 *
710 * 3. Checks that there exists at least one remote and emits a warning/error
711 * if both checks 1. and 2. are false (can be bypassed with `--force`).
712 *
713 * Returns 1 if checks 1. and 2. are true, otherwise 0.
714 */
715 static int can_use_remote_refs(const struct add_opts *opts)
716 {
717 if (!guess_remote) {
718 return 0;
719 } else if (refs_for_each_remote_ref(get_main_ref_store(the_repository), first_valid_ref, NULL)) {
720 return 1;
721 } else if (!opts->force && remote_get(NULL)) {
722 die(_("No local or remote refs exist despite at least one remote\n"
723 "present, stopping; use 'add -f' to override or fetch a remote first"));
724 }
725 return 0;
726 }
727
728 /**
729 * Determines whether `--orphan` should be inferred in the evaluation of
730 * `worktree add path/` or `worktree add -b branch path/` and emits an error
731 * if the supplied arguments would produce an illegal combination when the
732 * `--orphan` flag is included.
733 *
734 * `opts` and `opt_track` contain the other options & flags supplied to the
735 * command.
736 *
737 * remote determines whether to check `can_use_remote_refs()` or not. This
738 * is primarily to differentiate between the basic `add` DWIM and `add -b`.
739 *
740 * Returns 1 when inferring `--orphan`, 0 otherwise, and emits an error when
741 * `--orphan` is inferred but doing so produces an illegal combination of
742 * options and flags. Additionally produces an error when remote refs are
743 * checked and the repo is in a state that looks like the user added a remote
744 * but forgot to fetch (and did not override the warning with -f).
745 */
746 static int dwim_orphan(const struct add_opts *opts, int opt_track, int remote)
747 {
748 if (can_use_local_refs(opts)) {
749 return 0;
750 } else if (remote && can_use_remote_refs(opts)) {
751 return 0;
752 } else if (!opts->quiet) {
753 fprintf_ln(stderr, WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT);
754 }
755
756 if (opt_track) {
757 die(_("options '%s' and '%s' cannot be used together"),
758 "--orphan", "--track");
759 } else if (!opts->checkout) {
760 die(_("options '%s' and '%s' cannot be used together"),
761 "--orphan", "--no-checkout");
762 }
763 return 1;
764 }
765
766 static void advise_disambiguating_remotes(const char *path, const char *branch,
767 const struct string_list *matched_remote_names)
768 {
769 struct string_list_item *item;
770
771 advise(_("Branch name '%s' appears in multiple remotes:"), branch);
772 for_each_string_list_item(item, matched_remote_names) {
773 advise(_(" %s"), item->string);
774 }
775 advise(_("If you meant to create a worktree from a remote tracking branch on\n"
776 "<remote>, you can do so by:\n"
777 "\n"
778 " git worktree add -b %s %s <remote>/%s\n"
779 "\n"
780 "If you'd like to always prefer some remote, e.g. 'origin',\n"
781 "consider setting checkout.defaultRemote=origin in your config."),
782 branch, path, branch);
783 }
784
785 static char *dwim_branch(const struct add_opts *opts, const char *path, char **new_branch)
786 {
787 int n;
788 int branch_exists;
789 const char *s = worktree_basename(path, &n);
790 char *branchname = xstrndup(s, n);
791 struct strbuf ref = STRBUF_INIT;
792
793 branch_exists = !check_branch_ref(&ref, branchname) &&
794 refs_ref_exists(get_main_ref_store(the_repository),
795 ref.buf);
796 strbuf_release(&ref);
797 if (branch_exists)
798 return branchname;
799
800 *new_branch = branchname;
801 if (guess_remote) {
802 struct object_id oid;
803 char *remote;
804 int num_matches = 0;
805 struct string_list matched_remote_names = STRING_LIST_INIT_DUP;
806
807 remote = unique_tracking_name(*new_branch, &oid, &num_matches,
808 &matched_remote_names);
809 if (!remote && num_matches > 1) {
810 if (!opts->quiet &&
811 advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME))
812 advise_disambiguating_remotes(path, *new_branch,
813 &matched_remote_names);
814 die(_("'%s' matched multiple (%d) remote tracking branches"),
815 *new_branch, num_matches);
816 }
817 string_list_clear(&matched_remote_names, 0);
818 return remote;
819 }
820 return NULL;
821 }
822
823 static int add(int ac, const char **av, const char *prefix,
824 struct repository *repo UNUSED)
825 {
826 struct add_opts opts;
827 const char *new_branch_force = NULL;
828 char *path;
829 const char *branch;
830 char *branch_to_free = NULL;
831 char *new_branch_to_free = NULL;
832 const char *new_branch = NULL;
833 char *opt_track = NULL;
834 const char *lock_reason = NULL;
835 int keep_locked = 0;
836 int used_new_branch_options;
837 struct option options[] = {
838 OPT__FORCE(&opts.force,
839 N_("checkout <branch> even if already checked out in other worktree"),
840 PARSE_OPT_NOCOMPLETE),
841 OPT_STRING('b', NULL, &new_branch, N_("branch"),
842 N_("create a new branch")),
843 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
844 N_("create or reset a branch")),
845 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn branch")),
846 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
847 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
848 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
849 OPT_STRING(0, "reason", &lock_reason, N_("string"),
850 N_("reason for locking")),
851 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
852 OPT_PASSTHRU(0, "track", &opt_track, NULL,
853 N_("set up tracking mode (see git-branch(1))"),
854 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
855 OPT_BOOL(0, "guess-remote", &guess_remote,
856 N_("try to match the new branch name with a remote-tracking branch")),
857 OPT_BOOL(0, "relative-paths", &opts.relative_paths,
858 N_("use relative paths for worktrees")),
859 OPT_END()
860 };
861 int ret;
862
863 memset(&opts, 0, sizeof(opts));
864 opts.checkout = 1;
865 opts.relative_paths = use_relative_paths;
866 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
867 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
868 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
869 if (opts.detach && opts.orphan)
870 die(_("options '%s' and '%s' cannot be used together"),
871 "--orphan", "--detach");
872 if (opts.orphan && opt_track)
873 die(_("options '%s' and '%s' cannot be used together"),
874 "--orphan", "--track");
875 if (opts.orphan && !opts.checkout)
876 die(_("options '%s' and '%s' cannot be used together"),
877 "--orphan", "--no-checkout");
878 if (opts.orphan && ac == 2)
879 die(_("option '%s' and commit-ish cannot be used together"),
880 "--orphan");
881 if (lock_reason && !keep_locked)
882 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
883 if (lock_reason)
884 opts.keep_locked = lock_reason;
885 else if (keep_locked)
886 opts.keep_locked = _("added with --lock");
887
888 if (ac < 1 || ac > 2)
889 usage_with_options(git_worktree_add_usage, options);
890
891 path = prefix_filename(prefix, av[0]);
892 branch = ac < 2 ? "HEAD" : av[1];
893 used_new_branch_options = new_branch || new_branch_force;
894
895 if (!strcmp(branch, "-"))
896 branch = "@{-1}";
897
898 if (new_branch_force) {
899 struct strbuf symref = STRBUF_INIT;
900
901 new_branch = new_branch_force;
902
903 if (!opts.force &&
904 !check_branch_ref(&symref, new_branch) &&
905 refs_ref_exists(get_main_ref_store(the_repository), symref.buf))
906 die_if_checked_out(symref.buf, 0);
907 strbuf_release(&symref);
908 }
909
910 if (opts.orphan && !new_branch) {
911 int n;
912 const char *s = worktree_basename(path, &n);
913 new_branch = new_branch_to_free = xstrndup(s, n);
914 } else if (opts.orphan) {
915 ; /* no-op */
916 } else if (opts.detach) {
917 /* Check HEAD */
918 if (!strcmp(branch, "HEAD"))
919 can_use_local_refs(&opts);
920 } else if (ac < 2 && new_branch) {
921 /* DWIM: Infer --orphan when repo has no refs. */
922 opts.orphan = dwim_orphan(&opts, !!opt_track, 0);
923 } else if (ac < 2) {
924 /* DWIM: Guess branch name from path. */
925 char *s = dwim_branch(&opts, path, &new_branch_to_free);
926 if (s)
927 branch = branch_to_free = s;
928 new_branch = new_branch_to_free;
929
930 /* DWIM: Infer --orphan when repo has no refs. */
931 opts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);
932 } else if (ac == 2) {
933 struct commit *commit;
934
935 commit = lookup_commit_reference_by_name(branch);
936 if (!commit) {
937 struct object_id oid;
938 char *remote;
939 int num_matches = 0;
940 struct string_list matched_remote_names = STRING_LIST_INIT_DUP;
941
942 remote = unique_tracking_name(branch, &oid, &num_matches,
943 &matched_remote_names);
944 if (remote) {
945 new_branch = branch;
946 branch = new_branch_to_free = remote;
947 } else if (num_matches > 1) {
948 if (!opts.quiet &&
949 advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME))
950 advise_disambiguating_remotes(path, branch,
951 &matched_remote_names);
952 die(_("'%s' matched multiple (%d) remote tracking branches"),
953 branch, num_matches);
954 }
955 string_list_clear(&matched_remote_names, 0);
956 }
957
958 if (!strcmp(branch, "HEAD"))
959 can_use_local_refs(&opts);
960
961 }
962
963 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
964 int attempt_hint = !opts.quiet && (ac < 2);
965 if (attempt_hint && used_new_branch_options) {
966 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
967 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT,
968 new_branch, path);
969 } else if (attempt_hint) {
970 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
971 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT, path);
972 }
973 die(_("invalid reference: %s"), branch);
974 }
975
976 if (!opts.quiet)
977 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
978
979 if (opts.orphan) {
980 branch = new_branch;
981 } else if (new_branch) {
982 struct child_process cp = CHILD_PROCESS_INIT;
983 cp.git_cmd = 1;
984 strvec_push(&cp.args, "branch");
985 if (new_branch_force)
986 strvec_push(&cp.args, "--force");
987 if (opts.quiet)
988 strvec_push(&cp.args, "--quiet");
989 strvec_push(&cp.args, new_branch);
990 strvec_push(&cp.args, branch);
991 if (opt_track)
992 strvec_push(&cp.args, opt_track);
993 if (run_command(&cp))
994 return -1;
995 branch = new_branch;
996 } else if (opt_track) {
997 die(_("--[no-]track can only be used if a new branch is created"));
998 }
999
1000 ret = add_worktree(path, branch, &opts);
1001 free(path);
1002 free(opt_track);
1003 free(branch_to_free);
1004 free(new_branch_to_free);
1005 return ret;
1006 }
1007
1008 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
1009 {
1010 const char *reason;
1011
1012 printf("worktree %s%c", wt->path, line_terminator);
1013 if (wt->is_bare)
1014 printf("bare%c", line_terminator);
1015 else {
1016 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
1017 if (wt->is_detached)
1018 printf("detached%c", line_terminator);
1019 else if (wt->head_ref)
1020 printf("branch %s%c", wt->head_ref, line_terminator);
1021 }
1022
1023 reason = worktree_lock_reason(wt);
1024 if (reason) {
1025 fputs("locked", stdout);
1026 if (*reason) {
1027 fputc(' ', stdout);
1028 write_name_quoted(reason, stdout, line_terminator);
1029 } else {
1030 fputc(line_terminator, stdout);
1031 }
1032 }
1033
1034 reason = worktree_prune_reason(wt, expire);
1035 if (reason)
1036 printf("prunable %s%c", reason, line_terminator);
1037
1038 fputc(line_terminator, stdout);
1039 }
1040
1041 struct worktree_display {
1042 char *path;
1043 int width;
1044 };
1045
1046 static void show_worktree(struct worktree *wt, struct worktree_display *display,
1047 int path_maxwidth, int abbrev_len)
1048 {
1049 struct strbuf sb = STRBUF_INIT;
1050 const char *reason;
1051
1052 strbuf_addf(&sb, "%s%*s", display->path, 1 + path_maxwidth - display->width, "");
1053 if (wt->is_bare)
1054 strbuf_addstr(&sb, "(bare)");
1055 else {
1056 strbuf_addf(&sb, "%-*s ", abbrev_len,
1057 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
1058 if (wt->is_detached)
1059 strbuf_addstr(&sb, "(detached HEAD)");
1060 else if (wt->head_ref) {
1061 char *ref = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1062 wt->head_ref,
1063 0);
1064 strbuf_addf(&sb, "[%s]", ref);
1065 free(ref);
1066 } else
1067 strbuf_addstr(&sb, "(error)");
1068 }
1069
1070 reason = worktree_lock_reason(wt);
1071 if (verbose && reason && *reason)
1072 strbuf_addf(&sb, "\n\tlocked: %s", reason);
1073 else if (reason)
1074 strbuf_addstr(&sb, " locked");
1075
1076 reason = worktree_prune_reason(wt, expire);
1077 if (verbose && reason)
1078 strbuf_addf(&sb, "\n\tprunable: %s", reason);
1079 else if (reason)
1080 strbuf_addstr(&sb, " prunable");
1081
1082 printf("%s\n", sb.buf);
1083 strbuf_release(&sb);
1084 }
1085
1086 static void measure_widths(struct worktree **wt, int *abbrev,
1087 struct worktree_display **d, int *maxwidth)
1088 {
1089 int i, display_alloc = 0;
1090 struct worktree_display *display = NULL;
1091 struct strbuf buf = STRBUF_INIT;
1092
1093 for (i = 0; wt[i]; i++) {
1094 int sha1_len;
1095 ALLOC_GROW(display, i + 1, display_alloc);
1096 quote_path(wt[i]->path, NULL, &buf, 0);
1097 display[i].width = utf8_strwidth(buf.buf);
1098 display[i].path = strbuf_detach(&buf, NULL);
1099
1100 if (display[i].width > *maxwidth)
1101 *maxwidth = display[i].width;
1102 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
1103 if (sha1_len > *abbrev)
1104 *abbrev = sha1_len;
1105 }
1106 *d = display;
1107 }
1108
1109 static int pathcmp(const void *a_, const void *b_)
1110 {
1111 const struct worktree *const *a = a_;
1112 const struct worktree *const *b = b_;
1113 return fspathcmp((*a)->path, (*b)->path);
1114 }
1115
1116 static void pathsort(struct worktree **wt)
1117 {
1118 int n = 0;
1119 struct worktree **p = wt;
1120
1121 while (*p++)
1122 n++;
1123 QSORT(wt, n, pathcmp);
1124 }
1125
1126 static int list(int ac, const char **av, const char *prefix,
1127 struct repository *repo UNUSED)
1128 {
1129 int porcelain = 0;
1130 int line_terminator = '\n';
1131
1132 struct option options[] = {
1133 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
1134 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
1135 OPT_EXPIRY_DATE(0, "expire", &expire,
1136 N_("add 'prunable' annotation to missing worktrees older than <time>")),
1137 OPT_SET_INT('z', NULL, &line_terminator,
1138 N_("terminate records with a NUL character"), '\0'),
1139 OPT_END()
1140 };
1141
1142 expire = TIME_MAX;
1143 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
1144 if (ac)
1145 usage_with_options(git_worktree_list_usage, options);
1146 else if (verbose && porcelain)
1147 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1148 else if (!line_terminator && !porcelain)
1149 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1150 else {
1151 struct worktree **worktrees = get_worktrees();
1152 int path_maxwidth = 0, abbrev = DEFAULT_ABBREV, i;
1153 struct worktree_display *display = NULL;
1154
1155 /* sort worktrees by path but keep main worktree at top */
1156 pathsort(worktrees + 1);
1157
1158 if (!porcelain)
1159 measure_widths(worktrees, &abbrev,
1160 &display, &path_maxwidth);
1161
1162 for (i = 0; worktrees[i]; i++) {
1163 if (porcelain)
1164 show_worktree_porcelain(worktrees[i],
1165 line_terminator);
1166 else
1167 show_worktree(worktrees[i],
1168 &display[i], path_maxwidth, abbrev);
1169 }
1170 for (i = 0; display && worktrees[i]; i++)
1171 free(display[i].path);
1172 free(display);
1173 free_worktrees(worktrees);
1174 }
1175 return 0;
1176 }
1177
1178 static int lock_worktree(int ac, const char **av, const char *prefix,
1179 struct repository *repo UNUSED)
1180 {
1181 const char *reason = "", *old_reason;
1182 struct option options[] = {
1183 OPT_STRING(0, "reason", &reason, N_("string"),
1184 N_("reason for locking")),
1185 OPT_END()
1186 };
1187 struct worktree **worktrees, *wt;
1188 char *path;
1189
1190 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
1191 if (ac != 1)
1192 usage_with_options(git_worktree_lock_usage, options);
1193
1194 worktrees = get_worktrees();
1195 wt = find_worktree(worktrees, prefix, av[0]);
1196 if (!wt)
1197 die(_("'%s' is not a working tree"), av[0]);
1198 if (is_main_worktree(wt))
1199 die(_("The main working tree cannot be locked or unlocked"));
1200
1201 old_reason = worktree_lock_reason(wt);
1202 if (old_reason) {
1203 if (*old_reason)
1204 die(_("'%s' is already locked, reason: %s"),
1205 av[0], old_reason);
1206 die(_("'%s' is already locked"), av[0]);
1207 }
1208
1209 path = repo_common_path(the_repository, "worktrees/%s/locked", wt->id);
1210 write_file(path, "%s", reason);
1211
1212 free_worktrees(worktrees);
1213 free(path);
1214 return 0;
1215 }
1216
1217 static int unlock_worktree(int ac, const char **av, const char *prefix,
1218 struct repository *repo UNUSED)
1219 {
1220 struct option options[] = {
1221 OPT_END()
1222 };
1223 struct worktree **worktrees, *wt;
1224 char *path;
1225 int ret;
1226
1227 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
1228 if (ac != 1)
1229 usage_with_options(git_worktree_unlock_usage, options);
1230
1231 worktrees = get_worktrees();
1232 wt = find_worktree(worktrees, prefix, av[0]);
1233 if (!wt)
1234 die(_("'%s' is not a working tree"), av[0]);
1235 if (is_main_worktree(wt))
1236 die(_("The main working tree cannot be locked or unlocked"));
1237 if (!worktree_lock_reason(wt))
1238 die(_("'%s' is not locked"), av[0]);
1239
1240 path = repo_common_path(the_repository, "worktrees/%s/locked", wt->id);
1241 ret = unlink_or_warn(path);
1242
1243 free_worktrees(worktrees);
1244 free(path);
1245 return ret;
1246 }
1247
1248 static void validate_no_submodules(const struct worktree *wt)
1249 {
1250 struct index_state istate = INDEX_STATE_INIT(the_repository);
1251 struct strbuf path = STRBUF_INIT;
1252 int i, found_submodules = 0;
1253 char *wt_gitdir;
1254
1255 wt_gitdir = get_worktree_git_dir(wt);
1256
1257 if (is_directory(worktree_git_path(wt, "modules"))) {
1258 /*
1259 * There could be false positives, e.g. the "modules"
1260 * directory exists but is empty. But it's a rare case and
1261 * this simpler check is probably good enough for now.
1262 */
1263 found_submodules = 1;
1264 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1265 wt_gitdir) > 0) {
1266 for (i = 0; i < istate.cache_nr; i++) {
1267 struct cache_entry *ce = istate.cache[i];
1268 int err;
1269
1270 if (!S_ISGITLINK(ce->ce_mode))
1271 continue;
1272
1273 strbuf_reset(&path);
1274 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
1275 if (!is_submodule_populated_gently(path.buf, &err))
1276 continue;
1277
1278 found_submodules = 1;
1279 break;
1280 }
1281 }
1282 discard_index(&istate);
1283 strbuf_release(&path);
1284 free(wt_gitdir);
1285
1286 if (found_submodules)
1287 die(_("working trees containing submodules cannot be moved or removed"));
1288 }
1289
1290 static int move_worktree(int ac, const char **av, const char *prefix,
1291 struct repository *repo UNUSED)
1292 {
1293 int force = 0;
1294 struct option options[] = {
1295 OPT__FORCE(&force,
1296 N_("force move even if worktree is dirty or locked"),
1297 PARSE_OPT_NOCOMPLETE),
1298 OPT_BOOL(0, "relative-paths", &use_relative_paths,
1299 N_("use relative paths for worktrees")),
1300 OPT_END()
1301 };
1302 struct worktree **worktrees, *wt;
1303 struct strbuf dst = STRBUF_INIT;
1304 struct strbuf errmsg = STRBUF_INIT;
1305 const char *reason = NULL;
1306 char *path;
1307
1308 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1309 0);
1310 if (ac != 2)
1311 usage_with_options(git_worktree_move_usage, options);
1312
1313 path = prefix_filename(prefix, av[1]);
1314 strbuf_addstr(&dst, path);
1315 free(path);
1316
1317 worktrees = get_worktrees();
1318 wt = find_worktree(worktrees, prefix, av[0]);
1319 if (!wt)
1320 die(_("'%s' is not a working tree"), av[0]);
1321 if (is_main_worktree(wt))
1322 die(_("'%s' is a main working tree"), av[0]);
1323 if (is_directory(dst.buf)) {
1324 const char *sep = find_last_dir_sep(wt->path);
1325
1326 if (!sep)
1327 die(_("could not figure out destination name from '%s'"),
1328 wt->path);
1329 strbuf_trim_trailing_dir_sep(&dst);
1330 strbuf_addstr(&dst, sep);
1331 }
1332 check_candidate_path(dst.buf, force, worktrees, "move");
1333
1334 validate_no_submodules(wt);
1335
1336 if (force < 2)
1337 reason = worktree_lock_reason(wt);
1338 if (reason) {
1339 if (*reason)
1340 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1341 reason);
1342 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1343 }
1344 if (validate_worktree(wt, &errmsg, 0))
1345 die(_("validation failed, cannot move working tree: %s"),
1346 errmsg.buf);
1347 strbuf_release(&errmsg);
1348
1349 if (rename(wt->path, dst.buf) == -1)
1350 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1351
1352 update_worktree_location(wt, dst.buf, use_relative_paths);
1353
1354 strbuf_release(&dst);
1355 free_worktrees(worktrees);
1356 return 0;
1357 }
1358
1359 /*
1360 * Note, "git status --porcelain" is used to determine if it's safe to
1361 * delete a whole worktree. "git status" does not ignore user
1362 * configuration, so if a normal "git status" shows "clean" for the
1363 * user, then it's ok to remove it.
1364 *
1365 * This assumption may be a bad one. We may want to ignore
1366 * (potentially bad) user settings and only delete a worktree when
1367 * it's absolutely safe to do so from _our_ point of view because we
1368 * know better.
1369 */
1370 static void check_clean_worktree(struct worktree *wt,
1371 const char *original_path)
1372 {
1373 struct child_process cp;
1374 char buf[1];
1375 int ret;
1376
1377 /*
1378 * Until we sort this out, all submodules are "dirty" and
1379 * will abort this function.
1380 */
1381 validate_no_submodules(wt);
1382
1383 child_process_init(&cp);
1384 strvec_pushf(&cp.env, "%s=%s/.git",
1385 GIT_DIR_ENVIRONMENT, wt->path);
1386 strvec_pushf(&cp.env, "%s=%s",
1387 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1388 strvec_pushl(&cp.args, "status",
1389 "--porcelain", "--ignore-submodules=none",
1390 NULL);
1391 cp.git_cmd = 1;
1392 cp.dir = wt->path;
1393 cp.out = -1;
1394 ret = start_command(&cp);
1395 if (ret)
1396 die_errno(_("failed to run 'git status' on '%s'"),
1397 original_path);
1398 ret = xread(cp.out, buf, sizeof(buf));
1399 if (ret)
1400 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1401 original_path);
1402 close(cp.out);
1403 ret = finish_command(&cp);
1404 if (ret)
1405 die_errno(_("failed to run 'git status' on '%s', code %d"),
1406 original_path, ret);
1407 }
1408
1409 static int delete_git_work_tree(struct worktree *wt)
1410 {
1411 struct strbuf sb = STRBUF_INIT;
1412 int ret = 0;
1413
1414 strbuf_addstr(&sb, wt->path);
1415 if (remove_dir_recursively(&sb, 0)) {
1416 error_errno(_("failed to delete '%s'"), sb.buf);
1417 ret = -1;
1418 }
1419 strbuf_release(&sb);
1420 return ret;
1421 }
1422
1423 static int remove_worktree(int ac, const char **av, const char *prefix,
1424 struct repository *repo UNUSED)
1425 {
1426 int force = 0;
1427 struct option options[] = {
1428 OPT__FORCE(&force,
1429 N_("force removal even if worktree is dirty or locked"),
1430 PARSE_OPT_NOCOMPLETE),
1431 OPT_END()
1432 };
1433 struct worktree **worktrees, *wt;
1434 struct strbuf errmsg = STRBUF_INIT;
1435 const char *reason = NULL;
1436 int ret = 0;
1437
1438 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1439 if (ac != 1)
1440 usage_with_options(git_worktree_remove_usage, options);
1441
1442 worktrees = get_worktrees();
1443 wt = find_worktree(worktrees, prefix, av[0]);
1444 if (!wt)
1445 die(_("'%s' is not a working tree"), av[0]);
1446 if (is_main_worktree(wt))
1447 die(_("'%s' is a main working tree"), av[0]);
1448 if (force < 2)
1449 reason = worktree_lock_reason(wt);
1450 if (reason) {
1451 if (*reason)
1452 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1453 reason);
1454 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1455 }
1456 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1457 die(_("validation failed, cannot remove working tree: %s"),
1458 errmsg.buf);
1459 strbuf_release(&errmsg);
1460
1461 if (file_exists(wt->path)) {
1462 if (!force)
1463 check_clean_worktree(wt, av[0]);
1464
1465 ret |= delete_git_work_tree(wt);
1466 }
1467 /*
1468 * continue on even if ret is non-zero, there's no going back
1469 * from here.
1470 */
1471 ret |= delete_git_dir(wt->id);
1472 delete_worktrees_dir_if_empty();
1473
1474 free_worktrees(worktrees);
1475 return ret;
1476 }
1477
1478 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1479 {
1480 if (!iserr) {
1481 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1482 } else {
1483 int *exit_status = (int *)cb_data;
1484 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1485 *exit_status = 1;
1486 }
1487 }
1488
1489 static int repair(int ac, const char **av, const char *prefix,
1490 struct repository *repo UNUSED)
1491 {
1492 const char **p;
1493 const char *self[] = { ".", NULL };
1494 struct option options[] = {
1495 OPT_BOOL(0, "relative-paths", &use_relative_paths,
1496 N_("use relative paths for worktrees")),
1497 OPT_END()
1498 };
1499 int rc = 0;
1500
1501 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1502 p = ac > 0 ? av : self;
1503 for (; *p; p++)
1504 repair_worktree_at_path(*p, report_repair, &rc, use_relative_paths);
1505 repair_worktrees(report_repair, &rc, use_relative_paths);
1506 return rc;
1507 }
1508
1509 int cmd_worktree(int ac,
1510 const char **av,
1511 const char *prefix,
1512 struct repository *repo)
1513 {
1514 parse_opt_subcommand_fn *fn = NULL;
1515 struct option options[] = {
1516 OPT_SUBCOMMAND("add", &fn, add),
1517 OPT_SUBCOMMAND("prune", &fn, prune),
1518 OPT_SUBCOMMAND("list", &fn, list),
1519 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1520 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1521 OPT_SUBCOMMAND("move", &fn, move_worktree),
1522 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1523 OPT_SUBCOMMAND("repair", &fn, repair),
1524 OPT_END()
1525 };
1526
1527 repo_config(the_repository, git_worktree_config, NULL);
1528
1529 if (!prefix)
1530 prefix = "";
1531
1532 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1533
1534 prepare_repo_settings(the_repository);
1535 the_repository->settings.command_requires_full_index = 0;
1536
1537 return fn(ac, av, prefix, repo);
1538 }