Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/rstack/THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
1 change: 1 addition & 0 deletions packages/rstack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:",
Expand Down
43 changes: 43 additions & 0 deletions packages/rstack/src/fmt/runner.ts
Original file line number Diff line number Diff line change
@@ -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<FmtRunResult> => {
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 };
41 changes: 41 additions & 0 deletions packages/rstack/src/fmt/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,42 @@ interface FmtFileRequest {
options: PrettierOptions & Required<Pick<PrettierOptions, 'filepath' | 'parser'>>;
}

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;
Expand All @@ -61,8 +97,13 @@ export type {
DiscoverFmtFilesOptions,
FmtConfig,
FmtConfigDefinition,
FmtExitCode,
FmtFileResult,
FmtFileRequest,
FmtMode,
FmtRunResult,
FormatTextOptions,
FormatTextResult,
ResolvedFmtConfig,
RunFmtFilesOptions,
};
7 changes: 7 additions & 0 deletions packages/rstack/src/fmt/vendor/prettier-cli/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
29 changes: 29 additions & 0 deletions packages/rstack/src/fmt/vendor/prettier-cli/serial.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> => {
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 };
125 changes: 125 additions & 0 deletions packages/rstack/tests/fmt/runner.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>): Promise<void> => {
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');
});
});
37 changes: 37 additions & 0 deletions packages/rstack/tests/fmt/runnerWriteFailure.test.ts
Original file line number Diff line number Diff line change
@@ -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' },
},
],
});
});
Loading