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