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