fixture.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { $ } from "bun"
  2. import * as fs from "fs/promises"
  3. import os from "os"
  4. import path from "path"
  5. // Strip null bytes from paths (defensive fix for CI environment issues)
  6. function sanitizePath(p: string): string {
  7. return p.replace(/\0/g, "")
  8. }
  9. type TmpDirOptions<T> = {
  10. git?: boolean
  11. init?: (dir: string) => Promise<T>
  12. dispose?: (dir: string) => Promise<T>
  13. }
  14. export async function tmpdir<T>(options?: TmpDirOptions<T>) {
  15. const dirpath = sanitizePath(path.join(os.tmpdir(), "opencode-test-" + Math.random().toString(36).slice(2)))
  16. await fs.mkdir(dirpath, { recursive: true })
  17. if (options?.git) {
  18. await $`git init`.cwd(dirpath).quiet()
  19. await $`git commit --allow-empty -m "root commit ${dirpath}"`.cwd(dirpath).quiet()
  20. }
  21. const extra = await options?.init?.(dirpath)
  22. const realpath = sanitizePath(await fs.realpath(dirpath))
  23. const result = {
  24. [Symbol.asyncDispose]: async () => {
  25. await options?.dispose?.(dirpath)
  26. await fs.rm(dirpath, { recursive: true, force: true })
  27. },
  28. path: realpath,
  29. extra: extra as T,
  30. }
  31. return result
  32. }