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