diff --git a/packages/adapter-utils/src/git-workspace-sync.ts b/packages/adapter-utils/src/git-workspace-sync.ts index 084eb110dd9..d64bf2e368b 100644 --- a/packages/adapter-utils/src/git-workspace-sync.ts +++ b/packages/adapter-utils/src/git-workspace-sync.ts @@ -73,7 +73,7 @@ export function setExpensiveWorkspaceGitExecutor(executor: ExpensiveWorkspaceGit expensiveWorkspaceGitExecutor = executor; } -export const GIT_ARCHIVE_EXCLUDES = [".git", ".git/*"] as const; +export const GIT_ARCHIVE_EXCLUDES = [".git", ".git/*", "*/.git", "*/.git/*"] as const; /** * Identity flags for commits the sync machinery itself creates (the merge diff --git a/packages/adapter-utils/src/workspace-restore-merge.excluded-git.test.ts b/packages/adapter-utils/src/workspace-restore-merge.excluded-git.test.ts new file mode 100644 index 00000000000..7c996297686 --- /dev/null +++ b/packages/adapter-utils/src/workspace-restore-merge.excluded-git.test.ts @@ -0,0 +1,119 @@ +import { promises as fsPromises } from "node:fs"; +import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { shouldExcludePath } from "./exclude-patterns.js"; +import { GIT_ARCHIVE_EXCLUDES } from "./git-workspace-sync.js"; +import { + captureDirectorySnapshot, + disposeDirectorySnapshot, + mergeDirectoryWithBaseline, +} from "./workspace-restore-merge.js"; + +describe("workspace restore merge with excluded git entries", () => { + const cleanupDirs: string[] = []; + + afterEach(async () => { + while (cleanupDirs.length > 0) { + const dir = cleanupDirs.pop(); + if (!dir) continue; + await rm(dir, { recursive: true, force: true }).catch(() => undefined); + } + }); + + it("keeps restoring other entries when a scanned directory vanishes", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-")); + cleanupDirs.push(rootDir); + const target = path.join(rootDir, "target"), source = path.join(rootDir, "source"); + await mkdir(path.join(target, "repo", ".git"), { recursive: true }); + await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n"); + const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true }); + try { + await mkdir(source); + await writeFile(path.join(source, "repo"), "replacement"); + await writeFile(path.join(source, "independent"), "applied"); + const readdirSpy = vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ); + try { + await expect(mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target })).resolves.toBeUndefined(); + } finally { readdirSpy.mockRestore(); } + expect(await readFile(path.join(target, "independent"), "utf8")).toBe("applied"); + expect(await readFile(path.join(target, "repo"), "utf8")).toBe("replacement"); + } finally { await disposeDirectorySnapshot(baseline); await rm(rootDir, { recursive: true, force: true }); } + }); + + it("fails the restore when the excluded-entry scan hits a permission error", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-merge-")); + cleanupDirs.push(rootDir); + const target = path.join(rootDir, "target"), source = path.join(rootDir, "source"); + await mkdir(path.join(target, "repo", ".git"), { recursive: true }); + await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n"); + const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true }); + try { + await mkdir(source); + await writeFile(path.join(source, "repo"), "replacement"); + const readdirSpy = vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce( + Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }), + ); + try { + await expect(mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target })) + .rejects.toMatchObject({ code: "EACCES" }); + } finally { readdirSpy.mockRestore(); } + } finally { await disposeDirectorySnapshot(baseline); await rm(rootDir, { recursive: true, force: true }); } + }); + + it("excludes a nested clone's .git from the restore baseline", async () => { + const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-nested-git-"))); + try { + await mkdir(path.join(root, "repo", ".git"), { recursive: true }); + await writeFile(path.join(root, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n"); + await writeFile(path.join(root, "repo", "tracked.txt"), "host\n"); + const baseline = await captureDirectorySnapshot(root, { exclude: [...GIT_ARCHIVE_EXCLUDES] }); + try { + const entries: string[] = []; + for (const [entry] of baseline.entries as Iterable<[string, unknown]>) entries.push(entry); + expect(entries).toContain("repo/tracked.txt"); + expect(entries.some((entry) => entry === "repo/.git" || entry.startsWith("repo/.git/"))).toBe(false); + expect(shouldExcludePath("repo/.git/config", GIT_ARCHIVE_EXCLUDES)).toBe(true); + expect(shouldExcludePath(".git/config", GIT_ARCHIVE_EXCLUDES)).toBe(true); + expect(shouldExcludePath(".github/workflows/ci.yml", GIT_ARCHIVE_EXCLUDES)).toBe(false); + } finally { await disposeDirectorySnapshot(baseline); } + } finally { await rm(root, { recursive: true, force: true }); } + }); + + it("preserves excluded descendants when a non-strict restore replaces their parent with a file", async () => { + const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-excluded-replacement-"))); + const target = path.join(root, "target"), source = path.join(root, "source"); + await mkdir(path.join(target, "repo", ".git"), { recursive: true }); + await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n"); + await writeFile(path.join(target, "repo", "tracked.txt"), "host\n"); + const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true }); + try { + await mkdir(source); + await writeFile(path.join(source, "repo"), "replacement"); + await writeFile(path.join(source, "independent"), "applied"); + await mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target }); + expect((await lstat(path.join(target, "repo"))).isDirectory()).toBe(true); + expect(await readFile(path.join(target, "repo", ".git", "config"), "utf8")).toContain("repositoryformatversion"); + expect(await readFile(path.join(target, "independent"), "utf8")).toBe("applied"); + } finally { await disposeDirectorySnapshot(baseline); await rm(root, { recursive: true, force: true }); } + }); + + it.skipIf(process.platform === "win32")("preserves excluded descendants when a non-strict restore replaces their parent with a symlink", async () => { + const root = await fsPromises.realpath(await mkdtemp(path.join(os.tmpdir(), "directory-excluded-replacement-link-"))); + const target = path.join(root, "target"), source = path.join(root, "source"); + await mkdir(path.join(target, "repo", ".git"), { recursive: true }); + await writeFile(path.join(target, "repo", ".git", "config"), "[core]\n\trepositoryformatversion = 0\n"); + const baseline = await captureDirectorySnapshot(target, { exclude: [...GIT_ARCHIVE_EXCLUDES], diskBacked: true }); + try { + await mkdir(source); + await symlink(root, path.join(source, "repo")); + await mergeDirectoryWithBaseline({ baseline, sourceDir: source, targetDir: target }); + expect((await lstat(path.join(target, "repo"))).isDirectory()).toBe(true); + expect(await readFile(path.join(target, "repo", ".git", "config"), "utf8")).toContain("repositoryformatversion"); + } finally { await disposeDirectorySnapshot(baseline); await rm(root, { recursive: true, force: true }); } + }); +}); diff --git a/packages/adapter-utils/src/workspace-restore-merge.ts b/packages/adapter-utils/src/workspace-restore-merge.ts index 0fef6cbd02c..75f2ada30bb 100644 --- a/packages/adapter-utils/src/workspace-restore-merge.ts +++ b/packages/adapter-utils/src/workspace-restore-merge.ts @@ -598,10 +598,41 @@ async function withCanonicalDirectoryMergeLock( } } -async function copySnapshotEntry(sourceDir: string, targetDir: string, relative: string, entry: SnapshotEntry): Promise { +async function directoryContainsExcludedEntry(directory: string, relative: string, exclude: readonly string[]): Promise { + if (exclude.length === 0) return false; + const entries = await fs.readdir(directory, { withFileTypes: true }).catch((error: unknown) => { + if (isVanishedEntry(error)) return null; + throw error; + }); + if (!entries) return false; + for (const entry of entries) { + const child = path.posix.join(relative, entry.name); + if (shouldExcludePath(child, exclude)) return true; + if (entry.isDirectory() && await directoryContainsExcludedEntry(path.join(directory, entry.name), child, exclude)) return true; + } + return false; +} + +async function replacementWouldDiscardExcludedEntry(targetPath: string, relative: string, exclude: readonly string[]): Promise { + const existing = await fs.lstat(targetPath).catch(() => null); + if (!existing?.isDirectory()) return false; + if (!(await directoryContainsExcludedEntry(targetPath, relative, exclude))) return false; + console.warn(`workspace restore: skipped replacing ${relative} because it contains paths excluded from the restored snapshot`); + return true; +} + +async function copySnapshotEntry( + sourceDir: string, + targetDir: string, + relative: string, + entry: SnapshotEntry, + exclude: readonly string[], +): Promise { const sourcePath = path.join(sourceDir, relative); const targetPath = path.join(targetDir, relative); + if (entry.kind !== "dir" && await replacementWouldDiscardExcludedEntry(targetPath, relative, exclude)) return; + if (entry.kind === "dir") { const existing = await fs.lstat(targetPath).catch(() => null); if (existing?.isDirectory()) { @@ -797,7 +828,7 @@ export async function mergeDirectoryWithBaseline(input: { } for (const [relative, entry] of orderedEntries(source)) { if (!entriesMatch(input.baseline.entries.get(relative), entry) && - !(input.conflictPolicy === "reject" && entriesMatch(current.entries.get(relative), entry))) await copySnapshotEntry(input.sourceDir, canonicalTargetDir, relative, entry); + !(input.conflictPolicy === "reject" && entriesMatch(current.entries.get(relative), entry))) await copySnapshotEntry(input.sourceDir, canonicalTargetDir, relative, entry, input.baseline.exclude); } await input.afterApply?.(); } finally { await disposeDirectorySnapshot(current); }