Skip to content

Commit 1ff9ea0

Browse files
authored
feat(fmt): add --clear-cache option (#634)
1 parent 91a3f59 commit 1ff9ea0

5 files changed

Lines changed: 82 additions & 6 deletions

File tree

‎packages/rstack/src/cli/commandHelp.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,7 @@ const HELP_DEFINITIONS = {
448448
['-u, --ignore-unknown', 'Ignore unknown files'],
449449
['--no-cache', 'Disable the formatting cache'],
450450
['--cache-location <path>', 'Path to the formatting cache directory'],
451+
['--clear-cache', 'Delete the formatting cache and exit'],
451452
[
452453
'--no-error-on-unmatched-pattern',
453454
'Do not error when no files match',

‎packages/rstack/src/fmt/cli.ts‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
import { rm } from 'node:fs/promises';
12
import path from 'node:path';
23
import { performance } from 'node:perf_hooks';
34
import { color, logger } from 'rslog';
45
import { parseArgs } from '../cli/args.ts';
56
import { printCommandHelp } from '../cli/help.ts';
67
import type { LoadedRstackConfig } from '../config.ts';
7-
import { loadCliRstackConfig } from '../cli/config.ts';
8-
import { ensureProjectCacheDir } from '../projectCache.ts';
8+
import { getConfigState, loadCliRstackConfig } from '../cli/config.ts';
9+
import { ensureProjectCacheDir, getProjectCacheDir } from '../projectCache.ts';
910
import { fmtCacheFileName } from './cacheStore.ts';
1011
import { resolveFmtConfig } from './config.ts';
1112
import { discoverFmtFiles } from './discovery.ts';
@@ -17,6 +18,7 @@ import type { FmtMode, FmtRunResult, ResolvedFmtConfig } from './types.ts';
1718
interface ParsedFmtCLIArgs {
1819
cache: boolean;
1920
cacheLocation?: string;
21+
clearCache: boolean;
2022
mode: FmtMode;
2123
patterns: string[];
2224
ignorePaths: string[];
@@ -57,7 +59,7 @@ const parseMaxWorkers = (value: string | undefined): number | undefined => {
5759
return maxWorkers;
5860
};
5961

60-
/** Rejects the mode flags and file arguments that a server-like option replaces. */
62+
/** Rejects formatting modes and file arguments for standalone operations. */
6163
const assertExclusiveMode = (
6264
option: string,
6365
hasMode: boolean,
@@ -85,6 +87,7 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
8587
'ignore-unknown': { type: 'boolean', short: 'u' },
8688
'no-cache': { type: 'boolean' },
8789
'cache-location': { type: 'string' },
90+
'clear-cache': { type: 'boolean' },
8891
'no-error-on-unmatched-pattern': { type: 'boolean' },
8992
'with-node-modules': { type: 'boolean' },
9093
'parallel-workers': { type: 'string' },
@@ -122,6 +125,16 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
122125
const help = values.help ?? false;
123126
const stdinFilepath = values.stdinFilepath;
124127
const lsp = values.lsp ?? false;
128+
const clearCache = values.clearCache ?? false;
129+
130+
if (clearCache) {
131+
assertExclusiveMode('--clear-cache', modes.length > 0, positionals);
132+
if (lsp || stdinFilepath !== undefined || !cache) {
133+
throw new Error(
134+
'The --clear-cache option cannot be used with --lsp, --stdin-filepath, or --no-cache.',
135+
);
136+
}
137+
}
125138

126139
if (lsp) {
127140
assertExclusiveMode('--lsp', modes.length > 0, positionals);
@@ -138,6 +151,7 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
138151
return {
139152
cache,
140153
cacheLocation,
154+
clearCache,
141155
mode,
142156
patterns: positionals,
143157
ignorePaths,
@@ -151,6 +165,12 @@ const parseFmtArgs = (args: string[]): ParsedFmtCLIArgs => {
151165
};
152166
};
153167

168+
const getFmtCacheFilePath = (rootPath: string, cacheDirPath?: string): string =>
169+
path.join(
170+
cacheDirPath ?? path.join(getProjectCacheDir(rootPath), 'fmt'),
171+
fmtCacheFileName,
172+
);
173+
154174
const createDisplayPathResolver = (
155175
cwd: string,
156176
): ((filePath: string) => string) => {
@@ -273,6 +293,7 @@ const runFmtCLI = async (
273293
const {
274294
cache,
275295
cacheLocation,
296+
clearCache,
276297
help,
277298
ignorePaths,
278299
ignoreUnknown,
@@ -335,6 +356,18 @@ const runFmtCLI = async (
335356
}
336357
}
337358

359+
if (clearCache) {
360+
// Config discovery stays in cwd unless --config points elsewhere.
361+
// Clearing the cache only needs that location, not the config contents.
362+
const configPath = loadedConfig?.filePath ?? getConfigState().configPath;
363+
const rootPath = configPath ? path.dirname(configPath) : cwd;
364+
const cacheFilePath = getFmtCacheFilePath(rootPath, cacheDirPath);
365+
// Custom cache directories may contain files that do not belong to us.
366+
await rm(cacheFilePath, { force: true });
367+
logger.success(`Formatting cache cleared: ${color.dim(cacheFilePath)}`);
368+
return;
369+
}
370+
338371
const config = await loadFmtConfig(cwd, loadedConfig);
339372
const files = await discoverFmtFiles({
340373
cwd,
@@ -359,14 +392,14 @@ const runFmtCLI = async (
359392
let cacheContext;
360393
if (cacheDirPath) {
361394
cacheContext = {
362-
filePath: path.join(cacheDirPath, fmtCacheFileName),
395+
filePath: getFmtCacheFilePath(config.rootPath, cacheDirPath),
363396
rootPath: config.rootPath,
364397
};
365398
} else if (cache) {
366399
const cacheDir = await ensureProjectCacheDir(config.rootPath);
367400
if (cacheDir.status === 'available') {
368401
cacheContext = {
369-
filePath: path.join(cacheDir.path, 'fmt', fmtCacheFileName),
402+
filePath: getFmtCacheFilePath(config.rootPath),
370403
rootPath: config.rootPath,
371404
};
372405
}

‎packages/rstack/src/projectCache.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,5 @@ const ensureProjectCacheDir = async (
3535
}
3636
};
3737

38-
export { ensureProjectCacheDir };
38+
export { ensureProjectCacheDir, getProjectCacheDir };
3939
export type { ProjectCacheResult };

‎packages/rstack/tests/cli/fmt/__snapshots__/files.test.ts.snap‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Options:
1616
-u, --ignore-unknown Ignore unknown files
1717
--no-cache Disable the formatting cache
1818
--cache-location <path> Path to the formatting cache directory
19+
--clear-cache Delete the formatting cache and exit
1920
--no-error-on-unmatched-pattern Do not error when no files match
2021
--with-node-modules Process files inside node_modules
2122
--parallel-workers <count> Number of parallel workers

‎packages/rstack/tests/cli/fmt/cache.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,47 @@ test('--no-cache bypasses cache reads and writes', () => {
8282
expect(projectFileExists('.rstack/cache/.gitignore')).toBe(false);
8383
});
8484

85+
test('--clear-cache resolves the config root without loading config or formatting', () => {
86+
writeProjectFile('rstack.config.ts', 'throw new Error("must not load");');
87+
expect(runFmt(['--clear-cache']).status).toBe(0);
88+
expect(projectFileExists('.rstack')).toBe(false);
89+
90+
writeProjectFile('.rstack/cache/fmt/cache.json', 'stale cache');
91+
writeProjectFile('packages/app/index.ts', 'const value=1');
92+
93+
const result = runFmt(
94+
['--clear-cache', '--config', '../../rstack.config.ts'],
95+
resolveProjectPath('packages/app'),
96+
);
97+
98+
expect(result.status).toBe(0);
99+
expect(projectFileExists('.rstack/cache/fmt/cache.json')).toBe(false);
100+
expect(readProjectFile('packages/app/index.ts')).toBe('const value=1');
101+
});
102+
103+
test('--clear-cache only deletes its own cache file at a custom location', () => {
104+
writeProjectFile('.rstack/cache/fmt/cache.json', 'default cache');
105+
writeProjectFile('custom-cache/cache.json', 'custom cache');
106+
writeProjectFile('custom-cache/keep.txt', 'keep file');
107+
108+
const result = runFmt(['--clear-cache', '--cache-location', 'custom-cache']);
109+
110+
expect(result.status).toBe(0);
111+
expect(projectFileExists('custom-cache/cache.json')).toBe(false);
112+
expect(readProjectFile('custom-cache/keep.txt')).toBe('keep file');
113+
expect(readProjectFile('.rstack/cache/fmt/cache.json')).toBe('default cache');
114+
});
115+
116+
test.each(['--check', 'index.ts', '--no-cache'])(
117+
'--clear-cache rejects conflicting argument %s',
118+
(arg) => {
119+
const result = runFmt(['--clear-cache', arg]);
120+
121+
expect(result.status).toBe(2);
122+
expect(result.stderr).toContain('The --clear-cache option cannot be used');
123+
},
124+
);
125+
85126
test('bypasses the cache for files using the Tailwind plugin', () => {
86127
writeProjectFile(
87128
'rstack.config.ts',

0 commit comments

Comments
 (0)