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;
38 static int guess_remote;
39 static timestamp_t expire;
41 static int git_worktree_config(const char *var, const char *value, void *cb)
43 if (!strcmp(var, "worktree.guessremote")) {
44 guess_remote = git_config_bool(var, value);
48 return git_default_config(var, value, cb);
51 static int prune_worktree(const char *id, struct strbuf *reason)
59 if (!is_directory(git_path("worktrees/%s", id))) {
60 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
63 if (file_exists(git_path("worktrees/%s/locked", id)))
65 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
66 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
69 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
71 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
75 len = xsize_t(st.st_size);
78 read_result = read_in_full(fd, path, len);
79 if (read_result < 0) {
80 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
88 if (read_result != len) {
90 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
91 id, (uintmax_t)len, (uintmax_t)read_result);
95 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
98 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
103 if (!file_exists(path)) {
105 if (stat(git_path("worktrees/%s/index", id), &st) ||
106 st.st_mtime <= expire) {
107 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
117 static void prune_worktrees(void)
119 struct strbuf reason = STRBUF_INIT;
120 struct strbuf path = STRBUF_INIT;
121 DIR *dir = opendir(git_path("worktrees"));
126 while ((d = readdir(dir)) != NULL) {
127 if (is_dot_or_dotdot(d->d_name))
129 strbuf_reset(&reason);
130 if (!prune_worktree(d->d_name, &reason))
132 if (show_only || verbose)
133 printf("%s\n", reason.buf);
136 git_path_buf(&path, "worktrees/%s", d->d_name);
137 ret = remove_dir_recursively(&path, 0);
138 if (ret < 0 && errno == ENOTDIR)
139 ret = unlink(path.buf);
141 error_errno(_("failed to remove '%s'"), path.buf);
145 rmdir(git_path("worktrees"));
146 strbuf_release(&reason);
147 strbuf_release(&path);
150 static int prune(int ac, const char **av, const char *prefix)
152 struct option options[] = {
153 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
154 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
155 OPT_EXPIRY_DATE(0, "expire", &expire,
156 N_("expire working trees older than <time>")),
161 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
163 usage_with_options(worktree_usage, options);
168 static char *junk_work_tree;
169 static char *junk_git_dir;
171 static pid_t junk_pid;
173 static void remove_junk(void)
175 struct strbuf sb = STRBUF_INIT;
176 if (!is_junk || getpid() != junk_pid)
179 strbuf_addstr(&sb, junk_git_dir);
180 remove_dir_recursively(&sb, 0);
183 if (junk_work_tree) {
184 strbuf_addstr(&sb, junk_work_tree);
185 remove_dir_recursively(&sb, 0);
190 static void remove_junk_on_signal(int signo)
197 static const char *worktree_basename(const char *path, int *olen)
203 while (len && is_dir_sep(path[len - 1]))
206 for (name = path + len - 1; name > path; name--)
207 if (is_dir_sep(*name)) {
216 static int add_worktree(const char *path, const char *refname,
217 const struct add_opts *opts)
219 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
220 struct strbuf sb = STRBUF_INIT;
223 struct child_process cp = CHILD_PROCESS_INIT;
224 struct argv_array child_env = ARGV_ARRAY_INIT;
225 int counter = 0, len, ret;
226 struct strbuf symref = STRBUF_INIT;
227 struct commit *commit = NULL;
230 if (file_exists(path) && !is_empty_dir(path))
231 die(_("'%s' already exists"), path);
233 /* is 'refname' a branch or commit? */
234 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
235 ref_exists(symref.buf)) {
238 die_if_checked_out(symref.buf, 0);
240 commit = lookup_commit_reference_by_name(refname);
242 die(_("invalid reference: %s"), refname);
244 name = worktree_basename(path, &len);
245 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
247 if (safe_create_leading_directories_const(sb_repo.buf))
248 die_errno(_("could not create leading directories of '%s'"),
250 while (!stat(sb_repo.buf, &st)) {
252 strbuf_setlen(&sb_repo, len);
253 strbuf_addf(&sb_repo, "%d", counter);
255 name = strrchr(sb_repo.buf, '/') + 1;
259 sigchain_push_common(remove_junk_on_signal);
261 if (mkdir(sb_repo.buf, 0777))
262 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
263 junk_git_dir = xstrdup(sb_repo.buf);
267 * lock the incomplete repo so prune won't delete it, unlock
268 * after the preparation is over.
270 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
271 if (!opts->keep_locked)
272 write_file(sb.buf, "initializing");
274 write_file(sb.buf, "added with --lock");
276 strbuf_addf(&sb_git, "%s/.git", path);
277 if (safe_create_leading_directories_const(sb_git.buf))
278 die_errno(_("could not create leading directories of '%s'"),
280 junk_work_tree = xstrdup(path);
283 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
284 write_file(sb.buf, "%s", real_path(sb_git.buf));
285 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
286 real_path(get_git_common_dir()), name);
288 * This is to keep resolve_ref() happy. We need a valid HEAD
289 * or is_git_directory() will reject the directory. Any value which
290 * looks like an object ID will do since it will be immediately
291 * replaced by the symbolic-ref or update-ref invocation in the new
295 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
296 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
298 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
299 write_file(sb.buf, "../..");
301 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
303 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
304 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
308 argv_array_pushl(&cp.args, "update-ref", "HEAD",
309 oid_to_hex(&commit->object.oid), NULL);
311 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
313 cp.env = child_env.argv;
314 ret = run_command(&cp);
318 if (opts->checkout) {
320 argv_array_clear(&cp.args);
321 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
322 cp.env = child_env.argv;
323 ret = run_command(&cp);
329 FREE_AND_NULL(junk_work_tree);
330 FREE_AND_NULL(junk_git_dir);
333 if (ret || !opts->keep_locked) {
335 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
336 unlink_or_warn(sb.buf);
340 * Hook failure does not warrant worktree deletion, so run hook after
341 * is_junk is cleared, but do return appropriate code when hook fails.
343 if (!ret && opts->checkout) {
344 const char *hook = find_hook("post-checkout");
346 const char *env[] = { "GIT_DIR", "GIT_WORK_TREE", NULL };
349 cp.stdout_to_stderr = 1;
353 argv_array_pushl(&cp.args, absolute_path(hook),
354 oid_to_hex(&null_oid),
355 oid_to_hex(&commit->object.oid),
357 ret = run_command(&cp);
361 argv_array_clear(&child_env);
363 strbuf_release(&symref);
364 strbuf_release(&sb_repo);
365 strbuf_release(&sb_git);
369 static int add(int ac, const char **av, const char *prefix)
371 struct add_opts opts;
372 const char *new_branch_force = NULL;
375 const char *opt_track = NULL;
376 struct option options[] = {
377 OPT__FORCE(&opts.force,
378 N_("checkout <branch> even if already checked out in other worktree"),
379 PARSE_OPT_NOCOMPLETE),
380 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
381 N_("create a new branch")),
382 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
383 N_("create or reset a branch")),
384 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
385 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
386 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
387 OPT_PASSTHRU(0, "track", &opt_track, NULL,
388 N_("set up tracking mode (see git-branch(1))"),
389 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
390 OPT_BOOL(0, "guess-remote", &guess_remote,
391 N_("try to match the new branch name with a remote-tracking branch")),
395 memset(&opts, 0, sizeof(opts));
397 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
398 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
399 die(_("-b, -B, and --detach are mutually exclusive"));
400 if (ac < 1 || ac > 2)
401 usage_with_options(worktree_usage, options);
403 path = prefix_filename(prefix, av[0]);
404 branch = ac < 2 ? "HEAD" : av[1];
406 if (!strcmp(branch, "-"))
409 opts.force_new_branch = !!new_branch_force;
410 if (opts.force_new_branch) {
411 struct strbuf symref = STRBUF_INIT;
413 opts.new_branch = new_branch_force;
416 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
417 ref_exists(symref.buf))
418 die_if_checked_out(symref.buf, 0);
419 strbuf_release(&symref);
422 if (ac < 2 && !opts.new_branch && !opts.detach) {
424 const char *s = worktree_basename(path, &n);
425 opts.new_branch = xstrndup(s, n);
427 struct object_id oid;
429 unique_tracking_name(opts.new_branch, &oid);
435 if (ac == 2 && !opts.new_branch && !opts.detach) {
436 struct object_id oid;
437 struct commit *commit;
440 commit = lookup_commit_reference_by_name(branch);
442 remote = unique_tracking_name(branch, &oid);
444 opts.new_branch = branch;
450 if (opts.new_branch) {
451 struct child_process cp = CHILD_PROCESS_INIT;
453 argv_array_push(&cp.args, "branch");
454 if (opts.force_new_branch)
455 argv_array_push(&cp.args, "--force");
456 argv_array_push(&cp.args, opts.new_branch);
457 argv_array_push(&cp.args, branch);
459 argv_array_push(&cp.args, opt_track);
460 if (run_command(&cp))
462 branch = opts.new_branch;
463 } else if (opt_track) {
464 die(_("--[no-]track can only be used if a new branch is created"));
469 return add_worktree(path, branch, &opts);
472 static void show_worktree_porcelain(struct worktree *wt)
474 printf("worktree %s\n", wt->path);
478 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
480 printf("detached\n");
481 else if (wt->head_ref)
482 printf("branch %s\n", wt->head_ref);
487 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
489 struct strbuf sb = STRBUF_INIT;
490 int cur_path_len = strlen(wt->path);
491 int path_adj = cur_path_len - utf8_strwidth(wt->path);
493 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
495 strbuf_addstr(&sb, "(bare)");
497 strbuf_addf(&sb, "%-*s ", abbrev_len,
498 find_unique_abbrev(&wt->head_oid, DEFAULT_ABBREV));
500 strbuf_addstr(&sb, "(detached HEAD)");
501 else if (wt->head_ref) {
502 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
503 strbuf_addf(&sb, "[%s]", ref);
506 strbuf_addstr(&sb, "(error)");
508 printf("%s\n", sb.buf);
513 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
517 for (i = 0; wt[i]; i++) {
519 int path_len = strlen(wt[i]->path);
521 if (path_len > *maxlen)
523 sha1_len = strlen(find_unique_abbrev(&wt[i]->head_oid, *abbrev));
524 if (sha1_len > *abbrev)
529 static int list(int ac, const char **av, const char *prefix)
533 struct option options[] = {
534 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
538 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
540 usage_with_options(worktree_usage, options);
542 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
543 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
546 measure_widths(worktrees, &abbrev, &path_maxlen);
548 for (i = 0; worktrees[i]; i++) {
550 show_worktree_porcelain(worktrees[i]);
552 show_worktree(worktrees[i], path_maxlen, abbrev);
554 free_worktrees(worktrees);
559 static int lock_worktree(int ac, const char **av, const char *prefix)
561 const char *reason = "", *old_reason;
562 struct option options[] = {
563 OPT_STRING(0, "reason", &reason, N_("string"),
564 N_("reason for locking")),
567 struct worktree **worktrees, *wt;
569 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
571 usage_with_options(worktree_usage, options);
573 worktrees = get_worktrees(0);
574 wt = find_worktree(worktrees, prefix, av[0]);
576 die(_("'%s' is not a working tree"), av[0]);
577 if (is_main_worktree(wt))
578 die(_("The main working tree cannot be locked or unlocked"));
580 old_reason = is_worktree_locked(wt);
583 die(_("'%s' is already locked, reason: %s"),
585 die(_("'%s' is already locked"), av[0]);
588 write_file(git_common_path("worktrees/%s/locked", wt->id),
590 free_worktrees(worktrees);
594 static int unlock_worktree(int ac, const char **av, const char *prefix)
596 struct option options[] = {
599 struct worktree **worktrees, *wt;
602 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
604 usage_with_options(worktree_usage, options);
606 worktrees = get_worktrees(0);
607 wt = find_worktree(worktrees, prefix, av[0]);
609 die(_("'%s' is not a working tree"), av[0]);
610 if (is_main_worktree(wt))
611 die(_("The main working tree cannot be locked or unlocked"));
612 if (!is_worktree_locked(wt))
613 die(_("'%s' is not locked"), av[0]);
614 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
615 free_worktrees(worktrees);
619 static void validate_no_submodules(const struct worktree *wt)
621 struct index_state istate = { NULL };
622 int i, found_submodules = 0;
624 if (read_index_from(&istate, worktree_git_path(wt, "index"),
625 get_worktree_git_dir(wt)) > 0) {
626 for (i = 0; i < istate.cache_nr; i++) {
627 struct cache_entry *ce = istate.cache[i];
629 if (S_ISGITLINK(ce->ce_mode)) {
630 found_submodules = 1;
635 discard_index(&istate);
637 if (found_submodules)
638 die(_("working trees containing submodules cannot be moved or removed"));
641 static int move_worktree(int ac, const char **av, const char *prefix)
643 struct option options[] = {
646 struct worktree **worktrees, *wt;
647 struct strbuf dst = STRBUF_INIT;
648 struct strbuf errmsg = STRBUF_INIT;
652 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
654 usage_with_options(worktree_usage, options);
656 path = prefix_filename(prefix, av[1]);
657 strbuf_addstr(&dst, path);
660 worktrees = get_worktrees(0);
661 wt = find_worktree(worktrees, prefix, av[0]);
663 die(_("'%s' is not a working tree"), av[0]);
664 if (is_main_worktree(wt))
665 die(_("'%s' is a main working tree"), av[0]);
666 if (is_directory(dst.buf)) {
667 const char *sep = find_last_dir_sep(wt->path);
670 die(_("could not figure out destination name from '%s'"),
672 strbuf_trim_trailing_dir_sep(&dst);
673 strbuf_addstr(&dst, sep);
675 if (file_exists(dst.buf))
676 die(_("target '%s' already exists"), dst.buf);
678 validate_no_submodules(wt);
680 reason = is_worktree_locked(wt);
683 die(_("cannot move a locked working tree, lock reason: %s"),
685 die(_("cannot move a locked working tree"));
687 if (validate_worktree(wt, &errmsg, 0))
688 die(_("validation failed, cannot move working tree: %s"),
690 strbuf_release(&errmsg);
692 if (rename(wt->path, dst.buf) == -1)
693 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
695 update_worktree_location(wt, dst.buf);
697 strbuf_release(&dst);
698 free_worktrees(worktrees);
703 * Note, "git status --porcelain" is used to determine if it's safe to
704 * delete a whole worktree. "git status" does not ignore user
705 * configuration, so if a normal "git status" shows "clean" for the
706 * user, then it's ok to remove it.
708 * This assumption may be a bad one. We may want to ignore
709 * (potentially bad) user settings and only delete a worktree when
710 * it's absolutely safe to do so from _our_ point of view because we
713 static void check_clean_worktree(struct worktree *wt,
714 const char *original_path)
716 struct argv_array child_env = ARGV_ARRAY_INIT;
717 struct child_process cp;
722 * Until we sort this out, all submodules are "dirty" and
723 * will abort this function.
725 validate_no_submodules(wt);
727 argv_array_pushf(&child_env, "%s=%s/.git",
728 GIT_DIR_ENVIRONMENT, wt->path);
729 argv_array_pushf(&child_env, "%s=%s",
730 GIT_WORK_TREE_ENVIRONMENT, wt->path);
731 memset(&cp, 0, sizeof(cp));
732 argv_array_pushl(&cp.args, "status",
733 "--porcelain", "--ignore-submodules=none",
735 cp.env = child_env.argv;
739 ret = start_command(&cp);
741 die_errno(_("failed to run 'git status' on '%s'"),
743 ret = xread(cp.out, buf, sizeof(buf));
745 die(_("'%s' is dirty, use --force to delete it"),
748 ret = finish_command(&cp);
750 die_errno(_("failed to run 'git status' on '%s', code %d"),
754 static int delete_git_work_tree(struct worktree *wt)
756 struct strbuf sb = STRBUF_INIT;
759 strbuf_addstr(&sb, wt->path);
760 if (remove_dir_recursively(&sb, 0)) {
761 error_errno(_("failed to delete '%s'"), sb.buf);
768 static int delete_git_dir(struct worktree *wt)
770 struct strbuf sb = STRBUF_INIT;
773 strbuf_addstr(&sb, git_common_path("worktrees/%s", wt->id));
774 if (remove_dir_recursively(&sb, 0)) {
775 error_errno(_("failed to delete '%s'"), sb.buf);
782 static int remove_worktree(int ac, const char **av, const char *prefix)
785 struct option options[] = {
786 OPT_BOOL(0, "force", &force,
787 N_("force removing even if the worktree is dirty")),
790 struct worktree **worktrees, *wt;
791 struct strbuf errmsg = STRBUF_INIT;
795 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
797 usage_with_options(worktree_usage, options);
799 worktrees = get_worktrees(0);
800 wt = find_worktree(worktrees, prefix, av[0]);
802 die(_("'%s' is not a working tree"), av[0]);
803 if (is_main_worktree(wt))
804 die(_("'%s' is a main working tree"), av[0]);
805 reason = is_worktree_locked(wt);
808 die(_("cannot remove a locked working tree, lock reason: %s"),
810 die(_("cannot remove a locked working tree"));
812 if (validate_worktree(wt, &errmsg, WT_VALIDATE_WORKTREE_MISSING_OK))
813 die(_("validation failed, cannot remove working tree: %s"),
815 strbuf_release(&errmsg);
817 if (file_exists(wt->path)) {
819 check_clean_worktree(wt, av[0]);
821 ret |= delete_git_work_tree(wt);
824 * continue on even if ret is non-zero, there's no going back
827 ret |= delete_git_dir(wt);
829 free_worktrees(worktrees);
833 int cmd_worktree(int ac, const char **av, const char *prefix)
835 struct option options[] = {
839 git_config(git_worktree_config, NULL);
842 usage_with_options(worktree_usage, options);
845 if (!strcmp(av[1], "add"))
846 return add(ac - 1, av + 1, prefix);
847 if (!strcmp(av[1], "prune"))
848 return prune(ac - 1, av + 1, prefix);
849 if (!strcmp(av[1], "list"))
850 return list(ac - 1, av + 1, prefix);
851 if (!strcmp(av[1], "lock"))
852 return lock_worktree(ac - 1, av + 1, prefix);
853 if (!strcmp(av[1], "unlock"))
854 return unlock_worktree(ac - 1, av + 1, prefix);
855 if (!strcmp(av[1], "move"))
856 return move_worktree(ac - 1, av + 1, prefix);
857 if (!strcmp(av[1], "remove"))
858 return remove_worktree(ac - 1, av + 1, prefix);
859 usage_with_options(worktree_usage, options);