diff --git a/packages/rstack/THIRD_PARTY_NOTICES.md b/packages/rstack/THIRD_PARTY_NOTICES.md index 5431566..362f5c9 100644 --- a/packages/rstack/THIRD_PARTY_NOTICES.md +++ b/packages/rstack/THIRD_PARTY_NOTICES.md @@ -2,6 +2,62 @@ This package includes software developed by third parties. +## @prettier/cli + +Portions of the formatter runtime are derived from +[@prettier/cli](https://github.com/prettier/prettier-cli). + +License: MIT + +Copyright © James Long and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## atomically + +This package includes bundled code from +[atomically](https://github.com/fabiospampinato/atomically). + +License: MIT + +The MIT License (MIT) + +Copyright (c) 2020-present Fabio Spampinato + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + ## fast-ignore This package includes bundled code from [fast-ignore](https://github.com/fabiospampinato/fast-ignore). diff --git a/packages/rstack/package.json b/packages/rstack/package.json index 3a9cfd0..b037059 100644 --- a/packages/rstack/package.json +++ b/packages/rstack/package.json @@ -67,6 +67,7 @@ "@rstest/adapter-rslib": "catalog:", "@types/micromatch": "catalog:", "@types/node": "catalog:", + "atomically": "catalog:", "fast-ignore": "catalog:", "ignore": "catalog:", "is-binary-path": "catalog:", diff --git a/packages/rstack/src/fmt/runner.ts b/packages/rstack/src/fmt/runner.ts new file mode 100644 index 0000000..d64b98d --- /dev/null +++ b/packages/rstack/src/fmt/runner.ts @@ -0,0 +1,43 @@ +import type { FmtExitCode, FmtFileResult, FmtRunResult, RunFmtFilesOptions } from './types.ts'; +import { formatFileSerial } from './vendor/prettier-cli/serial.ts'; + +const runFmtFiles = async ({ files, mode }: RunFmtFilesOptions): Promise => { + const startTime = performance.now(); + const shouldWrite = mode === 'write'; + const results: FmtFileResult[] = []; + let exitCode: FmtExitCode = 0; + + for (const file of files) { + const fileStartTime = performance.now(); + + try { + const changed = await formatFileSerial(file, shouldWrite); + + if (changed && !shouldWrite && exitCode === 0) { + exitCode = 1; + } + + results.push({ + path: file.path, + status: changed ? (shouldWrite ? 'written' : 'different') : 'unchanged', + durationMs: performance.now() - fileStartTime, + }); + } catch (error) { + exitCode = 2; + results.push({ + path: file.path, + status: 'error', + error, + durationMs: performance.now() - fileStartTime, + }); + } + } + + return { + files: results, + exitCode, + durationMs: performance.now() - startTime, + }; +}; + +export { runFmtFiles }; diff --git a/packages/rstack/src/fmt/types.ts b/packages/rstack/src/fmt/types.ts index 16400e1..3bf345b 100644 --- a/packages/rstack/src/fmt/types.ts +++ b/packages/rstack/src/fmt/types.ts @@ -44,6 +44,42 @@ interface FmtFileRequest { options: PrettierOptions & Required>; } +type FmtMode = 'write' | 'check' | 'list-different'; +type FmtExitCode = 0 | 1 | 2; + +interface RunFmtFilesOptions { + /** Files with their final per-file Prettier options. */ + files: FmtFileRequest[]; + /** Whether to write changes or only report them. */ + mode: FmtMode; + /** Persistent cache support is added in a later implementation step. */ + cache: false; + /** Parallel execution support is added in a later implementation step. */ + parallel: false; +} + +interface SuccessfulFmtFileResult { + path: string; + status: 'unchanged' | 'written' | 'different'; + durationMs: number; +} + +interface FailedFmtFileResult { + path: string; + status: 'error'; + error: unknown; + durationMs: number; +} + +type FmtFileResult = SuccessfulFmtFileResult | FailedFmtFileResult; + +interface FmtRunResult { + files: FmtFileResult[]; + /** Recommended CLI exit code. */ + exitCode: FmtExitCode; + durationMs: number; +} + interface FormattedTextResult { status: 'formatted'; formatted: string; @@ -61,8 +97,13 @@ export type { DiscoverFmtFilesOptions, FmtConfig, FmtConfigDefinition, + FmtExitCode, + FmtFileResult, FmtFileRequest, + FmtMode, + FmtRunResult, FormatTextOptions, FormatTextResult, ResolvedFmtConfig, + RunFmtFilesOptions, }; diff --git a/packages/rstack/src/fmt/vendor/prettier-cli/LICENSE b/packages/rstack/src/fmt/vendor/prettier-cli/LICENSE new file mode 100644 index 0000000..5767e34 --- /dev/null +++ b/packages/rstack/src/fmt/vendor/prettier-cli/LICENSE @@ -0,0 +1,7 @@ +Copyright © James Long and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/rstack/src/fmt/vendor/prettier-cli/serial.ts b/packages/rstack/src/fmt/vendor/prettier-cli/serial.ts new file mode 100644 index 0000000..2254861 --- /dev/null +++ b/packages/rstack/src/fmt/vendor/prettier-cli/serial.ts @@ -0,0 +1,29 @@ +/** + * Derived from @prettier/cli v0.12.0. + * SPDX-License-Identifier: MIT + * Modified by Rstack contributors. + */ + +import { readFile, writeFile } from 'atomically'; +import { format } from 'prettier'; +import type { FmtFileRequest } from '../../types.ts'; + +const formatFileSerial = async ( + { path, options }: FmtFileRequest, + shouldWrite: boolean, +): Promise => { + const source = await readFile(path, 'utf8'); + const formatted = await format(source, options); + + if (source === formatted) { + return false; + } + + if (shouldWrite) { + await writeFile(path, formatted, 'utf8'); + } + + return true; +}; + +export { formatFileSerial }; diff --git a/packages/rstack/tests/fmt/runner.test.ts b/packages/rstack/tests/fmt/runner.test.ts new file mode 100644 index 0000000..f789e21 --- /dev/null +++ b/packages/rstack/tests/fmt/runner.test.ts @@ -0,0 +1,125 @@ +import { + chmodSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { expect, test } from 'rstack/test'; +import { runFmtFiles } from '../../src/fmt/runner.ts'; +import type { FmtFileRequest, FmtMode } from '../../src/fmt/types.ts'; + +const withProject = async (callback: (rootPath: string) => Promise): Promise => { + const rootPath = mkdtempSync(path.join(tmpdir(), 'rstack fmt runner ')); + + try { + await callback(rootPath); + } finally { + rmSync(rootPath, { force: true, recursive: true }); + } +}; + +const createRequest = (filePath: string): FmtFileRequest => ({ + path: filePath, + options: { + filepath: filePath, + parser: 'typescript', + }, +}); + +const run = (files: FmtFileRequest[], mode: FmtMode = 'write') => + runFmtFiles({ + files, + mode, + cache: false, + parallel: false, + }); + +test('does not rewrite unchanged files', async () => { + await withProject(async (rootPath) => { + const filePath = path.join(rootPath, 'unchanged.ts'); + const timestamp = new Date('2020-01-01T00:00:00.000Z'); + writeFileSync(filePath, 'const value = 1;\n'); + utimesSync(filePath, timestamp, timestamp); + const mtimeMs = statSync(filePath).mtimeMs; + + const result = await run([createRequest(filePath)]); + + expect(result).toMatchObject({ + exitCode: 0, + files: [{ path: filePath, status: 'unchanged' }], + }); + expect(statSync(filePath).mtimeMs).toBe(mtimeMs); + expect(result.durationMs).toBeGreaterThanOrEqual(0); + expect(result.files[0].durationMs).toBeGreaterThanOrEqual(0); + }); +}); + +test('writes changed files', async () => { + await withProject(async (rootPath) => { + const filePath = path.join(rootPath, 'changed.ts'); + writeFileSync(filePath, 'const value=1'); + + const result = await run([createRequest(filePath)]); + + expect(result).toMatchObject({ + exitCode: 0, + files: [{ path: filePath, status: 'written' }], + }); + expect(readFileSync(filePath, 'utf8')).toBe('const value = 1;\n'); + }); +}); + +test.runIf(process.platform !== 'win32')('preserves file mode when writing', async () => { + await withProject(async (rootPath) => { + const filePath = path.join(rootPath, 'executable.ts'); + writeFileSync(filePath, 'const value=1'); + chmodSync(filePath, 0o744); + + await run([createRequest(filePath)]); + + expect(statSync(filePath).mode & 0o777).toBe(0o744); + }); +}); + +for (const mode of ['check', 'list-different'] as const) { + test(`${mode} reports differences without writing`, async () => { + await withProject(async (rootPath) => { + const filePath = path.join(rootPath, 'different.ts'); + const source = 'const value=1'; + writeFileSync(filePath, source); + + const result = await run([createRequest(filePath)], mode); + + expect(result).toMatchObject({ + exitCode: 1, + files: [{ path: filePath, status: 'different' }], + }); + expect(readFileSync(filePath, 'utf8')).toBe(source); + }); + }); +} + +test('continues after a file fails and gives errors exit-code precedence', async () => { + await withProject(async (rootPath) => { + const invalidPath = path.join(rootPath, 'invalid.ts'); + const validPath = path.join(rootPath, 'valid.ts'); + writeFileSync(invalidPath, 'const value = ;'); + writeFileSync(validPath, 'const value=1'); + + const result = await run([createRequest(invalidPath), createRequest(validPath)], 'check'); + + expect(result).toMatchObject({ + exitCode: 2, + files: [ + { path: invalidPath, status: 'error' }, + { path: validPath, status: 'different' }, + ], + }); + expect(readFileSync(validPath, 'utf8')).toBe('const value=1'); + }); +}); diff --git a/packages/rstack/tests/fmt/runnerWriteFailure.test.ts b/packages/rstack/tests/fmt/runnerWriteFailure.test.ts new file mode 100644 index 0000000..88197fd --- /dev/null +++ b/packages/rstack/tests/fmt/runnerWriteFailure.test.ts @@ -0,0 +1,37 @@ +import { expect, rs, test } from 'rstack/test'; +import { runFmtFiles } from '../../src/fmt/runner.ts'; + +rs.mock('atomically', () => ({ + readFile: () => Promise.resolve('const value=1'), + writeFile: () => Promise.reject(new Error('atomic write failed')), +})); + +test('returns an error when the atomic write fails', async () => { + const filePath = '/virtual/example.ts'; + + const result = await runFmtFiles({ + files: [ + { + path: filePath, + options: { + filepath: filePath, + parser: 'typescript', + }, + }, + ], + mode: 'write', + cache: false, + parallel: false, + }); + + expect(result).toMatchObject({ + exitCode: 2, + files: [ + { + path: filePath, + status: 'error', + error: { message: 'atomic write failed' }, + }, + ], + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e31f88a..54e7e16 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -70,6 +70,9 @@ catalogs: '@types/react-dom': specifier: ^19.2.3 version: 19.2.3 + atomically: + specifier: 2.1.1 + version: 2.1.1 cspell-ban-words: specifier: ^0.0.4 version: 0.0.4 @@ -355,6 +358,9 @@ importers: '@types/node': specifier: 'catalog:' version: 24.13.3 + atomically: + specifier: 'catalog:' + version: 2.1.1 fast-ignore: specifier: 'catalog:' version: 2.0.0 @@ -1172,6 +1178,9 @@ packages: resolution: {integrity: sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==} hasBin: true + atomically@2.1.1: + resolution: {integrity: sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ==} + bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} @@ -2108,6 +2117,12 @@ packages: resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} engines: {node: '>=8'} + stubborn-fs@2.0.0: + resolution: {integrity: sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==} + + stubborn-utils@1.0.2: + resolution: {integrity: sha512-zOh9jPYI+xrNOyisSelgym4tolKTJCQd5GBhK0+0xJvcYDcwlOoxF/rnFKQ2KRZknXSG9jWAp66fwP6AxN9STg==} + style-to-js@1.1.21: resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==} @@ -2210,6 +2225,9 @@ packages: resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} engines: {node: '>=12'} + when-exit@2.1.5: + resolution: {integrity: sha512-VGkKJ564kzt6Ms1dbgPP/yuIoQCrsFAnRbptpC5wOEsDaNsbCB2bnfnaA8i/vRs5tjUSEOtIuvl9/MyVsvQZCg==} + ws@8.21.0: resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} engines: {node: '>=10.0.0'} @@ -2901,6 +2919,11 @@ snapshots: astring@1.9.0: {} + atomically@2.1.1: + dependencies: + stubborn-fs: 2.0.0 + when-exit: 2.1.5 + bail@2.0.2: {} big.js@5.2.2: {} @@ -4164,6 +4187,12 @@ snapshots: dependencies: min-indent: 1.0.1 + stubborn-fs@2.0.0: + dependencies: + stubborn-utils: 1.0.2 + + stubborn-utils@1.0.2: {} + style-to-js@1.1.21: dependencies: style-to-object: 1.0.14 @@ -4302,6 +4331,8 @@ snapshots: whatwg-mimetype@3.0.0: {} + when-exit@2.1.5: {} + ws@8.21.0: {} yaml@2.9.0: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 3b657e8..1dd3aa5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -33,6 +33,7 @@ catalog: '@types/react': '^19.2.17' '@types/react-dom': '^19.2.3' '@shikijs/transformers': '^4.3.1' + atomically: '2.1.1' 'cspell-ban-words': '^0.0.4' 'fast-ignore': '2.0.0' 'happy-dom': '^20.11.1'