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