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