| 442 | } |
| 443 | |
| 444 | export function useFS<T extends TestFsStructure>(root: string, structure: T, ensureConfig = true, task?: TestContext['task']) { |
| 445 | const files = new Set<string>() |
| 446 | const hasConfig = Object.keys(structure).some(file => file.includes('.config.')) |
| 447 | if (ensureConfig && !hasConfig) { |
| 448 | ;(structure as any)['./vitest.config.js'] = {} |
| 449 | } |
| 450 | for (const file in structure) { |
| 451 | const filepath = resolve(root, file) |
| 452 | files.add(filepath) |
| 453 | const content = getGeneratedFileContent(structure[file]) |
| 454 | fs.mkdirSync(dirname(filepath), { recursive: true }) |
| 455 | fs.writeFileSync(filepath, String(content), 'utf-8') |
| 456 | } |
| 457 | (task?.context.onTestFinished ?? onTestFinished)(() => { |
| 458 | if (process.env.VITEST_FS_CLEANUP !== 'false') { |
| 459 | fs.rmSync(root, { recursive: true, force: true }) |
| 460 | } |
| 461 | }) |
| 462 | return { |
| 463 | root, |
| 464 | readFile: (file: string): string => { |
| 465 | const filepath = resolve(root, file) |
| 466 | if (relative(root, filepath).startsWith('..')) { |
| 467 | throw new Error(`file ${file} is outside of the test file system`) |
| 468 | } |
| 469 | return fs.readFileSync(filepath, 'utf-8') |
| 470 | }, |
| 471 | editFile: (file: string, callback: (content: string) => string) => { |
| 472 | const filepath = resolve(root, file) |
| 473 | if (!files.has(filepath)) { |
| 474 | throw new Error(`file ${file} is outside of the test file system`) |
| 475 | } |
| 476 | const content = fs.readFileSync(filepath, 'utf-8') |
| 477 | fs.writeFileSync(filepath, callback(content)) |
| 478 | }, |
| 479 | createFile: (file: string, content: string) => { |
| 480 | if (file.startsWith('..')) { |
| 481 | throw new Error(`file ${file} is outside of the test file system`) |
| 482 | } |
| 483 | const filepath = resolve(root, file) |
| 484 | if (files.has(filepath)) { |
| 485 | throw new Error(`file ${file} already exists in the test file system`) |
| 486 | } |
| 487 | files.add(filepath) |
| 488 | createFile(filepath, content) |
| 489 | }, |
| 490 | statFile: (file: string): fs.Stats => { |
| 491 | const filepath = resolve(root, file) |
| 492 | |
| 493 | if (relative(root, filepath).startsWith('..')) { |
| 494 | throw new Error(`file ${file} is outside of the test file system`) |
| 495 | } |
| 496 | |
| 497 | return fs.statSync(filepath) |
| 498 | }, |
| 499 | resolveFile: (file: string): string => { |
| 500 | return resolve(root, file) |
| 501 | }, |