Merge branch 'tq/t1510'
[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 "refs.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 checkout;
31         int keep_locked;
32         const char *new_branch;
33         int force_new_branch;
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 prune_worktree(const char *id, struct strbuf *reason)
52 {
53         struct stat st;
54         char *path;
55         int fd;
56         size_t len;
57         ssize_t read_result;
58
59         if (!is_directory(git_path("worktrees/%s", id))) {
60                 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
61                 return 1;
62         }
63         if (file_exists(git_path("worktrees/%s/locked", id)))
64                 return 0;
65         if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
66                 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
67                 return 1;
68         }
69         fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
70         if (fd < 0) {
71                 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
72                             id, strerror(errno));
73                 return 1;
74         }
75         len = xsize_t(st.st_size);
76         path = xmallocz(len);
77
78         read_result = read_in_full(fd, path, len);
79         if (read_result < 0) {
80                 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
81                             id, strerror(errno));
82                 close(fd);
83                 free(path);
84                 return 1;
85         }
86         close(fd);
87
88         if (read_result != len) {
89                 strbuf_addf(reason,
90                             _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
91                             id, (uintmax_t)len, (uintmax_t)read_result);
92                 free(path);
93                 return 1;
94         }
95         while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
96                 len--;
97         if (!len) {
98                 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
99                 free(path);
100                 return 1;
101         }
102         path[len] = '\0';
103         if (!file_exists(path)) {
104                 free(path);
105                 if (stat(git_path("worktrees/%s/index", id), &st) ||
106                     st.st_mtime <= expire) {
107                         strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
108                         return 1;
109                 } else {
110                         return 0;
111                 }
112         }
113         free(path);
114         return 0;
115 }
116
117 static void prune_worktrees(void)
118 {
119         struct strbuf reason = STRBUF_INIT;
120         struct strbuf path = STRBUF_INIT;
121         DIR *dir = opendir(git_path("worktrees"));
122         struct dirent *d;
123         int ret;
124         if (!dir)
125                 return;
126         while ((d = readdir(dir)) != NULL) {
127                 if (is_dot_or_dotdot(d->d_name))
128                         continue;
129                 strbuf_reset(&reason);
130                 if (!prune_worktree(d->d_name, &reason))
131                         continue;
132                 if (show_only || verbose)
133                         printf("%s\n", reason.buf);
134                 if (show_only)
135                         continue;
136                 git_path_buf(&path, "worktrees/%s", d->d_name);
137                 ret = remove_dir_recursively(&path, 0);
138                 if (ret < 0 && errno == ENOTDIR)
139                         ret = unlink(path.buf);
140                 if (ret)
141                         error_errno(_("failed to remove '%s'"), path.buf);
142         }
143         closedir(dir);
144         if (!show_only)
145                 rmdir(git_path("worktrees"));
146         strbuf_release(&reason);
147         strbuf_release(&path);
148 }
149
150 static int prune(int ac, const char **av, const char *prefix)
151 {
152         struct option options[] = {
153                 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
154                 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
155                 OPT_EXPIRY_DATE(0, "expire", &expire,
156                                 N_("expire working trees older than <time>")),
157                 OPT_END()
158         };
159
160         expire = TIME_MAX;
161         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
162         if (ac)
163                 usage_with_options(worktree_usage, options);
164         prune_worktrees();
165         return 0;
166 }
167
168 static char *junk_work_tree;
169 static char *junk_git_dir;
170 static int is_junk;
171 static pid_t junk_pid;
172
173 static void remove_junk(void)
174 {
175         struct strbuf sb = STRBUF_INIT;
176         if (!is_junk || getpid() != junk_pid)
177                 return;
178         if (junk_git_dir) {
179                 strbuf_addstr(&sb, junk_git_dir);
180                 remove_dir_recursively(&sb, 0);
181                 strbuf_reset(&sb);
182         }
183         if (junk_work_tree) {
184                 strbuf_addstr(&sb, junk_work_tree);
185                 remove_dir_recursively(&sb, 0);
186         }
187         strbuf_release(&sb);
188 }
189
190 static void remove_junk_on_signal(int signo)
191 {
192         remove_junk();
193         sigchain_pop(signo);
194         raise(signo);
195 }
196
197 static const char *worktree_basename(const char *path, int *olen)
198 {
199         const char *name;
200         int len;
201
202         len = strlen(path);
203         while (len && is_dir_sep(path[len - 1]))
204                 len--;
205
206         for (name = path + len - 1; name > path; name--)
207                 if (is_dir_sep(*name)) {
208                         name++;
209                         break;
210                 }
211
212         *olen = len;
213         return name;
214 }
215
216 static int add_worktree(const char *path, const char *refname,
217                         const struct add_opts *opts)
218 {
219         struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
220         struct strbuf sb = STRBUF_INIT;
221         const char *name;
222         struct stat st;
223         struct child_process cp = CHILD_PROCESS_INIT;
224         struct argv_array child_env = ARGV_ARRAY_INIT;
225         int counter = 0, len, ret;
226         struct strbuf symref = STRBUF_INIT;
227         struct commit *commit = NULL;
228         int is_branch = 0;
229
230         if (file_exists(path) && !is_empty_dir(path))
231                 die(_("'%s' already exists"), path);
232
233         /* is 'refname' a branch or commit? */
234         if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
235             ref_exists(symref.buf)) {
236                 is_branch = 1;
237                 if (!opts->force)
238                         die_if_checked_out(symref.buf, 0);
239         }
240         commit = lookup_commit_reference_by_name(refname);
241         if (!commit)
242                 die(_("invalid reference: %s"), refname);
243
244         name = worktree_basename(path, &len);
245         git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
246         len = sb_repo.len;
247         if (safe_create_leading_directories_const(sb_repo.buf))
248                 die_errno(_("could not create leading directories of '%s'"),
249                           sb_repo.buf);
250         while (!stat(sb_repo.buf, &st)) {
251                 counter++;
252                 strbuf_setlen(&sb_repo, len);
253                 strbuf_addf(&sb_repo, "%d", counter);
254         }
255         name = strrchr(sb_repo.buf, '/') + 1;
256
257         junk_pid = getpid();
258         atexit(remove_junk);
259         sigchain_push_common(remove_junk_on_signal);
260
261         if (mkdir(sb_repo.buf, 0777))
262                 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
263         junk_git_dir = xstrdup(sb_repo.buf);
264         is_junk = 1;
265
266         /*
267          * lock the incomplete repo so prune won't delete it, unlock
268          * after the preparation is over.
269          */
270         strbuf_addf(&sb, "%s/locked", sb_repo.buf);
271         if (!opts->keep_locked)
272                 write_file(sb.buf, "initializing");
273         else
274                 write_file(sb.buf, "added with --lock");
275
276         strbuf_addf(&sb_git, "%s/.git", path);
277         if (safe_create_leading_directories_const(sb_git.buf))
278                 die_errno(_("could not create leading directories of '%s'"),
279                           sb_git.buf);
280         junk_work_tree = xstrdup(path);
281
282         strbuf_reset(&sb);
283         strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
284         write_file(sb.buf, "%s", real_path(sb_git.buf));
285         write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
286                    real_path(get_git_common_dir()), name);
287         /*
288          * This is to keep resolve_ref() happy. We need a valid HEAD
289          * or is_git_directory() will reject the directory. Any value which
290          * looks like an object ID will do since it will be immediately
291          * replaced by the symbolic-ref or update-ref invocation in the new
292          * worktree.
293          */
294         strbuf_reset(&sb);
295         strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
296         write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
297         strbuf_reset(&sb);
298         strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
299         write_file(sb.buf, "../..");
300
301         fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
302
303         argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
304         argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
305         cp.git_cmd = 1;
306
307         if (!is_branch)
308                 argv_array_pushl(&cp.args, "update-ref", "HEAD",
309                                  oid_to_hex(&commit->object.oid), NULL);
310         else
311                 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
312                                  symref.buf, NULL);
313         cp.env = child_env.argv;
314         ret = run_command(&cp);
315         if (ret)
316                 goto done;
317
318         if (opts->checkout) {
319                 cp.argv = NULL;
320                 argv_array_clear(&cp.args);
321                 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
322                 cp.env = child_env.argv;
323                 ret = run_command(&cp);
324                 if (ret)
325                         goto done;
326         }
327
328         is_junk = 0;
329         FREE_AND_NULL(junk_work_tree);
330         FREE_AND_NULL(junk_git_dir);
331
332 done:
333         if (ret || !opts->keep_locked) {
334                 strbuf_reset(&sb);
335                 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
336                 unlink_or_warn(sb.buf);
337         }
338
339         /*
340          * Hook failure does not warrant worktree deletion, so run hook after
341          * is_junk is cleared, but do return appropriate code when hook fails.
342          */
343         if (!ret && opts->checkout) {
344                 const char *hook = find_hook("post-checkout");
345                 if (hook) {
346                         const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
347                         cp.git_cmd = 0;
348                         cp.no_stdin = 1;
349                         cp.stdout_to_stderr = 1;
350                         cp.dir = path;
351                         cp.env = env;
352                         cp.argv = NULL;
353                         argv_array_pushl(&cp.args, absolute_path(hook),
354                                          oid_to_hex(&null_oid),
355                                          oid_to_hex(&commit->object.oid),
356                                          "1", NULL);
357                         ret = run_command(&cp);
358                 }
359         }
360
361         argv_array_clear(&child_env);
362         strbuf_release(&sb);
363         strbuf_release(&symref);
364         strbuf_release(&sb_repo);
365         strbuf_release(&sb_git);
366         return ret;
367 }
368
369 static int add(int ac, const char **av, const char *prefix)
370 {
371         struct add_opts opts;
372         const char *new_branch_force = NULL;
373         char *path;
374         const char *branch;
375         const char *opt_track = NULL;
376         struct option options[] = {
377                 OPT__FORCE(&opts.force,
378                            N_("checkout <branch> even if already checked out in other worktree"),
379                            PARSE_OPT_NOCOMPLETE),
380                 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
381                            N_("create a new branch")),
382                 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
383                            N_("create or reset a branch")),
384                 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
385                 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
386                 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
387                 OPT_PASSTHRU(0, "track", &opt_track, NULL,
388                              N_("set up tracking mode (see git-branch(1))"),
389                              PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
390                 OPT_BOOL(0, "guess-remote", &guess_remote,
391                          N_("try to match the new branch name with a remote-tracking branch")),
392                 OPT_END()
393         };
394
395         memset(&opts, 0, sizeof(opts));
396         opts.checkout = 1;
397         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
398         if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
399                 die(_("-b, -B, and --detach are mutually exclusive"));
400         if (ac < 1 || ac > 2)
401                 usage_with_options(worktree_usage, options);
402
403         path = prefix_filename(prefix, av[0]);
404         branch = ac < 2 ? "HEAD" : av[1];
405
406         if (!strcmp(branch, "-"))
407                 branch = "@{-1}";
408
409         opts.force_new_branch = !!new_branch_force;
410         if (opts.force_new_branch) {
411                 struct strbuf symref = STRBUF_INIT;
412
413                 opts.new_branch = new_branch_force;
414
415                 if (!opts.force &&
416                     !strbuf_check_branch_ref(&symref, opts.new_branch) &&
417                     ref_exists(symref.buf))
418                         die_if_checked_out(symref.buf, 0);
419                 strbuf_release(&symref);
420         }
421
422         if (ac < 2 && !opts.new_branch && !opts.detach) {
423                 int n;
424                 const char *s = worktree_basename(path, &n);
425                 opts.new_branch = xstrndup(s, n);
426                 if (guess_remote) {
427                         struct object_id oid;
428                         const char *remote =
429                                 unique_tracking_name(opts.new_branch, &oid);
430                         if (remote)
431                                 branch = remote;
432                 }
433         }
434
435         if (ac == 2 && !opts.new_branch && !opts.detach) {
436                 struct object_id oid;
437                 struct commit *commit;
438                 const char *remote;
439
440                 commit = lookup_commit_reference_by_name(branch);
441                 if (!commit) {
442                         remote = unique_tracking_name(branch, &oid);
443                         if (remote) {
444                                 opts.new_branch = branch;
445                                 branch = remote;
446                         }
447                 }
448         }
449
450         if (opts.new_branch) {
451                 struct child_process cp = CHILD_PROCESS_INIT;
452                 cp.git_cmd = 1;
453                 argv_array_push(&cp.args, "branch");
454                 if (opts.force_new_branch)
455                         argv_array_push(&cp.args, "--force");
456                 argv_array_push(&cp.args, opts.new_branch);
457                 argv_array_push(&cp.args, branch);
458                 if (opt_track)
459                         argv_array_push(&cp.args, opt_track);
460                 if (run_command(&cp))
461                         return -1;
462                 branch = opts.new_branch;
463         } else if (opt_track) {
464                 die(_("--[no-]track can only be used if a new branch is created"));
465         }
466
467         UNLEAK(path);
468         UNLEAK(opts);
469         return add_worktree(path, branch, &opts);
470 }
471
472 static void show_worktree_porcelain(struct worktree *wt)
473 {
474         printf("worktree %s\n", wt->path);
475         if (wt->is_bare)
476                 printf("bare\n");
477         else {
478                 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
479                 if (wt->is_detached)
480                         printf("detached\n");
481                 else if (wt->head_ref)
482                         printf("branch %s\n", wt->head_ref);
483         }
484         printf("\n");
485 }
486
487 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
488 {
489         struct strbuf sb = STRBUF_INIT;
490         int cur_path_len = strlen(wt->path);
491         int path_adj = cur_path_len - utf8_strwidth(wt->path);
492
493         strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
494         if (wt->is_bare)
495                 strbuf_addstr(&sb, "(bare)");
496         else {
497                 strbuf_addf(&sb, "%-*s ", abbrev_len,
498                                 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
499                 if (wt->is_detached)
500                         strbuf_addstr(&sb, "(detached HEAD)");
501                 else if (wt->head_ref) {
502                         char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
503                         strbuf_addf(&sb, "[%s]", ref);
504                         free(ref);
505                 } else
506                         strbuf_addstr(&sb, "(error)");
507         }
508         printf("%s\n", sb.buf);
509
510         strbuf_release(&sb);
511 }
512
513 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
514 {
515         int i;
516
517         for (i = 0; wt[i]; i++) {
518                 int sha1_len;
519                 int path_len = strlen(wt[i]->path);
520
521                 if (path_len > *maxlen)
522                         *maxlen = path_len;
523                 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
524                 if (sha1_len > *abbrev)
525                         *abbrev = sha1_len;
526         }
527 }
528
529 static int list(int ac, const char **av, const char *prefix)
530 {
531         int porcelain = 0;
532
533         struct option options[] = {
534                 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
535                 OPT_END()
536         };
537
538         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
539         if (ac)
540                 usage_with_options(worktree_usage, options);
541         else {
542                 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
543                 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
544
545                 if (!porcelain)
546                         measure_widths(worktrees, &abbrev, &path_maxlen);
547
548                 for (i = 0; worktrees[i]; i++) {
549                         if (porcelain)
550                                 show_worktree_porcelain(worktrees[i]);
551                         else
552                                 show_worktree(worktrees[i], path_maxlen, abbrev);
553                 }
554                 free_worktrees(worktrees);
555         }
556         return 0;
557 }
558
559 static int lock_worktree(int ac, const char **av, const char *prefix)
560 {
561         const char *reason = "", *old_reason;
562         struct option options[] = {
563                 OPT_STRING(0, "reason", &reason, N_("string"),
564                            N_("reason for locking")),
565                 OPT_END()
566         };
567         struct worktree **worktrees, *wt;
568
569         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
570         if (ac != 1)
571                 usage_with_options(worktree_usage, options);
572
573         worktrees = get_worktrees(0);
574         wt = find_worktree(worktrees, prefix, av[0]);
575         if (!wt)
576                 die(_("'%s' is not a working tree"), av[0]);
577         if (is_main_worktree(wt))
578                 die(_("The main working tree cannot be locked or unlocked"));
579
580         old_reason = is_worktree_locked(wt);
581         if (old_reason) {
582                 if (*old_reason)
583                         die(_("'%s' is already locked, reason: %s"),
584                             av[0], old_reason);
585                 die(_("'%s' is already locked"), av[0]);
586         }
587
588         write_file(git_common_path("worktrees/%s/locked", wt->id),
589                    "%s", reason);
590         free_worktrees(worktrees);
591         return 0;
592 }
593
594 static int unlock_worktree(int ac, const char **av, const char *prefix)
595 {
596         struct option options[] = {
597                 OPT_END()
598         };
599         struct worktree **worktrees, *wt;
600         int ret;
601
602         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
603         if (ac != 1)
604                 usage_with_options(worktree_usage, options);
605
606         worktrees = get_worktrees(0);
607         wt = find_worktree(worktrees, prefix, av[0]);
608         if (!wt)
609                 die(_("'%s' is not a working tree"), av[0]);
610         if (is_main_worktree(wt))
611                 die(_("The main working tree cannot be locked or unlocked"));
612         if (!is_worktree_locked(wt))
613                 die(_("'%s' is not locked"), av[0]);
614         ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
615         free_worktrees(worktrees);
616         return ret;
617 }
618
619 static void validate_no_submodules(const struct worktree *wt)
620 {
621         struct index_state istate = { NULL };
622         int i, found_submodules = 0;
623
624         if (read_index_from(&istate, worktree_git_path(wt, "index"),
625                             get_worktree_git_dir(wt)) > 0) {
626                 for (i = 0; i < istate.cache_nr; i++) {
627                         struct cache_entry *ce = istate.cache[i];
628
629                         if (S_ISGITLINK(ce->ce_mode)) {
630                                 found_submodules = 1;
631                                 break;
632                         }
633                 }
634         }
635         discard_index(&istate);
636
637         if (found_submodules)
638                 die(_("working trees containing submodules cannot be moved or removed"));
639 }
640
641 static int move_worktree(int ac, const char **av, const char *prefix)
642 {
643         struct option options[] = {
644                 OPT_END()
645         };
646         struct worktree **worktrees, *wt;
647         struct strbuf dst = STRBUF_INIT;
648         struct strbuf errmsg = STRBUF_INIT;
649         const char *reason;
650         char *path;
651
652         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
653         if (ac != 2)
654                 usage_with_options(worktree_usage, options);
655
656         path = prefix_filename(prefix, av[1]);
657         strbuf_addstr(&dst, path);
658         free(path);
659
660         worktrees = get_worktrees(0);
661         wt = find_worktree(worktrees, prefix, av[0]);
662         if (!wt)
663                 die(_("'%s' is not a working tree"), av[0]);
664         if (is_main_worktree(wt))
665                 die(_("'%s' is a main working tree"), av[0]);
666         if (is_directory(dst.buf)) {
667                 const char *sep = find_last_dir_sep(wt->path);
668
669                 if (!sep)
670                         die(_("could not figure out destination name from '%s'"),
671                             wt->path);
672                 strbuf_trim_trailing_dir_sep(&dst);
673                 strbuf_addstr(&dst, sep);
674         }
675         if (file_exists(dst.buf))
676                 die(_("target '%s' already exists"), dst.buf);
677
678         validate_no_submodules(wt);
679
680         reason = is_worktree_locked(wt);
681         if (reason) {
682                 if (*reason)
683                         die(_("cannot move a locked working tree, lock reason: %s"),
684                             reason);
685                 die(_("cannot move a locked working tree"));
686         }
687         if (validate_worktree(wt, &errmsg, 0))
688                 die(_("validation failed, cannot move working tree: %s"),
689                     errmsg.buf);
690         strbuf_release(&errmsg);
691
692         if (rename(wt->path, dst.buf) == -1)
693                 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
694
695         update_worktree_location(wt, dst.buf);
696
697         strbuf_release(&dst);
698         free_worktrees(worktrees);
699         return 0;
700 }
701
702 /*
703  * Note, "git status --porcelain" is used to determine if it's safe to
704  * delete a whole worktree. "git status" does not ignore user
705  * configuration, so if a normal "git status" shows "clean" for the
706  * user, then it's ok to remove it.
707  *
708  * This assumption may be a bad one. We may want to ignore
709  * (potentially bad) user settings and only delete a worktree when
710  * it's absolutely safe to do so from _our_ point of view because we
711  * know better.
712  */
713 static void check_clean_worktree(struct worktree *wt,
714                                  const char *original_path)
715 {
716         struct argv_array child_env = ARGV_ARRAY_INIT;
717         struct child_process cp;
718         char buf[1];
719         int ret;
720
721         /*
722          * Until we sort this out, all submodules are "dirty" and
723          * will abort this function.
724          */
725         validate_no_submodules(wt);
726
727         argv_array_pushf(&child_env, "%s=%s/.git",
728                          GIT_DIR_ENVIRONMENT, wt->path);
729         argv_array_pushf(&child_env, "%s=%s",
730                          GIT_WORK_TREE_ENVIRONMENT, wt->path);
731         memset(&cp, 0, sizeof(cp));
732         argv_array_pushl(&cp.args, "status",
733                          "--porcelain", "--ignore-submodules=none",
734                          NULL);
735         cp.env = child_env.argv;
736         cp.git_cmd = 1;
737         cp.dir = wt->path;
738         cp.out = -1;
739         ret = start_command(&cp);
740         if (ret)
741                 die_errno(_("failed to run 'git status' on '%s'"),
742                           original_path);
743         ret = xread(cp.out, buf, sizeof(buf));
744         if (ret)
745                 die(_("'%s' is dirty, use --force to delete it"),
746                     original_path);
747         close(cp.out);
748         ret = finish_command(&cp);
749         if (ret)
750                 die_errno(_("failed to run 'git status' on '%s', code %d"),
751                           original_path, ret);
752 }
753
754 static int delete_git_work_tree(struct worktree *wt)
755 {
756         struct strbuf sb = STRBUF_INIT;
757         int ret = 0;
758
759         strbuf_addstr(&sb, wt->path);
760         if (remove_dir_recursively(&sb, 0)) {
761                 error_errno(_("failed to delete '%s'"), sb.buf);
762                 ret = -1;
763         }
764         strbuf_release(&sb);
765         return ret;
766 }
767
768 static int delete_git_dir(struct worktree *wt)
769 {
770         struct strbuf sb = STRBUF_INIT;
771         int ret = 0;
772
773         strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
774         if (remove_dir_recursively(&sb, 0)) {
775                 error_errno(_("failed to delete '%s'"), sb.buf);
776                 ret = -1;
777         }
778         strbuf_release(&sb);
779         return ret;
780 }
781
782 static int remove_worktree(int ac, const char **av, const char *prefix)
783 {
784         int force = 0;
785         struct option options[] = {
786                 OPT_BOOL(0, "force", &force,
787                          N_("force removing even if the worktree is dirty")),
788                 OPT_END()
789         };
790         struct worktree **worktrees, *wt;
791         struct strbuf errmsg = STRBUF_INIT;
792         const char *reason;
793         int ret = 0;
794
795         ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
796         if (ac != 1)
797                 usage_with_options(worktree_usage, options);
798
799         worktrees = get_worktrees(0);
800         wt = find_worktree(worktrees, prefix, av[0]);
801         if (!wt)
802                 die(_("'%s' is not a working tree"), av[0]);
803         if (is_main_worktree(wt))
804                 die(_("'%s' is a main working tree"), av[0]);
805         reason = is_worktree_locked(wt);
806         if (reason) {
807                 if (*reason)
808                         die(_("cannot remove a locked working tree, lock reason: %s"),
809                             reason);
810                 die(_("cannot remove a locked working tree"));
811         }
812         if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
813                 die(_("validation failed, cannot remove working tree: %s"),
814                     errmsg.buf);
815         strbuf_release(&errmsg);
816
817         if (file_exists(wt->path)) {
818                 if (!force)
819                         check_clean_worktree(wt, av[0]);
820
821                 ret |= delete_git_work_tree(wt);
822         }
823         /*
824          * continue on even if ret is non-zero, there's no going back
825          * from here.
826          */
827         ret |= delete_git_dir(wt);
828
829         free_worktrees(worktrees);
830         return ret;
831 }
832
833 int cmd_worktree(int ac, const char **av, const char *prefix)
834 {
835         struct option options[] = {
836                 OPT_END()
837         };
838
839         git_config(git_worktree_config, NULL);
840
841         if (ac < 2)
842                 usage_with_options(worktree_usage, options);
843         if (!prefix)
844                 prefix = "";
845         if (!strcmp(av[1], "add"))
846                 return add(ac - 1, av + 1, prefix);
847         if (!strcmp(av[1], "prune"))
848                 return prune(ac - 1, av + 1, prefix);
849         if (!strcmp(av[1], "list"))
850                 return list(ac - 1, av + 1, prefix);
851         if (!strcmp(av[1], "lock"))
852                 return lock_worktree(ac - 1, av + 1, prefix);
853         if (!strcmp(av[1], "unlock"))
854                 return unlock_worktree(ac - 1, av + 1, prefix);
855         if (!strcmp(av[1], "move"))
856                 return move_worktree(ac - 1, av + 1, prefix);
857         if (!strcmp(av[1], "remove"))
858                 return remove_worktree(ac - 1, av + 1, prefix);
859         usage_with_options(worktree_usage, options);
860 }