fs-util.ts 9.7 KB

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