Skip to content

Commit 6338a31

Browse files
authored
feat(fmt): add serial runner (#121)
1 parent fba323c commit 6338a31

10 files changed

Lines changed: 371 additions & 0 deletions

File tree

packages/rstack/THIRD_PARTY_NOTICES.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,62 @@
22

33
This package includes software developed by third parties.
44

5+
## @prettier/cli
6+
7+
Portions of the formatter runtime are derived from
8+
[@prettier/cli](https://github.com/prettier/prettier-cli).
9+
10+
License: MIT
11+
12+
Copyright © James Long and contributors
13+
14+
Permission is hereby granted, free of charge, to any person obtaining a copy of
15+
this software and associated documentation files (the "Software"), to deal in
16+
the Software without restriction, including without limitation the rights to
17+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
18+
of the Software, and to permit persons to whom the Software is furnished to do
19+
so, subject to the following conditions:
20+
21+
The above copyright notice and this permission notice shall be included in all
22+
copies or substantial portions of the Software.
23+
24+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30+
SOFTWARE.
31+
32+
## atomically
33+
34+
This package includes bundled code from
35+
[atomically](https://github.com/fabiospampinato/atomically).
36+
37+
License: MIT
38+
39+
The MIT License (MIT)
40+
41+
Copyright (c) 2020-present Fabio Spampinato
42+
43+
Permission is hereby granted, free of charge, to any person obtaining a
44+
copy of this software and associated documentation files (the "Software"),
45+
to deal in the Software without restriction, including without limitation
46+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
47+
and/or sell copies of the Software, and to permit persons to whom the
48+
Software is furnished to do so, subject to the following conditions:
49+
50+
The above copyright notice and this permission notice shall be included in
51+
all copies or substantial portions of the Software.
52+
53+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
58+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
59+
DEALINGS IN THE SOFTWARE.
60+
561
## fast-ignore
662

763
This package includes bundled code from [fast-ignore](https://github.com/fabiospampinato/fast-ignore).

packages/rstack/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
"@rstest/adapter-rslib": "catalog:",
6868
"@types/micromatch": "catalog:",
6969
"@types/node": "catalog:",
70+
"atomically": "catalog:",
7071
"fast-ignore": "catalog:",
7172
"ignore": "catalog:",
7273
"is-binary-path": "catalog:",

packages/rstack/src/fmt/runner.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import type { FmtExitCode, FmtFileResult, FmtRunResult, RunFmtFilesOptions } from './types.ts';
2+
import { formatFileSerial } from './vendor/prettier-cli/serial.ts';
3+
4+
const runFmtFiles = async ({ files, mode }: RunFmtFilesOptions): Promise<FmtRunResult> => {
5+
const startTime = performance.now();
6+
const shouldWrite = mode === 'write';
7+
const results: FmtFileResult[] = [];
8+
let exitCode: FmtExitCode = 0;
9+
10+
for (const file of files) {
11+
const fileStartTime = performance.now();
12+
13+
try {
14+
const changed = await formatFileSerial(file, shouldWrite);
15+
16+
if (changed && !shouldWrite && exitCode === 0) {
17+
exitCode = 1;
18+
}
19+
20+
results.push({
21+
path: file.path,
22+
status: changed ? (shouldWrite ? 'written' : 'different') : 'unchanged',
23+
durationMs: performance.now() - fileStartTime,
24+
});
25+
} catch (error) {
26+
exitCode = 2;
27+
results.push({
28+
path: file.path,
29+
status: 'error',
30+
error,
31+
durationMs: performance.now() - fileStartTime,
32+
});
33+
}
34+
}
35+
36+
return {
37+
files: results,
38+
exitCode,
39+
durationMs: performance.now() - startTime,
40+
};
41+
};
42+
43+
export { runFmtFiles };

packages/rstack/src/fmt/types.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,42 @@ interface FmtFileRequest {
4444
options: PrettierOptions & Required<Pick<PrettierOptions, 'filepath' | 'parser'>>;
4545
}
4646

47+
type FmtMode = 'write' | 'check' | 'list-different';
48+
type FmtExitCode = 0 | 1 | 2;
49+
50+
interface RunFmtFilesOptions {
51+
/** Files with their final per-file Prettier options. */
52+
files: FmtFileRequest[];
53+
/** Whether to write changes or only report them. */
54+
mode: FmtMode;
55+
/** Persistent cache support is added in a later implementation step. */
56+
cache: false;
57+
/** Parallel execution support is added in a later implementation step. */
58+
parallel: false;
59+
}
60+
61+
interface SuccessfulFmtFileResult {
62+
path: string;
63+
status: 'unchanged' | 'written' | 'different';
64+
durationMs: number;
65+
}
66+
67+
interface FailedFmtFileResult {
68+
path: string;
69+
status: 'error';
70+
error: unknown;
71+
durationMs: number;
72+
}
73+
74+
type FmtFileResult = SuccessfulFmtFileResult | FailedFmtFileResult;
75+
76+
interface FmtRunResult {
77+
files: FmtFileResult[];
78+
/** Recommended CLI exit code. */
79+
exitCode: FmtExitCode;
80+
durationMs: number;
81+
}
82+
4783
interface FormattedTextResult {
4884
status: 'formatted';
4985
formatted: string;
@@ -61,8 +97,13 @@ export type {
6197
DiscoverFmtFilesOptions,
6298
FmtConfig,
6399
FmtConfigDefinition,
100+
FmtExitCode,
101+
FmtFileResult,
64102
FmtFileRequest,
103+
FmtMode,
104+
FmtRunResult,
65105
FormatTextOptions,
66106
FormatTextResult,
67107
ResolvedFmtConfig,
108+
RunFmtFilesOptions,
68109
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright © James Long and contributors
2+
3+
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:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
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.
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Derived from @prettier/cli v0.12.0.
3+
* SPDX-License-Identifier: MIT
4+
* Modified by Rstack contributors.
5+
*/
6+
7+
import { readFile, writeFile } from 'atomically';
8+
import { format } from 'prettier';
9+
import type { FmtFileRequest } from '../../types.ts';
10+
11+
const formatFileSerial = async (
12+
{ path, options }: FmtFileRequest,
13+
shouldWrite: boolean,
14+
): Promise<boolean> => {
15+
const source = await readFile(path, 'utf8');
16+
const formatted = await format(source, options);
17+
18+
if (source === formatted) {
19+
return false;
20+
}
21+
22+
if (shouldWrite) {
23+
await writeFile(path, formatted, 'utf8');
24+
}
25+
26+
return true;
27+
};
28+
29+
export { formatFileSerial };
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import {
2+
chmodSync,
3+
mkdtempSync,
4+
readFileSync,
5+
rmSync,
6+
statSync,
7+
utimesSync,
8+
writeFileSync,
9+
} from 'node:fs';
10+
import { tmpdir } from 'node:os';
11+
import path from 'node:path';
12+
import { expect, test } from 'rstack/test';
13+
import { runFmtFiles } from '../../src/fmt/runner.ts';
14+
import type { FmtFileRequest, FmtMode } from '../../src/fmt/types.ts';
15+
16+
const withProject = async (callback: (rootPath: string) => Promise<void>): Promise<void> => {
17+
const rootPath = mkdtempSync(path.join(tmpdir(), 'rstack fmt runner '));
18+
19+
try {
20+
await callback(rootPath);
21+
} finally {
22+
rmSync(rootPath, { force: true, recursive: true });
23+
}
24+
};
25+
26+
const createRequest = (filePath: string): FmtFileRequest => ({
27+
path: filePath,
28+
options: {
29+
filepath: filePath,
30+
parser: 'typescript',
31+
},
32+
});
33+
34+
const run = (files: FmtFileRequest[], mode: FmtMode = 'write') =>
35+
runFmtFiles({
36+
files,
37+
mode,
38+
cache: false,
39+
parallel: false,
40+
});
41+
42+
test('does not rewrite unchanged files', async () => {
43+
await withProject(async (rootPath) => {
44+
const filePath = path.join(rootPath, 'unchanged.ts');
45+
const timestamp = new Date('2020-01-01T00:00:00.000Z');
46+
writeFileSync(filePath, 'const value = 1;\n');
47+
utimesSync(filePath, timestamp, timestamp);
48+
const mtimeMs = statSync(filePath).mtimeMs;
49+
50+
const result = await run([createRequest(filePath)]);
51+
52+
expect(result).toMatchObject({
53+
exitCode: 0,
54+
files: [{ path: filePath, status: 'unchanged' }],
55+
});
56+
expect(statSync(filePath).mtimeMs).toBe(mtimeMs);
57+
expect(result.durationMs).toBeGreaterThanOrEqual(0);
58+
expect(result.files[0].durationMs).toBeGreaterThanOrEqual(0);
59+
});
60+
});
61+
62+
test('writes changed files', async () => {
63+
await withProject(async (rootPath) => {
64+
const filePath = path.join(rootPath, 'changed.ts');
65+
writeFileSync(filePath, 'const value=1');
66+
67+
const result = await run([createRequest(filePath)]);
68+
69+
expect(result).toMatchObject({
70+
exitCode: 0,
71+
files: [{ path: filePath, status: 'written' }],
72+
});
73+
expect(readFileSync(filePath, 'utf8')).toBe('const value = 1;\n');
74+
});
75+
});
76+
77+
test.runIf(process.platform !== 'win32')('preserves file mode when writing', async () => {
78+
await withProject(async (rootPath) => {
79+
const filePath = path.join(rootPath, 'executable.ts');
80+
writeFileSync(filePath, 'const value=1');
81+
chmodSync(filePath, 0o744);
82+
83+
await run([createRequest(filePath)]);
84+
85+
expect(statSync(filePath).mode & 0o777).toBe(0o744);
86+
});
87+
});
88+
89+
for (const mode of ['check', 'list-different'] as const) {
90+
test(`${mode} reports differences without writing`, async () => {
91+
await withProject(async (rootPath) => {
92+
const filePath = path.join(rootPath, 'different.ts');
93+
const source = 'const value=1';
94+
writeFileSync(filePath, source);
95+
96+
const result = await run([createRequest(filePath)], mode);
97+
98+
expect(result).toMatchObject({
99+
exitCode: 1,
100+
files: [{ path: filePath, status: 'different' }],
101+
});
102+
expect(readFileSync(filePath, 'utf8')).toBe(source);
103+
});
104+
});
105+
}
106+
107+
test('continues after a file fails and gives errors exit-code precedence', async () => {
108+
await withProject(async (rootPath) => {
109+
const invalidPath = path.join(rootPath, 'invalid.ts');
110+
const validPath = path.join(rootPath, 'valid.ts');
111+
writeFileSync(invalidPath, 'const value = ;');
112+
writeFileSync(validPath, 'const value=1');
113+
114+
const result = await run([createRequest(invalidPath), createRequest(validPath)], 'check');
115+
116+
expect(result).toMatchObject({
117+
exitCode: 2,
118+
files: [
119+
{ path: invalidPath, status: 'error' },
120+
{ path: validPath, status: 'different' },
121+
],
122+
});
123+
expect(readFileSync(validPath, 'utf8')).toBe('const value=1');
124+
});
125+
});
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { expect, rs, test } from 'rstack/test';
2+
import { runFmtFiles } from '../../src/fmt/runner.ts';
3+
4+
rs.mock('atomically', () => ({
5+
readFile: () => Promise.resolve('const value=1'),
6+
writeFile: () => Promise.reject(new Error('atomic write failed')),
7+
}));
8+
9+
test('returns an error when the atomic write fails', async () => {
10+
const filePath = '/virtual/example.ts';
11+
12+
const result = await runFmtFiles({
13+
files: [
14+
{
15+
path: filePath,
16+
options: {
17+
filepath: filePath,
18+
parser: 'typescript',
19+
},
20+
},
21+
],
22+
mode: 'write',
23+
cache: false,
24+
parallel: false,
25+
});
26+
27+
expect(result).toMatchObject({
28+
exitCode: 2,
29+
files: [
30+
{
31+
path: filePath,
32+
status: 'error',
33+
error: { message: 'atomic write failed' },
34+
},
35+
],
36+
});
37+
});

0 commit comments

Comments
 (0)