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