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