filesystem.ts 9.1 KB

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