opencode_offline/packages/opencode/test/fixture/fixture.ts

29 lines
851 B
TypeScript
Raw Normal View History

2025-09-27 14:17:08 +08:00
import { $ } from "bun"
2025-10-24 21:26:17 +08:00
import { realpathSync } from "fs"
2025-09-27 14:17:08 +08:00
import os from "os"
import path from "path"
2025-09-27 14:53:20 +08:00
type TmpDirOptions<T> = {
2025-09-27 14:17:08 +08:00
git?: boolean
2025-09-27 14:53:20 +08:00
init?: (dir: string) => Promise<T>
dispose?: (dir: string) => Promise<T>
2025-09-27 14:17:08 +08:00
}
2025-09-27 14:53:20 +08:00
export async function tmpdir<T>(options?: TmpDirOptions<T>) {
2025-09-27 14:17:08 +08:00
const dirpath = path.join(os.tmpdir(), "opencode-test-" + Math.random().toString(36).slice(2))
await $`mkdir -p ${dirpath}`.quiet()
2025-11-01 03:07:36 +08:00
if (options?.git) {
await $`git init`.cwd(dirpath).quiet()
await $`git commit --allow-empty -m "root commit ${dirpath}"`.cwd(dirpath).quiet()
}
2025-09-27 14:17:08 +08:00
const extra = await options?.init?.(dirpath)
const result = {
[Symbol.asyncDispose]: async () => {
await options?.dispose?.(dirpath)
await $`rm -rf ${dirpath}`.quiet()
},
2025-10-24 21:26:17 +08:00
path: realpathSync(dirpath),
2025-09-27 14:53:20 +08:00
extra: extra as T,
2025-09-27 14:17:08 +08:00
}
return result
}