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

46 lines
1.4 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"
import type { Config } from "../../src/config/config"
2025-09-27 14:17:08 +08:00
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
config?: Partial<Config.Info>
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()
}
if (options?.config) {
await Bun.write(
path.join(dirpath, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
...options.config,
}),
)
}
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
}