worktree: give "should be pruned?" function more meaningful name
[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 "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 delete_git_dir(const char *id)
51 {
52         struct strbuf sb = STRBUF_INIT;
53         int ret;
54
55         strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
56         ret = remove_dir_recursively(&sb, 0);
57         if (ret < 0 && errno == ENOTDIR)
58                 ret = unlink(sb.buf);
59         if (ret)
60                 error_errno(_("failed to delete '%s'"), sb.buf);
61         strbuf_release(&sb);
62         return ret;
63 }
64
65 static void delete_worktrees_dir_if_empty(void)
66 {
67         rmdir(git_path("worktrees")); /* ignore failed removal */
68 }
69
70 static int should_prune_worktree(const char *id, struct strbuf *reason)
71 {
72         struct stat st;
73         char *path;
74         int fd;
75         size_t len;
76         ssize_t read_result;
77
78         if (!is_directory(git_path("worktrees/%s", id))) {
79                 strbuf_addstr(reason, _("not a valid directory"));
80                 return 1;
81         }
82         if (file_exists(git_path("worktrees/%s/locked", id)))
83                 return 0;
84         if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
85                 strbuf_addstr(reason, _("gitdir file does not exist"));
86                 return 1;
87         }
88         fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
89         if (fd < 0) {
90                 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
91                             strerror(errno));
92                 return 1;
93         }
94         len = xsize_t(st.st_size);
95         path = xmallocz(len);
96
97         read_result = read_in_full(fd, path, len);
98         if (read_result < 0) {
99                 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
100                             strerror(errno));
101                 close(fd);
102                 free(path);
103                 return 1;
104         }
105         close(fd);
106
107         if (read_result != len) {
108                 strbuf_addf(reason,
109                             _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
110                             (uintmax_t)len, (uintmax_t)read_result);
111                 free(path);
112                 return 1;
113         }
114         while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
115                 len--;
116         if (!len) {
117                 strbuf_addstr(reason, _("invalid gitdir file"));
118                 free(path);
119                 return 1;
120         }
121         path[len] = '\0';
122         if (!file_exists(path)) {
123                 free(path);
124                 if (stat(git_path("worktrees/%s/index", id), &st) ||
125                     st.st_mtime <= expire) {
126                         strbuf_addstr(reason, _("gitdir file points to non-existent location"));
127                         return 1;
128                 } else {
129                         return 0;
130                 }
131         }
132         free(path);
133         return 0;
134 }
135
136 static void prune_worktrees(void)
137 {
138         struct strbuf reason = STRBUF_INIT;
139         DIR *dir = opendir(git_path("worktrees"));
140         struct dirent *d;
141         if (!dir)
142                 return;
143         while ((d = readdir(dir)) != NULL) {
144                 if (is_dot_or_dotdot(d->d_name))
145                         continue;
146                 strbuf_reset(&reason);
147                 if (!should_prune_worktree(d->d_name, &reason))
148                         continue;
149                 if (show_only || verbose)
150                         printf_ln(_("Removing %s/%s: %s"),
151                                   "worktrees", d->d_name, 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         wt = find_worktree_by_path(worktrees, path);
239         if (!wt)
240                 goto done;
241
242         locked = !!worktree_lock_reason(wt);
243         if ((!locked && opts->force) || (locked && opts->force > 1)) {
244                 if (delete_git_dir(wt->id))
245                     die(_("unable to re-add worktree '%s'"), path);
246                 goto done;
247         }
248
249         if (locked)
250                 die(_("'%s' is a missing but locked worktree;\nuse 'add -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path);
251         else
252                 die(_("'%s' is a missing but already registered worktree;\nuse 'add -f' to override, or 'prune' or 'remove' to clear"), path);
253
254 done:
255         free_worktrees(worktrees);
256 }
257
258 static int add_worktree(const char *path, const char *refname,
259                         const struct add_opts *opts)
260 {
261         struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
262         struct strbuf sb = STRBUF_INIT;
263         const char *name;
264         struct child_process cp = CHILD_PROCESS_INIT;
265         struct argv_array child_env = ARGV_ARRAY_INIT;
266         unsigned int counter = 0;
267         int len, ret;
268         struct strbuf symref = STRBUF_INIT;
269         struct commit *commit = NULL;
270         int is_branch = 0;
271         struct strbuf sb_name = STRBUF_INIT;
272
273         validate_worktree_add(path, opts);
274
275         /* is 'refname' a branch or commit? */
276         if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
277             ref_exists(symref.buf)) {
278                 is_branch = 1;
279                 if (!opts->force)
280                         die_if_checked_out(symref.buf, 0);
281         }
282         commit = lookup_commit_reference_by_name(refname);
283         if (!commit)
284                 die(_("invalid reference: %s"), refname);
285
286         name = worktree_basename(path, &len);
287         strbuf_add(&sb, name, path + len - name);
288         sanitize_refname_component(sb.buf, &sb_name);
289         if (!sb_name.len)
290                 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
291         strbuf_reset(&sb);
292         name = sb_name.buf;
293         git_path_buf(&sb_repo, "worktrees/%s", 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", oid_to_hex(&null_oid));
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", "--no-recurse-submodules", 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                         cp.trace2_hook_name = "post-checkout";
408                         argv_array_pushl(&cp.args, absolute_path(hook),
409                                          oid_to_hex(&null_oid),
410                                          oid_to_hex(&commit->object.oid),
411                                          "1", NULL);
412                         ret = run_command(&cp);
413                 }
414         }
415
416         argv_array_clear(&child_env);
417         strbuf_release(&sb);
418         strbuf_release(&symref);
419         strbuf_release(&sb_repo);
420         strbuf_release(&sb_git);
421         strbuf_release(&sb_name);
422         return ret;
423 }
424
425 static void print_preparing_worktree_line(int detach,
426                                           const char *branch,
427                                           const char *new_branch,
428                                           int force_new_branch)
429 {
430         if (force_new_branch) {
431                 struct commit *commit = lookup_commit_reference_by_name(new_branch);
432                 if (!commit)
433                         printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
434                 else
435                         printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
436                                   new_branch,
437                                   find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
438         } else if (new_branch) {
439                 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
440         } else {
441                 struct strbuf s = STRBUF_INIT;
442                 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
443                     ref_exists(s.buf))
444                         printf_ln(_("Preparing worktree (checking out '%s')"),
445                                   branch);
446                 else {
447                         struct commit *commit = lookup_commit_reference_by_name(branch);
448                         if (!commit)
449                                 die(_("invalid reference: %s"), branch);
450                         printf_ln(_("Preparing worktree (detached HEAD %s)"),
451                                   find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
452                 }
453                 strbuf_release(&s);
454         }
455 }
456
457 static const char *dwim_branch(const char *path, const char **new_branch)
458 {
459         int n;
460         const char *s = worktree_basename(path, &n);
461         const char *branchname = xstrndup(s, n);
462         struct strbuf ref = STRBUF_INIT;
463
464         UNLEAK(branchname);
465         if (!strbuf_check_branch_ref(&ref, branchname) &&
466             ref_exists(ref.buf)) {
467                 strbuf_release(&ref);
468                 return branchname;
469         }
470
471         *new_branch = branchname;
472         if (guess_remote) {
473                 struct object_id oid;
474                 const char *remote =
475                         unique_tracking_name(*new_branch, &oid, NULL);
476                 return remote;
477         }
478         return NULL;
479 }
480
481 static int add(int ac, const char **av, const char *prefix)
482 {
483         struct add_opts opts;
484         const char *new_branch_force = NULL;
485         char *path;
486         const char *branch;
487         const char *new_branch = NULL;
488         const char *opt_track = NULL;
489         struct option options[] = {
490                 OPT__FORCE(&opts.force,
491                            N_("checkout <branch> even if already checked out in other worktree"),
492                            PARSE_OPT_NOCOMPLETE),
493                 OPT_STRING('b', NULL, &new_branch, N_("branch"),
494                            N_("create a new branch")),
495                 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
496                            N_("create or reset a branch")),
497                 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
498                 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
499                 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
500                 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
501                 OPT_PASSTHRU(0, "track", &opt_track, NULL,
502                              N_("set up tracking mode (see git-branch(1))"),
503                              PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
504                 OPT_BOOL(0, "guess-remote", &guess_remote,
505                          N_("try to match the new branch name with a remote-tracking branch")),
506                 OPT_END()
507         };
508
509         memset(&opts, 0, sizeof(opts));
510         opts.checkout = 1;
511         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
512         if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
513                 die(_("-b, -B, and --detach are mutually exclusive"));
514         if (ac < 1 || ac > 2)
515                 usage_with_options(worktree_usage, options);
516
517         path = prefix_filename(prefix, av[0]);
518         branch = ac < 2 ? "HEAD" : av[1];
519
520         if (!strcmp(branch, "-"))
521                 branch = "@{-1}";
522
523         if (new_branch_force) {
524                 struct strbuf symref = STRBUF_INIT;
525
526                 new_branch = new_branch_force;
527
528                 if (!opts.force &&
529                     !strbuf_check_branch_ref(&symref, new_branch) &&
530                     ref_exists(symref.buf))
531                         die_if_checked_out(symref.buf, 0);
532                 strbuf_release(&symref);
533         }
534
535         if (ac < 2 && !new_branch && !opts.detach) {
536                 const char *s = dwim_branch(path, &new_branch);
537                 if (s)
538                         branch = s;
539         }
540
541         if (ac == 2 && !new_branch && !opts.detach) {
542                 struct object_id oid;
543                 struct commit *commit;
544                 const char *remote;
545
546                 commit = lookup_commit_reference_by_name(branch);
547                 if (!commit) {
548                         remote = unique_tracking_name(branch, &oid, NULL);
549                         if (remote) {
550                                 new_branch = branch;
551                                 branch = remote;
552                         }
553                 }
554         }
555         if (!opts.quiet)
556                 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
557
558         if (new_branch) {
559                 struct child_process cp = CHILD_PROCESS_INIT;
560                 cp.git_cmd = 1;
561                 argv_array_push(&cp.args, "branch");
562                 if (new_branch_force)
563                         argv_array_push(&cp.args, "--force");
564                 if (opts.quiet)
565                         argv_array_push(&cp.args, "--quiet");
566                 argv_array_push(&cp.args, new_branch);
567                 argv_array_push(&cp.args, branch);
568                 if (opt_track)
569                         argv_array_push(&cp.args, opt_track);
570                 if (run_command(&cp))
571                         return -1;
572                 branch = new_branch;
573         } else if (opt_track) {
574                 die(_("--[no-]track can only be used if a new branch is created"));
575         }
576
577         UNLEAK(path);
578         UNLEAK(opts);
579         return add_worktree(path, branch, &opts);
580 }
581
582 static void show_worktree_porcelain(struct worktree *wt)
583 {
584         printf("worktree %s\n", wt->path);
585         if (wt->is_bare)
586                 printf("bare\n");
587         else {
588                 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
589                 if (wt->is_detached)
590                         printf("detached\n");
591                 else if (wt->head_ref)
592                         printf("branch %s\n", wt->head_ref);
593         }
594         printf("\n");
595 }
596
597 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
598 {
599         struct strbuf sb = STRBUF_INIT;
600         int cur_path_len = strlen(wt->path);
601         int path_adj = cur_path_len - utf8_strwidth(wt->path);
602
603         strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
604         if (wt->is_bare)
605                 strbuf_addstr(&sb, "(bare)");
606         else {
607                 strbuf_addf(&sb, "%-*s ", abbrev_len,
608                                 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
609                 if (wt->is_detached)
610                         strbuf_addstr(&sb, "(detached HEAD)");
611                 else if (wt->head_ref) {
612                         char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
613                         strbuf_addf(&sb, "[%s]", ref);
614                         free(ref);
615                 } else
616                         strbuf_addstr(&sb, "(error)");
617         }
618         printf("%s\n", sb.buf);
619
620         strbuf_release(&sb);
621 }
622
623 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
624 {
625         int i;
626
627         for (i = 0; wt[i]; i++) {
628                 int sha1_len;
629                 int path_len = strlen(wt[i]->path);
630
631                 if (path_len > *maxlen)
632                         *maxlen = path_len;
633                 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
634                 if (sha1_len > *abbrev)
635                         *abbrev = sha1_len;
636         }
637 }
638
639 static int list(int ac, const char **av, const char *prefix)
640 {
641         int porcelain = 0;
642
643         struct option options[] = {
644                 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
645                 OPT_END()
646         };
647
648         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
649         if (ac)
650                 usage_with_options(worktree_usage, options);
651         else {
652                 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
653                 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
654
655                 if (!porcelain)
656                         measure_widths(worktrees, &abbrev, &path_maxlen);
657
658                 for (i = 0; worktrees[i]; i++) {
659                         if (porcelain)
660                                 show_worktree_porcelain(worktrees[i]);
661                         else
662                                 show_worktree(worktrees[i], path_maxlen, abbrev);
663                 }
664                 free_worktrees(worktrees);
665         }
666         return 0;
667 }
668
669 static int lock_worktree(int ac, const char **av, const char *prefix)
670 {
671         const char *reason = "", *old_reason;
672         struct option options[] = {
673                 OPT_STRING(0, "reason", &reason, N_("string"),
674                            N_("reason for locking")),
675                 OPT_END()
676         };
677         struct worktree **worktrees, *wt;
678
679         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
680         if (ac != 1)
681                 usage_with_options(worktree_usage, options);
682
683         worktrees = get_worktrees(0);
684         wt = find_worktree(worktrees, prefix, av[0]);
685         if (!wt)
686                 die(_("'%s' is not a working tree"), av[0]);
687         if (is_main_worktree(wt))
688                 die(_("The main working tree cannot be locked or unlocked"));
689
690         old_reason = worktree_lock_reason(wt);
691         if (old_reason) {
692                 if (*old_reason)
693                         die(_("'%s' is already locked, reason: %s"),
694                             av[0], old_reason);
695                 die(_("'%s' is already locked"), av[0]);
696         }
697
698         write_file(git_common_path("worktrees/%s/locked", wt->id),
699                    "%s", reason);
700         free_worktrees(worktrees);
701         return 0;
702 }
703
704 static int unlock_worktree(int ac, const char **av, const char *prefix)
705 {
706         struct option options[] = {
707                 OPT_END()
708         };
709         struct worktree **worktrees, *wt;
710         int ret;
711
712         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
713         if (ac != 1)
714                 usage_with_options(worktree_usage, options);
715
716         worktrees = get_worktrees(0);
717         wt = find_worktree(worktrees, prefix, av[0]);
718         if (!wt)
719                 die(_("'%s' is not a working tree"), av[0]);
720         if (is_main_worktree(wt))
721                 die(_("The main working tree cannot be locked or unlocked"));
722         if (!worktree_lock_reason(wt))
723                 die(_("'%s' is not locked"), av[0]);
724         ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
725         free_worktrees(worktrees);
726         return ret;
727 }
728
729 static void validate_no_submodules(const struct worktree *wt)
730 {
731         struct index_state istate = { NULL };
732         struct strbuf path = STRBUF_INIT;
733         int i, found_submodules = 0;
734
735         if (is_directory(worktree_git_path(wt, "modules"))) {
736                 /*
737                  * There could be false positives, e.g. the "modules"
738                  * directory exists but is empty. But it's a rare case and
739                  * this simpler check is probably good enough for now.
740                  */
741                 found_submodules = 1;
742         } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
743                                    get_worktree_git_dir(wt)) > 0) {
744                 for (i = 0; i < istate.cache_nr; i++) {
745                         struct cache_entry *ce = istate.cache[i];
746                         int err;
747
748                         if (!S_ISGITLINK(ce->ce_mode))
749                                 continue;
750
751                         strbuf_reset(&path);
752                         strbuf_addf(&path, "%s/%s", wt->path, ce->name);
753                         if (!is_submodule_populated_gently(path.buf, &err))
754                                 continue;
755
756                         found_submodules = 1;
757                         break;
758                 }
759         }
760         discard_index(&istate);
761         strbuf_release(&path);
762
763         if (found_submodules)
764                 die(_("working trees containing submodules cannot be moved or removed"));
765 }
766
767 static int move_worktree(int ac, const char **av, const char *prefix)
768 {
769         int force = 0;
770         struct option options[] = {
771                 OPT__FORCE(&force,
772                          N_("force move even if worktree is dirty or locked"),
773                          PARSE_OPT_NOCOMPLETE),
774                 OPT_END()
775         };
776         struct worktree **worktrees, *wt;
777         struct strbuf dst = STRBUF_INIT;
778         struct strbuf errmsg = STRBUF_INIT;
779         const char *reason = NULL;
780         char *path;
781
782         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
783         if (ac != 2)
784                 usage_with_options(worktree_usage, options);
785
786         path = prefix_filename(prefix, av[1]);
787         strbuf_addstr(&dst, path);
788         free(path);
789
790         worktrees = get_worktrees(0);
791         wt = find_worktree(worktrees, prefix, av[0]);
792         if (!wt)
793                 die(_("'%s' is not a working tree"), av[0]);
794         if (is_main_worktree(wt))
795                 die(_("'%s' is a main working tree"), av[0]);
796         if (is_directory(dst.buf)) {
797                 const char *sep = find_last_dir_sep(wt->path);
798
799                 if (!sep)
800                         die(_("could not figure out destination name from '%s'"),
801                             wt->path);
802                 strbuf_trim_trailing_dir_sep(&dst);
803                 strbuf_addstr(&dst, sep);
804         }
805         if (file_exists(dst.buf))
806                 die(_("target '%s' already exists"), dst.buf);
807
808         validate_no_submodules(wt);
809
810         if (force < 2)
811                 reason = worktree_lock_reason(wt);
812         if (reason) {
813                 if (*reason)
814                         die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
815                             reason);
816                 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
817         }
818         if (validate_worktree(wt, &errmsg, 0))
819                 die(_("validation failed, cannot move working tree: %s"),
820                     errmsg.buf);
821         strbuf_release(&errmsg);
822
823         if (rename(wt->path, dst.buf) == -1)
824                 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
825
826         update_worktree_location(wt, dst.buf);
827
828         strbuf_release(&dst);
829         free_worktrees(worktrees);
830         return 0;
831 }
832
833 /*
834  * Note, "git status --porcelain" is used to determine if it's safe to
835  * delete a whole worktree. "git status" does not ignore user
836  * configuration, so if a normal "git status" shows "clean" for the
837  * user, then it's ok to remove it.
838  *
839  * This assumption may be a bad one. We may want to ignore
840  * (potentially bad) user settings and only delete a worktree when
841  * it's absolutely safe to do so from _our_ point of view because we
842  * know better.
843  */
844 static void check_clean_worktree(struct worktree *wt,
845                                  const char *original_path)
846 {
847         struct argv_array child_env = ARGV_ARRAY_INIT;
848         struct child_process cp;
849         char buf[1];
850         int ret;
851
852         /*
853          * Until we sort this out, all submodules are "dirty" and
854          * will abort this function.
855          */
856         validate_no_submodules(wt);
857
858         argv_array_pushf(&child_env, "%s=%s/.git",
859                          GIT_DIR_ENVIRONMENT, wt->path);
860         argv_array_pushf(&child_env, "%s=%s",
861                          GIT_WORK_TREE_ENVIRONMENT, wt->path);
862         memset(&cp, 0, sizeof(cp));
863         argv_array_pushl(&cp.args, "status",
864                          "--porcelain", "--ignore-submodules=none",
865                          NULL);
866         cp.env = child_env.argv;
867         cp.git_cmd = 1;
868         cp.dir = wt->path;
869         cp.out = -1;
870         ret = start_command(&cp);
871         if (ret)
872                 die_errno(_("failed to run 'git status' on '%s'"),
873                           original_path);
874         ret = xread(cp.out, buf, sizeof(buf));
875         if (ret)
876                 die(_("'%s' contains modified or untracked files, use --force to delete it"),
877                     original_path);
878         close(cp.out);
879         ret = finish_command(&cp);
880         if (ret)
881                 die_errno(_("failed to run 'git status' on '%s', code %d"),
882                           original_path, ret);
883 }
884
885 static int delete_git_work_tree(struct worktree *wt)
886 {
887         struct strbuf sb = STRBUF_INIT;
888         int ret = 0;
889
890         strbuf_addstr(&sb, wt->path);
891         if (remove_dir_recursively(&sb, 0)) {
892                 error_errno(_("failed to delete '%s'"), sb.buf);
893                 ret = -1;
894         }
895         strbuf_release(&sb);
896         return ret;
897 }
898
899 static int remove_worktree(int ac, const char **av, const char *prefix)
900 {
901         int force = 0;
902         struct option options[] = {
903                 OPT__FORCE(&force,
904                          N_("force removal even if worktree is dirty or locked"),
905                          PARSE_OPT_NOCOMPLETE),
906                 OPT_END()
907         };
908         struct worktree **worktrees, *wt;
909         struct strbuf errmsg = STRBUF_INIT;
910         const char *reason = NULL;
911         int ret = 0;
912
913         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
914         if (ac != 1)
915                 usage_with_options(worktree_usage, options);
916
917         worktrees = get_worktrees(0);
918         wt = find_worktree(worktrees, prefix, av[0]);
919         if (!wt)
920                 die(_("'%s' is not a working tree"), av[0]);
921         if (is_main_worktree(wt))
922                 die(_("'%s' is a main working tree"), av[0]);
923         if (force < 2)
924                 reason = worktree_lock_reason(wt);
925         if (reason) {
926                 if (*reason)
927                         die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
928                             reason);
929                 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
930         }
931         if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
932                 die(_("validation failed, cannot remove working tree: %s"),
933                     errmsg.buf);
934         strbuf_release(&errmsg);
935
936         if (file_exists(wt->path)) {
937                 if (!force)
938                         check_clean_worktree(wt, av[0]);
939
940                 ret |= delete_git_work_tree(wt);
941         }
942         /*
943          * continue on even if ret is non-zero, there's no going back
944          * from here.
945          */
946         ret |= delete_git_dir(wt->id);
947         delete_worktrees_dir_if_empty();
948
949         free_worktrees(worktrees);
950         return ret;
951 }
952
953 int cmd_worktree(int ac, const char **av, const char *prefix)
954 {
955         struct option options[] = {
956                 OPT_END()
957         };
958
959         git_config(git_worktree_config, NULL);
960
961         if (ac < 2)
962                 usage_with_options(worktree_usage, options);
963         if (!prefix)
964                 prefix = "";
965         if (!strcmp(av[1], "add"))
966                 return add(ac - 1, av + 1, prefix);
967         if (!strcmp(av[1], "prune"))
968                 return prune(ac - 1, av + 1, prefix);
969         if (!strcmp(av[1], "list"))
970                 return list(ac - 1, av + 1, prefix);
971         if (!strcmp(av[1], "lock"))
972                 return lock_worktree(ac - 1, av + 1, prefix);
973         if (!strcmp(av[1], "unlock"))
974                 return unlock_worktree(ac - 1, av + 1, prefix);
975         if (!strcmp(av[1], "move"))
976                 return move_worktree(ac - 1, av + 1, prefix);
977         if (!strcmp(av[1], "remove"))
978                 return remove_worktree(ac - 1, av + 1, prefix);
979         usage_with_options(worktree_usage, options);
980 }