diff --git a/scripts/lib/resolve-formatter.js b/scripts/lib/resolve-formatter.js index 251264e78..e0d40bc38 100644 --- a/scripts/lib/resolve-formatter.js +++ b/scripts/lib/resolve-formatter.js @@ -44,8 +44,6 @@ const PRETTIER_CONFIGS = [ 'prettier.config.cts' ]; -const PROJECT_ROOT_MARKERS = ['package.json', ...BIOME_CONFIGS, ...PRETTIER_CONFIGS]; - // ── Windows .cmd shim mapping ─────────────────────────────────────── const WIN_CMD_SHIMS = { npx: 'npx.cmd', pnpm: 'pnpm.cmd', yarn: 'yarn.cmd', bunx: 'bunx.cmd' }; @@ -58,9 +56,9 @@ const FORMATTER_PACKAGES = { // ── Public helpers ────────────────────────────────────────────────── /** - * Walk up from `startDir` until a directory containing a known project - * root marker (package.json or formatter config) is found. - * Returns `startDir` as fallback when no marker exists above it. + * Walk up from `startDir` to the closest configured formatter, including + * shared workspace configs above a package.json. Stop at a repository or + * home boundary. Fall back to the nearest package, or `startDir` if absent. * * @param {string} startDir - Absolute directory path to start from * @returns {string} Absolute path to the project root @@ -70,21 +68,24 @@ function findProjectRoot(startDir) { const homeDir = os.homedir(); let dir = startDir; + let nearestPackage = null; while (dir !== path.dirname(dir)) { // Stop before checking the home directory to avoid treating global // dotfiles (e.g. ~/.prettierrc) as a project root marker. if (dir === homeDir) break; - for (const marker of PROJECT_ROOT_MARKERS) { - if (fs.existsSync(path.join(dir, marker))) { - projectRootCache.set(startDir, dir); - return dir; - } + if (detectFormatter(dir)) { + projectRootCache.set(startDir, dir); + return dir; } + if (nearestPackage === null && fs.existsSync(path.join(dir, 'package.json'))) nearestPackage = dir; + // .git may be a directory or a worktree's pointer file. + if (fs.existsSync(path.join(dir, '.git'))) break; dir = path.dirname(dir); } - projectRootCache.set(startDir, startDir); - return startDir; + const fallback = nearestPackage || startDir; + projectRootCache.set(startDir, fallback); + return fallback; } /** diff --git a/tests/hooks/workspace-formatter.test.js b/tests/hooks/workspace-formatter.test.js new file mode 100644 index 000000000..ee57f3ad8 --- /dev/null +++ b/tests/hooks/workspace-formatter.test.js @@ -0,0 +1,80 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const vm = require('vm'); +const { createRequire } = require('module'); +const { test } = require('node:test'); +const { clearCaches } = require('../../scripts/lib/resolve-formatter'); + +function loadHook(name, calls) { + const filename = path.resolve(__dirname, '../../scripts/hooks', name); + const nativeRequire = createRequire(filename); + const record = (bin, args, options) => { + calls.push({ bin, args: Array.from(args), cwd: options.cwd }); + return { status: 0, stdout: '', stderr: '' }; + }; + const mod = { exports: {} }; + vm.runInNewContext(fs.readFileSync(filename, 'utf8'), { + require: id => id === 'child_process' + ? { execFileSync: record, spawnSync: record } + : nativeRequire(id), + module: mod, exports: mod.exports, process, Buffer, + __dirname: path.dirname(filename), __filename: filename, + }, { filename }); + return mod.exports; +} + +function withWorkspace(fn) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-workspace-format-')); + clearCaches(); + try { + fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] })); + fs.writeFileSync(path.join(root, '.prettierrc'), '{}'); + const binary = path.join(root, 'node_modules', '.bin', process.platform === 'win32' ? 'prettier.cmd' : 'prettier'); + fs.mkdirSync(path.dirname(binary), { recursive: true }); + fs.writeFileSync(binary, 'fixture only; process calls are recorded'); + const files = ['first', 'second'].map(name => { + const pkg = path.join(root, 'packages', name); + fs.mkdirSync(path.join(pkg, 'src'), { recursive: true }); + fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({ name })); + const file = path.join(pkg, 'src', 'index.js'); + fs.writeFileSync(file, 'const value=1;'); + return file; + }); + fn({ root, binary, files }); + } finally { + clearCaches(); + fs.rmSync(root, { recursive: true, force: true }); + } +} + +test('post-edit formatter uses the workspace config and local binary', () => { + withWorkspace(({ root, binary, files }) => { + const calls = []; + const hook = loadHook('post-edit-format.js', calls); + const input = JSON.stringify({ tool_input: { file_path: files[0] } }); + assert.strictEqual(hook.run(input), input); + assert.deepStrictEqual(calls, [{ bin: binary, args: ['--write', files[0]], cwd: root }]); + }); +}); + +test('Stop batches files from sibling packages under their shared formatter', () => { + withWorkspace(({ root, binary, files }) => { + const calls = []; + const hook = loadHook('stop-format-typecheck.js', calls); + const sessionId = `workspace-format-${process.pid}-${Date.now()}`; + const accumulator = path.join(os.tmpdir(), `ecc-edited-${sessionId}.txt`); + fs.writeFileSync(accumulator, files.join('\n') + '\n'); + try { + const input = JSON.stringify({ session_id: sessionId }); + assert.strictEqual(hook.run(input), input); + assert.deepStrictEqual(calls, [{ bin: binary, args: ['--write', ...files], cwd: root }]); + assert.strictEqual(fs.existsSync(accumulator), false); + } finally { + fs.rmSync(accumulator, { force: true }); + } + }); +}); diff --git a/tests/lib/resolve-formatter.test.js b/tests/lib/resolve-formatter.test.js index 42185725f..1cc77b9f2 100644 --- a/tests/lib/resolve-formatter.test.js +++ b/tests/lib/resolve-formatter.test.js @@ -129,6 +129,53 @@ function runTests() { assert.strictEqual(first, second); }); + run('findProjectRoot: finds shared formatter config above workspace packages', () => { + for (const config of ['biome.json', '.prettierrc', 'prettier.config.ts']) { + const root = makeTmpDir(); + const workspace = path.join(root, 'packages', 'web'); + const source = path.join(workspace, 'src'); + fs.mkdirSync(source, { recursive: true }); + fs.writeFileSync(path.join(root, config), '{}'); + fs.writeFileSync(path.join(root, 'package.json'), '{}'); + fs.writeFileSync(path.join(workspace, 'package.json'), '{}'); + assert.strictEqual(findProjectRoot(source), root, config); + assert.strictEqual(detectFormatter(findProjectRoot(source)), config === 'biome.json' ? 'biome' : 'prettier'); + } + }); + + run('findProjectRoot: workspace formatter overrides the shared config', () => { + const root = makeTmpDir(); + const workspace = path.join(root, 'packages', 'web'); + fs.mkdirSync(workspace, { recursive: true }); + fs.writeFileSync(path.join(root, 'biome.json'), '{}'); + fs.writeFileSync(path.join(workspace, 'package.json'), JSON.stringify({ prettier: {} })); + assert.strictEqual(findProjectRoot(workspace), workspace); + assert.strictEqual(detectFormatter(workspace), 'prettier'); + }); + + run('findProjectRoot: retains the nearest package when no formatter is configured', () => { + const root = makeTmpDir(); + const workspace = path.join(root, 'packages', 'web'); + fs.mkdirSync(workspace, { recursive: true }); + fs.writeFileSync(path.join(root, 'package.json'), '{}'); + fs.writeFileSync(path.join(workspace, 'package.json'), '{}'); + assert.strictEqual(findProjectRoot(workspace), workspace); + }); + + run('findProjectRoot: does not borrow a formatter from outside a repository', () => { + for (const isWorktree of [false, true]) { + const outer = makeTmpDir(); + const repo = path.join(outer, 'repo'); + const source = path.join(repo, 'src'); + fs.mkdirSync(source, { recursive: true }); + fs.writeFileSync(path.join(outer, 'biome.json'), '{}'); + fs.writeFileSync(path.join(repo, 'package.json'), '{}'); + if (isWorktree) fs.writeFileSync(path.join(repo, '.git'), 'gitdir: ../worktrees/repo'); + else fs.mkdirSync(path.join(repo, '.git')); + assert.strictEqual(findProjectRoot(source), repo); + } + }); + // ── detectFormatter ─────────────────────────────────────────── run('detectFormatter: detects biome.json', () => {