cloudaxe-opencode/packages/opencode/src/file/watch.ts

54 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-07-01 17:44:52 +00:00
import { z } from "zod"
import { Bus } from "../bus"
import fs from "fs"
import { App } from "../app/app"
import { Log } from "../util/log"
2025-07-03 14:37:08 +00:00
import { Flag } from "../flag/flag"
2025-08-07 00:20:20 +00:00
import { Paths } from "../project/path"
2025-07-01 17:44:52 +00:00
export namespace FileWatcher {
const log = Log.create({ service: "file.watcher" })
export const Event = {
Updated: Bus.event(
"file.watcher.updated",
z.object({
file: z.string(),
event: z.union([z.literal("rename"), z.literal("change")]),
}),
),
}
2025-07-03 14:37:08 +00:00
const state = App.state(
2025-08-07 00:20:20 +00:00
() => Paths.use().worktree,
2025-07-03 14:37:08 +00:00
() => {
const app = App.use()
if (!app.info.git) return {}
2025-07-03 14:37:08 +00:00
try {
const watcher = fs.watch(app.info.path.cwd, { recursive: true }, (event, file) => {
log.info("change", { file, event })
if (!file) return
// for some reason async local storage is lost here
// https://github.com/oven-sh/bun/issues/20754
App.provideExisting(app, async () => {
Bus.publish(Event.Updated, {
file,
event,
2025-07-03 14:37:08 +00:00
})
})
})
2025-07-03 14:37:08 +00:00
return { watcher }
} catch {
return {}
}
},
async (state) => {
state.watcher?.close()
},
)
2025-07-01 17:44:52 +00:00
export function init() {
if (Flag.OPENCODE_DISABLE_WATCHER || true) return
2025-07-03 14:37:08 +00:00
state()
2025-07-01 17:44:52 +00:00
}
}