6 #include "parse-options.h"
7 #include "argv-array.h"
10 #include "run-command.h"
16 static const char * const worktree_usage[] = {
17 N_("git worktree add [<options>] <path> [<commit-ish>]"),
18 N_("git worktree list [<options>]"),
19 N_("git worktree lock [<options>] <path>"),
20 N_("git worktree move <worktree> <new-path>"),
21 N_("git worktree prune [<options>]"),
22 N_("git worktree remove [<options>] <worktree>"),
23 N_("git worktree unlock <path>"),
37 static int guess_remote;
38 static timestamp_t expire;
40 static int git_worktree_config(const char *var, const char *value, void *cb)
42 if (!strcmp(var, "worktree.guessremote")) {
43 guess_remote = git_config_bool(var, value);
47 return git_default_config(var, value, cb);
50 static int prune_worktree(const char *id, struct strbuf *reason)
58 if (!is_directory(git_path("worktrees/%s", id))) {
59 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
62 if (file_exists(git_path("worktrees/%s/locked", id)))
64 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
65 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
68 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
70 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
74 len = xsize_t(st.st_size);
77 read_result = read_in_full(fd, path, len);
78 if (read_result < 0) {
79 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
87 if (read_result != len) {
89 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
90 id, (uintmax_t)len, (uintmax_t)read_result);
94 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
97 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
102 if (!file_exists(path)) {
104 if (stat(git_path("worktrees/%s/index", id), &st) ||
105 st.st_mtime <= expire) {
106 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
116 static void prune_worktrees(void)
118 struct strbuf reason = STRBUF_INIT;
119 struct strbuf path = STRBUF_INIT;
120 DIR *dir = opendir(git_path("worktrees"));
125 while ((d = readdir(dir)) != NULL) {
126 if (is_dot_or_dotdot(d->d_name))
128 strbuf_reset(&reason);
129 if (!prune_worktree(d->d_name, &reason))
131 if (show_only || verbose)
132 printf("%s\n", reason.buf);
135 git_path_buf(&path, "worktrees/%s", d->d_name);
136 ret = remove_dir_recursively(&path, 0);
137 if (ret < 0 && errno == ENOTDIR)
138 ret = unlink(path.buf);
140 error_errno(_("failed to remove '%s'"), path.buf);
144 rmdir(git_path("worktrees"));
145 strbuf_release(&reason);
146 strbuf_release(&path);
149 static int prune(int ac, const char **av, const char *prefix)
151 struct option options[] = {
152 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
153 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
154 OPT_EXPIRY_DATE(0, "expire", &expire,
155 N_("expire working trees older than <time>")),
160 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
162 usage_with_options(worktree_usage, options);
167 static char *junk_work_tree;
168 static char *junk_git_dir;
170 static pid_t junk_pid;
172 static void remove_junk(void)
174 struct strbuf sb = STRBUF_INIT;
175 if (!is_junk || getpid() != junk_pid)
178 strbuf_addstr(&sb, junk_git_dir);
179 remove_dir_recursively(&sb, 0);
182 if (junk_work_tree) {
183 strbuf_addstr(&sb, junk_work_tree);
184 remove_dir_recursively(&sb, 0);
189 static void remove_junk_on_signal(int signo)
196 static const char *worktree_basename(const char *path, int *olen)
202 while (len && is_dir_sep(path[len - 1]))
205 for (name = path + len - 1; name > path; name--)
206 if (is_dir_sep(*name)) {
215 static int add_worktree(const char *path, const char *refname,
216 const struct add_opts *opts)
218 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
219 struct strbuf sb = STRBUF_INIT;
222 struct child_process cp = CHILD_PROCESS_INIT;
223 struct argv_array child_env = ARGV_ARRAY_INIT;
224 int counter = 0, len, ret;
225 struct strbuf symref = STRBUF_INIT;
226 struct commit *commit = NULL;
229 if (file_exists(path) && !is_empty_dir(path))
230 die(_("'%s' already exists"), path);
232 /* is 'refname' a branch or commit? */
233 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
234 ref_exists(symref.buf)) {
237 die_if_checked_out(symref.buf, 0);
239 commit = lookup_commit_reference_by_name(refname);
241 die(_("invalid reference: %s"), refname);
243 name = worktree_basename(path, &len);
244 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
246 if (safe_create_leading_directories_const(sb_repo.buf))
247 die_errno(_("could not create leading directories of '%s'"),
249 while (!stat(sb_repo.buf, &st)) {
251 strbuf_setlen(&sb_repo, len);
252 strbuf_addf(&sb_repo, "%d", counter);
254 name = strrchr(sb_repo.buf, '/') + 1;
258 sigchain_push_common(remove_junk_on_signal);
260 if (mkdir(sb_repo.buf, 0777))
261 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
262 junk_git_dir = xstrdup(sb_repo.buf);
266 * lock the incomplete repo so prune won't delete it, unlock
267 * after the preparation is over.
269 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
270 if (!opts->keep_locked)
271 write_file(sb.buf, "initializing");
273 write_file(sb.buf, "added with --lock");
275 strbuf_addf(&sb_git, "%s/.git", path);
276 if (safe_create_leading_directories_const(sb_git.buf))
277 die_errno(_("could not create leading directories of '%s'"),
279 junk_work_tree = xstrdup(path);
282 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
283 write_file(sb.buf, "%s", real_path(sb_git.buf));
284 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
285 real_path(get_git_common_dir()), name);
287 * This is to keep resolve_ref() happy. We need a valid HEAD
288 * or is_git_directory() will reject the directory. Any value which
289 * looks like an object ID will do since it will be immediately
290 * replaced by the symbolic-ref or update-ref invocation in the new
294 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
295 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
297 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
298 write_file(sb.buf, "../..");
300 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
301 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
305 argv_array_pushl(&cp.args, "update-ref", "HEAD",
306 oid_to_hex(&commit->object.oid), NULL);
308 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
311 argv_array_push(&cp.args, "--quiet");
314 cp.env = child_env.argv;
315 ret = run_command(&cp);
319 if (opts->checkout) {
321 argv_array_clear(&cp.args);
322 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
324 argv_array_push(&cp.args, "--quiet");
325 cp.env = child_env.argv;
326 ret = run_command(&cp);
332 FREE_AND_NULL(junk_work_tree);
333 FREE_AND_NULL(junk_git_dir);
336 if (ret || !opts->keep_locked) {
338 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
339 unlink_or_warn(sb.buf);
343 * Hook failure does not warrant worktree deletion, so run hook after
344 * is_junk is cleared, but do return appropriate code when hook fails.
346 if (!ret && opts->checkout) {
347 const char *hook = find_hook("post-checkout");
349 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
352 cp.stdout_to_stderr = 1;
356 argv_array_pushl(&cp.args, absolute_path(hook),
357 oid_to_hex(&null_oid),
358 oid_to_hex(&commit->object.oid),
360 ret = run_command(&cp);
364 argv_array_clear(&child_env);
366 strbuf_release(&symref);
367 strbuf_release(&sb_repo);
368 strbuf_release(&sb_git);
372 static void print_preparing_worktree_line(int detach,
374 const char *new_branch,
375 int force_new_branch)
377 if (force_new_branch) {
378 struct commit *commit = lookup_commit_reference_by_name(new_branch);
380 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
382 printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
384 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
385 } else if (new_branch) {
386 printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
388 struct strbuf s = STRBUF_INIT;
389 if (!detach && !strbuf_check_branch_ref(&s, branch) &&
391 printf_ln(_("Preparing worktree (checking out '%s')"),
394 struct commit *commit = lookup_commit_reference_by_name(branch);
396 die(_("invalid reference: %s"), branch);
397 printf_ln(_("Preparing worktree (detached HEAD %s)"),
398 find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
404 static const char *dwim_branch(const char *path, const char **new_branch)
407 const char *s = worktree_basename(path, &n);
408 const char *branchname = xstrndup(s, n);
409 struct strbuf ref = STRBUF_INIT;
412 if (!strbuf_check_branch_ref(&ref, branchname) &&
413 ref_exists(ref.buf)) {
414 strbuf_release(&ref);
418 *new_branch = branchname;
420 struct object_id oid;
422 unique_tracking_name(*new_branch, &oid, NULL);
428 static int add(int ac, const char **av, const char *prefix)
430 struct add_opts opts;
431 const char *new_branch_force = NULL;
434 const char *new_branch = NULL;
435 const char *opt_track = NULL;
436 struct option options[] = {
437 OPT__FORCE(&opts.force,
438 N_("checkout <branch> even if already checked out in other worktree"),
439 PARSE_OPT_NOCOMPLETE),
440 OPT_STRING('b', NULL, &new_branch, N_("branch"),
441 N_("create a new branch")),
442 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
443 N_("create or reset a branch")),
444 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
445 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
446 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
447 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
448 OPT_PASSTHRU(0, "track", &opt_track, NULL,
449 N_("set up tracking mode (see git-branch(1))"),
450 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
451 OPT_BOOL(0, "guess-remote", &guess_remote,
452 N_("try to match the new branch name with a remote-tracking branch")),
456 memset(&opts, 0, sizeof(opts));
458 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
459 if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
460 die(_("-b, -B, and --detach are mutually exclusive"));
461 if (ac < 1 || ac > 2)
462 usage_with_options(worktree_usage, options);
464 path = prefix_filename(prefix, av[0]);
465 branch = ac < 2 ? "HEAD" : av[1];
467 if (!strcmp(branch, "-"))
470 if (new_branch_force) {
471 struct strbuf symref = STRBUF_INIT;
473 new_branch = new_branch_force;
476 !strbuf_check_branch_ref(&symref, new_branch) &&
477 ref_exists(symref.buf))
478 die_if_checked_out(symref.buf, 0);
479 strbuf_release(&symref);
482 if (ac < 2 && !new_branch && !opts.detach) {
483 const char *s = dwim_branch(path, &new_branch);
488 if (ac == 2 && !new_branch && !opts.detach) {
489 struct object_id oid;
490 struct commit *commit;
493 commit = lookup_commit_reference_by_name(branch);
495 remote = unique_tracking_name(branch, &oid, NULL);
503 print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
506 struct child_process cp = CHILD_PROCESS_INIT;
508 argv_array_push(&cp.args, "branch");
509 if (new_branch_force)
510 argv_array_push(&cp.args, "--force");
512 argv_array_push(&cp.args, "--quiet");
513 argv_array_push(&cp.args, new_branch);
514 argv_array_push(&cp.args, branch);
516 argv_array_push(&cp.args, opt_track);
517 if (run_command(&cp))
520 } else if (opt_track) {
521 die(_("--[no-]track can only be used if a new branch is created"));
526 return add_worktree(path, branch, &opts);
529 static void show_worktree_porcelain(struct worktree *wt)
531 printf("worktree %s\n", wt->path);
535 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
537 printf("detached\n");
538 else if (wt->head_ref)
539 printf("branch %s\n", wt->head_ref);
544 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
546 struct strbuf sb = STRBUF_INIT;
547 int cur_path_len = strlen(wt->path);
548 int path_adj = cur_path_len - utf8_strwidth(wt->path);
550 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
552 strbuf_addstr(&sb, "(bare)");
554 strbuf_addf(&sb, "%-*s ", abbrev_len,
555 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
557 strbuf_addstr(&sb, "(detached HEAD)");
558 else if (wt->head_ref) {
559 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
560 strbuf_addf(&sb, "[%s]", ref);
563 strbuf_addstr(&sb, "(error)");
565 printf("%s\n", sb.buf);
570 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
574 for (i = 0; wt[i]; i++) {
576 int path_len = strlen(wt[i]->path);
578 if (path_len > *maxlen)
580 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
581 if (sha1_len > *abbrev)
586 static int list(int ac, const char **av, const char *prefix)
590 struct option options[] = {
591 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
595 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
597 usage_with_options(worktree_usage, options);
599 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
600 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
603 measure_widths(worktrees, &abbrev, &path_maxlen);
605 for (i = 0; worktrees[i]; i++) {
607 show_worktree_porcelain(worktrees[i]);
609 show_worktree(worktrees[i], path_maxlen, abbrev);
611 free_worktrees(worktrees);
616 static int lock_worktree(int ac, const char **av, const char *prefix)
618 const char *reason = "", *old_reason;
619 struct option options[] = {
620 OPT_STRING(0, "reason", &reason, N_("string"),
621 N_("reason for locking")),
624 struct worktree **worktrees, *wt;
626 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
628 usage_with_options(worktree_usage, options);
630 worktrees = get_worktrees(0);
631 wt = find_worktree(worktrees, prefix, av[0]);
633 die(_("'%s' is not a working tree"), av[0]);
634 if (is_main_worktree(wt))
635 die(_("The main working tree cannot be locked or unlocked"));
637 old_reason = is_worktree_locked(wt);
640 die(_("'%s' is already locked, reason: %s"),
642 die(_("'%s' is already locked"), av[0]);
645 write_file(git_common_path("worktrees/%s/locked", wt->id),
647 free_worktrees(worktrees);
651 static int unlock_worktree(int ac, const char **av, const char *prefix)
653 struct option options[] = {
656 struct worktree **worktrees, *wt;
659 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
661 usage_with_options(worktree_usage, options);
663 worktrees = get_worktrees(0);
664 wt = find_worktree(worktrees, prefix, av[0]);
666 die(_("'%s' is not a working tree"), av[0]);
667 if (is_main_worktree(wt))
668 die(_("The main working tree cannot be locked or unlocked"));
669 if (!is_worktree_locked(wt))
670 die(_("'%s' is not locked"), av[0]);
671 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
672 free_worktrees(worktrees);
676 static void validate_no_submodules(const struct worktree *wt)
678 struct index_state istate = { NULL };
679 int i, found_submodules = 0;
681 if (read_index_from(&istate, worktree_git_path(wt, "index"),
682 get_worktree_git_dir(wt)) > 0) {
683 for (i = 0; i < istate.cache_nr; i++) {
684 struct cache_entry *ce = istate.cache[i];
686 if (S_ISGITLINK(ce->ce_mode)) {
687 found_submodules = 1;
692 discard_index(&istate);
694 if (found_submodules)
695 die(_("working trees containing submodules cannot be moved or removed"));
698 static int move_worktree(int ac, const char **av, const char *prefix)
700 struct option options[] = {
703 struct worktree **worktrees, *wt;
704 struct strbuf dst = STRBUF_INIT;
705 struct strbuf errmsg = STRBUF_INIT;
709 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
711 usage_with_options(worktree_usage, options);
713 path = prefix_filename(prefix, av[1]);
714 strbuf_addstr(&dst, path);
717 worktrees = get_worktrees(0);
718 wt = find_worktree(worktrees, prefix, av[0]);
720 die(_("'%s' is not a working tree"), av[0]);
721 if (is_main_worktree(wt))
722 die(_("'%s' is a main working tree"), av[0]);
723 if (is_directory(dst.buf)) {
724 const char *sep = find_last_dir_sep(wt->path);
727 die(_("could not figure out destination name from '%s'"),
729 strbuf_trim_trailing_dir_sep(&dst);
730 strbuf_addstr(&dst, sep);
732 if (file_exists(dst.buf))
733 die(_("target '%s' already exists"), dst.buf);
735 validate_no_submodules(wt);
737 reason = is_worktree_locked(wt);
740 die(_("cannot move a locked working tree, lock reason: %s"),
742 die(_("cannot move a locked working tree"));
744 if (validate_worktree(wt, &errmsg, 0))
745 die(_("validation failed, cannot move working tree: %s"),
747 strbuf_release(&errmsg);
749 if (rename(wt->path, dst.buf) == -1)
750 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
752 update_worktree_location(wt, dst.buf);
754 strbuf_release(&dst);
755 free_worktrees(worktrees);
760 * Note, "git status --porcelain" is used to determine if it's safe to
761 * delete a whole worktree. "git status" does not ignore user
762 * configuration, so if a normal "git status" shows "clean" for the
763 * user, then it's ok to remove it.
765 * This assumption may be a bad one. We may want to ignore
766 * (potentially bad) user settings and only delete a worktree when
767 * it's absolutely safe to do so from _our_ point of view because we
770 static void check_clean_worktree(struct worktree *wt,
771 const char *original_path)
773 struct argv_array child_env = ARGV_ARRAY_INIT;
774 struct child_process cp;
779 * Until we sort this out, all submodules are "dirty" and
780 * will abort this function.
782 validate_no_submodules(wt);
784 argv_array_pushf(&child_env, "%s=%s/.git",
785 GIT_DIR_ENVIRONMENT, wt->path);
786 argv_array_pushf(&child_env, "%s=%s",
787 GIT_WORK_TREE_ENVIRONMENT, wt->path);
788 memset(&cp, 0, sizeof(cp));
789 argv_array_pushl(&cp.args, "status",
790 "--porcelain", "--ignore-submodules=none",
792 cp.env = child_env.argv;
796 ret = start_command(&cp);
798 die_errno(_("failed to run 'git status' on '%s'"),
800 ret = xread(cp.out, buf, sizeof(buf));
802 die(_("'%s' is dirty, use --force to delete it"),
805 ret = finish_command(&cp);
807 die_errno(_("failed to run 'git status' on '%s', code %d"),
811 static int delete_git_work_tree(struct worktree *wt)
813 struct strbuf sb = STRBUF_INIT;
816 strbuf_addstr(&sb, wt->path);
817 if (remove_dir_recursively(&sb, 0)) {
818 error_errno(_("failed to delete '%s'"), sb.buf);
825 static int delete_git_dir(struct worktree *wt)
827 struct strbuf sb = STRBUF_INIT;
830 strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
831 if (remove_dir_recursively(&sb, 0)) {
832 error_errno(_("failed to delete '%s'"), sb.buf);
839 static int remove_worktree(int ac, const char **av, const char *prefix)
842 struct option options[] = {
844 N_("force removing even if the worktree is dirty"),
845 PARSE_OPT_NOCOMPLETE),
848 struct worktree **worktrees, *wt;
849 struct strbuf errmsg = STRBUF_INIT;
853 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
855 usage_with_options(worktree_usage, options);
857 worktrees = get_worktrees(0);
858 wt = find_worktree(worktrees, prefix, av[0]);
860 die(_("'%s' is not a working tree"), av[0]);
861 if (is_main_worktree(wt))
862 die(_("'%s' is a main working tree"), av[0]);
863 reason = is_worktree_locked(wt);
866 die(_("cannot remove a locked working tree, lock reason: %s"),
868 die(_("cannot remove a locked working tree"));
870 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
871 die(_("validation failed, cannot remove working tree: %s"),
873 strbuf_release(&errmsg);
875 if (file_exists(wt->path)) {
877 check_clean_worktree(wt, av[0]);
879 ret |= delete_git_work_tree(wt);
882 * continue on even if ret is non-zero, there's no going back
885 ret |= delete_git_dir(wt);
887 free_worktrees(worktrees);
891 int cmd_worktree(int ac, const char **av, const char *prefix)
893 struct option options[] = {
897 git_config(git_worktree_config, NULL);
900 usage_with_options(worktree_usage, options);
903 if (!strcmp(av[1], "add"))
904 return add(ac - 1, av + 1, prefix);
905 if (!strcmp(av[1], "prune"))
906 return prune(ac - 1, av + 1, prefix);
907 if (!strcmp(av[1], "list"))
908 return list(ac - 1, av + 1, prefix);
909 if (!strcmp(av[1], "lock"))
910 return lock_worktree(ac - 1, av + 1, prefix);
911 if (!strcmp(av[1], "unlock"))
912 return unlock_worktree(ac - 1, av + 1, prefix);
913 if (!strcmp(av[1], "move"))
914 return move_worktree(ac - 1, av + 1, prefix);
915 if (!strcmp(av[1], "remove"))
916 return remove_worktree(ac - 1, av + 1, prefix);
917 usage_with_options(worktree_usage, options);