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