]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/worktree.c
Merge branch 'jc/do-not-just-explain-but-update-your-patch'
[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"
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
d179af67
ES
283/* check that path is viable location for worktree */
284static void check_candidate_path(const char *path,
285 int force,
286 struct worktree **worktrees,
287 const char *cmd)
45059e64 288{
cb56f55c
ES
289 struct worktree *wt;
290 int locked;
291
45059e64
ES
292 if (file_exists(path) && !is_empty_dir(path))
293 die(_("'%s' already exists"), path);
cb56f55c 294
bb69b3b0 295 wt = find_worktree_by_path(worktrees, path);
cb56f55c 296 if (!wt)
d179af67 297 return;
cb56f55c 298
d236f12b 299 locked = !!worktree_lock_reason(wt);
d179af67 300 if ((!locked && force) || (locked && force > 1)) {
e19831c9 301 if (delete_git_dir(wt->id))
d179af67
ES
302 die(_("unusable worktree destination '%s'"), path);
303 return;
e19831c9
ES
304 }
305
cb56f55c 306 if (locked)
b86339b1 307 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 308 else
b86339b1 309 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
45059e64
ES
310}
311
80a0548f 312static int add_worktree(const char *path, const char *refname,
5dd6e234 313 const struct add_opts *opts)
b979d950
ES
314{
315 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
3d7747e3 316 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
b979d950 317 const char *name;
542aa25d 318 struct child_process cp = CHILD_PROCESS_INIT;
22f9b7f3 319 struct strvec child_env = STRVEC_INIT;
7af01f23
MS
320 unsigned int counter = 0;
321 int len, ret;
f7c9dac1
ES
322 struct strbuf symref = STRBUF_INIT;
323 struct commit *commit = NULL;
ade546be 324 int is_branch = 0;
1de16aec 325 struct strbuf sb_name = STRBUF_INIT;
d179af67 326 struct worktree **worktrees;
b979d950 327
03f2465b 328 worktrees = get_worktrees();
d179af67
ES
329 check_candidate_path(path, opts->force, worktrees, "add");
330 free_worktrees(worktrees);
331 worktrees = NULL;
b979d950 332
f7c9dac1 333 /* is 'refname' a branch or commit? */
0ebf4a2a 334 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
ade546be
ES
335 ref_exists(symref.buf)) {
336 is_branch = 1;
f7c9dac1 337 if (!opts->force)
8d9fdd70 338 die_if_checked_out(symref.buf, 0);
f7c9dac1 339 }
ade546be
ES
340 commit = lookup_commit_reference_by_name(refname);
341 if (!commit)
342 die(_("invalid reference: %s"), refname);
f7c9dac1 343
f5682b2a 344 name = worktree_basename(path, &len);
1de16aec
NTND
345 strbuf_add(&sb, name, path + len - name);
346 sanitize_refname_component(sb.buf, &sb_name);
347 if (!sb_name.len)
348 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
349 strbuf_reset(&sb);
350 name = sb_name.buf;
351 git_path_buf(&sb_repo, "worktrees/%s", name);
b979d950
ES
352 len = sb_repo.len;
353 if (safe_create_leading_directories_const(sb_repo.buf))
354 die_errno(_("could not create leading directories of '%s'"),
355 sb_repo.buf);
7af01f23
MS
356
357 while (mkdir(sb_repo.buf, 0777)) {
b979d950 358 counter++;
7af01f23
MS
359 if ((errno != EEXIST) || !counter /* overflow */)
360 die_errno(_("could not create directory of '%s'"),
361 sb_repo.buf);
b979d950
ES
362 strbuf_setlen(&sb_repo, len);
363 strbuf_addf(&sb_repo, "%d", counter);
364 }
365 name = strrchr(sb_repo.buf, '/') + 1;
366
367 junk_pid = getpid();
368 atexit(remove_junk);
369 sigchain_push_common(remove_junk_on_signal);
370
b979d950
ES
371 junk_git_dir = xstrdup(sb_repo.buf);
372 is_junk = 1;
373
374 /*
375 * lock the incomplete repo so prune won't delete it, unlock
376 * after the preparation is over.
377 */
378 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
507e6e9e
NTND
379 if (!opts->keep_locked)
380 write_file(sb.buf, "initializing");
381 else
382 write_file(sb.buf, "added with --lock");
b979d950
ES
383
384 strbuf_addf(&sb_git, "%s/.git", path);
385 if (safe_create_leading_directories_const(sb_git.buf))
386 die_errno(_("could not create leading directories of '%s'"),
387 sb_git.buf);
388 junk_work_tree = xstrdup(path);
389
390 strbuf_reset(&sb);
391 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
3d7747e3
AM
392 strbuf_realpath(&realpath, sb_git.buf, 1);
393 write_file(sb.buf, "%s", realpath.buf);
394 strbuf_realpath(&realpath, get_git_common_dir(), 1);
1f76a10b 395 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
3d7747e3 396 realpath.buf, name);
b979d950
ES
397 /*
398 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
399 * or is_git_directory() will reject the directory. Any value which
400 * looks like an object ID will do since it will be immediately
401 * replaced by the symbolic-ref or update-ref invocation in the new
402 * worktree.
b979d950 403 */
b979d950
ES
404 strbuf_reset(&sb);
405 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
f6ca67d6 406 write_file(sb.buf, "%s", oid_to_hex(&null_oid));
b979d950
ES
407 strbuf_reset(&sb);
408 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 409 write_file(sb.buf, "../..");
b979d950 410
22f9b7f3
JK
411 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
412 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950 413 cp.git_cmd = 1;
7f44e3d1 414
ade546be 415 if (!is_branch)
22f9b7f3 416 strvec_pushl(&cp.args, "update-ref", "HEAD",
f6d8942b 417 oid_to_hex(&commit->object.oid), NULL);
371979c2 418 else {
22f9b7f3 419 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
f6d8942b 420 symref.buf, NULL);
371979c2 421 if (opts->quiet)
22f9b7f3 422 strvec_push(&cp.args, "--quiet");
371979c2
EP
423 }
424
d70a9eb6 425 cp.env = child_env.v;
7f44e3d1
ES
426 ret = run_command(&cp);
427 if (ret)
428 goto done;
429
ef2a0ac9
RZ
430 if (opts->checkout) {
431 cp.argv = NULL;
22f9b7f3
JK
432 strvec_clear(&cp.args);
433 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
371979c2 434 if (opts->quiet)
22f9b7f3 435 strvec_push(&cp.args, "--quiet");
d70a9eb6 436 cp.env = child_env.v;
ef2a0ac9
RZ
437 ret = run_command(&cp);
438 if (ret)
439 goto done;
b979d950 440 }
ef2a0ac9
RZ
441
442 is_junk = 0;
88ce3ef6
ÆAB
443 FREE_AND_NULL(junk_work_tree);
444 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 445
7f44e3d1 446done:
507e6e9e
NTND
447 if (ret || !opts->keep_locked) {
448 strbuf_reset(&sb);
449 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
450 unlink_or_warn(sb.buf);
451 }
ade546be
ES
452
453 /*
454 * Hook failure does not warrant worktree deletion, so run hook after
455 * is_junk is cleared, but do return appropriate code when hook fails.
456 */
a4bf1e3c
ES
457 if (!ret && opts->checkout) {
458 const char *hook = find_hook("post-checkout");
459 if (hook) {
460 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
461 cp.git_cmd = 0;
462 cp.no_stdin = 1;
463 cp.stdout_to_stderr = 1;
464 cp.dir = path;
465 cp.env = env;
466 cp.argv = NULL;
6206286e 467 cp.trace2_hook_name = "post-checkout";
22f9b7f3 468 strvec_pushl(&cp.args, absolute_path(hook),
f6d8942b
JK
469 oid_to_hex(&null_oid),
470 oid_to_hex(&commit->object.oid),
471 "1", NULL);
a4bf1e3c
ES
472 ret = run_command(&cp);
473 }
474 }
ade546be 475
22f9b7f3 476 strvec_clear(&child_env);
b979d950 477 strbuf_release(&sb);
f7c9dac1 478 strbuf_release(&symref);
b979d950
ES
479 strbuf_release(&sb_repo);
480 strbuf_release(&sb_git);
1de16aec 481 strbuf_release(&sb_name);
3d7747e3 482 strbuf_release(&realpath);
b979d950
ES
483 return ret;
484}
485
2c27002a
TG
486static void print_preparing_worktree_line(int detach,
487 const char *branch,
488 const char *new_branch,
489 int force_new_branch)
490{
491 if (force_new_branch) {
492 struct commit *commit = lookup_commit_reference_by_name(new_branch);
493 if (!commit)
494 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
495 else
496 printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
497 new_branch,
10174da9 498 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
2c27002a
TG
499 } else if (new_branch) {
500 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
501 } else {
502 struct strbuf s = STRBUF_INIT;
503 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
504 ref_exists(s.buf))
505 printf_ln(_("Preparing worktree (checking out '%s')"),
506 branch);
507 else {
508 struct commit *commit = lookup_commit_reference_by_name(branch);
509 if (!commit)
510 die(_("invalid reference: %s"), branch);
511 printf_ln(_("Preparing worktree (detached HEAD %s)"),
10174da9 512 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
2c27002a
TG
513 }
514 strbuf_release(&s);
515 }
516}
517
6427f871
TG
518static const char *dwim_branch(const char *path, const char **new_branch)
519{
520 int n;
521 const char *s = worktree_basename(path, &n);
f60a7b76
TG
522 const char *branchname = xstrndup(s, n);
523 struct strbuf ref = STRBUF_INIT;
524
525 UNLEAK(branchname);
526 if (!strbuf_check_branch_ref(&ref, branchname) &&
527 ref_exists(ref.buf)) {
528 strbuf_release(&ref);
529 return branchname;
530 }
531
532 *new_branch = branchname;
6427f871
TG
533 if (guess_remote) {
534 struct object_id oid;
535 const char *remote =
3c87aa94 536 unique_tracking_name(*new_branch, &oid, NULL);
6427f871
TG
537 return remote;
538 }
539 return NULL;
540}
541
fc56361f
ES
542static int add(int ac, const char **av, const char *prefix)
543{
5dd6e234
ES
544 struct add_opts opts;
545 const char *new_branch_force = NULL;
e4da43b1
JK
546 char *path;
547 const char *branch;
d861d34a 548 const char *new_branch = NULL;
e284e892 549 const char *opt_track = NULL;
fc56361f 550 struct option options[] = {
1224781d
NTND
551 OPT__FORCE(&opts.force,
552 N_("checkout <branch> even if already checked out in other worktree"),
fc3d4e0c 553 PARSE_OPT_NOCOMPLETE),
d861d34a 554 OPT_STRING('b', NULL, &new_branch, N_("branch"),
cbdf60fa
ES
555 N_("create a new branch")),
556 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
557 N_("create or reset a branch")),
c670aa47 558 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 559 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
507e6e9e 560 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
371979c2 561 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
e284e892
TG
562 OPT_PASSTHRU(0, "track", &opt_track, NULL,
563 N_("set up tracking mode (see git-branch(1))"),
564 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
71d6682d
TG
565 OPT_BOOL(0, "guess-remote", &guess_remote,
566 N_("try to match the new branch name with a remote-tracking branch")),
fc56361f
ES
567 OPT_END()
568 };
569
5dd6e234 570 memset(&opts, 0, sizeof(opts));
ef2a0ac9 571 opts.checkout = 1;
fc56361f 572 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
d861d34a 573 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
ab0b2c53 574 die(_("-b, -B, and --detach are mutually exclusive"));
0f4af3b9
ES
575 if (ac < 1 || ac > 2)
576 usage_with_options(worktree_usage, options);
fc56361f 577
116fb64e 578 path = prefix_filename(prefix, av[0]);
0f4af3b9 579 branch = ac < 2 ? "HEAD" : av[1];
fc56361f 580
1a450e2f
JDG
581 if (!strcmp(branch, "-"))
582 branch = "@{-1}";
583
d861d34a 584 if (new_branch_force) {
beb6f24b
NTND
585 struct strbuf symref = STRBUF_INIT;
586
d861d34a 587 new_branch = new_branch_force;
eef005dc 588
beb6f24b 589 if (!opts.force &&
d861d34a 590 !strbuf_check_branch_ref(&symref, new_branch) &&
beb6f24b 591 ref_exists(symref.buf))
8d9fdd70 592 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
593 strbuf_release(&symref);
594 }
595
d861d34a 596 if (ac < 2 && !new_branch && !opts.detach) {
6427f871
TG
597 const char *s = dwim_branch(path, &new_branch);
598 if (s)
599 branch = s;
1eb07d82
ES
600 }
601
d861d34a 602 if (ac == 2 && !new_branch && !opts.detach) {
4e853331
TG
603 struct object_id oid;
604 struct commit *commit;
605 const char *remote;
606
607 commit = lookup_commit_reference_by_name(branch);
608 if (!commit) {
3c87aa94 609 remote = unique_tracking_name(branch, &oid, NULL);
4e853331 610 if (remote) {
d861d34a 611 new_branch = branch;
4e853331
TG
612 branch = remote;
613 }
614 }
615 }
371979c2
EP
616 if (!opts.quiet)
617 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
2c27002a 618
d861d34a 619 if (new_branch) {
542aa25d 620 struct child_process cp = CHILD_PROCESS_INIT;
c2842439 621 cp.git_cmd = 1;
22f9b7f3 622 strvec_push(&cp.args, "branch");
d861d34a 623 if (new_branch_force)
22f9b7f3 624 strvec_push(&cp.args, "--force");
371979c2 625 if (opts.quiet)
22f9b7f3
JK
626 strvec_push(&cp.args, "--quiet");
627 strvec_push(&cp.args, new_branch);
628 strvec_push(&cp.args, branch);
e284e892 629 if (opt_track)
22f9b7f3 630 strvec_push(&cp.args, opt_track);
c2842439
ES
631 if (run_command(&cp))
632 return -1;
d861d34a 633 branch = new_branch;
e284e892
TG
634 } else if (opt_track) {
635 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
636 }
637
0e5bba53
JK
638 UNLEAK(path);
639 UNLEAK(opts);
80a0548f 640 return add_worktree(path, branch, &opts);
fc56361f
ES
641}
642
bb9c03b8
MR
643static void show_worktree_porcelain(struct worktree *wt)
644{
645 printf("worktree %s\n", wt->path);
646 if (wt->is_bare)
647 printf("bare\n");
648 else {
0f05154c 649 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
bb9c03b8
MR
650 if (wt->is_detached)
651 printf("detached\n");
a234563a 652 else if (wt->head_ref)
bb9c03b8
MR
653 printf("branch %s\n", wt->head_ref);
654 }
655 printf("\n");
656}
657
658static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
659{
660 struct strbuf sb = STRBUF_INIT;
661 int cur_path_len = strlen(wt->path);
662 int path_adj = cur_path_len - utf8_strwidth(wt->path);
663
664 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
665 if (wt->is_bare)
666 strbuf_addstr(&sb, "(bare)");
667 else {
668 strbuf_addf(&sb, "%-*s ", abbrev_len,
aab9583f 669 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
96f09e2a 670 if (wt->is_detached)
bb9c03b8 671 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
672 else if (wt->head_ref) {
673 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
674 strbuf_addf(&sb, "[%s]", ref);
675 free(ref);
676 } else
a234563a 677 strbuf_addstr(&sb, "(error)");
bb9c03b8 678 }
bb9c03b8 679
c57b3367
RS
680 if (!is_main_worktree(wt) && worktree_lock_reason(wt))
681 strbuf_addstr(&sb, " locked");
682
683 printf("%s\n", sb.buf);
bb9c03b8
MR
684 strbuf_release(&sb);
685}
686
687static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
688{
689 int i;
690
691 for (i = 0; wt[i]; i++) {
692 int sha1_len;
693 int path_len = strlen(wt[i]->path);
694
695 if (path_len > *maxlen)
696 *maxlen = path_len;
aab9583f 697 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
bb9c03b8
MR
698 if (sha1_len > *abbrev)
699 *abbrev = sha1_len;
700 }
701}
702
d9c54c2b
ES
703static int pathcmp(const void *a_, const void *b_)
704{
705 const struct worktree *const *a = a_;
706 const struct worktree *const *b = b_;
707 return fspathcmp((*a)->path, (*b)->path);
708}
709
710static void pathsort(struct worktree **wt)
711{
712 int n = 0;
713 struct worktree **p = wt;
714
715 while (*p++)
716 n++;
717 QSORT(wt, n, pathcmp);
718}
719
bb9c03b8
MR
720static int list(int ac, const char **av, const char *prefix)
721{
722 int porcelain = 0;
723
724 struct option options[] = {
725 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
726 OPT_END()
727 };
728
729 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
730 if (ac)
731 usage_with_options(worktree_usage, options);
732 else {
03f2465b 733 struct worktree **worktrees = get_worktrees();
bb9c03b8
MR
734 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
735
d9c54c2b
ES
736 /* sort worktrees by path but keep main worktree at top */
737 pathsort(worktrees + 1);
738
bb9c03b8
MR
739 if (!porcelain)
740 measure_widths(worktrees, &abbrev, &path_maxlen);
741
742 for (i = 0; worktrees[i]; i++) {
743 if (porcelain)
744 show_worktree_porcelain(worktrees[i]);
745 else
746 show_worktree(worktrees[i], path_maxlen, abbrev);
747 }
748 free_worktrees(worktrees);
749 }
750 return 0;
751}
752
58142c09
NTND
753static int lock_worktree(int ac, const char **av, const char *prefix)
754{
755 const char *reason = "", *old_reason;
756 struct option options[] = {
757 OPT_STRING(0, "reason", &reason, N_("string"),
758 N_("reason for locking")),
759 OPT_END()
760 };
761 struct worktree **worktrees, *wt;
762
763 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
764 if (ac != 1)
765 usage_with_options(worktree_usage, options);
766
03f2465b 767 worktrees = get_worktrees();
58142c09
NTND
768 wt = find_worktree(worktrees, prefix, av[0]);
769 if (!wt)
770 die(_("'%s' is not a working tree"), av[0]);
771 if (is_main_worktree(wt))
772 die(_("The main working tree cannot be locked or unlocked"));
773
d236f12b 774 old_reason = worktree_lock_reason(wt);
58142c09
NTND
775 if (old_reason) {
776 if (*old_reason)
777 die(_("'%s' is already locked, reason: %s"),
778 av[0], old_reason);
779 die(_("'%s' is already locked"), av[0]);
780 }
781
782 write_file(git_common_path("worktrees/%s/locked", wt->id),
783 "%s", reason);
784 free_worktrees(worktrees);
785 return 0;
786}
787
6d308627
NTND
788static int unlock_worktree(int ac, const char **av, const char *prefix)
789{
790 struct option options[] = {
791 OPT_END()
792 };
793 struct worktree **worktrees, *wt;
794 int ret;
795
796 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
797 if (ac != 1)
798 usage_with_options(worktree_usage, options);
799
03f2465b 800 worktrees = get_worktrees();
6d308627
NTND
801 wt = find_worktree(worktrees, prefix, av[0]);
802 if (!wt)
803 die(_("'%s' is not a working tree"), av[0]);
804 if (is_main_worktree(wt))
805 die(_("The main working tree cannot be locked or unlocked"));
d236f12b 806 if (!worktree_lock_reason(wt))
6d308627
NTND
807 die(_("'%s' is not locked"), av[0]);
808 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
809 free_worktrees(worktrees);
810 return ret;
811}
812
78d986b2
NTND
813static void validate_no_submodules(const struct worktree *wt)
814{
815 struct index_state istate = { NULL };
00a6d4d1 816 struct strbuf path = STRBUF_INIT;
78d986b2
NTND
817 int i, found_submodules = 0;
818
00a6d4d1
NTND
819 if (is_directory(worktree_git_path(wt, "modules"))) {
820 /*
821 * There could be false positives, e.g. the "modules"
822 * directory exists but is empty. But it's a rare case and
823 * this simpler check is probably good enough for now.
824 */
825 found_submodules = 1;
826 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
827 get_worktree_git_dir(wt)) > 0) {
78d986b2
NTND
828 for (i = 0; i < istate.cache_nr; i++) {
829 struct cache_entry *ce = istate.cache[i];
00a6d4d1 830 int err;
78d986b2 831
00a6d4d1
NTND
832 if (!S_ISGITLINK(ce->ce_mode))
833 continue;
834
835 strbuf_reset(&path);
836 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
837 if (!is_submodule_populated_gently(path.buf, &err))
838 continue;
839
840 found_submodules = 1;
841 break;
78d986b2
NTND
842 }
843 }
844 discard_index(&istate);
00a6d4d1 845 strbuf_release(&path);
78d986b2
NTND
846
847 if (found_submodules)
cc73385c 848 die(_("working trees containing submodules cannot be moved or removed"));
78d986b2
NTND
849}
850
9f792bb4
NTND
851static int move_worktree(int ac, const char **av, const char *prefix)
852{
68a6b3a1 853 int force = 0;
9f792bb4 854 struct option options[] = {
68a6b3a1
ES
855 OPT__FORCE(&force,
856 N_("force move even if worktree is dirty or locked"),
857 PARSE_OPT_NOCOMPLETE),
9f792bb4
NTND
858 OPT_END()
859 };
860 struct worktree **worktrees, *wt;
861 struct strbuf dst = STRBUF_INIT;
862 struct strbuf errmsg = STRBUF_INIT;
68a6b3a1 863 const char *reason = NULL;
9f792bb4
NTND
864 char *path;
865
866 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
867 if (ac != 2)
868 usage_with_options(worktree_usage, options);
869
870 path = prefix_filename(prefix, av[1]);
871 strbuf_addstr(&dst, path);
872 free(path);
873
03f2465b 874 worktrees = get_worktrees();
9f792bb4
NTND
875 wt = find_worktree(worktrees, prefix, av[0]);
876 if (!wt)
877 die(_("'%s' is not a working tree"), av[0]);
878 if (is_main_worktree(wt))
879 die(_("'%s' is a main working tree"), av[0]);
c64a8d20
NTND
880 if (is_directory(dst.buf)) {
881 const char *sep = find_last_dir_sep(wt->path);
882
883 if (!sep)
884 die(_("could not figure out destination name from '%s'"),
885 wt->path);
886 strbuf_trim_trailing_dir_sep(&dst);
887 strbuf_addstr(&dst, sep);
888 }
810382ed 889 check_candidate_path(dst.buf, force, worktrees, "move");
9f792bb4 890
78d986b2
NTND
891 validate_no_submodules(wt);
892
68a6b3a1 893 if (force < 2)
d236f12b 894 reason = worktree_lock_reason(wt);
9f792bb4
NTND
895 if (reason) {
896 if (*reason)
68a6b3a1 897 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
9f792bb4 898 reason);
68a6b3a1 899 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
9f792bb4 900 }
ee6763af 901 if (validate_worktree(wt, &errmsg, 0))
9f792bb4
NTND
902 die(_("validation failed, cannot move working tree: %s"),
903 errmsg.buf);
904 strbuf_release(&errmsg);
905
906 if (rename(wt->path, dst.buf) == -1)
907 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
908
909 update_worktree_location(wt, dst.buf);
910
911 strbuf_release(&dst);
912 free_worktrees(worktrees);
913 return 0;
914}
915
cc73385c
NTND
916/*
917 * Note, "git status --porcelain" is used to determine if it's safe to
918 * delete a whole worktree. "git status" does not ignore user
919 * configuration, so if a normal "git status" shows "clean" for the
920 * user, then it's ok to remove it.
921 *
922 * This assumption may be a bad one. We may want to ignore
923 * (potentially bad) user settings and only delete a worktree when
924 * it's absolutely safe to do so from _our_ point of view because we
925 * know better.
926 */
927static void check_clean_worktree(struct worktree *wt,
928 const char *original_path)
929{
cc73385c
NTND
930 struct child_process cp;
931 char buf[1];
932 int ret;
933
934 /*
935 * Until we sort this out, all submodules are "dirty" and
936 * will abort this function.
937 */
938 validate_no_submodules(wt);
939
27ed6ccc 940 child_process_init(&cp);
1aadb47a 941 strvec_pushf(&cp.env_array, "%s=%s/.git",
f6d8942b 942 GIT_DIR_ENVIRONMENT, wt->path);
1aadb47a 943 strvec_pushf(&cp.env_array, "%s=%s",
f6d8942b 944 GIT_WORK_TREE_ENVIRONMENT, wt->path);
22f9b7f3 945 strvec_pushl(&cp.args, "status",
f6d8942b
JK
946 "--porcelain", "--ignore-submodules=none",
947 NULL);
cc73385c
NTND
948 cp.git_cmd = 1;
949 cp.dir = wt->path;
950 cp.out = -1;
951 ret = start_command(&cp);
952 if (ret)
953 die_errno(_("failed to run 'git status' on '%s'"),
954 original_path);
955 ret = xread(cp.out, buf, sizeof(buf));
956 if (ret)
507e5470 957 die(_("'%s' contains modified or untracked files, use --force to delete it"),
cc73385c
NTND
958 original_path);
959 close(cp.out);
960 ret = finish_command(&cp);
961 if (ret)
962 die_errno(_("failed to run 'git status' on '%s', code %d"),
963 original_path, ret);
964}
965
966static int delete_git_work_tree(struct worktree *wt)
967{
968 struct strbuf sb = STRBUF_INIT;
969 int ret = 0;
970
971 strbuf_addstr(&sb, wt->path);
972 if (remove_dir_recursively(&sb, 0)) {
973 error_errno(_("failed to delete '%s'"), sb.buf);
974 ret = -1;
975 }
976 strbuf_release(&sb);
977 return ret;
978}
979
cc73385c
NTND
980static int remove_worktree(int ac, const char **av, const char *prefix)
981{
982 int force = 0;
983 struct option options[] = {
d228eea5 984 OPT__FORCE(&force,
f4143101 985 N_("force removal even if worktree is dirty or locked"),
d228eea5 986 PARSE_OPT_NOCOMPLETE),
cc73385c
NTND
987 OPT_END()
988 };
989 struct worktree **worktrees, *wt;
990 struct strbuf errmsg = STRBUF_INIT;
f4143101 991 const char *reason = NULL;
cc73385c
NTND
992 int ret = 0;
993
994 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
995 if (ac != 1)
996 usage_with_options(worktree_usage, options);
997
03f2465b 998 worktrees = get_worktrees();
cc73385c
NTND
999 wt = find_worktree(worktrees, prefix, av[0]);
1000 if (!wt)
1001 die(_("'%s' is not a working tree"), av[0]);
1002 if (is_main_worktree(wt))
1003 die(_("'%s' is a main working tree"), av[0]);
f4143101 1004 if (force < 2)
d236f12b 1005 reason = worktree_lock_reason(wt);
cc73385c
NTND
1006 if (reason) {
1007 if (*reason)
f4143101 1008 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
cc73385c 1009 reason);
f4143101 1010 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
cc73385c 1011 }
ee6763af 1012 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
cc73385c
NTND
1013 die(_("validation failed, cannot remove working tree: %s"),
1014 errmsg.buf);
1015 strbuf_release(&errmsg);
1016
ee6763af
NTND
1017 if (file_exists(wt->path)) {
1018 if (!force)
1019 check_clean_worktree(wt, av[0]);
cc73385c 1020
ee6763af
NTND
1021 ret |= delete_git_work_tree(wt);
1022 }
cc73385c
NTND
1023 /*
1024 * continue on even if ret is non-zero, there's no going back
1025 * from here.
1026 */
602aaed0 1027 ret |= delete_git_dir(wt->id);
3a540433 1028 delete_worktrees_dir_if_empty();
cc73385c
NTND
1029
1030 free_worktrees(worktrees);
1031 return ret;
1032}
1033
bdd1f3e4
ES
1034static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1035{
1036 if (!iserr) {
1037 printf_ln(_("repair: %s: %s"), msg, path);
1038 } else {
1039 int *exit_status = (int *)cb_data;
1040 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1041 *exit_status = 1;
1042 }
1043}
1044
e8e1ff24
ES
1045static int repair(int ac, const char **av, const char *prefix)
1046{
b214ab5a
ES
1047 const char **p;
1048 const char *self[] = { ".", NULL };
e8e1ff24
ES
1049 struct option options[] = {
1050 OPT_END()
1051 };
1052 int rc = 0;
1053
1054 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
bdd1f3e4 1055 repair_worktrees(report_repair, &rc);
b214ab5a
ES
1056 p = ac > 0 ? av : self;
1057 for (; *p; p++)
1058 repair_worktree_at_path(*p, report_repair, &rc);
e8e1ff24
ES
1059 return rc;
1060}
1061
df0b6cfb
NTND
1062int cmd_worktree(int ac, const char **av, const char *prefix)
1063{
1064 struct option options[] = {
1065 OPT_END()
1066 };
1067
e92445a7 1068 git_config(git_worktree_config, NULL);
d49028e6 1069
df0b6cfb
NTND
1070 if (ac < 2)
1071 usage_with_options(worktree_usage, options);
0409e0b6
NTND
1072 if (!prefix)
1073 prefix = "";
fc56361f
ES
1074 if (!strcmp(av[1], "add"))
1075 return add(ac - 1, av + 1, prefix);
df0b6cfb
NTND
1076 if (!strcmp(av[1], "prune"))
1077 return prune(ac - 1, av + 1, prefix);
bb9c03b8
MR
1078 if (!strcmp(av[1], "list"))
1079 return list(ac - 1, av + 1, prefix);
58142c09
NTND
1080 if (!strcmp(av[1], "lock"))
1081 return lock_worktree(ac - 1, av + 1, prefix);
6d308627
NTND
1082 if (!strcmp(av[1], "unlock"))
1083 return unlock_worktree(ac - 1, av + 1, prefix);
9f792bb4
NTND
1084 if (!strcmp(av[1], "move"))
1085 return move_worktree(ac - 1, av + 1, prefix);
cc73385c
NTND
1086 if (!strcmp(av[1], "remove"))
1087 return remove_worktree(ac - 1, av + 1, prefix);
e8e1ff24
ES
1088 if (!strcmp(av[1], "repair"))
1089 return repair(ac - 1, av + 1, prefix);
df0b6cfb
NTND
1090 usage_with_options(worktree_usage, options);
1091}