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