watcher.ts 5.2 KB

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