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