fs-util.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { NodeFileSystem } from "@effect/platform-node"
  2. import path, { dirname, isAbsolute, join, relative, sep } from "path"
  3. import { realpathSync } from "fs"
  4. import { readdir } from "fs/promises"
  5. import { lookup } from "mime-types"
  6. import { Context, Effect, FileSystem, Layer, Schema } from "effect"
  7. import type { PlatformError } from "effect/PlatformError"
  8. import { Glob } from "./util/glob"
  9. import { serviceUse } from "./effect/service-use"
  10. import { makeGlobalNode } from "./effect/app-node"
  11. import { filesystem } from "./effect/app-node-platform"
  12. export namespace FSUtil {
  13. export class FileSystemError extends Schema.TaggedErrorClass<FileSystemError>()("FileSystemError", {
  14. method: Schema.String,
  15. cause: Schema.optional(Schema.Defect()),
  16. }) {
  17. override get message() {
  18. const detail = this.cause instanceof Error ? this.cause.message : this.cause && String(this.cause)
  19. return `Filesystem operation failed: ${this.method}${detail ? `: ${detail}` : ""}`
  20. }
  21. }
  22. export type Error = PlatformError | FileSystemError
  23. export interface DirEntry {
  24. readonly name: string
  25. readonly type: "file" | "directory" | "symlink" | "other"
  26. }
  27. export interface Interface extends FileSystem.FileSystem {
  28. readonly isDir: (path: string) => Effect.Effect<boolean>
  29. readonly isFile: (path: string) => Effect.Effect<boolean>
  30. readonly existsSafe: (path: string) => Effect.Effect<boolean>
  31. readonly readFileStringSafe: (path: string) => Effect.Effect<string | undefined, Error>
  32. readonly readJson: (path: string) => Effect.Effect<unknown, Error>
  33. readonly writeJson: (path: string, data: unknown, mode?: number) => Effect.Effect<void, Error>
  34. readonly ensureDir: (path: string) => Effect.Effect<void, Error>
  35. readonly writeWithDirs: (path: string, content: string | Uint8Array, mode?: number) => Effect.Effect<void, Error>
  36. readonly readDirectoryEntries: (path: string) => Effect.Effect<DirEntry[], Error>
  37. readonly resolve: (path: string) => Effect.Effect<string>
  38. readonly findUp: (target: string, start: string, stop?: string) => Effect.Effect<string[], Error>
  39. readonly up: (options: { targets: string[]; start: string; stop?: string }) => Effect.Effect<string[], Error>
  40. readonly globUp: (pattern: string, start: string, stop?: string) => Effect.Effect<string[], Error>
  41. readonly glob: (pattern: string, options?: Glob.Options) => Effect.Effect<string[], Error>
  42. readonly globMatch: (pattern: string, filepath: string) => boolean
  43. }
  44. export class Service extends Context.Service<Service, Interface>()("@opencode/FileSystem") {}
  45. export const use = serviceUse(Service)
  46. // Exported so simulation can wrap this layer and override the methods that
  47. // bypass the injected FileSystem (readDirectoryEntries, glob, globUp).
  48. export const layer = Layer.effect(
  49. Service,
  50. Effect.gen(function* () {
  51. const fs = yield* FileSystem.FileSystem
  52. const existsSafe = Effect.fn("FileSystem.existsSafe")(function* (path: string) {
  53. return yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false))
  54. })
  55. const readFileStringSafe = Effect.fn("FileSystem.readFileStringSafe")(function* (path: string) {
  56. return yield* fs.readFileString(path).pipe(
  57. Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(undefined)),
  58. Effect.catchReason("PlatformError", "PermissionDenied", () => Effect.succeed(undefined)),
  59. )
  60. })
  61. const isDir = Effect.fn("FileSystem.isDir")(function* (path: string) {
  62. const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void))
  63. return info?.type === "Directory"
  64. })
  65. const isFile = Effect.fn("FileSystem.isFile")(function* (path: string) {
  66. const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void))
  67. return info?.type === "File"
  68. })
  69. const readDirectoryEntries = Effect.fn("FileSystem.readDirectoryEntries")(function* (dirPath: string) {
  70. return yield* Effect.tryPromise({
  71. try: async () => {
  72. const entries = await readdir(dirPath, { withFileTypes: true })
  73. return entries.map(
  74. (e): DirEntry => ({
  75. name: e.name,
  76. type: e.isDirectory() ? "directory" : e.isSymbolicLink() ? "symlink" : e.isFile() ? "file" : "other",
  77. }),
  78. )
  79. },
  80. catch: (cause) => new FileSystemError({ method: "readDirectoryEntries", cause }),
  81. })
  82. })
  83. const resolve = Effect.fn("FileSystem.resolve")(function* (input: string) {
  84. const resolved = path.resolve(windowsPath(input))
  85. return yield* fs.realPath(resolved).pipe(
  86. Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(resolved)),
  87. Effect.orDie,
  88. )
  89. })
  90. const readJson = Effect.fn("FileSystem.readJson")(function* (path: string) {
  91. const text = yield* fs.readFileString(path)
  92. return yield* Effect.try({
  93. try: () => JSON.parse(text),
  94. catch: (cause) => new FileSystemError({ method: "readJson", cause }),
  95. })
  96. })
  97. const writeJson = Effect.fn("FileSystem.writeJson")(function* (path: string, data: unknown, mode?: number) {
  98. const content = JSON.stringify(data, null, 2)
  99. yield* fs.writeFileString(path, content)
  100. if (mode) yield* fs.chmod(path, mode)
  101. })
  102. const ensureDir = Effect.fn("FileSystem.ensureDir")(function* (path: string) {
  103. yield* fs.makeDirectory(path, { recursive: true })
  104. })
  105. const writeWithDirs = Effect.fn("FileSystem.writeWithDirs")(function* (
  106. path: string,
  107. content: string | Uint8Array,
  108. mode?: number,
  109. ) {
  110. const write = typeof content === "string" ? fs.writeFileString(path, content) : fs.writeFile(path, content)
  111. yield* write.pipe(
  112. Effect.catchIf(
  113. (e) => e.reason._tag === "NotFound",
  114. () =>
  115. Effect.gen(function* () {
  116. yield* fs.makeDirectory(dirname(path), { recursive: true })
  117. yield* write
  118. }),
  119. ),
  120. )
  121. if (mode) yield* fs.chmod(path, mode)
  122. })
  123. const glob = Effect.fn("FileSystem.glob")(function* (pattern: string, options?: Glob.Options) {
  124. return yield* Effect.tryPromise({
  125. try: () => Glob.scan(pattern, options),
  126. catch: (cause) => new FileSystemError({ method: "glob", cause }),
  127. })
  128. })
  129. const findUp = Effect.fn("FileSystem.findUp")(function* (target: string, start: string, stop?: string) {
  130. const result: string[] = []
  131. let current = start
  132. while (true) {
  133. const search = join(current, target)
  134. if (yield* fs.exists(search)) result.push(search)
  135. if (stop === current) break
  136. const parent = dirname(current)
  137. if (parent === current) break
  138. current = parent
  139. }
  140. return result
  141. })
  142. const up = Effect.fn("FileSystem.up")(function* (options: { targets: string[]; start: string; stop?: string }) {
  143. const result: string[] = []
  144. let current = options.start
  145. while (true) {
  146. for (const target of options.targets) {
  147. const search = join(current, target)
  148. if (yield* fs.exists(search)) result.push(search)
  149. }
  150. if (options.stop === current) break
  151. const parent = dirname(current)
  152. if (parent === current) break
  153. current = parent
  154. }
  155. return result
  156. })
  157. const globUp = Effect.fn("FileSystem.globUp")(function* (pattern: string, start: string, stop?: string) {
  158. const result: string[] = []
  159. let current = start
  160. while (true) {
  161. const matches = yield* glob(pattern, { cwd: current, absolute: true, include: "file", dot: true }).pipe(
  162. Effect.catch(() => Effect.succeed([] as string[])),
  163. )
  164. result.push(...matches)
  165. if (stop === current) break
  166. const parent = dirname(current)
  167. if (parent === current) break
  168. current = parent
  169. }
  170. return result
  171. })
  172. return Service.of({
  173. ...fs,
  174. existsSafe,
  175. readFileStringSafe,
  176. isDir,
  177. isFile,
  178. readDirectoryEntries,
  179. resolve,
  180. readJson,
  181. writeJson,
  182. ensureDir,
  183. writeWithDirs,
  184. findUp,
  185. up,
  186. globUp,
  187. glob,
  188. globMatch: Glob.match,
  189. })
  190. }),
  191. )
  192. export const node = makeGlobalNode({ service: Service, layer: layer, deps: [filesystem] })
  193. // Pure helpers that don't need Effect (path manipulation, sync operations)
  194. export function mimeType(p: string): string {
  195. return lookup(p) || "application/octet-stream"
  196. }
  197. export function normalizePath(p: string): string {
  198. if (process.platform !== "win32") return p
  199. const resolved = path.resolve(windowsPath(p))
  200. try {
  201. return realpathSync.native(resolved)
  202. } catch {
  203. return resolved
  204. }
  205. }
  206. export function normalizePathPattern(p: string): string {
  207. if (process.platform !== "win32") return p
  208. if (p === "*") return p
  209. const match = p.match(/^(.*)[\\/]\*$/)
  210. if (!match) return normalizePath(p)
  211. const dir = /^[A-Za-z]:$/.test(match[1]) ? match[1] + "\\" : match[1]
  212. return join(normalizePath(dir), "*")
  213. }
  214. export function resolve(p: string): string {
  215. const resolved = path.resolve(windowsPath(p))
  216. try {
  217. return normalizePath(realpathSync(resolved))
  218. } catch (e: any) {
  219. if (e?.code === "ENOENT") return normalizePath(resolved)
  220. throw e
  221. }
  222. }
  223. export function windowsPath(p: string): string {
  224. if (process.platform !== "win32") return p
  225. return p
  226. .replace(/^\/([a-zA-Z]):(?:[\\/]|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
  227. .replace(/^\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
  228. .replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
  229. .replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
  230. }
  231. export function overlaps(a: string, b: string) {
  232. return contains(a, b) || contains(b, a)
  233. }
  234. export function contains(parent: string, child: string) {
  235. const result = relative(parent, child)
  236. return result === "" || (!isAbsolute(result) && result !== ".." && !result.startsWith(`..${sep}`))
  237. }
  238. }