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