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

35 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-09-27 14:17:08 +08:00
import { $ } from "bun"
2025-12-10 08:46:38 +08:00
import * as fs from "fs/promises"
2025-09-27 14:17:08 +08:00
import os from "os"
import path from "path"
2025-12-10 08:46:38 +08:00
// Strip null bytes from paths (defensive fix for CI environment issues)
function sanitizePath(p: string): string {
return p.replace(/\0/g, "")
}
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-12-10 08:46:38 +08:00
const dirpath = sanitizePath(path.join(os.tmpdir(), "opencode-test-" + Math.random().toString(36).slice(2)))
await fs.mkdir(dirpath, { recursive: true })
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)
2025-12-10 08:46:38 +08:00
const realpath = sanitizePath(await fs.realpath(dirpath))
2025-09-27 14:17:08 +08:00
const result = {
[Symbol.asyncDispose]: async () => {
await options?.dispose?.(dirpath)
2025-12-10 08:53:50 +08:00
// await fs.rm(dirpath, { recursive: true, force: true })
2025-09-27 14:17:08 +08:00
},
2025-12-10 08:46:38 +08:00
path: realpath,
2025-09-27 14:53:20 +08:00
extra: extra as T,
2025-09-27 14:17:08 +08:00
}
return result
}