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