_helper.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import path from 'node:path'
  2. import os from 'node:os'
  3. import { promises as fs } from 'node:fs'
  4. import { execFile } from 'node:child_process'
  5. import { promisify } from 'node:util'
  6. import { CacheManager } from '../../src/cache/index.js'
  7. const execFileAsync = promisify(execFile)
  8. /**
  9. * 造 git 书仓库 + 缓存。files={相对路径:内容}。commits=[{message,files}] 逐个额外提交(用于造 ch(N) 历史)。
  10. */
  11. export async function makeGitBook(files, { commits = [] } = {}) {
  12. const root = await fs.mkdtemp(path.join(os.tmpdir(), 'wnw-sm-'))
  13. const git = (a) => execFileAsync('git', a, { cwd: root })
  14. await git(['init', '-q'])
  15. await git(['config', 'user.email', 't@example.com'])
  16. await git(['config', 'user.name', 'test'])
  17. await fs.writeFile(path.join(root, '.gitignore'), '.cache/\n工作区/\n', 'utf8')
  18. await writeAll(root, files)
  19. await git(['add', '-A'])
  20. await git(['commit', '-q', '-m', 'init'])
  21. for (const c of commits) {
  22. await writeAll(root, c.files)
  23. await git(['add', '-A'])
  24. await git(['commit', '-q', '-m', c.message])
  25. }
  26. const dbDir = await fs.mkdtemp(path.join(os.tmpdir(), 'wnw-sm-db-'))
  27. const cache = new CacheManager(path.join(dbDir, 'index.db'))
  28. await cache.ensureReady(root)
  29. return {
  30. root,
  31. git,
  32. ctx: { repoPath: root, cache },
  33. cleanup: async () => {
  34. await cache.close()
  35. await fs.rm(root, { recursive: true, force: true })
  36. await fs.rm(dbDir, { recursive: true, force: true })
  37. },
  38. }
  39. }
  40. async function writeAll(root, files = {}) {
  41. for (const [rel, content] of Object.entries(files)) {
  42. const full = path.join(root, rel)
  43. await fs.mkdir(path.dirname(full), { recursive: true })
  44. await fs.writeFile(full, content, 'utf8')
  45. }
  46. }
  47. export const chapter = (n, body = '正文。', vol = 1) =>
  48. `---\n章号: ${n}\n标题: 第${n}章\n卷: ${vol}\n字数: 100\n章定位: 推进\n钩子: 危机钩-强\n情绪定位: 铺垫\n---\n${body}`