Skip to content
17 changes: 12 additions & 5 deletions packages/opencode/src/storage/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,21 @@ export namespace Storage {
const target = path.join(dir, ...key) + ".json"
return withErrorHandling(async () => {
using _ = await Lock.read(target)
return Bun.file(target).json() as Promise<T>
return (await Bun.file(target).json()) as T
})
}

export async function update<T>(key: string[], fn: (draft: T) => void) {
const dir = await state().then((x) => x.dir)
const target = path.join(dir, ...key) + ".json"
return withErrorHandling(async () => {
using _ = await Lock.write("storage")
using _ = await Lock.write(target)
const content = await Bun.file(target).json()
fn(content)
await Bun.write(target, JSON.stringify(content, null, 2))
const jsonContent = JSON.stringify(content, null, 2)
const tempFile = target + ".tmp"
await Bun.write(tempFile, jsonContent)
await fs.rename(tempFile, target)
return content as T
})
}
Expand All @@ -190,8 +193,12 @@ export namespace Storage {
const dir = await state().then((x) => x.dir)
const target = path.join(dir, ...key) + ".json"
return withErrorHandling(async () => {
using _ = await Lock.write("storage")
await Bun.write(target, JSON.stringify(content, null, 2))
using _ = await Lock.write(target)
const jsonContent = JSON.stringify(content, null, 2)
await fs.mkdir(path.dirname(target), { recursive: true })
const tempFile = target + ".tmp"
await Bun.write(tempFile, jsonContent)
await fs.rename(tempFile, target)
})
}

Expand Down