Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(config): deprecate cache.dir option #5229

Merged
merged 19 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 2 additions & 10 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1732,18 +1732,10 @@ Test above this limit will be queued to run when available slot appears.

### cache<NonProjectOption />

- **Type**: `false | { dir? }`
- **Type**: `false`
- **CLI**: `--no-cache`, `--cache=false`

Options to configure Vitest cache policy. At the moment Vitest stores cache for test results to run the longer and failed tests first.

#### cache.dir

- **Type**: `string`
- **Default**: `node_modules/.vitest`
- **CLI**: `--cache.dir=./cache`

Path to cache directory.
Use this option if you want to disable the cache feature. At the moment Vitest stores cache file in Vite's [cacheDir](https://vitejs.dev/config/shared-options.html#cachedir) for test results to run the longer and failed tests first.

### sequence

Expand Down
10 changes: 4 additions & 6 deletions packages/vitest/src/node/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { resolve } from 'pathe'
import { loadConfigFromFile } from 'vite'
import { configFiles } from '../../constants'
import type { CliOptions } from '../cli/cli-api'
import { slash } from '../../utils'
import { FilesStatsCache } from './files'
import { ResultsCache } from './results'

Expand All @@ -21,11 +20,10 @@ export class VitestCache {
return this.stats.getStats(key)
}

