TypeScript
fix(server): the Files tree lists symlinked files and folders (#21920)
KishanRPatela3cf3f0fe7bf
diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.tsindex 730d02c577f..6bef5f04263 100644--- a/apps/server/src/workspace/WorkspaceEntries.test.ts+++ b/apps/server/src/workspace/WorkspaceEntries.test.ts@@ -1,4 +1,5 @@// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFSP from "node:fs/promises";import * as NodeServices from "@effect/platform-node/NodeServices";import { it, afterEach, describe, expect } from "@effect/vitest";import * as Effect from "effect/Effect";@@ -132,6 +133,113 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {}),);+ it.effect("lists symlinks as what they point to, hiding ones that cannot be opened", () =>+ Effect.gen(function* () {+ const platform = yield* HostProcess.Platform;+ if (platform === "win32") return;+ const cwd = yield* makeTempDir({ git: true });+ const outside = yield* makeTempDir();+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* writeTextFile(cwd, "real.txt");+ yield* writeTextFile(cwd, "realdir/nested.txt");+ yield* writeTextFile(outside, "outside.txt");+ yield* fileSystem.symlink("real.txt", path.join(cwd, "link.txt"));+ yield* fileSystem.symlink("realdir", path.join(cwd, "linkdir"));+ yield* fileSystem.symlink(outside, path.join(cwd, "outside-link"));+ yield* fileSystem.symlink(".git", path.join(cwd, "git-link"));+ yield* fileSystem.symlink("missing", path.join(cwd, "dangling"));++ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;+ const root = yield* workspaceEntries.list({ cwd, directoryPath: "" });+ expect(root.entries.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([+ { path: "link.txt", kind: "file" },+ { path: "linkdir", kind: "directory" },+ { path: "real.txt", kind: "file" },+ { path: "realdir", kind: "directory" },+ ]);+ expect(yield* workspaceEntries.list({ cwd, directoryPath: "linkdir" })).toEqual({+ entries: [{ path: "linkdir/nested.txt", kind: "file" }],+ truncated: false,+ });+ }),+ );++ it.effect("hides folder links that lead back to a folder on the listed path", () =>+ // "Expand all folders" loads every folder it expands, so a link that loops would+ // keep nesting the same entries without end.+ Effect.gen(function* () {+ const platform = yield* HostProcess.Platform;+ if (platform === "win32") return;+ const cwd = yield* makeTempDir();+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* writeTextFile(cwd, "a/file.txt");+ yield* writeTextFile(cwd, "b/file.txt");+ yield* fileSystem.symlink(".", path.join(cwd, "self"));+ yield* fileSystem.symlink("..", path.join(cwd, "a/up"));+ yield* fileSystem.symlink("../b", path.join(cwd, "a/to-b"));+ yield* fileSystem.symlink("../a", path.join(cwd, "b/to-a"));++ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;+ const paths = (directoryPath: string) =>+ workspaceEntries+ .list({ cwd, directoryPath })+ .pipe(Effect.map(({ entries }) => entries.map((entry) => entry.path).toSorted()));+ expect(yield* paths("")).toEqual(["a", "b"]);+ // A link into a sibling folder is fine on its own...+ expect(yield* paths("a")).toEqual(["a/file.txt", "a/to-b"]);+ // ...but once followed, the sibling's link back is hidden.+ expect(yield* paths("a/to-b")).toEqual(["a/to-b/file.txt"]);+ }),+ );++ it.effect("resolves a folder of many symlinks in bounded batches", () =>+ Effect.gen(function* () {+ const platform = yield* HostProcess.Platform;+ if (platform === "win32") return;+ const cwd = yield* makeTempDir();+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ // Shaped like a pnpm `node_modules`: one link per package into `.pnpm`.+ const directoryPath = [...Array.from({ length: 80 }, () => "nested"), "node_modules"].join(+ "/",+ );+ const packages = Array.from({ length: 200 }, (_, index) => `pkg-${index}`);+ yield* Effect.forEach(+ packages,+ (name) =>+ Effect.gen(function* () {+ yield* writeTextFile(cwd, `${directoryPath}/.pnpm/${name}/index.js`);+ yield* fileSystem.symlink(`.pnpm/${name}`, path.join(cwd, directoryPath, name));+ }),+ { concurrency: 32, discard: true },+ );+ const realpath = NodeFSP.realpath;+ let inFlight = 0;+ let maxInFlight = 0;+ vi.spyOn(NodeFSP, "realpath").mockImplementation((async (target: string) => {+ maxInFlight = Math.max(maxInFlight, ++inFlight);+ try {+ return await realpath(target);+ } finally {+ inFlight--;+ }+ }) as typeof NodeFSP.realpath);++ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;+ const { entries } = yield* workspaceEntries.list({ cwd, directoryPath });+ expect(entries.map((entry) => entry.path).toSorted()).toEqual(+ [+ `${directoryPath}/.pnpm`,+ ...packages.map((name) => `${directoryPath}/${name}`),+ ].toSorted(),+ );+ expect(entries.every((entry) => entry.kind === "directory")).toBe(true);+ expect(maxInFlight).toBeLessThanOrEqual(64);+ }),+ );+it.effect("labels the children of wide folders exactly as git does for each child", () =>Effect.gen(function* () {// Above 1,000 children, listing first asks whether the whole folder is ignored.diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.tsindex 5f1c5f2660a..0b853ccdaa4 100644--- a/apps/server/src/workspace/WorkspaceEntries.ts+++ b/apps/server/src/workspace/WorkspaceEntries.ts@@ -117,6 +117,9 @@ const IGNORED_FILES_LIMIT = 200;/** Paths sent to one `git check-ignore` call when labelling a folder's children. */const IGNORE_CHECK_CHUNK_SIZE = 1000;+/** Children classified at once when listing a folder; each symlink costs a realpath and a stat. */+const SYMLINK_RESOLVE_BATCH_SIZE = 64;+const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (input: FilesystemBrowseInput,path: Path.Path,@@ -318,13 +321,71 @@ export const make = Effect.gen(function* () {throw new Error("Directory must be inside the workspace and outside .git.");}const children = await NodeFSP.readdir(directory, { withFileTypes: true });+ const isSameOrInside = (parent: string, child: string) => {+ const relativeChild = path.relative(parent, child);+ return (+ relativeChild !== ".." &&+ !relativeChild.startsWith(`..${path.sep}`) &&+ !path.isAbsolute(relativeChild)+ );+ };+ // Reject canonical ancestors so "Expand all folders" cannot follow a cycle.+ let visitedFolders: Promise<ReadonlyArray<string>> | undefined;+ const loadVisitedFolders = () =>+ (visitedFolders ??= (async () => {+ const folders = [root];+ let current = normalizedCwd;+ for (const segment of target.relativePath.split("/").filter(Boolean)) {+ current = path.join(current, segment);+ folders.push(await NodeFSP.realpath(current));+ }+ return folders;+ })());+ const resolveSymlinkKind = async (+ name: string,+ ): Promise<ProjectEntry["kind"] | undefined> => {+ const resolved = await NodeFSP.realpath(path.join(directory, name)).catch(+ () => undefined,+ );+ if (+ resolved === undefined ||+ !isSameOrInside(root, resolved) ||+ path.relative(root, resolved).split(path.sep).includes(".git")+ ) {+ return undefined;+ }+ const stat = await NodeFSP.stat(resolved).catch(() => undefined);+ if (stat?.isFile()) return "file";+ if (!stat?.isDirectory()) return undefined;+ const folders = await loadVisitedFolders();+ return folders.some((folder) => isSameOrInside(resolved, folder))+ ? undefined+ : "directory";+ };+ // Bound filesystem work for directories such as pnpm node_modules.+ const kinds: Array<ProjectEntry["kind"] | undefined> = [];+ for (let offset = 0; offset < children.length; offset += SYMLINK_RESOLVE_BATCH_SIZE) {+ kinds.push(+ ...(await Promise.all(+ children+ .slice(offset, offset + SYMLINK_RESOLVE_BATCH_SIZE)+ .map(async (child): Promise<ProjectEntry["kind"] | undefined> => {+ if (child.name === ".git") return undefined;+ if (child.isDirectory()) return "directory";+ if (child.isFile()) return "file";+ return child.isSymbolicLink() ? resolveSymlinkKind(child.name) : undefined;+ }),+ )),+ );+ }return {- entries: children.flatMap((child): ProjectEntry[] => {- if (child.name === ".git" || (!child.isDirectory() && !child.isFile())) return [];+ entries: children.flatMap((child, index): ProjectEntry[] => {+ const kind = kinds[index];+ if (kind === undefined) return [];return [{path: target.relativePath ? `${target.relativePath}/${child.name}` : child.name,- kind: child.isDirectory() ? "directory" : "file",+ kind,},];}),