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