static resolveCacheDir(root: string, dir: string | undefined, projectName: string | undefined) {
const baseDir = slash(dir || 'node_modules/.vitest')
static resolveCacheDir(dir: string, projectName: string | undefined) {
return projectName
? resolve(root, baseDir, crypto.createHash('md5').update(projectName, 'utf-8').digest('hex'))
: resolve(root, baseDir)
? resolve(dir, crypto.createHash('md5').update(projectName, 'utf-8').digest('hex'))
: dir
}

static async clearCache(options: CliOptions) {
Expand All @@ -47,7 +45,7 @@ export class VitestCache {
if (cache === false)
throw new Error('Cache is disabled')

const cachePath = VitestCache.resolveCacheDir(root, cache?.dir, projectName)
const cachePath = VitestCache.resolveCacheDir(config!.cacheDir!, projectName)

let cleared = false

Expand Down
7 changes: 3 additions & 4 deletions packages/vitest/src/node/cache/results.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs'
import { dirname, relative, resolve } from 'pathe'
import type { File, ResolvedConfig } from '../../types'
import type { File } from '../../types'
import { version } from '../../../package.json'

export interface SuiteResultCache {
Expand All @@ -19,10 +19,9 @@ export class ResultsCache {
return this.cachePath
}

setConfig(root: string, config: ResolvedConfig['cache']) {
setConfig(root: string, cacheDir: string) {
this.root = root
if (config)
this.cachePath = resolve(config.dir, 'results.json')
this.cachePath = resolve(cacheDir, 'results.json')
}

getResults(key: string) {
Expand Down
9 changes: 1 addition & 8 deletions packages/vitest/src/node/cli/cli-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -538,20 +538,13 @@ export const cliOptionsConfig: VitestCLIOptions = {
cache: {
description: 'Enable cache',
argument: '', // allow only boolean
subcommands: {
dir: {
description: 'Path to the cache directory',
argument: '<path>',
normalize: true,
},
},
// cache can only be "false" or an object
transform(cache) {
if (cache)
return {}
return cache
},
},
} as VitestCLIOptions['cache'],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, you need to manually pass null to dir subcommand instead of removing it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for letting me know, I've updated it.

maxConcurrency: {
description: 'Maximum number of concurrent tests in a suite (default: 5)',
argument: '<number>',
Expand Down
11 changes: 7 additions & 4 deletions packages/vitest/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { defaultBrowserPort, defaultPort, extraInlineDeps } from '../constants'
import { benchmarkConfigDefaults, configDefaults } from '../defaults'
import { isCI, stdProvider, toArray } from '../utils'
import type { BuiltinPool } from '../types/pool-options'
import { VitestCache } from './cache'
import { BaseSequencer } from './sequencers/BaseSequencer'
import { RandomSequencer } from './sequencers/RandomSequencer'
import type { BenchmarkBuiltinReporters } from './reporters'
Expand Down Expand Up @@ -436,9 +435,13 @@ export function resolveConfig(
resolved.css.modules.classNameStrategy ??= 'stable'
}

resolved.cache ??= { dir: '' }
if (resolved.cache)
resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name)
if (resolved.cache && resolved.cache.dir) {
console.warn(
c.yellow(
`${c.inverse(c.yellow(' Vitest '))} "cache.dir" is deprecated. Use vite's "cacheDir" instead.`,
),
)
}

resolved.sequence ??= {} as any
if (!resolved.sequence?.sequencer) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export class Vitest {
? await createBenchmarkReporters(toArray(resolved.benchmark?.reporters), this.runner)
: await createReporters(resolved.reporters, this)

this.cache.results.setConfig(resolved.root, resolved.cache)
this.cache.results.setConfig(resolved.root, server.config.cacheDir)
try {
await this.cache.results.readFromCache()
}
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/node/plugins/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ export function VitestOptimizer(): Plugin {
order: 'post',
handler(viteConfig) {
const testConfig = viteConfig.test || {}
const webOptimizer = resolveOptimizerConfig(testConfig.deps?.optimizer?.web, viteConfig.optimizeDeps, testConfig)
const ssrOptimizer = resolveOptimizerConfig(testConfig.deps?.optimizer?.ssr, viteConfig.ssr?.optimizeDeps, testConfig)
const webOptimizer = resolveOptimizerConfig(testConfig.deps?.optimizer?.web, viteConfig.optimizeDeps, viteConfig)
const ssrOptimizer = resolveOptimizerConfig(testConfig.deps?.optimizer?.ssr, viteConfig.ssr?.optimizeDeps, viteConfig)

viteConfig.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || viteConfig.cacheDir
viteConfig.optimizeDeps = webOptimizer.optimizeDeps
Expand Down
8 changes: 3 additions & 5 deletions packages/vitest/src/node/plugins/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { searchForWorkspaceRoot, version as viteVersion } from 'vite'
import type { DepOptimizationOptions, ResolvedConfig, UserConfig as ViteConfig } from 'vite'
import { dirname } from 'pathe'
import type { DepsOptimizationOptions, InlineConfig } from '../../types'
import type { DepsOptimizationOptions } from '../../types'
import { VitestCache } from '../cache'
import { rootDir } from '../../paths'

export function resolveOptimizerConfig(_testOptions: DepsOptimizationOptions | undefined, viteOptions: DepOptimizationOptions | undefined, testConfig: InlineConfig) {
export function resolveOptimizerConfig(_testOptions: DepsOptimizationOptions | undefined, viteOptions: DepOptimizationOptions | undefined, viteConfig: ViteConfig) {
const testOptions = _testOptions || {}
const newConfig: { cacheDir?: string; optimizeDeps: DepOptimizationOptions } = {} as any
const [major, minor, fix] = viteVersion.split('.').map(Number)
Expand All @@ -24,8 +24,6 @@ export function resolveOptimizerConfig(_testOptions: DepsOptimizationOptions | u
}
}
else {
const root = testConfig.root ?? process.cwd()
const cacheDir = testConfig.cache !== false ? testConfig.cache?.dir : undefined
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still need to handle it during the deprecation period

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated it. I'm new to the optimizer config, not sure if this is right change, could you please help to review again? Thank you so much!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would expect test.cache.dir to just set cacheDir, everything else should just refer to config.cacheDir

const currentInclude = (testOptions.include || viteOptions?.include || [])
const exclude = [
'vitest',
Expand All @@ -39,7 +37,7 @@ export function resolveOptimizerConfig(_testOptions: DepsOptimizationOptions | u

const include = (testOptions.include || viteOptions?.include || []).filter((n: string) => !exclude.includes(n))

newConfig.cacheDir = cacheDir ?? VitestCache.resolveCacheDir(root, cacheDir, testConfig.name)
newConfig.cacheDir = viteConfig.test?.cache ? VitestCache.resolveCacheDir(viteConfig.cacheDir!, viteConfig.test?.name) : undefined
newConfig.optimizeDeps = {
...viteOptions,
...testOptions,
Expand Down
10 changes: 8 additions & 2 deletions packages/vitest/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,10 +606,13 @@ export interface InlineConfig {

/**
* Options for configuring cache policy.
* @default { dir: 'node_modules/.vitest' }
* @default { dir: 'node_modules/.vite' }
*/
cache?: false | {
dir?: string
/**
* @deprecated Use Vite's `cacheDir` instead.
*/
dir: string
}

/**
Expand Down Expand Up @@ -816,6 +819,9 @@ export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'f
}

cache: {
/**
* @deprecated
*/
dir: string
} | false

Expand Down
7 changes: 2 additions & 5 deletions test/cache/vitest-custom.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { defineConfig } from 'vite'

export default defineConfig({
test: {
cache: {
dir: 'cache/.vitest-custom',
},
},
cacheDir: 'cache/.vitest-custom',
test: {},
})
4 changes: 1 addition & 3 deletions test/cache/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { defineConfig } from 'vite'

export default defineConfig({
cacheDir: 'cache/.vitest-base',
test: {
pool: 'forks',
cache: {
dir: 'cache/.vitest-base',
},
},
})
8 changes: 1 addition & 7 deletions test/core/test/cli-test.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,7 @@ test('cache is parsed correctly', () => {
expect(getCLIOptions('--cache')).toEqual({ cache: {} })
expect(getCLIOptions('--no-cache')).toEqual({ cache: false })

expect(getCLIOptions('--cache.dir=./test/cache.json')).toEqual({
cache: { dir: 'test/cache.json' },
})
expect(getCLIOptions('--cache.dir ./test/cache.json')).toEqual({
cache: { dir: 'test/cache.json' },
})
expect(getCLIOptions('--cache.dir .\\test\\cache.json')).toEqual({
expect(getCLIOptions('--cache.dir=./test/cache.json')).not.toEqual({
cache: { dir: 'test/cache.json' },
})
})
Expand Down