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
1 change: 1 addition & 0 deletions packages/rstack/src/cli/commandHelp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ const HELP_DEFINITIONS = {
['-u, --ignore-unknown', 'Ignore unknown files'],
['--no-cache', 'Disable the formatting cache'],
['--cache-location <path>', 'Path to the formatting cache directory'],
['--clear-cache', 'Delete the formatting cache and exit'],
[
'--no-error-on-unmatched-pattern',
'Do not error when no files match',
Expand Down
43 changes: 38 additions & 5 deletions packages/rstack/src/fmt/cli.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { rm } from 'node:fs/promises';
import path from 'node:path';
import { performance } from 'node:perf_hooks';
import { color, logger } from 'rslog';
import { parseArgs } from '../cli/args.ts';
import { printCommandHelp } from '../cli/help.ts';
import type { LoadedRstackConfig } from '../config.ts';
import { loadCliRstackConfig } from '../cli/config.ts';
import { ensureProjectCacheDir } from '../projectCache.ts';
import { getConfigState, loadCliRstackConfig } from '../cli/config.ts';
import { ensureProjectCacheDir, getProjectCacheDir } from '../projectCache.ts';
import { fmtCacheFileName } from './cacheStore.ts';
import { resolveFmtConfig } from './config.ts';
import { discoverFmtFiles } from './discovery.ts';
Expand All @@ -17,6 +18,7 @@ import type { FmtMode, FmtRunResult, ResolvedFmtConfig } from './types.ts';
interface ParsedFmtCLIArgs {
cache: boolean;
cacheLocation?: string;
clearCache: boolean;
mode: FmtMode;
patterns: string[];
ignorePaths: string[];
Expand Down Expand Up @@ -57,7 +59,7 @@ const parseMaxWorkers = (value: string | undefined): number | undefined => {
return maxWorkers;
};

/** Rejects the mode flags and file arguments that a server-like option replaces. */
/** Rejects formatting modes and file arguments for standalone operations. */
const assertExclusiveMode = (
option: string,
hasMode: boolean,
Expand Down Expand Up @@ -85,6 +87,7 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
'ignore-unknown': { type: 'boolean', short: 'u' },
'no-cache': { type: 'boolean' },
'cache-location': { type: 'string' },
'clear-cache': { type: 'boolean' },
'no-error-on-unmatched-pattern': { type: 'boolean' },
'with-node-modules': { type: 'boolean' },
'parallel-workers': { type: 'string' },
Expand Down Expand Up @@ -122,6 +125,16 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
const help = values.help ?? false;
const stdinFilepath = values.stdinFilepath;
const lsp = values.lsp ?? false;
const clearCache = values.clearCache ?? false;

if (clearCache) {
assertExclusiveMode('--clear-cache', modes.length > 0, positionals);
if (lsp || stdinFilepath !== undefined || !cache) {
throw new Error(
'The --clear-cache option cannot be used with --lsp, --stdin-filepath, or --no-cache.',
);
}
}

if (lsp) {
assertExclusiveMode('--lsp', modes.length > 0, positionals);
Expand All @@ -138,6 +151,7 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
return {
cache,
cacheLocation,
clearCache,
mode,
patterns: positionals,
ignorePaths,
Expand All @@ -151,6 +165,12 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
};
};

const getFmtCacheFilePath = (rootPath: string, cacheDirPath?: string): string =>
path.join(
cacheDirPath ?? path.join(getProjectCacheDir(rootPath), 'fmt'),
fmtCacheFileName,
);

const createDisplayPathResolver = (
cwd: string,
): ((filePath: string) => string) => {
Expand Down Expand Up @@ -273,6 +293,7 @@ const runFmtCLI = async (
const {
cache,
cacheLocation,
clearCache,
help,
ignorePaths,
ignoreUnknown,
Expand Down Expand Up @@ -335,6 +356,18 @@ const runFmtCLI = async (
}
}

if (clearCache) {
// Config discovery stays in cwd unless --config points elsewhere.
// Clearing the cache only needs that location, not the config contents.
const configPath = loadedConfig?.filePath ?? getConfigState().configPath;
const rootPath = configPath ? path.dirname(configPath) : cwd;
const cacheFilePath = getFmtCacheFilePath(rootPath, cacheDirPath);
// Custom cache directories may contain files that do not belong to us.
await rm(cacheFilePath, { force: true });
logger.success(`Formatting cache cleared: ${color.dim(cacheFilePath)}`);
return;
}

const config = await loadFmtConfig(cwd, loadedConfig);
const files = await discoverFmtFiles({
cwd,
Expand All @@ -359,14 +392,14 @@ const runFmtCLI = async (
let cacheContext;
if (cacheDirPath) {
cacheContext = {
filePath: path.join(cacheDirPath, fmtCacheFileName),
filePath: getFmtCacheFilePath(config.rootPath, cacheDirPath),
rootPath: config.rootPath,
};
} else if (cache) {
const cacheDir = await ensureProjectCacheDir(config.rootPath);
if (cacheDir.status === 'available') {
cacheContext = {
filePath: path.join(cacheDir.path, 'fmt', fmtCacheFileName),
filePath: getFmtCacheFilePath(config.rootPath),
rootPath: config.rootPath,
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/rstack/src/projectCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ const ensureProjectCacheDir = async (
}
};

export { ensureProjectCacheDir };
export { ensureProjectCacheDir, getProjectCacheDir };
export type { ProjectCacheResult };
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Options:
-u, --ignore-unknown Ignore unknown files
--no-cache Disable the formatting cache
--cache-location <path> Path to the formatting cache directory
--clear-cache Delete the formatting cache and exit
--no-error-on-unmatched-pattern Do not error when no files match
--with-node-modules Process files inside node_modules
--parallel-workers <count> Number of parallel workers
Expand Down
41 changes: 41 additions & 0 deletions packages/rstack/tests/cli/fmt/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,47 @@ test('--no-cache bypasses cache reads and writes', () => {
expect(projectFileExists('.rstack/cache/.gitignore')).toBe(false);
});

test('--clear-cache resolves the config root without loading config or formatting', () => {
writeProjectFile('rstack.config.ts', 'throw new Error("must not load");');
expect(runFmt(['--clear-cache']).status).toBe(0);
expect(projectFileExists('.rstack')).toBe(false);

writeProjectFile('.rstack/cache/fmt/cache.json', 'stale cache');
writeProjectFile('packages/app/index.ts', 'const value=1');

const result = runFmt(
['--clear-cache', '--config', '../../rstack.config.ts'],
resolveProjectPath('packages/app'),
);

expect(result.status).toBe(0);
expect(projectFileExists('.rstack/cache/fmt/cache.json')).toBe(false);
expect(readProjectFile('packages/app/index.ts')).toBe('const value=1');
});

test('--clear-cache only deletes its own cache file at a custom location', () => {
writeProjectFile('.rstack/cache/fmt/cache.json', 'default cache');
writeProjectFile('custom-cache/cache.json', 'custom cache');
writeProjectFile('custom-cache/keep.txt', 'keep file');

const result = runFmt(['--clear-cache', '--cache-location', 'custom-cache']);

expect(result.status).toBe(0);
expect(projectFileExists('custom-cache/cache.json')).toBe(false);
expect(readProjectFile('custom-cache/keep.txt')).toBe('keep file');
expect(readProjectFile('.rstack/cache/fmt/cache.json')).toBe('default cache');
});

test.each(['--check', 'index.ts', '--no-cache'])(
'--clear-cache rejects conflicting argument %s',
(arg) => {
const result = runFmt(['--clear-cache', arg]);

expect(result.status).toBe(2);
expect(result.stderr).toContain('The --clear-cache option cannot be used');
},
);

test('bypasses the cache for files using the Tailwind plugin', () => {
writeProjectFile(
'rstack.config.ts',
Expand Down
Loading