watcher.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. export * as Watcher from "./watcher"
  2. // @ts-ignore
  3. import { createWrapper } from "@parcel/watcher/wrapper"
  4. import type ParcelWatcher from "@parcel/watcher"
  5. import { Cause, Context, Effect, Layer } from "effect"
  6. import { FileSystemWatcher } from "@opencode-ai/schema/filesystem-watcher"
  7. import path from "path"
  8. import { Config } from "../config"
  9. import { EventV2 } from "../event"
  10. import { Flag } from "../flag/flag"
  11. import { FSUtil } from "../fs-util"
  12. import { Git } from "../git"
  13. import { Location } from "../location"
  14. import { lazy } from "../util/lazy"
  15. import { Ignore } from "./ignore"
  16. import { Protected } from "./protected"
  17. declare const OPENCODE_LIBC: string | undefined
  18. const SUBSCRIBE_TIMEOUT_MS = 10_000
  19. export const Event = FileSystemWatcher.Event
  20. const watcher = lazy((): typeof import("@parcel/watcher") | undefined => {
  21. try {
  22. const libc = typeof OPENCODE_LIBC === "undefined" ? undefined : OPENCODE_LIBC
  23. const binding = require(
  24. `@parcel/watcher-${process.platform}-${process.arch}${process.platform === "linux" ? `-${libc || "glibc"}` : ""}`,
  25. )
  26. return createWrapper(binding) as typeof import("@parcel/watcher")
  27. } catch {
  28. return
  29. }
  30. })
  31. function getBackend() {
  32. if (process.platform === "win32") return "windows"
  33. if (process.platform === "darwin") return "fs-events"
  34. if (process.platform === "linux") return "inotify"
  35. }
  36. function protecteds(dir: string) {
  37. return Protected.paths().filter((item) => {
  38. const relative = path.relative(dir, item)
  39. return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative)
  40. })
  41. }
  42. export const hasNativeBinding = () => !!watcher()
  43. export interface Interface {}
  44. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/FileWatcher") {}
  45. export const layer = Layer.effect(
  46. Service,
  47. Effect.gen(function* () {
  48. if (yield* Flag.OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER) return Service.of({})
  49. const backend = getBackend()
  50. const location = yield* Location.Service
  51. if (!backend) {
  52. yield* Effect.logError("watcher backend not supported", {
  53. directory: location.directory,
  54. platform: process.platform,
  55. })
  56. return Service.of({})
  57. }
  58. const w = watcher()
  59. if (!w) return Service.of({})
  60. yield* Effect.logInfo("watcher backend", { directory: location.directory, platform: process.platform, backend })
  61. const events = yield* EventV2.Service
  62. const fs = yield* FSUtil.Service
  63. const git = yield* Git.Service
  64. const context = yield* Effect.context()
  65. const runFork = Effect.runForkWith(context)
  66. const subscriptions: ParcelWatcher.AsyncSubscription[] = []
  67. yield* Effect.addFinalizer(() =>
  68. Effect.promise(() => Promise.allSettled(subscriptions.map((subscription) => subscription.unsubscribe()))),
  69. )
  70. const callback: ParcelWatcher.SubscribeCallback = (_error, updates) => {
  71. for (const update of updates) {
  72. if (update.type === "create") runFork(events.publish(Event.Updated, { file: update.path, event: "add" }))
  73. if (update.type === "update") runFork(events.publish(Event.Updated, { file: update.path, event: "change" }))
  74. if (update.type === "delete") runFork(events.publish(Event.Updated, { file: update.path, event: "unlink" }))
  75. }
  76. }
  77. const subscribe = (directory: string, ignore: string[]) => {
  78. const pending = w.subscribe(directory, callback, { ignore, backend })
  79. return Effect.promise(() => pending).pipe(
  80. Effect.tap((subscription) => Effect.sync(() => subscriptions.push(subscription))),
  81. Effect.timeout(SUBSCRIBE_TIMEOUT_MS),
  82. Effect.catchCause((cause) => {
  83. pending.then((subscription) => subscription.unsubscribe()).catch(() => {})
  84. return Effect.logError("failed to subscribe", { directory, cause: Cause.pretty(cause) })
  85. }),
  86. )
  87. }
  88. const config = (yield* (yield* Config.Service).entries())
  89. .filter((entry): entry is Config.Document => entry.type === "document")
  90. .flatMap((item) => item.info.watcher?.ignore ?? [])
  91. if (yield* Flag.OPENCODE_EXPERIMENTAL_FILEWATCHER) {
  92. yield* Effect.forkScoped(
  93. subscribe(location.directory, [...Ignore.PATTERNS, ...config, ...protecteds(location.directory)]),
  94. )
  95. }
  96. if (location.vcs?.type === "git") {
  97. const resolved = (yield* git.repo.discover(location.directory))?.gitDirectory
  98. const vcs = resolved ? yield* fs.realPath(resolved).pipe(Effect.catch(() => Effect.succeed(resolved))) : undefined
  99. if (vcs && !config.includes(".git") && !config.includes(vcs) && (!resolved || !config.includes(resolved))) {
  100. const ignore = (yield* fs.readDirectoryEntries(vcs).pipe(Effect.catch(() => Effect.succeed([])))).flatMap(
  101. (entry) => (entry.name === "HEAD" ? [] : [entry.name]),
  102. )
  103. yield* Effect.forkScoped(subscribe(vcs, ignore))
  104. }
  105. }
  106. return Service.of({})
  107. }).pipe(
  108. Effect.catchCause((cause) => {
  109. return Effect.logError("failed to init watcher service", { cause: Cause.pretty(cause) }).pipe(
  110. Effect.as(Service.of({})),
  111. )
  112. }),
  113. ),
  114. )
  115. export const locationLayer = layer.pipe(Layer.provide(Config.locationLayer), Layer.provide(Git.defaultLayer))