filesystem.ts 9.0 KB

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