_helper.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import path from 'node:path'
  2. import os from 'node:os'
  3. import { fileURLToPath } from 'node:url'
  4. import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
  5. import { CacheManager } from '../../src/cache/index.js'
  6. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  7. // 共享的示例书仓库(只读,命令测试默认喂它)
  8. export const fixtureRoot = path.join(__dirname, '../fixtures/sample-book')
  9. /**
  10. * 用共享 sample-book fixture 建命令运行上下文。
  11. * @returns {Promise<{ctx: {repoPath, cache}, cleanup: () => Promise<void>}>}
  12. */
  13. export function fixtureCtx() {
  14. return repoCtx(fixtureRoot, null)
  15. }
  16. /**
  17. * 建命令运行上下文。
  18. * @param {string|null} repoPath 现成书仓库路径(与 files 二选一)
  19. * @param {object|null} files {相对路径: 内容} → 在临时目录现造一个书仓库
  20. */
  21. export async function repoCtx(repoPath, files) {
  22. let tmpRepo = null
  23. if (files) {
  24. tmpRepo = await mkdtemp(path.join(os.tmpdir(), 'wnw-cmd-repo-'))
  25. for (const [rel, content] of Object.entries(files)) {
  26. const full = path.join(tmpRepo, rel)
  27. await mkdir(path.dirname(full), { recursive: true })
  28. await writeFile(full, content, 'utf8')
  29. }
  30. repoPath = tmpRepo
  31. }
  32. // db 放独立临时目录,绝不写进书仓库
  33. const dbDir = await mkdtemp(path.join(os.tmpdir(), 'wnw-cmd-db-'))
  34. const cache = new CacheManager(path.join(dbDir, 'index.db'))
  35. await cache.ensureReady(repoPath)
  36. return {
  37. ctx: { repoPath, cache },
  38. cleanup: async () => {
  39. await cache.close()
  40. await rm(dbDir, { recursive: true, force: true })
  41. if (tmpRepo) await rm(tmpRepo, { recursive: true, force: true })
  42. },
  43. }
  44. }