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>"),
32 const char *new_branch;
34 int checkout_existing_branch;
39 static int guess_remote;
40 static timestamp_t expire;
42 static int git_worktree_config(const char *var, const char *value, void *cb)
44 if (!strcmp(var, "worktree.guessremote")) {
45 guess_remote = git_config_bool(var, value);
49 return git_default_config(var, value, cb);
52 static int prune_worktree(const char *id, struct strbuf *reason)
60 if (!is_directory(git_path("worktrees/%s", id))) {
61 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
64 if (file_exists(git_path("worktrees/%s/locked", id)))
66 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
67 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
70 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
72 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
76 len = xsize_t(st.st_size);
79 read_result = read_in_full(fd, path, len);
80 if (read_result < 0) {
81 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
89 if (read_result != len) {
91 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
92 id, (uintmax_t)len, (uintmax_t)read_result);
96 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
99 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
104 if (!file_exists(path)) {
108 * the repo is moved manually and has not been
111 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
112 st_link.st_nlink > 1)
114 if (st.st_mtime <= expire) {
115 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
125 static void prune_worktrees(void)
127 struct strbuf reason = STRBUF_INIT;
128 struct strbuf path = STRBUF_INIT;
129 DIR *dir = opendir(git_path("worktrees"));
134 while ((d = readdir(dir)) != NULL) {
135 if (is_dot_or_dotdot(d->d_name))
137 strbuf_reset(&reason);
138 if (!prune_worktree(d->d_name, &reason))
140 if (show_only || verbose)
141 printf("%s\n", reason.buf);
144 git_path_buf(&path, "worktrees/%s", d->d_name);
145 ret = remove_dir_recursively(&path, 0);
146 if (ret < 0 && errno == ENOTDIR)
147 ret = unlink(path.buf);
149 error_errno(_("failed to remove '%s'"), path.buf);
153 rmdir(git_path("worktrees"));
154 strbuf_release(&reason);
155 strbuf_release(&path);
158 static int prune(int ac, const char **av, const char *prefix)
160 struct option options[] = {
161 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
162 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
163 OPT_EXPIRY_DATE(0, "expire", &expire,
164 N_("expire working trees older than <time>")),
169 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
171 usage_with_options(worktree_usage, options);
176 static char *junk_work_tree;
177 static char *junk_git_dir;
179 static pid_t junk_pid;
181 static void remove_junk(void)
183 struct strbuf sb = STRBUF_INIT;
184 if (!is_junk || getpid() != junk_pid)
187 strbuf_addstr(&sb, junk_git_dir);
188 remove_dir_recursively(&sb, 0);
191 if (junk_work_tree) {
192 strbuf_addstr(&sb, junk_work_tree);
193 remove_dir_recursively(&sb, 0);
198 static void remove_junk_on_signal(int signo)
205 static const char *worktree_basename(const char *path, int *olen)
211 while (len && is_dir_sep(path[len - 1]))
214 for (name = path + len - 1; name > path; name--)
215 if (is_dir_sep(*name)) {
224 static int add_worktree(const char *path, const char *refname,
225 const struct add_opts *opts)
227 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
228 struct strbuf sb = STRBUF_INIT;
231 struct child_process cp = CHILD_PROCESS_INIT;
232 struct argv_array child_env = ARGV_ARRAY_INIT;
233 int counter = 0, len, ret;
234 struct strbuf symref = STRBUF_INIT;
235 struct commit *commit = NULL;
238 if (file_exists(path) && !is_empty_dir(path))
239 die(_("'%s' already exists"), path);
241 /* is 'refname' a branch or commit? */
242 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
243 ref_exists(symref.buf)) {
246 die_if_checked_out(symref.buf, 0);
248 commit = lookup_commit_reference_by_name(refname);
250 die(_("invalid reference: %s"), refname);
252 name = worktree_basename(path, &len);
253 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
255 if (safe_create_leading_directories_const(sb_repo.buf))
256 die_errno(_("could not create leading directories of '%s'"),
258 while (!stat(sb_repo.buf, &st)) {
260 strbuf_setlen(&sb_repo, len);
261 strbuf_addf(&sb_repo, "%d", counter);
263 name = strrchr(sb_repo.buf, '/') + 1;
267 sigchain_push_common(remove_junk_on_signal);
269 if (mkdir(sb_repo.buf, 0777))
270 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
271 junk_git_dir = xstrdup(sb_repo.buf);
275 * lock the incomplete repo so prune won't delete it, unlock
276 * after the preparation is over.
278 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
279 if (!opts->keep_locked)
280 write_file(sb.buf, "initializing");
282 write_file(sb.buf, "added with --lock");
284 strbuf_addf(&sb_git, "%s/.git", path);
285 if (safe_create_leading_directories_const(sb_git.buf))
286 die_errno(_("could not create leading directories of '%s'"),
288 junk_work_tree = xstrdup(path);
291 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
292 write_file(sb.buf, "%s", real_path(sb_git.buf));
293 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
294 real_path(get_git_common_dir()), name);
296 * This is to keep resolve_ref() happy. We need a valid HEAD
297 * or is_git_directory() will reject the directory. Any value which
298 * looks like an object ID will do since it will be immediately
299 * replaced by the symbolic-ref or update-ref invocation in the new
303 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
304 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
306 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
307 write_file(sb.buf, "../..");
309 fprintf(stderr, _("Preparing %s (identifier %s)"), path, name);
311 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
312 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
316 argv_array_pushl(&cp.args, "update-ref", "HEAD",
317 oid_to_hex(&commit->object.oid), NULL);
319 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
321 cp.env = child_env.argv;
322 ret = run_command(&cp);
326 if (opts->checkout_existing_branch)
327 fprintf(stderr, _(", checking out existing branch '%s'"),
329 else if (opts->new_branch)
330 fprintf(stderr, _(", creating new branch '%s'"), opts->new_branch);
332 fprintf(stderr, _(", setting HEAD to %s"),
333 find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV));
336 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
338 fprintf(stderr, " %s", sb.buf);
341 if (opts->checkout) {
343 argv_array_clear(&cp.args);
344 argv_array_pushl(&cp.args, "reset", "--hard", "--quiet", NULL);
345 cp.env = child_env.argv;
346 ret = run_command(&cp);
352 FREE_AND_NULL(junk_work_tree);
353 FREE_AND_NULL(junk_git_dir);
356 if (ret || !opts->keep_locked) {
358 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
359 unlink_or_warn(sb.buf);
363 * Hook failure does not warrant worktree deletion, so run hook after
364 * is_junk is cleared, but do return appropriate code when hook fails.
366 if (!ret && opts->checkout) {
367 const char *hook = find_hook("post-checkout");
369 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
372 cp.stdout_to_stderr = 1;
376 argv_array_pushl(&cp.args, absolute_path(hook),
377 oid_to_hex(&null_oid),
378 oid_to_hex(&commit->object.oid),
380 ret = run_command(&cp);
384 argv_array_clear(&child_env);
386 strbuf_release(&symref);
387 strbuf_release(&sb_repo);
388 strbuf_release(&sb_git);
392 static int add(int ac, const char **av, const char *prefix)
394 struct add_opts opts;
395 const char *new_branch_force = NULL;
398 const char *opt_track = NULL;
399 struct option options[] = {
400 OPT__FORCE(&opts.force,
401 N_("checkout <branch> even if already checked out in other worktree"),
402 PARSE_OPT_NOCOMPLETE),
403 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
404 N_("create a new branch")),
405 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
406 N_("create or reset a branch")),
407 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
408 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
409 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
410 OPT_PASSTHRU(0, "track", &opt_track, NULL,
411 N_("set up tracking mode (see git-branch(1))"),
412 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
413 OPT_BOOL(0, "guess-remote", &guess_remote,
414 N_("try to match the new branch name with a remote-tracking branch")),
418 memset(&opts, 0, sizeof(opts));
420 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
421 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
422 die(_("-b, -B, and --detach are mutually exclusive"));
423 if (ac < 1 || ac > 2)
424 usage_with_options(worktree_usage, options);
426 path = prefix_filename(prefix, av[0]);
427 branch = ac < 2 ? "HEAD" : av[1];
429 if (!strcmp(branch, "-"))
432 opts.force_new_branch = !!new_branch_force;
433 if (opts.force_new_branch) {
434 struct strbuf symref = STRBUF_INIT;
436 opts.new_branch = new_branch_force;
439 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
440 ref_exists(symref.buf))
441 die_if_checked_out(symref.buf, 0);
442 strbuf_release(&symref);
445 if (ac < 2 && !opts.new_branch && !opts.detach) {
447 const char *s = worktree_basename(path, &n);
448 const char *branchname = xstrndup(s, n);
449 struct strbuf ref = STRBUF_INIT;
451 if (!strbuf_check_branch_ref(&ref, branchname) &&
452 ref_exists(ref.buf)) {
454 opts.checkout_existing_branch = 1;
457 opts.new_branch = branchname;
459 struct object_id oid;
461 unique_tracking_name(opts.new_branch, &oid);
466 strbuf_release(&ref);
469 if (ac == 2 && !opts.new_branch && !opts.detach) {
470 struct object_id oid;
471 struct commit *commit;
474 commit = lookup_commit_reference_by_name(branch);
476 remote = unique_tracking_name(branch, &oid);
478 opts.new_branch = branch;
484 if (opts.new_branch) {
485 struct child_process cp = CHILD_PROCESS_INIT;
487 argv_array_push(&cp.args, "branch");
488 if (opts.force_new_branch)
489 argv_array_push(&cp.args, "--force");
490 argv_array_push(&cp.args, opts.new_branch);
491 argv_array_push(&cp.args, branch);
493 argv_array_push(&cp.args, opt_track);
494 if (run_command(&cp))
496 branch = opts.new_branch;
497 } else if (opt_track) {
498 die(_("--[no-]track can only be used if a new branch is created"));
503 return add_worktree(path, branch, &opts);
506 static void show_worktree_porcelain(struct worktree *wt)
508 printf("worktree %s\n", wt->path);
512 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
514 printf("detached\n");
515 else if (wt->head_ref)
516 printf("branch %s\n", wt->head_ref);
521 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
523 struct strbuf sb = STRBUF_INIT;
524 int cur_path_len = strlen(wt->path);
525 int path_adj = cur_path_len - utf8_strwidth(wt->path);
527 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
529 strbuf_addstr(&sb, "(bare)");
531 strbuf_addf(&sb, "%-*s ", abbrev_len,
532 find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
534 strbuf_addstr(&sb, "(detached HEAD)");
535 else if (wt->head_ref) {
536 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
537 strbuf_addf(&sb, "[%s]", ref);
540 strbuf_addstr(&sb, "(error)");
542 printf("%s\n", sb.buf);
547 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
551 for (i = 0; wt[i]; i++) {
553 int path_len = strlen(wt[i]->path);
555 if (path_len > *maxlen)
557 sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
558 if (sha1_len > *abbrev)
563 static int list(int ac, const char **av, const char *prefix)
567 struct option options[] = {
568 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
572 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
574 usage_with_options(worktree_usage, options);
576 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
577 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
580 measure_widths(worktrees, &abbrev, &path_maxlen);
582 for (i = 0; worktrees[i]; i++) {
584 show_worktree_porcelain(worktrees[i]);
586 show_worktree(worktrees[i], path_maxlen, abbrev);
588 free_worktrees(worktrees);
593 static int lock_worktree(int ac, const char **av, const char *prefix)
595 const char *reason = "", *old_reason;
596 struct option options[] = {
597 OPT_STRING(0, "reason", &reason, N_("string"),
598 N_("reason for locking")),
601 struct worktree **worktrees, *wt;
603 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
605 usage_with_options(worktree_usage, options);
607 worktrees = get_worktrees(0);
608 wt = find_worktree(worktrees, prefix, av[0]);
610 die(_("'%s' is not a working tree"), av[0]);
611 if (is_main_worktree(wt))
612 die(_("The main working tree cannot be locked or unlocked"));
614 old_reason = is_worktree_locked(wt);
617 die(_("'%s' is already locked, reason: %s"),
619 die(_("'%s' is already locked"), av[0]);
622 write_file(git_common_path("worktrees/%s/locked", wt->id),
624 free_worktrees(worktrees);
628 static int unlock_worktree(int ac, const char **av, const char *prefix)
630 struct option options[] = {
633 struct worktree **worktrees, *wt;
636 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
638 usage_with_options(worktree_usage, options);
640 worktrees = get_worktrees(0);
641 wt = find_worktree(worktrees, prefix, av[0]);
643 die(_("'%s' is not a working tree"), av[0]);
644 if (is_main_worktree(wt))
645 die(_("The main working tree cannot be locked or unlocked"));
646 if (!is_worktree_locked(wt))
647 die(_("'%s' is not locked"), av[0]);
648 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
649 free_worktrees(worktrees);
653 static void validate_no_submodules(const struct worktree *wt)
655 struct index_state istate = { NULL };
656 int i, found_submodules = 0;
658 if (read_index_from(&istate, worktree_git_path(wt, "index"),
659 get_worktree_git_dir(wt)) > 0) {
660 for (i = 0; i < istate.cache_nr; i++) {
661 struct cache_entry *ce = istate.cache[i];
663 if (S_ISGITLINK(ce->ce_mode)) {
664 found_submodules = 1;
669 discard_index(&istate);
671 if (found_submodules)
672 die(_("working trees containing submodules cannot be moved or removed"));
675 static int move_worktree(int ac, const char **av, const char *prefix)
677 struct option options[] = {
680 struct worktree **worktrees, *wt;
681 struct strbuf dst = STRBUF_INIT;
682 struct strbuf errmsg = STRBUF_INIT;
686 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
688 usage_with_options(worktree_usage, options);
690 path = prefix_filename(prefix, av[1]);
691 strbuf_addstr(&dst, path);
694 worktrees = get_worktrees(0);
695 wt = find_worktree(worktrees, prefix, av[0]);
697 die(_("'%s' is not a working tree"), av[0]);
698 if (is_main_worktree(wt))
699 die(_("'%s' is a main working tree"), av[0]);
700 if (is_directory(dst.buf)) {
701 const char *sep = find_last_dir_sep(wt->path);
704 die(_("could not figure out destination name from '%s'"),
706 strbuf_trim_trailing_dir_sep(&dst);
707 strbuf_addstr(&dst, sep);
709 if (file_exists(dst.buf))
710 die(_("target '%s' already exists"), dst.buf);
712 validate_no_submodules(wt);
714 reason = is_worktree_locked(wt);
717 die(_("cannot move a locked working tree, lock reason: %s"),
719 die(_("cannot move a locked working tree"));
721 if (validate_worktree(wt, &errmsg, 0))
722 die(_("validation failed, cannot move working tree: %s"),
724 strbuf_release(&errmsg);
726 if (rename(wt->path, dst.buf) == -1)
727 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
729 update_worktree_location(wt, dst.buf);
731 strbuf_release(&dst);
732 free_worktrees(worktrees);
737 * Note, "git status --porcelain" is used to determine if it's safe to
738 * delete a whole worktree. "git status" does not ignore user
739 * configuration, so if a normal "git status" shows "clean" for the
740 * user, then it's ok to remove it.
742 * This assumption may be a bad one. We may want to ignore
743 * (potentially bad) user settings and only delete a worktree when
744 * it's absolutely safe to do so from _our_ point of view because we
747 static void check_clean_worktree(struct worktree *wt,
748 const char *original_path)
750 struct argv_array child_env = ARGV_ARRAY_INIT;
751 struct child_process cp;
756 * Until we sort this out, all submodules are "dirty" and
757 * will abort this function.
759 validate_no_submodules(wt);
761 argv_array_pushf(&child_env, "%s=%s/.git",
762 GIT_DIR_ENVIRONMENT, wt->path);
763 argv_array_pushf(&child_env, "%s=%s",
764 GIT_WORK_TREE_ENVIRONMENT, wt->path);
765 memset(&cp, 0, sizeof(cp));
766 argv_array_pushl(&cp.args, "status",
767 "--porcelain", "--ignore-submodules=none",
769 cp.env = child_env.argv;
773 ret = start_command(&cp);
775 die_errno(_("failed to run 'git status' on '%s'"),
777 ret = xread(cp.out, buf, sizeof(buf));
779 die(_("'%s' is dirty, use --force to delete it"),
782 ret = finish_command(&cp);
784 die_errno(_("failed to run 'git status' on '%s', code %d"),
788 static int delete_git_work_tree(struct worktree *wt)
790 struct strbuf sb = STRBUF_INIT;
793 strbuf_addstr(&sb, wt->path);
794 if (remove_dir_recursively(&sb, 0)) {
795 error_errno(_("failed to delete '%s'"), sb.buf);
802 static int delete_git_dir(struct worktree *wt)
804 struct strbuf sb = STRBUF_INIT;
807 strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
808 if (remove_dir_recursively(&sb, 0)) {
809 error_errno(_("failed to delete '%s'"), sb.buf);
816 static int remove_worktree(int ac, const char **av, const char *prefix)
819 struct option options[] = {
820 OPT_BOOL(0, "force", &force,
821 N_("force removing even if the worktree is dirty")),
824 struct worktree **worktrees, *wt;
825 struct strbuf errmsg = STRBUF_INIT;
829 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
831 usage_with_options(worktree_usage, options);
833 worktrees = get_worktrees(0);
834 wt = find_worktree(worktrees, prefix, av[0]);
836 die(_("'%s' is not a working tree"), av[0]);
837 if (is_main_worktree(wt))
838 die(_("'%s' is a main working tree"), av[0]);
839 reason = is_worktree_locked(wt);
842 die(_("cannot remove a locked working tree, lock reason: %s"),
844 die(_("cannot remove a locked working tree"));
846 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
847 die(_("validation failed, cannot remove working tree: %s"),
849 strbuf_release(&errmsg);
851 if (file_exists(wt->path)) {
853 check_clean_worktree(wt, av[0]);
855 ret |= delete_git_work_tree(wt);
858 * continue on even if ret is non-zero, there's no going back
861 ret |= delete_git_dir(wt);
863 free_worktrees(worktrees);
867 int cmd_worktree(int ac, const char **av, const char *prefix)
869 struct option options[] = {
873 git_config(git_worktree_config, NULL);
876 usage_with_options(worktree_usage, options);
879 if (!strcmp(av[1], "add"))
880 return add(ac - 1, av + 1, prefix);
881 if (!strcmp(av[1], "prune"))
882 return prune(ac - 1, av + 1, prefix);
883 if (!strcmp(av[1], "list"))
884 return list(ac - 1, av + 1, prefix);
885 if (!strcmp(av[1], "lock"))
886 return lock_worktree(ac - 1, av + 1, prefix);
887 if (!strcmp(av[1], "unlock"))
888 return unlock_worktree(ac - 1, av + 1, prefix);
889 if (!strcmp(av[1], "move"))
890 return move_worktree(ac - 1, av + 1, prefix);
891 if (!strcmp(av[1], "remove"))
892 return remove_worktree(ac - 1, av + 1, prefix);
893 usage_with_options(worktree_usage, options);