worktree remove: allow it when $GIT_WORK_TREE is already gone
[git/git.git] / builtin / worktree.c
CommitLineData
df0b6cfb 1#include "cache.h"
4e853331 2#include "checkout.h"
b2141fc1 3#include "config.h"
df0b6cfb
NTND
4#include "builtin.h"
5#include "dir.h"
6#include "parse-options.h"
fc56361f 7#include "argv-array.h"
f7c9dac1
ES
8#include "branch.h"
9#include "refs.h"
fc56361f 10#include "run-command.h"
b979d950 11#include "sigchain.h"
799767cc 12#include "refs.h"
bb9c03b8
MR
13#include "utf8.h"
14#include "worktree.h"
df0b6cfb
NTND
15
16static const char * const worktree_usage[] = {
ae9f2745 17 N_("git worktree add [<options>] <path> [<branch>]"),
bb9c03b8 18 N_("git worktree list [<options>]"),
58142c09 19 N_("git worktree lock [<options>] <path>"),
9f792bb4 20 N_("git worktree move <worktree> <new-path>"),
7b722d90 21 N_("git worktree prune [<options>]"),
cc73385c 22 N_("git worktree remove [<options>] <worktree>"),
6d308627 23 N_("git worktree unlock <path>"),
df0b6cfb
NTND
24 NULL
25};
26
5dd6e234
ES
27struct add_opts {
28 int force;
29 int detach;
ef2a0ac9 30 int checkout;
507e6e9e 31 int keep_locked;
5dd6e234
ES
32 const char *new_branch;
33 int force_new_branch;
34};
35
df0b6cfb
NTND
36static int show_only;
37static int verbose;
e92445a7 38static int guess_remote;
dddbad72 39static timestamp_t expire;
df0b6cfb 40
e92445a7
TG
41static int git_worktree_config(const char *var, const char *value, void *cb)
42{
43 if (!strcmp(var, "worktree.guessremote")) {
44 guess_remote = git_config_bool(var, value);
45 return 0;
46 }
47
48 return git_default_config(var, value, cb);
49}
50
df0b6cfb
NTND
51static int prune_worktree(const char *id, struct strbuf *reason)
52{
53 struct stat st;
54 char *path;
228740b6
JK
55 int fd;
56 size_t len;
8a1a8d2a 57 ssize_t read_result;
df0b6cfb
NTND
58
59 if (!is_directory(git_path("worktrees/%s", id))) {
60 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
61 return 1;
62 }
63 if (file_exists(git_path("worktrees/%s/locked", id)))
64 return 0;
65 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
66 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
67 return 1;
68 }
69 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
70 if (fd < 0) {
71 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
72 id, strerror(errno));
73 return 1;
74 }
228740b6 75 len = xsize_t(st.st_size);
3733e694 76 path = xmallocz(len);
8a1a8d2a
JK
77
78 read_result = read_in_full(fd, path, len);
79 if (read_result < 0) {
80 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
81 id, strerror(errno));
82 close(fd);
83 free(path);
84 return 1;
85 }
df0b6cfb 86 close(fd);
8a1a8d2a
JK
87
88 if (read_result != len) {
89 strbuf_addf(reason,
90 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
91 id, (uintmax_t)len, (uintmax_t)read_result);
92 free(path);
93 return 1;
94 }
df0b6cfb
NTND
95 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
96 len--;
97 if (!len) {
98 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
99 free(path);
100 return 1;
101 }
102 path[len] = '\0';
103 if (!file_exists(path)) {
104 struct stat st_link;
105 free(path);
106 /*
107 * the repo is moved manually and has not been
108 * accessed since?
109 */
110 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
111 st_link.st_nlink > 1)
112 return 0;
113 if (st.st_mtime <= expire) {
114 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
115 return 1;
116 } else {
117 return 0;
118 }
119 }
120 free(path);
121 return 0;
122}
123
124static void prune_worktrees(void)
125{
126 struct strbuf reason = STRBUF_INIT;
127 struct strbuf path = STRBUF_INIT;
128 DIR *dir = opendir(git_path("worktrees"));
129 struct dirent *d;
130 int ret;
131 if (!dir)
132 return;
133 while ((d = readdir(dir)) != NULL) {
afb9e30b 134 if (is_dot_or_dotdot(d->d_name))
df0b6cfb
NTND
135 continue;
136 strbuf_reset(&reason);
137 if (!prune_worktree(d->d_name, &reason))
138 continue;
139 if (show_only || verbose)
140 printf("%s\n", reason.buf);
141 if (show_only)
142 continue;
8c2ca3a6 143 git_path_buf(&path, "worktrees/%s", d->d_name);
df0b6cfb
NTND
144 ret = remove_dir_recursively(&path, 0);
145 if (ret < 0 && errno == ENOTDIR)
146 ret = unlink(path.buf);
147 if (ret)
8d19e930 148 error_errno(_("failed to remove '%s'"), path.buf);
df0b6cfb
NTND
149 }
150 closedir(dir);
151 if (!show_only)
152 rmdir(git_path("worktrees"));
153 strbuf_release(&reason);
154 strbuf_release(&path);
155}
156
157static int prune(int ac, const char **av, const char *prefix)
158{
159 struct option options[] = {
160 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
2488dcab 161 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
df0b6cfb 162 OPT_EXPIRY_DATE(0, "expire", &expire,
2488dcab 163 N_("expire working trees older than <time>")),
df0b6cfb
NTND
164 OPT_END()
165 };
166
dddbad72 167 expire = TIME_MAX;
df0b6cfb
NTND
168 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
169 if (ac)
170 usage_with_options(worktree_usage, options);
171 prune_worktrees();
172 return 0;
173}
174
b979d950
ES
175static char *junk_work_tree;
176static char *junk_git_dir;
177static int is_junk;
178static pid_t junk_pid;
179
180static void remove_junk(void)
181{
182 struct strbuf sb = STRBUF_INIT;
183 if (!is_junk || getpid() != junk_pid)
184 return;
185 if (junk_git_dir) {
186 strbuf_addstr(&sb, junk_git_dir);
187 remove_dir_recursively(&sb, 0);
188 strbuf_reset(&sb);
189 }
190 if (junk_work_tree) {
191 strbuf_addstr(&sb, junk_work_tree);
192 remove_dir_recursively(&sb, 0);
193 }
194 strbuf_release(&sb);
195}
196
197static void remove_junk_on_signal(int signo)
198{
199 remove_junk();
200 sigchain_pop(signo);
201 raise(signo);
202}
203
f5682b2a
ES
204static const char *worktree_basename(const char *path, int *olen)
205{
206 const char *name;
207 int len;
208
209 len = strlen(path);
210 while (len && is_dir_sep(path[len - 1]))
211 len--;
212
213 for (name = path + len - 1; name > path; name--)
214 if (is_dir_sep(*name)) {
215 name++;
216 break;
217 }
218
219 *olen = len;
220 return name;
221}
222
80a0548f 223static int add_worktree(const char *path, const char *refname,
5dd6e234 224 const struct add_opts *opts)
b979d950
ES
225{
226 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
227 struct strbuf sb = STRBUF_INIT;
228 const char *name;
229 struct stat st;
542aa25d 230 struct child_process cp = CHILD_PROCESS_INIT;
ae2a3827 231 struct argv_array child_env = ARGV_ARRAY_INIT;
b979d950 232 int counter = 0, len, ret;
f7c9dac1
ES
233 struct strbuf symref = STRBUF_INIT;
234 struct commit *commit = NULL;
ade546be 235 int is_branch = 0;
b979d950
ES
236
237 if (file_exists(path) && !is_empty_dir(path))
238 die(_("'%s' already exists"), path);
239
f7c9dac1 240 /* is 'refname' a branch or commit? */
0ebf4a2a 241 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
ade546be
ES
242 ref_exists(symref.buf)) {
243 is_branch = 1;
f7c9dac1 244 if (!opts->force)
8d9fdd70 245 die_if_checked_out(symref.buf, 0);
f7c9dac1 246 }
ade546be
ES
247 commit = lookup_commit_reference_by_name(refname);
248 if (!commit)
249 die(_("invalid reference: %s"), refname);
f7c9dac1 250
f5682b2a 251 name = worktree_basename(path, &len);
8c2ca3a6 252 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
b979d950
ES
253 len = sb_repo.len;
254 if (safe_create_leading_directories_const(sb_repo.buf))
255 die_errno(_("could not create leading directories of '%s'"),
256 sb_repo.buf);
257 while (!stat(sb_repo.buf, &st)) {
258 counter++;
259 strbuf_setlen(&sb_repo, len);
260 strbuf_addf(&sb_repo, "%d", counter);
261 }
262 name = strrchr(sb_repo.buf, '/') + 1;
263
264 junk_pid = getpid();
265 atexit(remove_junk);
266 sigchain_push_common(remove_junk_on_signal);
267
268 if (mkdir(sb_repo.buf, 0777))
269 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
270 junk_git_dir = xstrdup(sb_repo.buf);
271 is_junk = 1;
272
273 /*
274 * lock the incomplete repo so prune won't delete it, unlock
275 * after the preparation is over.
276 */
277 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
507e6e9e
NTND
278 if (!opts->keep_locked)
279 write_file(sb.buf, "initializing");
280 else
281 write_file(sb.buf, "added with --lock");
b979d950
ES
282
283 strbuf_addf(&sb_git, "%s/.git", path);
284 if (safe_create_leading_directories_const(sb_git.buf))
285 die_errno(_("could not create leading directories of '%s'"),
286 sb_git.buf);
287 junk_work_tree = xstrdup(path);
288
289 strbuf_reset(&sb);
290 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
1f76a10b
JH
291 write_file(sb.buf, "%s", real_path(sb_git.buf));
292 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
b979d950
ES
293 real_path(get_git_common_dir()), name);
294 /*
295 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
296 * or is_git_directory() will reject the directory. Any value which
297 * looks like an object ID will do since it will be immediately
298 * replaced by the symbolic-ref or update-ref invocation in the new
299 * worktree.
b979d950 300 */
b979d950
ES
301 strbuf_reset(&sb);
302 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
dabd35f4 303 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
b979d950
ES
304 strbuf_reset(&sb);
305 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 306 write_file(sb.buf, "../..");
b979d950 307
cd2f4713 308 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
b979d950 309
ae2a3827
ES
310 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
311 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950 312 cp.git_cmd = 1;
7f44e3d1 313
ade546be 314 if (!is_branch)
7f44e3d1 315 argv_array_pushl(&cp.args, "update-ref", "HEAD",
f2fd0760 316 oid_to_hex(&commit->object.oid), NULL);
7f44e3d1
ES
317 else
318 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
319 symref.buf, NULL);
320 cp.env = child_env.argv;
321 ret = run_command(&cp);
322 if (ret)
323 goto done;
324
ef2a0ac9
RZ
325 if (opts->checkout) {
326 cp.argv = NULL;
327 argv_array_clear(&cp.args);
328 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
329 cp.env = child_env.argv;
330 ret = run_command(&cp);
331 if (ret)
332 goto done;
b979d950 333 }
ef2a0ac9
RZ
334
335 is_junk = 0;
88ce3ef6
ÆAB
336 FREE_AND_NULL(junk_work_tree);
337 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 338
7f44e3d1 339done:
507e6e9e
NTND
340 if (ret || !opts->keep_locked) {
341 strbuf_reset(&sb);
342 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
343 unlink_or_warn(sb.buf);
344 }
ade546be
ES
345
346 /*
347 * Hook failure does not warrant worktree deletion, so run hook after
348 * is_junk is cleared, but do return appropriate code when hook fails.
349 */
350 if (!ret && opts->checkout)
351 ret = run_hook_le(NULL, "post-checkout", oid_to_hex(&null_oid),
352 oid_to_hex(&commit->object.oid), "1", NULL);
353
ae2a3827 354 argv_array_clear(&child_env);
b979d950 355 strbuf_release(&sb);
f7c9dac1 356 strbuf_release(&symref);
b979d950
ES
357 strbuf_release(&sb_repo);
358 strbuf_release(&sb_git);
359 return ret;
360}
361
fc56361f
ES
362static int add(int ac, const char **av, const char *prefix)
363{
5dd6e234
ES
364 struct add_opts opts;
365 const char *new_branch_force = NULL;
e4da43b1
JK
366 char *path;
367 const char *branch;
e284e892 368 const char *opt_track = NULL;
fc56361f 369 struct option options[] = {
5dd6e234
ES
370 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
371 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
cbdf60fa
ES
372 N_("create a new branch")),
373 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
374 N_("create or reset a branch")),
5dd6e234 375 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 376 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
507e6e9e 377 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
e284e892
TG
378 OPT_PASSTHRU(0, "track", &opt_track, NULL,
379 N_("set up tracking mode (see git-branch(1))"),
380 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
71d6682d
TG
381 OPT_BOOL(0, "guess-remote", &guess_remote,
382 N_("try to match the new branch name with a remote-tracking branch")),
fc56361f
ES
383 OPT_END()
384 };
385
5dd6e234 386 memset(&opts, 0, sizeof(opts));
ef2a0ac9 387 opts.checkout = 1;
fc56361f 388 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
ab0b2c53
ES
389 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
390 die(_("-b, -B, and --detach are mutually exclusive"));
0f4af3b9
ES
391 if (ac < 1 || ac > 2)
392 usage_with_options(worktree_usage, options);
fc56361f 393
116fb64e 394 path = prefix_filename(prefix, av[0]);
0f4af3b9 395 branch = ac < 2 ? "HEAD" : av[1];
fc56361f 396
1a450e2f
JDG
397 if (!strcmp(branch, "-"))
398 branch = "@{-1}";
399
5dd6e234 400 opts.force_new_branch = !!new_branch_force;
beb6f24b
NTND
401 if (opts.force_new_branch) {
402 struct strbuf symref = STRBUF_INIT;
403
5dd6e234 404 opts.new_branch = new_branch_force;
eef005dc 405
beb6f24b
NTND
406 if (!opts.force &&
407 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
408 ref_exists(symref.buf))
8d9fdd70 409 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
410 strbuf_release(&symref);
411 }
412
5c942570 413 if (ac < 2 && !opts.new_branch && !opts.detach) {
1eb07d82
ES
414 int n;
415 const char *s = worktree_basename(path, &n);
5dd6e234 416 opts.new_branch = xstrndup(s, n);
71d6682d
TG
417 if (guess_remote) {
418 struct object_id oid;
419 const char *remote =
420 unique_tracking_name(opts.new_branch, &oid);
421 if (remote)
422 branch = remote;
423 }
1eb07d82
ES
424 }
425
4e853331
TG
426 if (ac == 2 && !opts.new_branch && !opts.detach) {
427 struct object_id oid;
428 struct commit *commit;
429 const char *remote;
430
431 commit = lookup_commit_reference_by_name(branch);
432 if (!commit) {
433 remote = unique_tracking_name(branch, &oid);
434 if (remote) {
435 opts.new_branch = branch;
436 branch = remote;
437 }
438 }
439 }
440
c2842439 441 if (opts.new_branch) {
542aa25d 442 struct child_process cp = CHILD_PROCESS_INIT;
c2842439
ES
443 cp.git_cmd = 1;
444 argv_array_push(&cp.args, "branch");
445 if (opts.force_new_branch)
446 argv_array_push(&cp.args, "--force");
447 argv_array_push(&cp.args, opts.new_branch);
448 argv_array_push(&cp.args, branch);
e284e892
TG
449 if (opt_track)
450 argv_array_push(&cp.args, opt_track);
c2842439
ES
451 if (run_command(&cp))
452 return -1;
453 branch = opts.new_branch;
e284e892
TG
454 } else if (opt_track) {
455 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
456 }
457
0e5bba53
JK
458 UNLEAK(path);
459 UNLEAK(opts);
80a0548f 460 return add_worktree(path, branch, &opts);
fc56361f
ES
461}
462
bb9c03b8
MR
463static void show_worktree_porcelain(struct worktree *wt)
464{
465 printf("worktree %s\n", wt->path);
466 if (wt->is_bare)
467 printf("bare\n");
468 else {
0f05154c 469 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
bb9c03b8
MR
470 if (wt->is_detached)
471 printf("detached\n");
a234563a 472 else if (wt->head_ref)
bb9c03b8
MR
473 printf("branch %s\n", wt->head_ref);
474 }
475 printf("\n");
476}
477
478static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
479{
480 struct strbuf sb = STRBUF_INIT;
481 int cur_path_len = strlen(wt->path);
482 int path_adj = cur_path_len - utf8_strwidth(wt->path);
483
484 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
485 if (wt->is_bare)
486 strbuf_addstr(&sb, "(bare)");
487 else {
488 strbuf_addf(&sb, "%-*s ", abbrev_len,
0f05154c 489 find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
96f09e2a 490 if (wt->is_detached)
bb9c03b8 491 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
492 else if (wt->head_ref) {
493 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
494 strbuf_addf(&sb, "[%s]", ref);
495 free(ref);
496 } else
a234563a 497 strbuf_addstr(&sb, "(error)");
bb9c03b8
MR
498 }
499 printf("%s\n", sb.buf);
500
501 strbuf_release(&sb);
502}
503
504static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
505{
506 int i;
507
508 for (i = 0; wt[i]; i++) {
509 int sha1_len;
510 int path_len = strlen(wt[i]->path);
511
512 if (path_len > *maxlen)
513 *maxlen = path_len;
0f05154c 514 sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
bb9c03b8
MR
515 if (sha1_len > *abbrev)
516 *abbrev = sha1_len;
517 }
518}
519
520static int list(int ac, const char **av, const char *prefix)
521{
522 int porcelain = 0;
523
524 struct option options[] = {
525 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
526 OPT_END()
527 };
528
529 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
530 if (ac)
531 usage_with_options(worktree_usage, options);
532 else {
4df1d4d4 533 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
bb9c03b8
MR
534 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
535
536 if (!porcelain)
537 measure_widths(worktrees, &abbrev, &path_maxlen);
538
539 for (i = 0; worktrees[i]; i++) {
540 if (porcelain)
541 show_worktree_porcelain(worktrees[i]);
542 else
543 show_worktree(worktrees[i], path_maxlen, abbrev);
544 }
545 free_worktrees(worktrees);
546 }
547 return 0;
548}
549
58142c09
NTND
550static int lock_worktree(int ac, const char **av, const char *prefix)
551{
552 const char *reason = "", *old_reason;
553 struct option options[] = {
554 OPT_STRING(0, "reason", &reason, N_("string"),
555 N_("reason for locking")),
556 OPT_END()
557 };
558 struct worktree **worktrees, *wt;
559
560 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
561 if (ac != 1)
562 usage_with_options(worktree_usage, options);
563
4fff1ef7 564 worktrees = get_worktrees(0);
58142c09
NTND
565 wt = find_worktree(worktrees, prefix, av[0]);
566 if (!wt)
567 die(_("'%s' is not a working tree"), av[0]);
568 if (is_main_worktree(wt))
569 die(_("The main working tree cannot be locked or unlocked"));
570
571 old_reason = is_worktree_locked(wt);
572 if (old_reason) {
573 if (*old_reason)
574 die(_("'%s' is already locked, reason: %s"),
575 av[0], old_reason);
576 die(_("'%s' is already locked"), av[0]);
577 }
578
579 write_file(git_common_path("worktrees/%s/locked", wt->id),
580 "%s", reason);
581 free_worktrees(worktrees);
582 return 0;
583}
584
6d308627
NTND
585static int unlock_worktree(int ac, const char **av, const char *prefix)
586{
587 struct option options[] = {
588 OPT_END()
589 };
590 struct worktree **worktrees, *wt;
591 int ret;
592
593 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
594 if (ac != 1)
595 usage_with_options(worktree_usage, options);
596
4fff1ef7 597 worktrees = get_worktrees(0);
6d308627
NTND
598 wt = find_worktree(worktrees, prefix, av[0]);
599 if (!wt)
600 die(_("'%s' is not a working tree"), av[0]);
601 if (is_main_worktree(wt))
602 die(_("The main working tree cannot be locked or unlocked"));
603 if (!is_worktree_locked(wt))
604 die(_("'%s' is not locked"), av[0]);
605 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
606 free_worktrees(worktrees);
607 return ret;
608}
609
78d986b2
NTND
610static void validate_no_submodules(const struct worktree *wt)
611{
612 struct index_state istate = { NULL };
613 int i, found_submodules = 0;
614
615 if (read_index_from(&istate, worktree_git_path(wt, "index")) > 0) {
616 for (i = 0; i < istate.cache_nr; i++) {
617 struct cache_entry *ce = istate.cache[i];
618
619 if (S_ISGITLINK(ce->ce_mode)) {
620 found_submodules = 1;
621 break;
622 }
623 }
624 }
625 discard_index(&istate);
626
627 if (found_submodules)
cc73385c 628 die(_("working trees containing submodules cannot be moved or removed"));
78d986b2
NTND
629}
630
9f792bb4
NTND
631static int move_worktree(int ac, const char **av, const char *prefix)
632{
633 struct option options[] = {
634 OPT_END()
635 };
636 struct worktree **worktrees, *wt;
637 struct strbuf dst = STRBUF_INIT;
638 struct strbuf errmsg = STRBUF_INIT;
639 const char *reason;
640 char *path;
641
642 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
643 if (ac != 2)
644 usage_with_options(worktree_usage, options);
645
646 path = prefix_filename(prefix, av[1]);
647 strbuf_addstr(&dst, path);
648 free(path);
649
650 worktrees = get_worktrees(0);
651 wt = find_worktree(worktrees, prefix, av[0]);
652 if (!wt)
653 die(_("'%s' is not a working tree"), av[0]);
654 if (is_main_worktree(wt))
655 die(_("'%s' is a main working tree"), av[0]);
c64a8d20
NTND
656 if (is_directory(dst.buf)) {
657 const char *sep = find_last_dir_sep(wt->path);
658
659 if (!sep)
660 die(_("could not figure out destination name from '%s'"),
661 wt->path);
662 strbuf_trim_trailing_dir_sep(&dst);
663 strbuf_addstr(&dst, sep);
664 }
9f792bb4 665 if (file_exists(dst.buf))
c64a8d20 666 die(_("target '%s' already exists"), dst.buf);
9f792bb4 667
78d986b2
NTND
668 validate_no_submodules(wt);
669
9f792bb4
NTND
670 reason = is_worktree_locked(wt);
671 if (reason) {
672 if (*reason)
673 die(_("cannot move a locked working tree, lock reason: %s"),
674 reason);
675 die(_("cannot move a locked working tree"));
676 }
ee6763af 677 if (validate_worktree(wt, &errmsg, 0))
9f792bb4
NTND
678 die(_("validation failed, cannot move working tree: %s"),
679 errmsg.buf);
680 strbuf_release(&errmsg);
681
682 if (rename(wt->path, dst.buf) == -1)
683 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
684
685 update_worktree_location(wt, dst.buf);
686
687 strbuf_release(&dst);
688 free_worktrees(worktrees);
689 return 0;
690}
691
cc73385c
NTND
692/*
693 * Note, "git status --porcelain" is used to determine if it's safe to
694 * delete a whole worktree. "git status" does not ignore user
695 * configuration, so if a normal "git status" shows "clean" for the
696 * user, then it's ok to remove it.
697 *
698 * This assumption may be a bad one. We may want to ignore
699 * (potentially bad) user settings and only delete a worktree when
700 * it's absolutely safe to do so from _our_ point of view because we
701 * know better.
702 */
703static void check_clean_worktree(struct worktree *wt,
704 const char *original_path)
705{
706 struct argv_array child_env = ARGV_ARRAY_INIT;
707 struct child_process cp;
708 char buf[1];
709 int ret;
710
711 /*
712 * Until we sort this out, all submodules are "dirty" and
713 * will abort this function.
714 */
715 validate_no_submodules(wt);
716
717 argv_array_pushf(&child_env, "%s=%s/.git",
718 GIT_DIR_ENVIRONMENT, wt->path);
719 argv_array_pushf(&child_env, "%s=%s",
720 GIT_WORK_TREE_ENVIRONMENT, wt->path);
721 memset(&cp, 0, sizeof(cp));
722 argv_array_pushl(&cp.args, "status",
723 "--porcelain", "--ignore-submodules=none",
724 NULL);
725 cp.env = child_env.argv;
726 cp.git_cmd = 1;
727 cp.dir = wt->path;
728 cp.out = -1;
729 ret = start_command(&cp);
730 if (ret)
731 die_errno(_("failed to run 'git status' on '%s'"),
732 original_path);
733 ret = xread(cp.out, buf, sizeof(buf));
734 if (ret)
735 die(_("'%s' is dirty, use --force to delete it"),
736 original_path);
737 close(cp.out);
738 ret = finish_command(&cp);
739 if (ret)
740 die_errno(_("failed to run 'git status' on '%s', code %d"),
741 original_path, ret);
742}
743
744static int delete_git_work_tree(struct worktree *wt)
745{
746 struct strbuf sb = STRBUF_INIT;
747 int ret = 0;
748
749 strbuf_addstr(&sb, wt->path);
750 if (remove_dir_recursively(&sb, 0)) {
751 error_errno(_("failed to delete '%s'"), sb.buf);
752 ret = -1;
753 }
754 strbuf_release(&sb);
755 return ret;
756}
757
758static int delete_git_dir(struct worktree *wt)
759{
760 struct strbuf sb = STRBUF_INIT;
761 int ret = 0;
762
763 strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
764 if (remove_dir_recursively(&sb, 0)) {
765 error_errno(_("failed to delete '%s'"), sb.buf);
766 ret = -1;
767 }
768 strbuf_release(&sb);
769 return ret;
770}
771
772static int remove_worktree(int ac, const char **av, const char *prefix)
773{
774 int force = 0;
775 struct option options[] = {
776 OPT_BOOL(0, "force", &force,
777 N_("force removing even if the worktree is dirty")),
778 OPT_END()
779 };
780 struct worktree **worktrees, *wt;
781 struct strbuf errmsg = STRBUF_INIT;
782 const char *reason;
783 int ret = 0;
784
785 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
786 if (ac != 1)
787 usage_with_options(worktree_usage, options);
788
789 worktrees = get_worktrees(0);
790 wt = find_worktree(worktrees, prefix, av[0]);
791 if (!wt)
792 die(_("'%s' is not a working tree"), av[0]);
793 if (is_main_worktree(wt))
794 die(_("'%s' is a main working tree"), av[0]);
795 reason = is_worktree_locked(wt);
796 if (reason) {
797 if (*reason)
798 die(_("cannot remove a locked working tree, lock reason: %s"),
799 reason);
800 die(_("cannot remove a locked working tree"));
801 }
ee6763af 802 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
cc73385c
NTND
803 die(_("validation failed, cannot remove working tree: %s"),
804 errmsg.buf);
805 strbuf_release(&errmsg);
806
ee6763af
NTND
807 if (file_exists(wt->path)) {
808 if (!force)
809 check_clean_worktree(wt, av[0]);
cc73385c 810
ee6763af
NTND
811 ret |= delete_git_work_tree(wt);
812 }
cc73385c
NTND
813 /*
814 * continue on even if ret is non-zero, there's no going back
815 * from here.
816 */
817 ret |= delete_git_dir(wt);
818
819 free_worktrees(worktrees);
820 return ret;
821}
822
df0b6cfb
NTND
823int cmd_worktree(int ac, const char **av, const char *prefix)
824{
825 struct option options[] = {
826 OPT_END()
827 };
828
e92445a7 829 git_config(git_worktree_config, NULL);
d49028e6 830
df0b6cfb
NTND
831 if (ac < 2)
832 usage_with_options(worktree_usage, options);
0409e0b6
NTND
833 if (!prefix)
834 prefix = "";
fc56361f
ES
835 if (!strcmp(av[1], "add"))
836 return add(ac - 1, av + 1, prefix);
df0b6cfb
NTND
837 if (!strcmp(av[1], "prune"))
838 return prune(ac - 1, av + 1, prefix);
bb9c03b8
MR
839 if (!strcmp(av[1], "list"))
840 return list(ac - 1, av + 1, prefix);
58142c09
NTND
841 if (!strcmp(av[1], "lock"))
842 return lock_worktree(ac - 1, av + 1, prefix);
6d308627
NTND
843 if (!strcmp(av[1], "unlock"))
844 return unlock_worktree(ac - 1, av + 1, prefix);
9f792bb4
NTND
845 if (!strcmp(av[1], "move"))
846 return move_worktree(ac - 1, av + 1, prefix);
cc73385c
NTND
847 if (!strcmp(av[1], "remove"))
848 return remove_worktree(ac - 1, av + 1, prefix);
df0b6cfb
NTND
849 usage_with_options(worktree_usage, options);
850}