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