]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/worktree.c
treewide: be explicit about dependence on gettext.h
[thirdparty/git.git] / builtin / worktree.c
1 #include "cache.h"
2 #include "checkout.h"
3 #include "config.h"
4 #include "builtin.h"
5 #include "dir.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "parse-options.h"
9 #include "strvec.h"
10 #include "branch.h"
11 #include "refs.h"
12 #include "run-command.h"
13 #include "hook.h"
14 #include "sigchain.h"
15 #include "submodule.h"
16 #include "utf8.h"
17 #include "worktree.h"
18 #include "quote.h"
19
20 #define BUILTIN_WORKTREE_ADD_USAGE \
21 N_("git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n" \
22 " [-b <new-branch>] <path> [<commit-ish>]")
23 #define BUILTIN_WORKTREE_LIST_USAGE \
24 N_("git worktree list [-v | --porcelain [-z]]")
25 #define BUILTIN_WORKTREE_LOCK_USAGE \
26 N_("git worktree lock [--reason <string>] <worktree>")
27 #define BUILTIN_WORKTREE_MOVE_USAGE \
28 N_("git worktree move <worktree> <new-path>")
29 #define BUILTIN_WORKTREE_PRUNE_USAGE \
30 N_("git worktree prune [-n] [-v] [--expire <expire>]")
31 #define BUILTIN_WORKTREE_REMOVE_USAGE \
32 N_("git worktree remove [-f] <worktree>")
33 #define BUILTIN_WORKTREE_REPAIR_USAGE \
34 N_("git worktree repair [<path>...]")
35 #define BUILTIN_WORKTREE_UNLOCK_USAGE \
36 N_("git worktree unlock <worktree>")
37
38 static const char * const git_worktree_usage[] = {
39 BUILTIN_WORKTREE_ADD_USAGE,
40 BUILTIN_WORKTREE_LIST_USAGE,
41 BUILTIN_WORKTREE_LOCK_USAGE,
42 BUILTIN_WORKTREE_MOVE_USAGE,
43 BUILTIN_WORKTREE_PRUNE_USAGE,
44 BUILTIN_WORKTREE_REMOVE_USAGE,
45 BUILTIN_WORKTREE_REPAIR_USAGE,
46 BUILTIN_WORKTREE_UNLOCK_USAGE,
47 NULL
48 };
49
50 static const char * const git_worktree_add_usage[] = {
51 BUILTIN_WORKTREE_ADD_USAGE,
52 NULL,
53 };
54
55 static const char * const git_worktree_list_usage[] = {
56 BUILTIN_WORKTREE_LIST_USAGE,
57 NULL
58 };
59
60 static const char * const git_worktree_lock_usage[] = {
61 BUILTIN_WORKTREE_LOCK_USAGE,
62 NULL
63 };
64
65 static const char * const git_worktree_move_usage[] = {
66 BUILTIN_WORKTREE_MOVE_USAGE,
67 NULL
68 };
69
70 static const char * const git_worktree_prune_usage[] = {
71 BUILTIN_WORKTREE_PRUNE_USAGE,
72 NULL
73 };
74
75 static const char * const git_worktree_remove_usage[] = {
76 BUILTIN_WORKTREE_REMOVE_USAGE,
77 NULL
78 };
79
80 static const char * const git_worktree_repair_usage[] = {
81 BUILTIN_WORKTREE_REPAIR_USAGE,
82 NULL
83 };
84
85 static const char * const git_worktree_unlock_usage[] = {
86 BUILTIN_WORKTREE_UNLOCK_USAGE,
87 NULL
88 };
89
90 struct add_opts {
91 int force;
92 int detach;
93 int quiet;
94 int checkout;
95 const char *keep_locked;
96 };
97
98 static int show_only;
99 static int verbose;
100 static int guess_remote;
101 static timestamp_t expire;
102
103 static int git_worktree_config(const char *var, const char *value, void *cb)
104 {
105 if (!strcmp(var, "worktree.guessremote")) {
106 guess_remote = git_config_bool(var, value);
107 return 0;
108 }
109
110 return git_default_config(var, value, cb);
111 }
112
113 static int delete_git_dir(const char *id)
114 {
115 struct strbuf sb = STRBUF_INIT;
116 int ret;
117
118 strbuf_addstr(&sb, git_common_path("worktrees/%s", id));
119 ret = remove_dir_recursively(&sb, 0);
120 if (ret < 0 && errno == ENOTDIR)
121 ret = unlink(sb.buf);
122 if (ret)
123 error_errno(_("failed to delete '%s'"), sb.buf);
124 strbuf_release(&sb);
125 return ret;
126 }
127
128 static void delete_worktrees_dir_if_empty(void)
129 {
130 rmdir(git_path("worktrees")); /* ignore failed removal */
131 }
132
133 static void prune_worktree(const char *id, const char *reason)
134 {
135 if (show_only || verbose)
136 fprintf_ln(stderr, _("Removing %s/%s: %s"), "worktrees", id, reason);
137 if (!show_only)
138 delete_git_dir(id);
139 }
140
141 static int prune_cmp(const void *a, const void *b)
142 {
143 const struct string_list_item *x = a;
144 const struct string_list_item *y = b;
145 int c;
146
147 if ((c = fspathcmp(x->string, y->string)))
148 return c;
149 /*
150 * paths same; prune_dupes() removes all but the first worktree entry
151 * having the same path, so sort main worktree ('util' is NULL) above
152 * linked worktrees ('util' not NULL) since main worktree can't be
153 * removed
154 */
155 if (!x->util)
156 return -1;
157 if (!y->util)
158 return 1;
159 /* paths same; sort by .git/worktrees/<id> */
160 return strcmp(x->util, y->util);
161 }
162
163 static void prune_dups(struct string_list *l)
164 {
165 int i;
166
167 QSORT(l->items, l->nr, prune_cmp);
168 for (i = 1; i < l->nr; i++) {
169 if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
170 prune_worktree(l->items[i].util, "duplicate entry");
171 }
172 }
173
174 static void prune_worktrees(void)
175 {
176 struct strbuf reason = STRBUF_INIT;
177 struct strbuf main_path = STRBUF_INIT;
178 struct string_list kept = STRING_LIST_INIT_DUP;
179 DIR *dir = opendir(git_path("worktrees"));
180 struct dirent *d;
181 if (!dir)
182 return;
183 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
184 char *path;
185 strbuf_reset(&reason);
186 if (should_prune_worktree(d->d_name, &reason, &path, expire))
187 prune_worktree(d->d_name, reason.buf);
188 else if (path)
189 string_list_append_nodup(&kept, path)->util = xstrdup(d->d_name);
190 }
191 closedir(dir);
192
193 strbuf_add_absolute_path(&main_path, get_git_common_dir());
194 /* massage main worktree absolute path to match 'gitdir' content */
195 strbuf_strip_suffix(&main_path, "/.");
196 string_list_append_nodup(&kept, strbuf_detach(&main_path, NULL));
197 prune_dups(&kept);
198 string_list_clear(&kept, 1);
199
200 if (!show_only)
201 delete_worktrees_dir_if_empty();
202 strbuf_release(&reason);
203 }
204
205 static int prune(int ac, const char **av, const char *prefix)
206 {
207 struct option options[] = {
208 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
209 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
210 OPT_EXPIRY_DATE(0, "expire", &expire,
211 N_("expire working trees older than <time>")),
212 OPT_END()
213 };
214
215 expire = TIME_MAX;
216 ac = parse_options(ac, av, prefix, options, git_worktree_prune_usage,
217 0);
218 if (ac)
219 usage_with_options(git_worktree_prune_usage, options);
220 prune_worktrees();
221 return 0;
222 }
223
224 static char *junk_work_tree;
225 static char *junk_git_dir;
226 static int is_junk;
227 static pid_t junk_pid;
228
229 static void remove_junk(void)
230 {
231 struct strbuf sb = STRBUF_INIT;
232 if (!is_junk || getpid() != junk_pid)
233 return;
234 if (junk_git_dir) {
235 strbuf_addstr(&sb, junk_git_dir);
236 remove_dir_recursively(&sb, 0);
237 strbuf_reset(&sb);
238 }
239 if (junk_work_tree) {
240 strbuf_addstr(&sb, junk_work_tree);
241 remove_dir_recursively(&sb, 0);
242 }
243 strbuf_release(&sb);
244 }
245
246 static void remove_junk_on_signal(int signo)
247 {
248 remove_junk();
249 sigchain_pop(signo);
250 raise(signo);
251 }
252
253 static const char *worktree_basename(const char *path, int *olen)
254 {
255 const char *name;
256 int len;
257
258 len = strlen(path);
259 while (len && is_dir_sep(path[len - 1]))
260 len--;
261
262 for (name = path + len - 1; name > path; name--)
263 if (is_dir_sep(*name)) {
264 name++;
265 break;
266 }
267
268 *olen = len;
269 return name;
270 }
271
272 /* check that path is viable location for worktree */
273 static void check_candidate_path(const char *path,
274 int force,
275 struct worktree **worktrees,
276 const char *cmd)
277 {
278 struct worktree *wt;
279 int locked;
280
281 if (file_exists(path) && !is_empty_dir(path))
282 die(_("'%s' already exists"), path);
283
284 wt = find_worktree_by_path(worktrees, path);
285 if (!wt)
286 return;
287
288 locked = !!worktree_lock_reason(wt);
289 if ((!locked && force) || (locked && force > 1)) {
290 if (delete_git_dir(wt->id))
291 die(_("unusable worktree destination '%s'"), path);
292 return;
293 }
294
295 if (locked)
296 die(_("'%s' is a missing but locked worktree;\nuse '%s -f -f' to override, or 'unlock' and 'prune' or 'remove' to clear"), path, cmd);
297 else
298 die(_("'%s' is a missing but already registered worktree;\nuse '%s -f' to override, or 'prune' or 'remove' to clear"), path, cmd);
299 }
300
301 static void copy_sparse_checkout(const char *worktree_git_dir)
302 {
303 char *from_file = git_pathdup("info/sparse-checkout");
304 char *to_file = xstrfmt("%s/info/sparse-checkout", worktree_git_dir);
305
306 if (file_exists(from_file)) {
307 if (safe_create_leading_directories(to_file) ||
308 copy_file(to_file, from_file, 0666))
309 error(_("failed to copy '%s' to '%s'; sparse-checkout may not work correctly"),
310 from_file, to_file);
311 }
312
313 free(from_file);
314 free(to_file);
315 }
316
317 static void copy_filtered_worktree_config(const char *worktree_git_dir)
318 {
319 char *from_file = git_pathdup("config.worktree");
320 char *to_file = xstrfmt("%s/config.worktree", worktree_git_dir);
321
322 if (file_exists(from_file)) {
323 struct config_set cs = { { 0 } };
324 const char *core_worktree;
325 int bare;
326
327 if (safe_create_leading_directories(to_file) ||
328 copy_file(to_file, from_file, 0666)) {
329 error(_("failed to copy worktree config from '%s' to '%s'"),
330 from_file, to_file);
331 goto worktree_copy_cleanup;
332 }
333
334 git_configset_init(&cs);
335 git_configset_add_file(&cs, from_file);
336
337 if (!git_configset_get_bool(&cs, "core.bare", &bare) &&
338 bare &&
339 git_config_set_multivar_in_file_gently(
340 to_file, "core.bare", NULL, "true", 0))
341 error(_("failed to unset '%s' in '%s'"),
342 "core.bare", to_file);
343 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree) &&
344 git_config_set_in_file_gently(to_file,
345 "core.worktree", NULL))
346 error(_("failed to unset '%s' in '%s'"),
347 "core.worktree", to_file);
348
349 git_configset_clear(&cs);
350 }
351
352 worktree_copy_cleanup:
353 free(from_file);
354 free(to_file);
355 }
356
357 static int checkout_worktree(const struct add_opts *opts,
358 struct strvec *child_env)
359 {
360 struct child_process cp = CHILD_PROCESS_INIT;
361 cp.git_cmd = 1;
362 strvec_pushl(&cp.args, "reset", "--hard", "--no-recurse-submodules", NULL);
363 if (opts->quiet)
364 strvec_push(&cp.args, "--quiet");
365 strvec_pushv(&cp.env, child_env->v);
366 return run_command(&cp);
367 }
368
369 static int add_worktree(const char *path, const char *refname,
370 const struct add_opts *opts)
371 {
372 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
373 struct strbuf sb = STRBUF_INIT, realpath = STRBUF_INIT;
374 const char *name;
375 struct child_process cp = CHILD_PROCESS_INIT;
376 struct strvec child_env = STRVEC_INIT;
377 unsigned int counter = 0;
378 int len, ret;
379 struct strbuf symref = STRBUF_INIT;
380 struct commit *commit = NULL;
381 int is_branch = 0;
382 struct strbuf sb_name = STRBUF_INIT;
383 struct worktree **worktrees;
384
385 worktrees = get_worktrees();
386 check_candidate_path(path, opts->force, worktrees, "add");
387 free_worktrees(worktrees);
388 worktrees = NULL;
389
390 /* is 'refname' a branch or commit? */
391 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
392 ref_exists(symref.buf)) {
393 is_branch = 1;
394 if (!opts->force)
395 die_if_checked_out(symref.buf, 0);
396 }
397 commit = lookup_commit_reference_by_name(refname);
398 if (!commit)
399 die(_("invalid reference: %s"), refname);
400
401 name = worktree_basename(path, &len);
402 strbuf_add(&sb, name, path + len - name);
403 sanitize_refname_component(sb.buf, &sb_name);
404 if (!sb_name.len)
405 BUG("How come '%s' becomes empty after sanitization?", sb.buf);
406 strbuf_reset(&sb);
407 name = sb_name.buf;
408 git_path_buf(&sb_repo, "worktrees/%s", name);
409 len = sb_repo.len;
410 if (safe_create_leading_directories_const(sb_repo.buf))
411 die_errno(_("could not create leading directories of '%s'"),
412 sb_repo.buf);
413
414 while (mkdir(sb_repo.buf, 0777)) {
415 counter++;
416 if ((errno != EEXIST) || !counter /* overflow */)
417 die_errno(_("could not create directory of '%s'"),
418 sb_repo.buf);
419 strbuf_setlen(&sb_repo, len);
420 strbuf_addf(&sb_repo, "%d", counter);
421 }
422 name = strrchr(sb_repo.buf, '/') + 1;
423
424 junk_pid = getpid();
425 atexit(remove_junk);
426 sigchain_push_common(remove_junk_on_signal);
427
428 junk_git_dir = xstrdup(sb_repo.buf);
429 is_junk = 1;
430
431 /*
432 * lock the incomplete repo so prune won't delete it, unlock
433 * after the preparation is over.
434 */
435 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
436 if (opts->keep_locked)
437 write_file(sb.buf, "%s", opts->keep_locked);
438 else
439 write_file(sb.buf, _("initializing"));
440
441 strbuf_addf(&sb_git, "%s/.git", path);
442 if (safe_create_leading_directories_const(sb_git.buf))
443 die_errno(_("could not create leading directories of '%s'"),
444 sb_git.buf);
445 junk_work_tree = xstrdup(path);
446
447 strbuf_reset(&sb);
448 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
449 strbuf_realpath(&realpath, sb_git.buf, 1);
450 write_file(sb.buf, "%s", realpath.buf);
451 strbuf_realpath(&realpath, get_git_common_dir(), 1);
452 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
453 realpath.buf, name);
454 /*
455 * This is to keep resolve_ref() happy. We need a valid HEAD
456 * or is_git_directory() will reject the directory. Any value which
457 * looks like an object ID will do since it will be immediately
458 * replaced by the symbolic-ref or update-ref invocation in the new
459 * worktree.
460 */
461 strbuf_reset(&sb);
462 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
463 write_file(sb.buf, "%s", oid_to_hex(null_oid()));
464 strbuf_reset(&sb);
465 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
466 write_file(sb.buf, "../..");
467
468 /*
469 * If the current worktree has sparse-checkout enabled, then copy
470 * the sparse-checkout patterns from the current worktree.
471 */
472 if (core_apply_sparse_checkout)
473 copy_sparse_checkout(sb_repo.buf);
474
475 /*
476 * If we are using worktree config, then copy all current config
477 * values from the current worktree into the new one, that way the
478 * new worktree behaves the same as this one.
479 */
480 if (repository_format_worktree_config)
481 copy_filtered_worktree_config(sb_repo.buf);
482
483 strvec_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
484 strvec_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
485 cp.git_cmd = 1;
486
487 if (!is_branch)
488 strvec_pushl(&cp.args, "update-ref", "HEAD",
489 oid_to_hex(&commit->object.oid), NULL);
490 else {
491 strvec_pushl(&cp.args, "symbolic-ref", "HEAD",
492 symref.buf, NULL);
493 if (opts->quiet)
494 strvec_push(&cp.args, "--quiet");
495 }
496
497 strvec_pushv(&cp.env, child_env.v);
498 ret = run_command(&cp);
499 if (ret)
500 goto done;
501
502 if (opts->checkout &&
503 (ret = checkout_worktree(opts, &child_env)))
504 goto done;
505
506 is_junk = 0;
507 FREE_AND_NULL(junk_work_tree);
508 FREE_AND_NULL(junk_git_dir);
509
510 done:
511 if (ret || !opts->keep_locked) {
512 strbuf_reset(&sb);
513 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
514 unlink_or_warn(sb.buf);
515 }
516
517 /*
518 * Hook failure does not warrant worktree deletion, so run hook after
519 * is_junk is cleared, but do return appropriate code when hook fails.
520 */
521 if (!ret && opts->checkout) {
522 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
523
524 strvec_pushl(&opt.env, "GIT_DIR", "GIT_WORK_TREE", NULL);
525 strvec_pushl(&opt.args,
526 oid_to_hex(null_oid()),
527 oid_to_hex(&commit->object.oid),
528 "1",
529 NULL);
530 opt.dir = path;
531
532 ret = run_hooks_opt("post-checkout", &opt);
533 }
534
535 strvec_clear(&child_env);
536 strbuf_release(&sb);
537 strbuf_release(&symref);
538 strbuf_release(&sb_repo);
539 strbuf_release(&sb_git);
540 strbuf_release(&sb_name);
541 strbuf_release(&realpath);
542 return ret;
543 }
544
545 static void print_preparing_worktree_line(int detach,
546 const char *branch,
547 const char *new_branch,
548 int force_new_branch)
549 {
550 if (force_new_branch) {
551 struct commit *commit = lookup_commit_reference_by_name(new_branch);
552 if (!commit)
553 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
554 else
555 fprintf_ln(stderr, _("Preparing worktree (resetting branch '%s'; was at %s)"),
556 new_branch,
557 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
558 } else if (new_branch) {
559 fprintf_ln(stderr, _("Preparing worktree (new branch '%s')"), new_branch);
560 } else {
561 struct strbuf s = STRBUF_INIT;
562 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
563 ref_exists(s.buf))
564 fprintf_ln(stderr, _("Preparing worktree (checking out '%s')"),
565 branch);
566 else {
567 struct commit *commit = lookup_commit_reference_by_name(branch);
568 if (!commit)
569 die(_("invalid reference: %s"), branch);
570 fprintf_ln(stderr, _("Preparing worktree (detached HEAD %s)"),
571 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
572 }
573 strbuf_release(&s);
574 }
575 }
576
577 static const char *dwim_branch(const char *path, const char **new_branch)
578 {
579 int n;
580 int branch_exists;
581 const char *s = worktree_basename(path, &n);
582 const char *branchname = xstrndup(s, n);
583 struct strbuf ref = STRBUF_INIT;
584
585 UNLEAK(branchname);
586
587 branch_exists = !strbuf_check_branch_ref(&ref, branchname) &&
588 ref_exists(ref.buf);
589 strbuf_release(&ref);
590 if (branch_exists)
591 return branchname;
592
593 *new_branch = branchname;
594 if (guess_remote) {
595 struct object_id oid;
596 const char *remote =
597 unique_tracking_name(*new_branch, &oid, NULL);
598 return remote;
599 }
600 return NULL;
601 }
602
603 static int add(int ac, const char **av, const char *prefix)
604 {
605 struct add_opts opts;
606 const char *new_branch_force = NULL;
607 char *path;
608 const char *branch;
609 const char *new_branch = NULL;
610 const char *opt_track = NULL;
611 const char *lock_reason = NULL;
612 int keep_locked = 0;
613 struct option options[] = {
614 OPT__FORCE(&opts.force,
615 N_("checkout <branch> even if already checked out in other worktree"),
616 PARSE_OPT_NOCOMPLETE),
617 OPT_STRING('b', NULL, &new_branch, N_("branch"),
618 N_("create a new branch")),
619 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
620 N_("create or reset a branch")),
621 OPT_BOOL('d', "detach", &opts.detach, N_("detach HEAD at named commit")),
622 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
623 OPT_BOOL(0, "lock", &keep_locked, N_("keep the new working tree locked")),
624 OPT_STRING(0, "reason", &lock_reason, N_("string"),
625 N_("reason for locking")),
626 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
627 OPT_PASSTHRU(0, "track", &opt_track, NULL,
628 N_("set up tracking mode (see git-branch(1))"),
629 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
630 OPT_BOOL(0, "guess-remote", &guess_remote,
631 N_("try to match the new branch name with a remote-tracking branch")),
632 OPT_END()
633 };
634 int ret;
635
636 memset(&opts, 0, sizeof(opts));
637 opts.checkout = 1;
638 ac = parse_options(ac, av, prefix, options, git_worktree_add_usage, 0);
639 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
640 die(_("options '%s', '%s', and '%s' cannot be used together"), "-b", "-B", "--detach");
641 if (lock_reason && !keep_locked)
642 die(_("the option '%s' requires '%s'"), "--reason", "--lock");
643 if (lock_reason)
644 opts.keep_locked = lock_reason;
645 else if (keep_locked)
646 opts.keep_locked = _("added with --lock");
647
648 if (ac < 1 || ac > 2)
649 usage_with_options(git_worktree_add_usage, options);
650
651 path = prefix_filename(prefix, av[0]);
652 branch = ac < 2 ? "HEAD" : av[1];
653
654 if (!strcmp(branch, "-"))
655 branch = "@{-1}";
656
657 if (new_branch_force) {
658 struct strbuf symref = STRBUF_INIT;
659
660 new_branch = new_branch_force;
661
662 if (!opts.force &&
663 !strbuf_check_branch_ref(&symref, new_branch) &&
664 ref_exists(symref.buf))
665 die_if_checked_out(symref.buf, 0);
666 strbuf_release(&symref);
667 }
668
669 if (ac < 2 && !new_branch && !opts.detach) {
670 const char *s = dwim_branch(path, &new_branch);
671 if (s)
672 branch = s;
673 }
674
675 if (ac == 2 && !new_branch && !opts.detach) {
676 struct object_id oid;
677 struct commit *commit;
678 const char *remote;
679
680 commit = lookup_commit_reference_by_name(branch);
681 if (!commit) {
682 remote = unique_tracking_name(branch, &oid, NULL);
683 if (remote) {
684 new_branch = branch;
685 branch = remote;
686 }
687 }
688 }
689 if (!opts.quiet)
690 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
691
692 if (new_branch) {
693 struct child_process cp = CHILD_PROCESS_INIT;
694 cp.git_cmd = 1;
695 strvec_push(&cp.args, "branch");
696 if (new_branch_force)
697 strvec_push(&cp.args, "--force");
698 if (opts.quiet)
699 strvec_push(&cp.args, "--quiet");
700 strvec_push(&cp.args, new_branch);
701 strvec_push(&cp.args, branch);
702 if (opt_track)
703 strvec_push(&cp.args, opt_track);
704 if (run_command(&cp))
705 return -1;
706 branch = new_branch;
707 } else if (opt_track) {
708 die(_("--[no-]track can only be used if a new branch is created"));
709 }
710
711 ret = add_worktree(path, branch, &opts);
712 free(path);
713 return ret;
714 }
715
716 static void show_worktree_porcelain(struct worktree *wt, int line_terminator)
717 {
718 const char *reason;
719
720 printf("worktree %s%c", wt->path, line_terminator);
721 if (wt->is_bare)
722 printf("bare%c", line_terminator);
723 else {
724 printf("HEAD %s%c", oid_to_hex(&wt->head_oid), line_terminator);
725 if (wt->is_detached)
726 printf("detached%c", line_terminator);
727 else if (wt->head_ref)
728 printf("branch %s%c", wt->head_ref, line_terminator);
729 }
730
731 reason = worktree_lock_reason(wt);
732 if (reason) {
733 fputs("locked", stdout);
734 if (*reason) {
735 fputc(' ', stdout);
736 write_name_quoted(reason, stdout, line_terminator);
737 } else {
738 fputc(line_terminator, stdout);
739 }
740 }
741
742 reason = worktree_prune_reason(wt, expire);
743 if (reason)
744 printf("prunable %s%c", reason, line_terminator);
745
746 fputc(line_terminator, stdout);
747 }
748
749 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
750 {
751 struct strbuf sb = STRBUF_INIT;
752 int cur_path_len = strlen(wt->path);
753 int path_adj = cur_path_len - utf8_strwidth(wt->path);
754 const char *reason;
755
756 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
757 if (wt->is_bare)
758 strbuf_addstr(&sb, "(bare)");
759 else {
760 strbuf_addf(&sb, "%-*s ", abbrev_len,
761 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
762 if (wt->is_detached)
763 strbuf_addstr(&sb, "(detached HEAD)");
764 else if (wt->head_ref) {
765 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
766 strbuf_addf(&sb, "[%s]", ref);
767 free(ref);
768 } else
769 strbuf_addstr(&sb, "(error)");
770 }
771
772 reason = worktree_lock_reason(wt);
773 if (verbose && reason && *reason)
774 strbuf_addf(&sb, "\n\tlocked: %s", reason);
775 else if (reason)
776 strbuf_addstr(&sb, " locked");
777
778 reason = worktree_prune_reason(wt, expire);
779 if (verbose && reason)
780 strbuf_addf(&sb, "\n\tprunable: %s", reason);
781 else if (reason)
782 strbuf_addstr(&sb, " prunable");
783
784 printf("%s\n", sb.buf);
785 strbuf_release(&sb);
786 }
787
788 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
789 {
790 int i;
791
792 for (i = 0; wt[i]; i++) {
793 int sha1_len;
794 int path_len = strlen(wt[i]->path);
795
796 if (path_len > *maxlen)
797 *maxlen = path_len;
798 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
799 if (sha1_len > *abbrev)
800 *abbrev = sha1_len;
801 }
802 }
803
804 static int pathcmp(const void *a_, const void *b_)
805 {
806 const struct worktree *const *a = a_;
807 const struct worktree *const *b = b_;
808 return fspathcmp((*a)->path, (*b)->path);
809 }
810
811 static void pathsort(struct worktree **wt)
812 {
813 int n = 0;
814 struct worktree **p = wt;
815
816 while (*p++)
817 n++;
818 QSORT(wt, n, pathcmp);
819 }
820
821 static int list(int ac, const char **av, const char *prefix)
822 {
823 int porcelain = 0;
824 int line_terminator = '\n';
825
826 struct option options[] = {
827 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
828 OPT__VERBOSE(&verbose, N_("show extended annotations and reasons, if available")),
829 OPT_EXPIRY_DATE(0, "expire", &expire,
830 N_("add 'prunable' annotation to worktrees older than <time>")),
831 OPT_SET_INT('z', NULL, &line_terminator,
832 N_("terminate records with a NUL character"), '\0'),
833 OPT_END()
834 };
835
836 expire = TIME_MAX;
837 ac = parse_options(ac, av, prefix, options, git_worktree_list_usage, 0);
838 if (ac)
839 usage_with_options(git_worktree_list_usage, options);
840 else if (verbose && porcelain)
841 die(_("options '%s' and '%s' cannot be used together"), "--verbose", "--porcelain");
842 else if (!line_terminator && !porcelain)
843 die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
844 else {
845 struct worktree **worktrees = get_worktrees();
846 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
847
848 /* sort worktrees by path but keep main worktree at top */
849 pathsort(worktrees + 1);
850
851 if (!porcelain)
852 measure_widths(worktrees, &abbrev, &path_maxlen);
853
854 for (i = 0; worktrees[i]; i++) {
855 if (porcelain)
856 show_worktree_porcelain(worktrees[i],
857 line_terminator);
858 else
859 show_worktree(worktrees[i], path_maxlen, abbrev);
860 }
861 free_worktrees(worktrees);
862 }
863 return 0;
864 }
865
866 static int lock_worktree(int ac, const char **av, const char *prefix)
867 {
868 const char *reason = "", *old_reason;
869 struct option options[] = {
870 OPT_STRING(0, "reason", &reason, N_("string"),
871 N_("reason for locking")),
872 OPT_END()
873 };
874 struct worktree **worktrees, *wt;
875
876 ac = parse_options(ac, av, prefix, options, git_worktree_lock_usage, 0);
877 if (ac != 1)
878 usage_with_options(git_worktree_lock_usage, options);
879
880 worktrees = get_worktrees();
881 wt = find_worktree(worktrees, prefix, av[0]);
882 if (!wt)
883 die(_("'%s' is not a working tree"), av[0]);
884 if (is_main_worktree(wt))
885 die(_("The main working tree cannot be locked or unlocked"));
886
887 old_reason = worktree_lock_reason(wt);
888 if (old_reason) {
889 if (*old_reason)
890 die(_("'%s' is already locked, reason: %s"),
891 av[0], old_reason);
892 die(_("'%s' is already locked"), av[0]);
893 }
894
895 write_file(git_common_path("worktrees/%s/locked", wt->id),
896 "%s", reason);
897 free_worktrees(worktrees);
898 return 0;
899 }
900
901 static int unlock_worktree(int ac, const char **av, const char *prefix)
902 {
903 struct option options[] = {
904 OPT_END()
905 };
906 struct worktree **worktrees, *wt;
907 int ret;
908
909 ac = parse_options(ac, av, prefix, options, git_worktree_unlock_usage, 0);
910 if (ac != 1)
911 usage_with_options(git_worktree_unlock_usage, options);
912
913 worktrees = get_worktrees();
914 wt = find_worktree(worktrees, prefix, av[0]);
915 if (!wt)
916 die(_("'%s' is not a working tree"), av[0]);
917 if (is_main_worktree(wt))
918 die(_("The main working tree cannot be locked or unlocked"));
919 if (!worktree_lock_reason(wt))
920 die(_("'%s' is not locked"), av[0]);
921 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
922 free_worktrees(worktrees);
923 return ret;
924 }
925
926 static void validate_no_submodules(const struct worktree *wt)
927 {
928 struct index_state istate = INDEX_STATE_INIT(the_repository);
929 struct strbuf path = STRBUF_INIT;
930 int i, found_submodules = 0;
931
932 if (is_directory(worktree_git_path(wt, "modules"))) {
933 /*
934 * There could be false positives, e.g. the "modules"
935 * directory exists but is empty. But it's a rare case and
936 * this simpler check is probably good enough for now.
937 */
938 found_submodules = 1;
939 } else if (read_index_from(&istate, worktree_git_path(wt, "index"),
940 get_worktree_git_dir(wt)) > 0) {
941 for (i = 0; i < istate.cache_nr; i++) {
942 struct cache_entry *ce = istate.cache[i];
943 int err;
944
945 if (!S_ISGITLINK(ce->ce_mode))
946 continue;
947
948 strbuf_reset(&path);
949 strbuf_addf(&path, "%s/%s", wt->path, ce->name);
950 if (!is_submodule_populated_gently(path.buf, &err))
951 continue;
952
953 found_submodules = 1;
954 break;
955 }
956 }
957 discard_index(&istate);
958 strbuf_release(&path);
959
960 if (found_submodules)
961 die(_("working trees containing submodules cannot be moved or removed"));
962 }
963
964 static int move_worktree(int ac, const char **av, const char *prefix)
965 {
966 int force = 0;
967 struct option options[] = {
968 OPT__FORCE(&force,
969 N_("force move even if worktree is dirty or locked"),
970 PARSE_OPT_NOCOMPLETE),
971 OPT_END()
972 };
973 struct worktree **worktrees, *wt;
974 struct strbuf dst = STRBUF_INIT;
975 struct strbuf errmsg = STRBUF_INIT;
976 const char *reason = NULL;
977 char *path;
978
979 ac = parse_options(ac, av, prefix, options, git_worktree_move_usage,
980 0);
981 if (ac != 2)
982 usage_with_options(git_worktree_move_usage, options);
983
984 path = prefix_filename(prefix, av[1]);
985 strbuf_addstr(&dst, path);
986 free(path);
987
988 worktrees = get_worktrees();
989 wt = find_worktree(worktrees, prefix, av[0]);
990 if (!wt)
991 die(_("'%s' is not a working tree"), av[0]);
992 if (is_main_worktree(wt))
993 die(_("'%s' is a main working tree"), av[0]);
994 if (is_directory(dst.buf)) {
995 const char *sep = find_last_dir_sep(wt->path);
996
997 if (!sep)
998 die(_("could not figure out destination name from '%s'"),
999 wt->path);
1000 strbuf_trim_trailing_dir_sep(&dst);
1001 strbuf_addstr(&dst, sep);
1002 }
1003 check_candidate_path(dst.buf, force, worktrees, "move");
1004
1005 validate_no_submodules(wt);
1006
1007 if (force < 2)
1008 reason = worktree_lock_reason(wt);
1009 if (reason) {
1010 if (*reason)
1011 die(_("cannot move a locked working tree, lock reason: %s\nuse 'move -f -f' to override or unlock first"),
1012 reason);
1013 die(_("cannot move a locked working tree;\nuse 'move -f -f' to override or unlock first"));
1014 }
1015 if (validate_worktree(wt, &errmsg, 0))
1016 die(_("validation failed, cannot move working tree: %s"),
1017 errmsg.buf);
1018 strbuf_release(&errmsg);
1019
1020 if (rename(wt->path, dst.buf) == -1)
1021 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
1022
1023 update_worktree_location(wt, dst.buf);
1024
1025 strbuf_release(&dst);
1026 free_worktrees(worktrees);
1027 return 0;
1028 }
1029
1030 /*
1031 * Note, "git status --porcelain" is used to determine if it's safe to
1032 * delete a whole worktree. "git status" does not ignore user
1033 * configuration, so if a normal "git status" shows "clean" for the
1034 * user, then it's ok to remove it.
1035 *
1036 * This assumption may be a bad one. We may want to ignore
1037 * (potentially bad) user settings and only delete a worktree when
1038 * it's absolutely safe to do so from _our_ point of view because we
1039 * know better.
1040 */
1041 static void check_clean_worktree(struct worktree *wt,
1042 const char *original_path)
1043 {
1044 struct child_process cp;
1045 char buf[1];
1046 int ret;
1047
1048 /*
1049 * Until we sort this out, all submodules are "dirty" and
1050 * will abort this function.
1051 */
1052 validate_no_submodules(wt);
1053
1054 child_process_init(&cp);
1055 strvec_pushf(&cp.env, "%s=%s/.git",
1056 GIT_DIR_ENVIRONMENT, wt->path);
1057 strvec_pushf(&cp.env, "%s=%s",
1058 GIT_WORK_TREE_ENVIRONMENT, wt->path);
1059 strvec_pushl(&cp.args, "status",
1060 "--porcelain", "--ignore-submodules=none",
1061 NULL);
1062 cp.git_cmd = 1;
1063 cp.dir = wt->path;
1064 cp.out = -1;
1065 ret = start_command(&cp);
1066 if (ret)
1067 die_errno(_("failed to run 'git status' on '%s'"),
1068 original_path);
1069 ret = xread(cp.out, buf, sizeof(buf));
1070 if (ret)
1071 die(_("'%s' contains modified or untracked files, use --force to delete it"),
1072 original_path);
1073 close(cp.out);
1074 ret = finish_command(&cp);
1075 if (ret)
1076 die_errno(_("failed to run 'git status' on '%s', code %d"),
1077 original_path, ret);
1078 }
1079
1080 static int delete_git_work_tree(struct worktree *wt)
1081 {
1082 struct strbuf sb = STRBUF_INIT;
1083 int ret = 0;
1084
1085 strbuf_addstr(&sb, wt->path);
1086 if (remove_dir_recursively(&sb, 0)) {
1087 error_errno(_("failed to delete '%s'"), sb.buf);
1088 ret = -1;
1089 }
1090 strbuf_release(&sb);
1091 return ret;
1092 }
1093
1094 static int remove_worktree(int ac, const char **av, const char *prefix)
1095 {
1096 int force = 0;
1097 struct option options[] = {
1098 OPT__FORCE(&force,
1099 N_("force removal even if worktree is dirty or locked"),
1100 PARSE_OPT_NOCOMPLETE),
1101 OPT_END()
1102 };
1103 struct worktree **worktrees, *wt;
1104 struct strbuf errmsg = STRBUF_INIT;
1105 const char *reason = NULL;
1106 int ret = 0;
1107
1108 ac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);
1109 if (ac != 1)
1110 usage_with_options(git_worktree_remove_usage, options);
1111
1112 worktrees = get_worktrees();
1113 wt = find_worktree(worktrees, prefix, av[0]);
1114 if (!wt)
1115 die(_("'%s' is not a working tree"), av[0]);
1116 if (is_main_worktree(wt))
1117 die(_("'%s' is a main working tree"), av[0]);
1118 if (force < 2)
1119 reason = worktree_lock_reason(wt);
1120 if (reason) {
1121 if (*reason)
1122 die(_("cannot remove a locked working tree, lock reason: %s\nuse 'remove -f -f' to override or unlock first"),
1123 reason);
1124 die(_("cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first"));
1125 }
1126 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
1127 die(_("validation failed, cannot remove working tree: %s"),
1128 errmsg.buf);
1129 strbuf_release(&errmsg);
1130
1131 if (file_exists(wt->path)) {
1132 if (!force)
1133 check_clean_worktree(wt, av[0]);
1134
1135 ret |= delete_git_work_tree(wt);
1136 }
1137 /*
1138 * continue on even if ret is non-zero, there's no going back
1139 * from here.
1140 */
1141 ret |= delete_git_dir(wt->id);
1142 delete_worktrees_dir_if_empty();
1143
1144 free_worktrees(worktrees);
1145 return ret;
1146 }
1147
1148 static void report_repair(int iserr, const char *path, const char *msg, void *cb_data)
1149 {
1150 if (!iserr) {
1151 fprintf_ln(stderr, _("repair: %s: %s"), msg, path);
1152 } else {
1153 int *exit_status = (int *)cb_data;
1154 fprintf_ln(stderr, _("error: %s: %s"), msg, path);
1155 *exit_status = 1;
1156 }
1157 }
1158
1159 static int repair(int ac, const char **av, const char *prefix)
1160 {
1161 const char **p;
1162 const char *self[] = { ".", NULL };
1163 struct option options[] = {
1164 OPT_END()
1165 };
1166 int rc = 0;
1167
1168 ac = parse_options(ac, av, prefix, options, git_worktree_repair_usage, 0);
1169 p = ac > 0 ? av : self;
1170 for (; *p; p++)
1171 repair_worktree_at_path(*p, report_repair, &rc);
1172 repair_worktrees(report_repair, &rc);
1173 return rc;
1174 }
1175
1176 int cmd_worktree(int ac, const char **av, const char *prefix)
1177 {
1178 parse_opt_subcommand_fn *fn = NULL;
1179 struct option options[] = {
1180 OPT_SUBCOMMAND("add", &fn, add),
1181 OPT_SUBCOMMAND("prune", &fn, prune),
1182 OPT_SUBCOMMAND("list", &fn, list),
1183 OPT_SUBCOMMAND("lock", &fn, lock_worktree),
1184 OPT_SUBCOMMAND("unlock", &fn, unlock_worktree),
1185 OPT_SUBCOMMAND("move", &fn, move_worktree),
1186 OPT_SUBCOMMAND("remove", &fn, remove_worktree),
1187 OPT_SUBCOMMAND("repair", &fn, repair),
1188 OPT_END()
1189 };
1190
1191 git_config(git_worktree_config, NULL);
1192
1193 if (!prefix)
1194 prefix = "";
1195
1196 ac = parse_options(ac, av, prefix, options, git_worktree_usage, 0);
1197 return fn(ac, av, prefix);
1198 }