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