interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / builtin / worktree.c

1541 lines · 44631 bytes Raw Blame History
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
67static 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
79static const char * const git_worktree_add_usage[] = {
80 BUILTIN_WORKTREE_ADD_USAGE,
81 NULL,
82};
83
84static const char * const git_worktree_list_usage[] = {
85 BUILTIN_WORKTREE_LIST_USAGE,
86 NULL
87};
88
89static const char * const git_worktree_lock_usage[] = {
90 BUILTIN_WORKTREE_LOCK_USAGE,
91 NULL
92};
93
94static const char * const git_worktree_move_usage[] = {
95 BUILTIN_WORKTREE_MOVE_USAGE,
96 NULL
97};
98
99static const char * const git_worktree_prune_usage[] = {
100 BUILTIN_WORKTREE_PRUNE_USAGE,
101 NULL
102};
103
104static const char * const git_worktree_remove_usage[] = {
105 BUILTIN_WORKTREE_REMOVE_USAGE,
106 NULL
107};
108
109static const char * const git_worktree_repair_usage[] = {
110 BUILTIN_WORKTREE_REPAIR_USAGE,
111 NULL
112};
113
114static const char * const git_worktree_unlock_usage[] = {
115 BUILTIN_WORKTREE_UNLOCK_USAGE,
116 NULL
117};
118
119struct 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
129static int show_only;
130static int verbose;
131static int guess_remote;
132static int use_relative_paths;
133static timestamp_t expire;
134
135static 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
149static 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
164static 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
171static 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
179static 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
201static 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
212static void prune_worktrees(void)
213{
214 struct strbuf reason = STRBUF_INIT;
215 struct strbuf main_path = STRBUF_INIT;
216 struct string_list kept = STRING_LIST_INIT_DUP;
217 char *path;
218 DIR *dir;
219 struct dirent *d;
220
221 path = repo_git_path(the_repository, "worktrees");
222 dir = opendir(path);
223 free(path);
224 if (!dir)
225 return;
226 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
227 char *path;
228 strbuf_reset(&reason);
229 if (should_prune_worktree(the_repository, d->d_name, &reason, &path, expire))
230 prune_worktree(d->d_name, reason.buf);
231 else if (path)
232 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
233 }
234 closedir(dir);
235
236 strbuf_add_absolute_path(&main_path, repo_get_common_dir(the_repository));
237 /* massage main worktree absolute path to match 'gitdir' content */
238 strbuf_strip_suffix(&main_path, "/.");
239 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
240 prune_dups(&kept);
241 string_list_clear(&kept, 1);
242
243 if (!show_only)
244 delete_worktrees_dir_if_empty();
245 strbuf_release(&reason);
246}
247
248static 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
268static char *junk_work_tree;
269static char *junk_git_dir;
270static int is_junk;
271static pid_t junk_pid;
272
273static 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
290static void remove_junk_on_signal(int signo)
291{
292 remove_junk();
293 sigchain_pop(signo);
294 raise(signo);
295}
296
297static char *worktree_basename_dup(const char *path)
298{
299 const char *name;
300 int len;
301
302 len = strlen(path);
303 while (len && is_dir_sep(path[len - 1]))
304 len--;
305
306 name = path + len;
307 while (name > path && !is_dir_sep(name[-1]))
308 name--;
309
310 return xmemdupz(name, path + len - name);
311}
312
313/* check that path is viable location for worktree */
314static void check_candidate_path(const char *path,
315 int force,
316 struct worktree **worktrees,
317 const char *cmd)
318{
319 struct worktree *wt;
320 int locked;
321
322 if (file_exists(path) && !is_empty_dir(path))
323 die(_("'%s' already exists"), path);
324
325 wt = find_worktree_by_path(worktrees, path);
326 if (!wt)
327 return;
328
329 locked = !!worktree_lock_reason(wt);
330 if ((!locked && force) || (locked && force > 1)) {
331 if (delete_git_dir(wt->id))
332 die(_("unusable worktree destination '%s'"), path);
333 return;
334 }
335
336 if (locked)
337 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
338 else
339 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
340}
341
342static void copy_sparse_checkout(const char *worktree_git_dir)
343{
344 char *from_file = repo_git_path(the_repository, "info/sparse-checkout");
345 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
346
347 if (file_exists(from_file)) {
348 if (safe_create_leading_directories(the_repository, to_file) ||
349 copy_file(the_repository, to_file, from_file, 0666))
350 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
351 from_file, to_file);
352 }
353
354 free(from_file);
355 free(to_file);
356}
357
358static void copy_filtered_worktree_config(const char *worktree_git_dir)
359{
360 char *from_file = repo_git_path(the_repository, "config.worktree");
361 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
362
363 if (file_exists(from_file)) {
364 struct config_set cs = { { 0 } };
365 int bare;
366
367 if (safe_create_leading_directories(the_repository, to_file) ||
368 copy_file(the_repository, to_file, from_file, 0666)) {
369 error(_("failed to copy worktree config from '%s' to '%s'"),
370 from_file, to_file);
371 goto worktree_copy_cleanup;
372 }
373
374 git_configset_init(&cs);
375 git_configset_add_file(&cs, from_file);
376
377 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
378 bare &&
379 repo_config_set_multivar_in_file_gently(the_repository,
380 to_file, "core.bare", NULL, "true", NULL, 0))
381 error(_("failed to unset '%s' in '%s'"),
382 "core.bare", to_file);
383 if (!git_configset_get(&cs, "core.worktree") &&
384 repo_config_set_in_file_gently(the_repository, to_file,
385 "core.worktree", NULL, NULL))
386 error(_("failed to unset '%s' in '%s'"),
387 "core.worktree", to_file);
388
389 git_configset_clear(&cs);
390 }
391
392worktree_copy_cleanup:
393 free(from_file);
394 free(to_file);
395}
396
397static int checkout_worktree(const struct add_opts *opts,
398 struct strvec *child_env)
399{
400 struct child_process cp = CHILD_PROCESS_INIT;
401 cp.git_cmd = 1;
402 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
403 if (opts->quiet)
404 strvec_push(&cp.args, "--quiet");
405 strvec_pushv(&cp.env, child_env->v);
406 return run_command(&cp);
407}
408
409static int make_worktree_orphan(const char * ref, const struct add_opts *opts,
410 struct strvec *child_env)
411{
412 struct strbuf symref = STRBUF_INIT;
413 struct child_process cp = CHILD_PROCESS_INIT;
414
415 validate_new_branchname(ref, &symref, 0);
416 strvec_pushl(&cp.args, "symbolic-ref", "HEAD", symref.buf, NULL);
417 if (opts->quiet)
418 strvec_push(&cp.args, "--quiet");
419 strvec_pushv(&cp.env, child_env->v);
420 strbuf_release(&symref);
421 cp.git_cmd = 1;
422 return run_command(&cp);
423}
424
425/*
426 * References for worktrees are generally stored in '$GIT_DIR/worktrees/<wt_id>'.
427 * But when using alternate reference directories, we want to store the worktree
428 * references in '$ALTERNATE_REFERENCE_DIR/worktrees/<wt_id>'.
429 *
430 * Create the necessary folder structure to facilitate the same. But to ensure
431 * that the former path is still considered a Git directory, add stubs.
432 */
433static void setup_alternate_ref_dir(struct worktree *wt, const char *wt_git_path)
434{
435 struct strbuf sb = STRBUF_INIT;
436 char *path;
437
438 path = wt->repo->ref_storage_payload;
439 if (!path)
440 return;
441
442 if (!is_absolute_path(path))
443 strbuf_addf(&sb, "%s/", wt->repo->commondir);
444
445 strbuf_addf(&sb, "%s/worktrees", path);
446 safe_create_dir(wt->repo, sb.buf, 1);
447 strbuf_addf(&sb, "/%s", wt->id);
448 safe_create_dir(wt->repo, sb.buf, 1);
449 strbuf_reset(&sb);
450
451 strbuf_addf(&sb, "this worktree stores references in %s/worktrees/%s",
452 path, wt->id);
453 refs_create_refdir_stubs(wt->repo, wt_git_path, sb.buf);
454
455 strbuf_release(&sb);
456}
457
458static int add_worktree(const char *path, const char *refname,
459 const struct add_opts *opts)
460{
461 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
462 struct strbuf sb = STRBUF_INIT;
463 const char *name;
464 char *name_to_free = NULL;
465 struct strvec child_env = STRVEC_INIT;
466 unsigned int counter = 0;
467 int len, ret;
468 struct strbuf symref = STRBUF_INIT;
469 struct commit *commit = NULL;
470 int is_branch = 0;
471 struct strbuf sb_name = STRBUF_INIT;
472 struct worktree **worktrees, *wt = NULL;
473 struct ref_store *wt_refs;
474 struct repo_config_values *cfg = repo_config_values(the_repository);
475
476 worktrees = get_worktrees(the_repository);
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(the_repository, &symref, refname) &&
483 refs_ref_exists(get_main_ref_store(the_repository), symref.buf)) {
484 is_branch = 1;
485 if (!opts->force)
486 die_if_checked_out(symref.buf, 0);
487 }
488 commit = lookup_commit_reference_by_name(refname);
489 if (!commit && !opts->orphan)
490 die(_("invalid reference: %s"), refname);
491
492 name = name_to_free = worktree_basename_dup(path);
493 if (!*name)
494 die(_("invalid path '%s'"), path);
495 sanitize_refname_component(name, &sb_name);
496 if (!sb_name.len)
497 BUG("How come '%s' becomes empty after sanitization?", name);
498 name = sb_name.buf;
499 repo_git_path_replace(the_repository, &sb_repo, "worktrees/%s", name);
500 len = sb_repo.len;
501 if (safe_create_leading_directories_const(the_repository, sb_repo.buf))
502 die_errno(_("could not create leading directories of '%s'"),
503 sb_repo.buf);
504
505 while (mkdir(sb_repo.buf, 0777)) {
506 counter++;
507 if ((errno != EEXIST) || !counter /* overflow */)
508 die_errno(_("could not create directory of '%s'"),
509 sb_repo.buf);
510 strbuf_setlen(&sb_repo, len);
511 strbuf_addf(&sb_repo, "%d", counter);
512 }
513 name = strrchr(sb_repo.buf, '/') + 1;
514
515 junk_pid = getpid();
516 atexit(remove_junk);
517 sigchain_push_common(remove_junk_on_signal);
518
519 junk_git_dir = xstrdup(sb_repo.buf);
520 is_junk = 1;
521
522 /*
523 * lock the incomplete repo so prune won't delete it, unlock
524 * after the preparation is over.
525 */
526 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
527 if (opts->keep_locked)
528 write_file(sb.buf, "%s", opts->keep_locked);
529 else
530 write_file(sb.buf, _("initializing"));
531
532 strbuf_addf(&sb_git, "%s/.git", path);
533 if (safe_create_leading_directories_const(the_repository, sb_git.buf))
534 die_errno(_("could not create leading directories of '%s'"),
535 sb_git.buf);
536 junk_work_tree = xstrdup(path);
537
538 strbuf_reset(&sb);
539 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
540 write_worktree_linking_files(the_repository, sb_git.buf,
541 sb.buf, opts->relative_paths);
542 strbuf_reset(&sb);
543 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
544 write_file(sb.buf, "../..");
545
546 /*
547 * Set up the ref store of the worktree and create the HEAD reference.
548 */
549 wt = get_linked_worktree(the_repository, name, 1);
550 if (!wt) {
551 ret = error(_("could not find created worktree '%s'"), name);
552 goto done;
553 }
554 setup_alternate_ref_dir(wt, sb_repo.buf);
555 wt_refs = get_worktree_ref_store(wt);
556
557 ret = ref_store_create_on_disk(wt_refs, REF_STORE_CREATE_ON_DISK_IS_WORKTREE, &sb);
558 if (ret)
559 goto done;
560
561 if (!is_branch && commit)
562 ret = refs_update_ref(wt_refs, NULL, "HEAD", &commit->object.oid,
563 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
564 else
565 ret = refs_update_symref(wt_refs, "HEAD", symref.buf, NULL);
566 if (ret)
567 goto done;
568
569 /*
570 * If the current worktree has sparse-checkout enabled, then copy
571 * the sparse-checkout patterns from the current worktree.
572 */
573 if (cfg->apply_sparse_checkout)
574 copy_sparse_checkout(sb_repo.buf);
575
576 /*
577 * If we are using worktree config, then copy all current config
578 * values from the current worktree into the new one, that way the
579 * new worktree behaves the same as this one.
580 */
581 if (the_repository->repository_format_worktree_config)
582 copy_filtered_worktree_config(sb_repo.buf);
583
584 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
585 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
586
587 if (opts->orphan &&
588 (ret = make_worktree_orphan(refname, opts, &child_env)))
589 goto done;
590
591 if (opts->checkout &&
592 (ret = checkout_worktree(opts, &child_env)))
593 goto done;
594
595 is_junk = 0;
596 FREE_AND_NULL(junk_work_tree);
597 FREE_AND_NULL(junk_git_dir);
598
599done:
600 if (ret || !opts->keep_locked) {
601 strbuf_reset(&sb);
602 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
603 unlink_or_warn(sb.buf);
604 }
605
606 /*
607 * Hook failure does not warrant worktree deletion, so run hook after
608 * is_junk is cleared, but do return appropriate code when hook fails.
609 */
610 if (!ret && opts->checkout && !opts->orphan) {
611 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT_FORCE_SERIAL;
612
613 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
614 strvec_pushl(&opt.args,
615 oid_to_hex(null_oid(the_hash_algo)),
616 oid_to_hex(&commit->object.oid),
617 "1",
618 NULL);
619 opt.dir = path;
620
621 ret = run_hooks_opt(the_repository, "post-checkout", &opt);
622 }
623
624 strvec_clear(&child_env);
625 strbuf_release(&sb);
626 strbuf_release(&symref);
627 strbuf_release(&sb_repo);
628 strbuf_release(&sb_git);
629 strbuf_release(&sb_name);
630 free_worktree(wt);
631 free(name_to_free);
632 return ret;
633}
634
635static 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(the_repository, &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 */
673static 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 */
690static 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 */
715static 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 */
746static 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
766static 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
785static char *dwim_branch(const struct add_opts *opts, const char *path, char **new_branch)
786{
787 int branch_exists;
788 char *branchname = worktree_basename_dup(path);
789 struct strbuf ref = STRBUF_INIT;
790
791 branch_exists = !check_branch_ref(the_repository, &ref, branchname) &&
792 refs_ref_exists(get_main_ref_store(the_repository),
793 ref.buf);
794 strbuf_release(&ref);
795 if (branch_exists)
796 return branchname;
797
798 *new_branch = branchname;
799 if (guess_remote) {
800 struct object_id oid;
801 char *remote;
802 int num_matches = 0;
803 struct string_list matched_remote_names = STRING_LIST_INIT_DUP;
804
805 remote = unique_tracking_name(*new_branch, &oid, &num_matches,
806 &matched_remote_names);
807 if (!remote && num_matches > 1) {
808 if (!opts->quiet &&
809 advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME))
810 advise_disambiguating_remotes(path, *new_branch,
811 &matched_remote_names);
812 die(_("'%s' matched multiple (%d) remote tracking branches"),
813 *new_branch, num_matches);
814 }
815 string_list_clear(&matched_remote_names, 0);
816 return remote;
817 }
818 return NULL;
819}
820
821static int add(int ac, const char **av, const char *prefix,
822 struct repository *repo UNUSED)
823{
824 struct add_opts opts;
825 const char *new_branch_force = NULL;
826 char *path;
827 const char *branch;
828 char *branch_to_free = NULL;
829 char *new_branch_to_free = NULL;
830 const char *new_branch = NULL;
831 char *opt_track = NULL;
832 const char *lock_reason = NULL;
833 int keep_locked = 0;
834 int used_new_branch_options;
835 struct option options[] = {
836 OPT__FORCE(&opts.force,
837 N_("checkout <branch> even if already checked out in other worktree"),
838 PARSE_OPT_NOCOMPLETE),
839 OPT_STRING('b', NULL, &new_branch, N_("branch"),
840 N_("create a new branch")),
841 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
842 N_("create or reset a branch")),
843 OPT_BOOL(0, "orphan", &opts.orphan, N_("create unborn branch")),
844 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
845 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
846 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
847 OPT_STRING(0, "reason", &lock_reason, N_("string"),
848 N_("reason for locking")),
849 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
850 OPT_PASSTHRU(0, "track", &opt_track, NULL,
851 N_("set up tracking mode (see git-branch(1))"),
852 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
853 OPT_BOOL(0, "guess-remote", &guess_remote,
854 N_("try to match the new branch name with a remote-tracking branch")),
855 OPT_BOOL(0, "relative-paths", &opts.relative_paths,
856 N_("use relative paths for worktrees")),
857 OPT_END()
858 };
859 int ret;
860
861 memset(&opts, 0, sizeof(opts));
862 opts.checkout = 1;
863 opts.relative_paths = use_relative_paths;
864 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
865 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
866 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
867 if (opts.detach && opts.orphan)
868 die(_("options '%s' and '%s' cannot be used together"),
869 "--orphan", "--detach");
870 if (opts.orphan && opt_track)
871 die(_("options '%s' and '%s' cannot be used together"),
872 "--orphan", "--track");
873 if (opts.orphan && !opts.checkout)
874 die(_("options '%s' and '%s' cannot be used together"),
875 "--orphan", "--no-checkout");
876 if (opts.orphan && ac == 2)
877 die(_("option '%s' and commit-ish cannot be used together"),
878 "--orphan");
879 if (lock_reason && !keep_locked)
880 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
881 if (lock_reason)
882 opts.keep_locked = lock_reason;
883 else if (keep_locked)
884 opts.keep_locked = _("added with --lock");
885
886 if (ac < 1 || ac > 2)
887 usage_with_options(git_worktree_add_usage, options);
888
889 path = prefix_filename(prefix, av[0]);
890 branch = ac < 2 ? "HEAD" : av[1];
891 used_new_branch_options = new_branch || new_branch_force;
892
893 if (!strcmp(branch, "-"))
894 branch = "@{-1}";
895
896 if (new_branch_force) {
897 struct strbuf symref = STRBUF_INIT;
898
899 new_branch = new_branch_force;
900
901 if (!opts.force &&
902 !check_branch_ref(the_repository, &symref, new_branch) &&
903 refs_ref_exists(get_main_ref_store(the_repository), symref.buf))
904 die_if_checked_out(symref.buf, 0);
905 strbuf_release(&symref);
906 }
907
908 if (opts.orphan && !new_branch) {
909 new_branch = new_branch_to_free = worktree_basename_dup(path);
910 } else if (opts.orphan) {
911 ; /* no-op */
912 } else if (opts.detach) {
913 /* Check HEAD */
914 if (!strcmp(branch, "HEAD"))
915 can_use_local_refs(&opts);
916 } else if (ac < 2 && new_branch) {
917 /* DWIM: Infer --orphan when repo has no refs. */
918 opts.orphan = dwim_orphan(&opts, !!opt_track, 0);
919 } else if (ac < 2) {
920 /* DWIM: Guess branch name from path. */
921 char *s = dwim_branch(&opts, path, &new_branch_to_free);
922 if (s)
923 branch = branch_to_free = s;
924 new_branch = new_branch_to_free;
925
926 /* DWIM: Infer --orphan when repo has no refs. */
927 opts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);
928 } else if (ac == 2 && new_branch) {
929 if (!strcmp(branch, "HEAD"))
930 can_use_local_refs(&opts);
931 } else if (ac == 2) {
932 struct commit *commit;
933
934 commit = lookup_commit_reference_by_name(branch);
935 if (!commit) {
936 struct object_id oid;
937 char *remote;
938 int num_matches = 0;
939 struct string_list matched_remote_names = STRING_LIST_INIT_DUP;
940
941 remote = unique_tracking_name(branch, &oid, &num_matches,
942 &matched_remote_names);
943 if (remote) {
944 new_branch = branch;
945 branch = new_branch_to_free = remote;
946 } else if (num_matches > 1) {
947 if (!opts.quiet &&
948 advice_enabled(ADVICE_CHECKOUT_AMBIGUOUS_REMOTE_BRANCH_NAME))
949 advise_disambiguating_remotes(path, branch,
950 &matched_remote_names);
951 die(_("'%s' matched multiple (%d) remote tracking branches"),
952 branch, num_matches);
953 }
954 string_list_clear(&matched_remote_names, 0);
955 }
956
957 if (!strcmp(branch, "HEAD"))
958 can_use_local_refs(&opts);
959
960 }
961
962 if (!opts.orphan && !lookup_commit_reference_by_name(branch)) {
963 int attempt_hint = !opts.quiet && (ac < 2);
964 if (attempt_hint && used_new_branch_options) {
965 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
966 WORKTREE_ADD_ORPHAN_WITH_DASH_B_HINT_TEXT,
967 new_branch, path);
968 } else if (attempt_hint) {
969 advise_if_enabled(ADVICE_WORKTREE_ADD_ORPHAN,
970 WORKTREE_ADD_ORPHAN_NO_DASH_B_HINT_TEXT, path);
971 }
972 die(_("invalid reference: %s"), branch);
973 }
974
975 if (!opts.quiet)
976 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
977
978 if (opts.orphan) {
979 branch = new_branch;
980 } else if (new_branch) {
981 struct child_process cp = CHILD_PROCESS_INIT;
982 cp.git_cmd = 1;
983 strvec_push(&cp.args, "branch");
984 if (new_branch_force)
985 strvec_push(&cp.args, "--force");
986 if (opts.quiet)
987 strvec_push(&cp.args, "--quiet");
988 strvec_push(&cp.args, new_branch);
989 strvec_push(&cp.args, branch);
990 if (opt_track)
991 strvec_push(&cp.args, opt_track);
992 if (run_command(&cp)) {
993 ret = -1;
994 goto cleanup;
995 }
996 branch = new_branch;
997 } else if (opt_track) {
998 die(_("--[no-]track can only be used if a new branch is created"));
999 }
1000
1001 ret = add_worktree(path, branch, &opts);
1002cleanup:
1003 free(path);
1004 free(opt_track);
1005 free(branch_to_free);
1006 free(new_branch_to_free);
1007 return ret;
1008}
1009
1010static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
1011{
1012 const char *reason;
1013
1014 printf("worktree %s%c", wt->path, line_terminator);
1015 if (wt->is_bare)
1016 printf("bare%c", line_terminator);
1017 else {
1018 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
1019 if (wt->is_detached)
1020 printf("detached%c", line_terminator);
1021 else if (wt->head_ref)
1022 printf("branch %s%c", wt->head_ref, line_terminator);
1023 }
1024
1025 reason = worktree_lock_reason(wt);
1026 if (reason) {
1027 fputs("locked", stdout);
1028 if (*reason) {
1029 fputc(' ', stdout);
1030 write_name_quoted(reason, stdout, line_terminator);
1031 } else {
1032 fputc(line_terminator, stdout);
1033 }
1034 }
1035
1036 reason = worktree_prune_reason(wt, expire);
1037 if (reason)
1038 printf("prunable %s%c", reason, line_terminator);
1039
1040 fputc(line_terminator, stdout);
1041}
1042
1043struct worktree_display {
1044 char *path;
1045 int width;
1046};
1047
1048static void show_worktree(struct worktree *wt, struct worktree_display *display,
1049 int path_maxwidth, int abbrev_len)
1050{
1051 struct strbuf sb = STRBUF_INIT;
1052 const char *reason;
1053
1054 strbuf_addf(&sb, "%s%*s", display->path, 1 + path_maxwidth - display->width, "");
1055 if (wt->is_bare)
1056 strbuf_addstr(&sb, "(bare)");
1057 else {
1058 strbuf_addf(&sb, "%-*s ", abbrev_len,
1059 repo_find_unique_abbrev(the_repository, &wt->head_oid, DEFAULT_ABBREV));
1060 if (wt->is_detached)
1061 strbuf_addstr(&sb, "(detached HEAD)");
1062 else if (wt->head_ref) {
1063 char *ref = refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1064 wt->head_ref,
1065 0);
1066 strbuf_addf(&sb, "[%s]", ref);
1067 free(ref);
1068 } else
1069 strbuf_addstr(&sb, "(error)");
1070 }
1071
1072 reason = worktree_lock_reason(wt);
1073 if (verbose && reason && *reason)
1074 strbuf_addf(&sb, "\n\tlocked: %s", reason);
1075 else if (reason)
1076 strbuf_addstr(&sb, " locked");
1077
1078 reason = worktree_prune_reason(wt, expire);
1079 if (verbose && reason)
1080 strbuf_addf(&sb, "\n\tprunable: %s", reason);
1081 else if (reason)
1082 strbuf_addstr(&sb, " prunable");
1083
1084 printf("%s\n", sb.buf);
1085 strbuf_release(&sb);
1086}
1087
1088static void measure_widths(struct worktree **wt, int *abbrev,
1089 struct worktree_display **d, int *maxwidth)
1090{
1091 int i, display_alloc = 0;
1092 struct worktree_display *display = NULL;
1093 struct strbuf buf = STRBUF_INIT;
1094
1095 for (i = 0; wt[i]; i++) {
1096 int sha1_len;
1097 ALLOC_GROW(display, i + 1, display_alloc);
1098 quote_path(wt[i]->path, NULL, &buf, 0);
1099 display[i].width = utf8_strwidth(buf.buf);
1100 display[i].path = strbuf_detach(&buf, NULL);
1101
1102 if (display[i].width > *maxwidth)
1103 *maxwidth = display[i].width;
1104 sha1_len = strlen(repo_find_unique_abbrev(the_repository, &wt[i]->head_oid, *abbrev));
1105 if (sha1_len > *abbrev)
1106 *abbrev = sha1_len;
1107 }
1108 *d = display;
1109}
1110
1111static int pathcmp(const void *a_, const void *b_)
1112{
1113 const struct worktree *const *a = a_;
1114 const struct worktree *const *b = b_;
1115 return fspathcmp((*a)->path, (*b)->path);
1116}
1117
1118static void pathsort(struct worktree **wt)
1119{
1120 int n = 0;
1121 struct worktree **p = wt;
1122
1123 while (*p++)
1124 n++;
1125 QSORT(wt, n, pathcmp);
1126}
1127
1128static int list(int ac, const char **av, const char *prefix,
1129 struct repository *repo UNUSED)
1130{
1131 int porcelain = 0;
1132 int line_terminator = '\n';
1133
1134 struct option options[] = {
1135 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
1136 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
1137 OPT_EXPIRY_DATE(0, "expire", &expire,
1138 N_("add 'prunable' annotation to missing worktrees older than <time>")),
1139 OPT_SET_INT('z', NULL, &line_terminator,
1140 N_("terminate records with a NUL character"), '\0'),
1141 OPT_END()
1142 };
1143
1144 expire = TIME_MAX;
1145 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
1146 if (ac)
1147 usage_with_options(git_worktree_list_usage, options);
1148 else if (verbose && porcelain)
1149 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
1150 else if (!line_terminator && !porcelain)
1151 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
1152 else {
1153 struct worktree **worktrees = get_worktrees(the_repository);
1154 int path_maxwidth = 0, abbrev = DEFAULT_ABBREV, i;
1155 struct worktree_display *display = NULL;
1156
1157 /* sort worktrees by path but keep main worktree at top */
1158 pathsort(worktrees + 1);
1159
1160 if (!porcelain)
1161 measure_widths(worktrees, &abbrev,
1162 &display, &path_maxwidth);
1163
1164 for (i = 0; worktrees[i]; i++) {
1165 if (porcelain)
1166 show_worktree_porcelain(worktrees[i],
1167 line_terminator);
1168 else
1169 show_worktree(worktrees[i],
1170 &display[i], path_maxwidth, abbrev);
1171 }
1172 for (i = 0; display && worktrees[i]; i++)
1173 free(display[i].path);
1174 free(display);
1175 free_worktrees(worktrees);
1176 }
1177 return 0;
1178}
1179
1180static int lock_worktree(int ac, const char **av, const char *prefix,
1181 struct repository *repo UNUSED)
1182{
1183 const char *reason = "", *old_reason;
1184 struct option options[] = {
1185 OPT_STRING(0, "reason", &reason, N_("string"),
1186 N_("reason for locking")),
1187 OPT_END()
1188 };
1189 struct worktree **worktrees, *wt;
1190 char *path;
1191
1192 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
1193 if (ac != 1)
1194 usage_with_options(git_worktree_lock_usage, options);
1195
1196 worktrees = get_worktrees(the_repository);
1197 wt = find_worktree(worktrees, prefix, av[0]);
1198 if (!wt)
1199 die(_("'%s' is not a working tree"), av[0]);
1200 if (is_main_worktree(wt))
1201 die(_("The main working tree cannot be locked or unlocked"));
1202
1203 old_reason = worktree_lock_reason(wt);
1204 if (old_reason) {
1205 if (*old_reason)
1206 die(_("'%s' is already locked, reason: %s"),
1207 av[0], old_reason);
1208 die(_("'%s' is already locked"), av[0]);
1209 }
1210
1211 path = repo_common_path(the_repository, "worktrees/%s/locked", wt->id);
1212 write_file(path, "%s", reason);
1213
1214 free_worktrees(worktrees);
1215 free(path);
1216 return 0;
1217}
1218
1219static int unlock_worktree(int ac, const char **av, const char *prefix,
1220 struct repository *repo UNUSED)
1221{
1222 struct option options[] = {
1223 OPT_END()
1224 };
1225 struct worktree **worktrees, *wt;
1226 char *path;
1227 int ret;
1228
1229 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
1230 if (ac != 1)
1231 usage_with_options(git_worktree_unlock_usage, options);
1232
1233 worktrees = get_worktrees(the_repository);
1234 wt = find_worktree(worktrees, prefix, av[0]);
1235 if (!wt)
1236 die(_("'%s' is not a working tree"), av[0]);
1237 if (is_main_worktree(wt))
1238 die(_("The main working tree cannot be locked or unlocked"));
1239 if (!worktree_lock_reason(wt))
1240 die(_("'%s' is not locked"), av[0]);
1241
1242 path = repo_common_path(the_repository, "worktrees/%s/locked", wt->id);
1243 ret = unlink_or_warn(path);
1244
1245 free_worktrees(worktrees);
1246 free(path);
1247 return ret;
1248}
1249
1250static void validate_no_submodules(const struct worktree *wt)
1251{
1252 struct index_state istate = INDEX_STATE_INIT(the_repository);
1253 struct strbuf path = STRBUF_INIT;
1254 int i, found_submodules = 0;
1255 char *wt_gitdir;
1256
1257 wt_gitdir = get_worktree_git_dir(wt);
1258
1259 if (is_directory(worktree_git_path(wt, "modules"))) {
1260 /*
1261 * There could be false positives, e.g. the "modules"
1262 * directory exists but is empty. But it's a rare case and
1263 * this simpler check is probably good enough for now.
1264 */
1265 found_submodules = 1;
1266 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
1267 wt_gitdir) > 0) {
1268 for (i = 0; i < istate.cache_nr; i++) {
1269 struct cache_entry *ce = istate.cache[i];
1270 int err;
1271
1272 if (!S_ISGITLINK(ce->ce_mode))
1273 continue;
1274
1275 strbuf_reset(&path);
1276 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
1277 if (!is_submodule_populated_gently(path.buf, &err))
1278 continue;
1279
1280 found_submodules = 1;
1281 break;
1282 }
1283 }
1284 discard_index(&istate);
1285 strbuf_release(&path);
1286 free(wt_gitdir);
1287
1288 if (found_submodules)
1289 die(_("working trees containing submodules cannot be moved or removed"));
1290}
1291
1292static int move_worktree(int ac, const char **av, const char *prefix,
1293 struct repository *repo UNUSED)
1294{
1295 int force = 0;
1296 struct option options[] = {
1297 OPT__FORCE(&force,
1298 N_("force move even if worktree is dirty or locked"),
1299 PARSE_OPT_NOCOMPLETE),
1300 OPT_BOOL(0, "relative-paths", &use_relative_paths,
1301 N_("use relative paths for worktrees")),
1302 OPT_END()
1303 };
1304 struct worktree **worktrees, *wt;
1305 struct strbuf dst = STRBUF_INIT;
1306 struct strbuf errmsg = STRBUF_INIT;
1307 const char *reason = NULL;
1308 char *path;
1309
1310 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
1311 0);
1312 if (ac != 2)
1313 usage_with_options(git_worktree_move_usage, options);
1314
1315 path = prefix_filename(prefix, av[1]);
1316 strbuf_addstr(&dst, path);
1317 free(path);
1318
1319 worktrees = get_worktrees(the_repository);
1320 wt = find_worktree(worktrees, prefix, av[0]);
1321 if (!wt)
1322 die(_("'%s' is not a working tree"), av[0]);
1323 if (is_main_worktree(wt))
1324 die(_("'%s' is a main working tree"), av[0]);
1325 if (is_directory(dst.buf)) {
1326 const char *sep = find_last_dir_sep(wt->path);
1327
1328 if (!sep)
1329 die(_("could not figure out destination name from '%s'"),
1330 wt->path);
1331 strbuf_trim_trailing_dir_sep(&dst);
1332 strbuf_addstr(&dst, sep);
1333 }
1334 check_candidate_path(dst.buf, force, worktrees, "move");
1335
1336 validate_no_submodules(wt);
1337
1338 if (force < 2)
1339 reason = worktree_lock_reason(wt);
1340 if (reason) {
1341 if (*reason)
1342 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1343 reason);
1344 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1345 }
1346 if (validate_worktree(wt, &errmsg, 0))
1347 die(_("validation failed, cannot move working tree: %s"),
1348 errmsg.buf);
1349 strbuf_release(&errmsg);
1350
1351 if (rename(wt->path, dst.buf) == -1)
1352 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1353
1354 update_worktree_location(wt, dst.buf, use_relative_paths);
1355
1356 strbuf_release(&dst);
1357 free_worktrees(worktrees);
1358 return 0;
1359}
1360
1361/*
1362 * Note, "git status --porcelain" is used to determine if it's safe to
1363 * delete a whole worktree. "git status" does not ignore user
1364 * configuration, so if a normal "git status" shows "clean" for the
1365 * user, then it's ok to remove it.
1366 *
1367 * This assumption may be a bad one. We may want to ignore
1368 * (potentially bad) user settings and only delete a worktree when
1369 * it's absolutely safe to do so from _our_ point of view because we
1370 * know better.
1371 */
1372static void check_clean_worktree(struct worktree *wt,
1373 const char *original_path)
1374{
1375 struct child_process cp;
1376 char buf[1];
1377 int ret;
1378
1379 /*
1380 * Until we sort this out, all submodules are "dirty" and
1381 * will abort this function.
1382 */
1383 validate_no_submodules(wt);
1384
1385 child_process_init(&cp);
1386 strvec_pushf(&cp.env, "%s=%s/.git",
1387 GIT_DIR_ENVIRONMENT, wt->path);
1388 strvec_pushf(&cp.env, "%s=%s",
1389 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1390 strvec_pushl(&cp.args, "status",
1391 "--porcelain", "--ignore-submodules=none",
1392 NULL);
1393 cp.git_cmd = 1;
1394 cp.dir = wt->path;
1395 cp.out = -1;
1396 ret = start_command(&cp);
1397 if (ret)
1398 die_errno(_("failed to run 'git status' on '%s'"),
1399 original_path);
1400 ret = xread(cp.out, buf, sizeof(buf));
1401 if (ret)
1402 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1403 original_path);
1404 close(cp.out);
1405 ret = finish_command(&cp);
1406 if (ret)
1407 die_errno(_("failed to run 'git status' on '%s', code %d"),
1408 original_path, ret);
1409}
1410
1411static int delete_git_work_tree(struct worktree *wt)
1412{
1413 struct strbuf sb = STRBUF_INIT;
1414 int ret = 0;
1415
1416 strbuf_addstr(&sb, wt->path);
1417 if (remove_dir_recursively(&sb, 0)) {
1418 error_errno(_("failed to delete '%s'"), sb.buf);
1419 ret = -1;
1420 }
1421 strbuf_release(&sb);
1422 return ret;
1423}
1424
1425static int remove_worktree(int ac, const char **av, const char *prefix,
1426 struct repository *repo UNUSED)
1427{
1428 int force = 0;
1429 struct option options[] = {
1430 OPT__FORCE(&force,
1431 N_("force removal even if worktree is dirty or locked"),
1432 PARSE_OPT_NOCOMPLETE),
1433 OPT_END()
1434 };
1435 struct worktree **worktrees, *wt;
1436 struct strbuf errmsg = STRBUF_INIT;
1437 const char *reason = NULL;
1438 int ret = 0;
1439
1440 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1441 if (ac != 1)
1442 usage_with_options(git_worktree_remove_usage, options);
1443
1444 worktrees = get_worktrees(the_repository);
1445 wt = find_worktree(worktrees, prefix, av[0]);
1446 if (!wt)
1447 die(_("'%s' is not a working tree"), av[0]);
1448 if (is_main_worktree(wt))
1449 die(_("'%s' is a main working tree"), av[0]);
1450 if (force < 2)
1451 reason = worktree_lock_reason(wt);
1452 if (reason) {
1453 if (*reason)
1454 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1455 reason);
1456 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1457 }
1458 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1459 die(_("validation failed, cannot remove working tree: %s"),
1460 errmsg.buf);
1461 strbuf_release(&errmsg);
1462
1463 if (file_exists(wt->path)) {
1464 if (!force)
1465 check_clean_worktree(wt, av[0]);
1466
1467 ret |= delete_git_work_tree(wt);
1468 }
1469 /*
1470 * continue on even if ret is non-zero, there's no going back
1471 * from here.
1472 */
1473 ret |= delete_git_dir(wt->id);
1474 delete_worktrees_dir_if_empty();
1475
1476 free_worktrees(worktrees);
1477 return ret;
1478}
1479
1480static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1481{
1482 if (!iserr) {
1483 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1484 } else {
1485 int *exit_status = (int *)cb_data;
1486 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1487 *exit_status = 1;
1488 }
1489}
1490
1491static int repair(int ac, const char **av, const char *prefix,
1492 struct repository *repo UNUSED)
1493{
1494 const char **p;
1495 const char *self[] = { ".", NULL };
1496 struct option options[] = {
1497 OPT_BOOL(0, "relative-paths", &use_relative_paths,
1498 N_("use relative paths for worktrees")),
1499 OPT_END()
1500 };
1501 int rc = 0;
1502
1503 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1504 p = ac > 0 ? av : self;
1505 for (; *p; p++)
1506 repair_worktree_at_path(the_repository, *p, report_repair,
1507 &rc, use_relative_paths);
1508 repair_worktrees(the_repository, report_repair, &rc, use_relative_paths);
1509 return rc;
1510}
1511
1512int cmd_worktree(int ac,
1513 const char **av,
1514 const char *prefix,
1515 struct repository *repo)
1516{
1517 parse_opt_subcommand_fn *fn = NULL;
1518 struct option options[] = {
1519 OPT_SUBCOMMAND("add", &fn, add),
1520 OPT_SUBCOMMAND("prune", &fn, prune),
1521 OPT_SUBCOMMAND("list", &fn, list),
1522 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1523 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1524 OPT_SUBCOMMAND("move", &fn, move_worktree),
1525 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1526 OPT_SUBCOMMAND("repair", &fn, repair),
1527 OPT_END()
1528 };
1529
1530 repo_config(the_repository, git_worktree_config, NULL);
1531
1532 if (!prefix)
1533 prefix = "";
1534
1535 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1536
1537 prepare_repo_settings(the_repository);
1538 the_repository->settings.command_requires_full_index = 0;
1539
1540 return fn(ac, av, prefix, repo);
1541}