Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

fix(vcs): prevent removing worktrees containing the open project (#2150)

l0ng-aifd717d2305e8
diff --git a/crates/ide-host/src/ops/vcs.rs b/crates/ide-host/src/ops/vcs.rs
index ae499bfdf..04afa3fa5 100644
--- a/crates/ide-host/src/ops/vcs.rs
+++ b/crates/ide-host/src/ops/vcs.rs
@@ -24,3 +24,37 @@ pub async fn status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
mod commands;
pub use commands::*;
+
+fn check_worktree_removal(project_root: &std::path::Path, path: &std::path::Path) -> IdeResult<()> {
+ fn canonical_path(path: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
+ let mut existing = path.to_path_buf();
+ let mut tail = Vec::new();
+ let mut real = loop {
+ match dunce::canonicalize(&existing) {
+ Ok(real) => break real,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ let Some(part) = existing.components().next_back() else { return Err(e) };
+ tail.push(part.as_os_str().to_owned());
+ if !existing.pop() {
+ return Err(e);
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ };
+ // The project or worktree may already be gone; resolve its missing tail too.
+ for part in tail.into_iter().rev() {
+ if part == ".." {
+ real.pop();
+ } else if part != "." {
+ real.push(part);
+ }
+ }
+ Ok(real)
+ }
+
+ if canonical_path(project_root)?.starts_with(canonical_path(path)?) {
+ return Err(ide_core::IdeError::invalid("Cannot remove a worktree containing the open project."));
+ }
+ Ok(())
+}
diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs
index d4adf0741..df307d746 100644
--- a/crates/ide-host/src/ops/vcs/commands.rs
+++ b/crates/ide-host/src/ops/vcs/commands.rs
@@ -1041,6 +1041,12 @@ pub async fn vcs_remove_worktree(
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
+ let path = if path.is_absolute() {
+ path
+ } else {
+ project.with_repo_at(repo.as_deref(), |r| Ok(r.root().join(&path)))?
+ };
+ check_worktree_removal(&project.root, &path)?;
let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force));
project.refresh_repositories();
result
diff --git a/crates/ide-host/tests/vcs_worktrees.rs b/crates/ide-host/tests/vcs_worktrees.rs
index 57304d189..ad6554405 100644
--- a/crates/ide-host/tests/vcs_worktrees.rs
+++ b/crates/ide-host/tests/vcs_worktrees.rs
@@ -91,3 +91,109 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
let roots = f.project.repos().roots();
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
+
+impl Fixture {
+ async fn open(&self, root: &std::path::Path) {
+ self.host.trust.decide(root, true, false).unwrap();
+ let project = self.host.open_project("main", root).unwrap();
+ wait_for_repos(&project, 1).await;
+ }
+
+ fn linked(&self, path: &std::path::Path, branch: &str) {
+ git(&self.root, &["worktree", "add", "-b", branch, path.to_str().unwrap()]);
+ }
+
+ async fn assert_protected(&self, path: &std::path::Path) {
+ for force in [false, true] {
+ let error =
+ vcs::vcs_remove_worktree(&self.host, "main", None, path.to_path_buf(), force).await.unwrap_err();
+ assert_eq!(error.message, "Cannot remove a worktree containing the open project.");
+ assert!(path.join("file.txt").exists());
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cannot_remove_the_open_linked_worktree_or_its_ancestor() {
+ let f = Fixture::new().await;
+ let linked = f.root.with_file_name("front");
+ f.linked(&linked, "front");
+ let nested = linked.join("src");
+ std::fs::create_dir(&nested).unwrap();
+ std::fs::write(linked.join("file.txt"), "uncommitted changes\n").unwrap();
+ for root in [&linked, &nested] {
+ f.open(root).await;
+ f.assert_protected(&linked).await;
+ assert_eq!(std::fs::read_to_string(linked.join("file.txt")).unwrap(), "uncommitted changes\n");
+ // Relative paths must be judged from the same repository as git uses.
+ let error = vcs::vcs_remove_worktree(&f.host, "main", None, ".".into(), true).await.unwrap_err();
+ assert_eq!(error.message, "Cannot remove a worktree containing the open project.");
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn sibling_with_a_shared_prefix_and_worktrees_below_the_project_stay_removable() {
+ for force in [false, true] {
+ let f = Fixture::new().await;
+ let linked = f.root.with_file_name("front");
+ let sibling = f.root.with_file_name("front-wt");
+ f.linked(&linked, "front");
+ f.linked(&sibling, "sibling");
+ f.open(&sibling).await;
+ vcs::vcs_remove_worktree(&f.host, "main", None, linked.clone(), force).await.unwrap();
+ assert!(!linked.exists());
+ assert!(sibling.exists());
+
+ let below = sibling.join("below");
+ f.linked(&below, "below");
+ vcs::vcs_remove_worktree(&f.host, "main", Some(sibling.clone()), below.clone(), force).await.unwrap();
+ assert!(!below.exists());
+
+ let parent = f.root.parent().unwrap();
+ f.open(parent).await;
+ vcs::vcs_remove_worktree(&f.host, "main", Some(f.root.clone()), sibling.clone(), force).await.unwrap();
+ assert!(!sibling.exists());
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn symlinked_project_root_is_protected() {
+ let f = Fixture::new().await;
+ let linked = f.root.with_file_name("front");
+ f.linked(&linked, "front");
+ let alias = f.root.with_file_name("alias");
+ std::os::unix::fs::symlink(&linked, &alias).unwrap();
+ f.open(&alias).await;
+ f.assert_protected(&linked).await;
+ f.assert_protected(&alias).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn missing_project_and_worktree_paths_still_use_canonical_ancestors() {
+ let f = Fixture::new().await;
+ let linked = f.root.with_file_name("front");
+ f.linked(&linked, "front");
+ let nested = linked.join("src");
+ std::fs::create_dir(&nested).unwrap();
+ f.open(&nested).await;
+ std::fs::remove_dir(&nested).unwrap();
+ f.assert_protected(&linked).await;
+ std::fs::remove_dir_all(&linked).unwrap();
+ for force in [false, true] {
+ let error =
+ vcs::vcs_remove_worktree(&f.host, "main", Some(f.root.clone()), linked.clone(), force).await.unwrap_err();
+ assert_eq!(error.message, "Cannot remove a worktree containing the open project.");
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn tmp_alias_is_protected() {
+ let f = Fixture::new().await;
+ let linked = f.root.with_file_name("front");
+ f.linked(&linked, "front");
+ f.open(&linked).await;
+ let alias = std::path::Path::new("/").join(linked.strip_prefix("/private").unwrap());
+ f.assert_protected(&alias).await;
+}
diff --git a/src/features/vcs/__tests__/worktreesPanel.test.tsx b/src/features/vcs/__tests__/worktreesPanel.test.tsx
index 28c3114da..ee5ff8225 100644
--- a/src/features/vcs/__tests__/worktreesPanel.test.tsx
+++ b/src/features/vcs/__tests__/worktreesPanel.test.tsx
@@ -1,5 +1,5 @@
import { beforeEach, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
const { list } = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
@@ -9,6 +9,7 @@ vi.mock("@/platform/ipc", async (original) => {
import { WorktreesPanel } from "../gitMenuDialogs";
import { useVcs } from "../store";
+import { useProject } from "@/platform/project";
const worktrees = [
{ path: "/work/app", branch: "main", head: "12345678", main: true, locked: false, prunable: false },
@@ -16,6 +17,7 @@ const worktrees = [
];
beforeEach(() => {
+ useProject.setState({ project: { root: "/work/app-feature" } as never });
list.mockReset().mockResolvedValue({ status: "ok", data: worktrees });
useVcs.setState({ root: "/work/app-feature", roots: ["/work/app-feature"], repo: null });
});
@@ -33,3 +35,32 @@ it("marks both opened roots current while grouping their repository once", async
expect(screen.getByText("current /work/app")).toBeInTheDocument();
expect(screen.getAllByRole("treeitem")).toHaveLength(3);
});
+
+it.each(["/work/app-feature", "/work/app-feature/src"])(
+ "disables removal of the worktree containing project %s",
+ async (root) => {
+ useProject.setState({ project: { root } as never });
+ render(<WorktreesPanel />);
+ fireEvent.mouseDown(await screen.findByText("feature"));
+ const remove = screen.getByRole("button", { name: "Remove Worktree" });
+ expect(remove).toBeDisabled();
+ expect(remove).toHaveAttribute("data-tooltip", "Cannot remove a worktree containing the open project.");
+ },
+);
+
+it.each(["/work", "/work/app-feature-sibling"])(
+ "allows removal when project %s is outside the worktree",
+ async (root) => {
+ useProject.setState({ project: { root } as never });
+ render(<WorktreesPanel />);
+ fireEvent.mouseDown(await screen.findByText("feature"));
+ expect(screen.getByRole("button", { name: "Remove Worktree" })).toBeEnabled();
+ },
+);
+
+it("keeps the main worktree protected", async () => {
+ useProject.setState({ project: { root: "/work" } as never });
+ render(<WorktreesPanel />);
+ fireEvent.mouseDown(await screen.findByText("main"));
+ expect(screen.getByRole("button", { name: "Remove Worktree" })).toBeDisabled();
+});
diff --git a/src/features/vcs/gitMenuDialogs.tsx b/src/features/vcs/gitMenuDialogs.tsx
index 2d24b5666..fcde9c019 100644
--- a/src/features/vcs/gitMenuDialogs.tsx
+++ b/src/features/vcs/gitMenuDialogs.tsx
@@ -24,9 +24,10 @@ import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
import { confirmDialog, openDialog } from "./dialogs";
import { errorMessage, runOp, runRemote, saveAll } from "./ops";
import { currentRepo, loadBranches, refreshNow, repoName, useVcs } from "./store";
-import { groupWorktrees, isCurrentWorktree, type RepoWorktrees } from "./worktrees";
+import { groupWorktrees, isCurrentWorktree, worktreeContainsProject, type RepoWorktrees } from "./worktrees";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
+import { useProject } from "@/platform/project";
// --- shared -----------------------------------------------------------------
@@ -596,6 +597,7 @@ interface WorktreeNode {
* tool window's Worktrees tab. `listClassName` replaces the dialog's default height.
*/
export function WorktreesPanel({ className, listClassName }: { className?: string; listClassName?: string }) {
+ const projectRoot = useProject((s) => s.project?.root);
const repo = useVcs((s) => s.repo);
const repos = useVcs((s) => s.roots);
const [groups, setGroups] = useState<RepoWorktrees[]>([]);
@@ -640,6 +642,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
? groups.find((g) => g.worktrees.some((w) => `w:${w.path}` === selected))
: undefined;
const current = currentGroup?.worktrees.find((w) => `w:${w.path}` === selected);
+ const containsProject = !!current && worktreeContainsProject(current.path, projectRoot);
const selectedKeys = useMemo(() => new Set(selected ? [selected] : []), [selected]);
const isCurrent = (path: string) => repos.some((root) => isCurrentWorktree(path, root));
const icon = (node: WorktreeNode) =>
@@ -656,7 +659,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
};
const remove = async () => {
- if (!current || !currentGroup || current.main) return;
+ if (!current || !currentGroup || current.main || containsProject) return;
const ok = await confirmDialog({
title: "Remove Worktree",
message: tx`Remove the worktree at ${current.path}? Its folder is deleted.`,
@@ -694,9 +697,10 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
/>
<IconButton
icon="minus"
- title="Remove Worktree"
+ title={containsProject ? "Cannot remove a worktree containing the open project." : "Remove Worktree"}
+ aria-label="Remove Worktree"
size="small"
- disabled={!current || current.main}
+ disabled={!current || current.main || containsProject}
onClick={() => void remove()}
/>
<IconButton
diff --git a/src/features/vcs/worktrees.test.ts b/src/features/vcs/worktrees.test.ts
index c1346d04c..8b4b26b79 100644
--- a/src/features/vcs/worktrees.test.ts
+++ b/src/features/vcs/worktrees.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { groupWorktrees, isCurrentWorktree, type RepoWorktrees } from "./worktrees";
+import { groupWorktrees, isCurrentWorktree, worktreeContainsProject, type RepoWorktrees } from "./worktrees";
const worktree = (path: string, main = false) => ({
path,
@@ -80,3 +80,19 @@ describe("groupWorktrees", () => {
expect(groupWorktrees([failed])).toEqual([failed]);
});
});
+
+describe("worktreeContainsProject", () => {
+ it.each([
+ ["/p/front", "/p/front", true],
+ ["/p/front/", "/p/front/src", true],
+ ["/p/front", "/p/front-wt", false],
+ ["/p/front/linked", "/p/front", false],
+ ["/", "/p/front", true],
+ ["C:\\Work\\App", "c:/work/app/src", true],
+ ["C:/Work/App/", "c:/work/app-wt", false],
+ ["/Work/App", "/work/app", false],
+ ["/p/front", null, false],
+ ])("compares %s with project %s", (path, root, expected) => {
+ expect(worktreeContainsProject(path, root)).toBe(expected);
+ });
+});
diff --git a/src/features/vcs/worktrees.ts b/src/features/vcs/worktrees.ts
index 4ebd8f3f7..4a60d6fb4 100644
--- a/src/features/vcs/worktrees.ts
+++ b/src/features/vcs/worktrees.ts
@@ -17,6 +17,14 @@ export function isCurrentWorktree(path: string, root: string | null | undefined)
return !!root && pathKey(path) === pathKey(root);
}
+/** Whether deleting this worktree would also delete the window's project folder. */
+export function worktreeContainsProject(path: string, projectRoot: string | null | undefined): boolean {
+ if (!projectRoot) return false;
+ const worktree = pathKey(path);
+ const project = pathKey(projectRoot);
+ return project === worktree || project.startsWith(worktree.endsWith("/") ? worktree : worktree + "/");
+}
+
/** The worktrees of one repository, loaded from one of its roots. */
export interface RepoWorktrees {
/** A VCS root of the repository the query ran from. */
diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json
index 7af553708..557dfc470 100644
--- a/src/platform/locales/text/en.json
+++ b/src/platform/locales/text/en.json
@@ -1,4 +1,5 @@
{
+ "Cannot remove a worktree containing the open project.": "Cannot remove a worktree containing the open project.",
"Delete Remote Branches": "Delete Remote Branches",
"Delete the {length} branches '{names}' on the remote? The remote-tracking branches are removed as well.": "Delete the {length} branches '{names}' on the remote? The remote-tracking branches are removed as well.",
"Add or Remove Caret": "Add or Remove Caret",
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 1d73af218..38a823ac7 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -1,4 +1,5 @@
{
+ "Cannot remove a worktree containing the open project.": "无法移除包含当前打开项目的工作树。",
"Select Python Environment Folder": "选择 Python 环境文件夹",
"Checking interpreter": "正在检查解释器",
"Cannot run this Python interpreter. Select a working Python executable or virtualenv folder.": "无法运行此 Python 解释器。请选择可用的 Python 可执行文件或虚拟环境文件夹。",