fixture.ts 851 B

12345678910111213141516171819202122232425262728
  1. import { $ } from "bun"
  2. import { realpathSync } from "fs"
  3. import os from "os"
  4. import path from "path"
  5. type TmpDirOptions<T> = {
  6. git?: boolean
  7. init?: (dir: string) => Promise<T>
  8. dispose?: (dir: string) => Promise<T>
  9. }
  10. export async function tmpdir<T>(options?: TmpDirOptions<T>) {
  11. const dirpath = path.join(os.tmpdir(), "opencode-test-" + Math.random().toString(36).slice(2))
  12. await $`mkdir -p ${dirpath}`.quiet()
  13. if (options?.git) {
  14. await $`git init`.cwd(dirpath).quiet()
  15. await $`git commit --allow-empty -m "root commit ${dirpath}"`.cwd(dirpath).quiet()
  16. }
  17. const extra = await options?.init?.(dirpath)
  18. const result = {
  19. [Symbol.asyncDispose]: async () => {
  20. await options?.dispose?.(dirpath)
  21. await $`rm -rf ${dirpath}`.quiet()
  22. },
  23. path: realpathSync(dirpath),
  24. extra: extra as T,
  25. }
  26. return result
  27. }