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