mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-04 03:35:36 +08:00
Add Glob module and portable FileSystem.glob (#9438)
Co-authored-by: Effect Bot <tech-ops@effectful.co> Co-authored-by: Tim Smart <hello@timsmart.co>
This commit is contained in:
committed by
effect-bot
co-authored by
Effect Bot
Tim Smart
parent
89fd619fcb
commit
91c14fe52f
@@ -0,0 +1,11 @@
|
||||
---
|
||||
"effect": minor
|
||||
"@effect/platform-node-shared": minor
|
||||
"@effect/platform-deno": minor
|
||||
---
|
||||
|
||||
Add experimental `Glob` path matching and a shared `FileSystem.glob` implementation for Node, Bun, and Deno.
|
||||
|
||||
- Breaking: custom `FileSystem` implementations, including inputs to `FileSystem.make`, must provide `readDirectoryEntries`; mapping `readDirectory` names to `{ name, type: "Unknown" }` is supported. Wrappers must apply directory-listing changes to both methods.
|
||||
- `FileSystem.make` now derives `glob` instead of accepting it. Apply custom overrides afterward with `FileSystem.of({ ...fs, glob: customGlob })`.
|
||||
- Glob patterns use `/` separators and backslash escapes; Node extglobs no longer expand. Results use `/` separators and are relative to `root` unless the pattern is absolute. Deno wildcards now skip dotfiles unless explicitly named or `dot: true`; unreadable wildcard-reached directories are skipped, while read failures at the root or a leading literal directory propagate.
|
||||
@@ -17,6 +17,7 @@ import * as Cause from "./Cause.ts"
|
||||
import * as Context from "./Context.ts"
|
||||
import * as Effect from "./Effect.ts"
|
||||
import { pipe } from "./Function.ts"
|
||||
import * as Glob from "./internal/glob.ts"
|
||||
import * as Layer from "./Layer.ts"
|
||||
import * as Option from "./Option.ts"
|
||||
import { badArgument, type PlatformError, systemError } from "./PlatformError.ts"
|
||||
@@ -130,13 +131,36 @@ export interface FileSystem {
|
||||
gid: number
|
||||
) => Effect.Effect<void, PlatformError>
|
||||
/**
|
||||
* Glob a directory.
|
||||
* Finds paths under `root` that match a glob pattern.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Patterns follow `Glob.make`: wildcards skip names that start with `.`
|
||||
* unless the pattern segment starts with `.` or `dot` is `true`, and
|
||||
* `dir/**` includes `dir` itself. Results are `/`-separated paths relative
|
||||
* to `root` (or absolute for an absolute pattern), visited depth-first with
|
||||
* each directory's entries sorted by name. `**` does not traverse symbolic
|
||||
* links to directories, but a link named by another segment is followed.
|
||||
* Paths that match an `exclude` pattern are dropped, and excluded
|
||||
* directories are not read. Entries whose type cannot be determined, such
|
||||
* as broken links, are treated as files.
|
||||
*
|
||||
* Read failures at the root or a leading literal directory propagate. Missing
|
||||
* paths return an empty result; unreadable wildcard-reached directories are
|
||||
* skipped.
|
||||
*
|
||||
* **Gotchas**
|
||||
*
|
||||
* Wildcard matching is case-sensitive. Leading literal segments use `stat`,
|
||||
* so their case sensitivity follows the file system and results retain the
|
||||
* pattern's spelling.
|
||||
*/
|
||||
readonly glob: (
|
||||
pattern: string,
|
||||
options?: {
|
||||
readonly root?: string | undefined
|
||||
readonly exclude?: ReadonlyArray<string> | undefined
|
||||
readonly dot?: boolean | undefined
|
||||
}
|
||||
) => Effect.Effect<Array<string>, PlatformError>
|
||||
/**
|
||||
@@ -247,6 +271,22 @@ export interface FileSystem {
|
||||
readonly recursive?: boolean | undefined
|
||||
}
|
||||
) => Effect.Effect<Array<string>, PlatformError>
|
||||
/**
|
||||
* Lists a directory with the type of each entry.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Returns the same bare names as `readDirectory(path)`, excluding `.` and
|
||||
* `..`, in no particular order. Types describe entries, not symlink targets.
|
||||
* `"Unknown"` is allowed when the listing cannot determine the type, and
|
||||
* `glob` then falls back to `stat`.
|
||||
*
|
||||
* **Gotchas**
|
||||
*
|
||||
* Wrappers that change `readDirectory`, such as by prefixing paths, must
|
||||
* apply the same change here for `glob` to list the correct directory.
|
||||
*/
|
||||
readonly readDirectoryEntries: (path: string) => Effect.Effect<ReadonlyArray<DirectoryEntry>, PlatformError>
|
||||
/**
|
||||
* Read the contents of a file.
|
||||
*/
|
||||
@@ -478,6 +518,21 @@ export type OpenFlag =
|
||||
*/
|
||||
export const FileSystem: Context.Service<FileSystem, FileSystem> = Context.Service("effect/FileSystem")
|
||||
|
||||
/**
|
||||
* A directory entry with its type, independent of any symlink target.
|
||||
* `"Unknown"` means the listing could not determine the type.
|
||||
*
|
||||
* @see {@link FileSystem} `readDirectoryEntries`, which returns these entries
|
||||
*
|
||||
* @stability unstable
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface DirectoryEntry {
|
||||
readonly name: string
|
||||
readonly type: File.Type
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a FileSystem implementation from a partial implementation.
|
||||
*
|
||||
@@ -490,8 +545,10 @@ export const FileSystem: Context.Service<FileSystem, FileSystem> = Context.Servi
|
||||
* **Details**
|
||||
*
|
||||
* This function takes a partial FileSystem implementation and automatically provides
|
||||
* default implementations for `exists`, `readFileString`, `stream`, `sink`, and
|
||||
* `writeFileString` methods based on the provided core methods.
|
||||
* default implementations for `exists`, `glob`, `readFileString`, `stream`, `sink`,
|
||||
* and `writeFileString` methods based on the provided core methods. `glob` walks
|
||||
* the tree with `readDirectoryEntries`, using `stat` and `readLink` for entries
|
||||
* whose type is `"Unknown"`.
|
||||
*
|
||||
* @see {@link makeNoop} for a testing stub that accepts method overrides without requiring a complete implementation
|
||||
* @see {@link layerNoop} for providing a no-op `FileSystem` as a `Layer` in tests
|
||||
@@ -501,11 +558,12 @@ export const FileSystem: Context.Service<FileSystem, FileSystem> = Context.Servi
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const make = (
|
||||
impl: Omit<FileSystem, typeof TypeId | "exists" | "readFileString" | "stream" | "sink" | "writeFileString">
|
||||
impl: Omit<FileSystem, typeof TypeId | "exists" | "glob" | "readFileString" | "stream" | "sink" | "writeFileString">
|
||||
): FileSystem =>
|
||||
FileSystem.of({
|
||||
...impl,
|
||||
[TypeId]: TypeId,
|
||||
glob: Glob.make(impl),
|
||||
exists: (path) =>
|
||||
pipe(
|
||||
impl.access(path),
|
||||
@@ -692,6 +750,9 @@ export const makeNoop = (fileSystem: Partial<FileSystem>): FileSystem =>
|
||||
readDirectory(path) {
|
||||
return Effect.fail(notFound("readDirectory", path))
|
||||
},
|
||||
readDirectoryEntries(path) {
|
||||
return Effect.fail(notFound("readDirectoryEntries", path))
|
||||
},
|
||||
readFile(path) {
|
||||
return Effect.fail(notFound("readFile", path))
|
||||
},
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Matches `/`-separated paths without accessing the file system, using the
|
||||
* same pattern syntax as `FileSystem.glob`.
|
||||
*
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import { format } from "./Formatter.ts"
|
||||
import { dual } from "./Function.ts"
|
||||
import { type Inspectable, NodeInspectSymbol } from "./Inspectable.ts"
|
||||
import * as internal from "./internal/glob.ts"
|
||||
import { type Pipeable, pipeArguments } from "./Pipeable.ts"
|
||||
|
||||
const TypeId = "~effect/Glob"
|
||||
|
||||
/**
|
||||
* A compiled glob pattern.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* `pattern` is the source text and `dot` records whether wildcards match names
|
||||
* that start with `.`. Match paths against it with {@link match}.
|
||||
*
|
||||
* @see {@link make} for compiling a pattern
|
||||
*
|
||||
* @stability experimental
|
||||
* @category models
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export interface Glob extends Pipeable, Inspectable {
|
||||
readonly [TypeId]: typeof TypeId
|
||||
readonly pattern: string
|
||||
readonly dot: boolean
|
||||
}
|
||||
|
||||
interface GlobImpl extends Glob {
|
||||
readonly compiled: internal.Compiled
|
||||
}
|
||||
|
||||
const GlobProto = {
|
||||
[TypeId]: TypeId,
|
||||
toJSON(this: Glob) {
|
||||
return { _id: "Glob", pattern: this.pattern, dot: this.dot }
|
||||
},
|
||||
toString(this: Glob) {
|
||||
return `Glob(${format(this.toJSON())})`
|
||||
},
|
||||
[NodeInspectSymbol](this: Glob) {
|
||||
return this.toJSON()
|
||||
},
|
||||
pipe() {
|
||||
return pipeArguments(this, arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a glob pattern into a reusable `Glob`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Patterns use `/` as the separator. `*` matches any run of characters within
|
||||
* one path segment, `?` matches one character, and `[...]` matches one
|
||||
* character from a set, with `!` or `^` negating it and POSIX classes such as
|
||||
* `[[:digit:]]` allowed. `{a,b}` expands to each alternative and may nest. A
|
||||
* segment that is exactly `**` matches zero or more whole segments. A trailing
|
||||
* `/` matches only directories, and `\` makes the next character literal.
|
||||
*
|
||||
* **Gotchas**
|
||||
*
|
||||
* Wildcards and `**` skip names that start with `.` unless the pattern segment
|
||||
* itself starts with `.` or `dot` is `true`; they never match `.` or `..`.
|
||||
* `x/.` is the same as `x/`, and a `.` or `..` segment after `**` makes the
|
||||
* pattern match nothing, as does the empty pattern. UNC patterns and paths
|
||||
* such as `//server/share` are not supported and never match. Braces and
|
||||
* commas inside `[...]` are class members. Extended glob syntax and leading
|
||||
* `!` negation are not interpreted, but ordinary wildcards still apply within
|
||||
* them (for example, `?(a)` matches `x(a)`). Malformed syntax, such as an
|
||||
* unclosed `[`, matches literally. Braces also stay literal if expansion would
|
||||
* exceed 10,000 alternatives.
|
||||
*
|
||||
* **Example** (Matching source files)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Glob } from "effect"
|
||||
*
|
||||
* const sources = Glob.make("src/**\/*.{ts,tsx}")
|
||||
*
|
||||
* Glob.match(sources, "src/index.ts") // => true
|
||||
* Glob.match(sources, "src/ui/Button.tsx") // => true
|
||||
* Glob.match(sources, "src/.cache/index.ts") // => false
|
||||
* Glob.match(sources, "test/index.ts") // => false
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category constructors
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const make = (pattern: string, options?: {
|
||||
/** Whether wildcards and `**` match names that start with `.`. */
|
||||
readonly dot?: boolean | undefined
|
||||
}): Glob => {
|
||||
const dot = options?.dot ?? false
|
||||
const self = Object.create(GlobProto)
|
||||
self.pattern = pattern
|
||||
self.dot = dot
|
||||
self.compiled = internal.compile([pattern], dot)
|
||||
return self
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a `/`-separated path matches a `Glob`.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* Empty segments and `./` segments in the path are ignored. A trailing `/`
|
||||
* marks the path as a directory, which a pattern ending in `/` requires.
|
||||
*
|
||||
* **Example** (Filtering paths)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Glob, pipe } from "effect"
|
||||
*
|
||||
* const tests = Glob.make("**\/*.test.ts")
|
||||
* const paths = ["src/a.ts", "src/a.test.ts", "test/b.test.ts"]
|
||||
*
|
||||
* paths.filter((path) => Glob.match(tests, path)) // => ["src/a.test.ts", "test/b.test.ts"]
|
||||
* pipe(tests, Glob.match("./src/a.test.ts")) // => true
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category predicates
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const match: {
|
||||
(path: string): (self: Glob) => boolean
|
||||
(self: Glob, path: string): boolean
|
||||
} = dual(2, (self: Glob, path: string): boolean => internal.match((self as GlobImpl).compiled, path))
|
||||
|
||||
/**
|
||||
* Escapes glob syntax so a string matches only itself.
|
||||
*
|
||||
* **Example** (Matching a literal file name)
|
||||
*
|
||||
* ```ts import.meta.vitest
|
||||
* import { Glob } from "effect"
|
||||
*
|
||||
* const name = "report[1].txt"
|
||||
*
|
||||
* Glob.match(Glob.make(name), name) // => false
|
||||
* Glob.match(Glob.make(Glob.escape(name)), name) // => true
|
||||
* ```
|
||||
*
|
||||
* @stability experimental
|
||||
* @category utils
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const escape = (input: string): string => input.replace(/[\\*?[\]{}]/g, "\\$&")
|
||||
@@ -290,6 +290,12 @@ export * as Formatter from "./Formatter.ts"
|
||||
*/
|
||||
export * as Function from "./Function.ts"
|
||||
|
||||
/**
|
||||
* @stability experimental
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export * as Glob from "./Glob.ts"
|
||||
|
||||
/**
|
||||
* @stability unstable
|
||||
* @since 4.0.0
|
||||
|
||||
@@ -0,0 +1,736 @@
|
||||
import * as Arr from "../Array.ts"
|
||||
import * as Effect from "../Effect.ts"
|
||||
import type * as FileSystem from "../FileSystem.ts"
|
||||
import * as Order from "../Order.ts"
|
||||
import type { PlatformError } from "../PlatformError.ts"
|
||||
import * as Predicate from "../Predicate.ts"
|
||||
|
||||
/** @internal */
|
||||
export type Token =
|
||||
| { readonly _tag: "Char"; readonly value: string }
|
||||
| { readonly _tag: "Any" }
|
||||
| { readonly _tag: "Star" }
|
||||
/** `ranges` holds inclusive code point pairs: `[from0, to0, from1, to1, ...]`. */
|
||||
| { readonly _tag: "Class"; readonly ranges: ReadonlyArray<number>; readonly negated: boolean }
|
||||
|
||||
/** @internal */
|
||||
export type Node =
|
||||
| { readonly _tag: "Globstar" }
|
||||
| { readonly _tag: "Literal"; readonly value: string }
|
||||
| { readonly _tag: "Wildcard"; readonly tokens: ReadonlyArray<Token>; readonly leadingDot: boolean }
|
||||
/** Ends one expanded pattern. */
|
||||
| { readonly _tag: "End"; readonly directoryOnly: boolean }
|
||||
|
||||
type States = ReadonlySet<number>
|
||||
|
||||
/**
|
||||
* Every expanded pattern's nodes laid out in one array, so a match state is an
|
||||
* index into `nodes` and `initial` holds the start of each pattern.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export interface Compiled {
|
||||
readonly nodes: ReadonlyArray<Node>
|
||||
readonly initial: States
|
||||
readonly dot: boolean
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// compilation
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
const maxExpansions = 10_000
|
||||
|
||||
const maxExpandedLength = 2 ** 22
|
||||
const maxBraceDepth = 64
|
||||
|
||||
/** @internal */
|
||||
export const compile = (patterns: ReadonlyArray<string>, dot: boolean): Compiled => {
|
||||
const nodes: Array<Node> = []
|
||||
const starts = new Set<number>()
|
||||
for (const pattern of patterns) {
|
||||
for (const expanded of expandBraces(pattern)) {
|
||||
const start = nodes.length
|
||||
if (compilePattern(expanded, nodes)) {
|
||||
starts.add(start)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { nodes, initial: closure(nodes, starts), dot }
|
||||
}
|
||||
|
||||
// Reject UNC paths rather than collapsing them into local absolute paths.
|
||||
const isUnc = (path: string): boolean => path.startsWith("//") && path[2] !== undefined && path[2] !== "/"
|
||||
|
||||
// Appends the pattern's nodes, or appends nothing when it can match no path
|
||||
const compilePattern = (pattern: string, nodes: Array<Node>): boolean => {
|
||||
if (pattern === "" || isUnc(pattern)) {
|
||||
return false
|
||||
}
|
||||
const raw = splitSegments(pattern)
|
||||
const globstar = raw.indexOf("**")
|
||||
if (globstar !== -1 && raw.some((segment, i) => i > globstar && (segment === "." || segment === ".."))) {
|
||||
return false
|
||||
}
|
||||
const { directory, segments } = normalize(raw)
|
||||
if (segments.length === 0) {
|
||||
return false
|
||||
}
|
||||
for (const segment of segments) {
|
||||
if (segment !== "**") {
|
||||
nodes.push(compileSegment(Array.from(segment)))
|
||||
} else if (nodes[nodes.length - 1] !== globstarNode) {
|
||||
nodes.push(globstarNode)
|
||||
}
|
||||
}
|
||||
nodes.push({ _tag: "End", directoryOnly: directory })
|
||||
return true
|
||||
}
|
||||
|
||||
const globstarNode: Node = { _tag: "Globstar" }
|
||||
|
||||
const splitSegments = (pattern: string): Array<string> => {
|
||||
const segments: Array<string> = []
|
||||
let start = 0
|
||||
for (let i = 0; i < pattern.length; i++) {
|
||||
if (pattern[i] === "\\") {
|
||||
i++
|
||||
} else if (pattern[i] === "/") {
|
||||
segments.push(pattern.slice(start, i))
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
segments.push(pattern.slice(start))
|
||||
return segments
|
||||
}
|
||||
|
||||
const drive = /^[A-Za-z]:/
|
||||
|
||||
const isDrive = (segment: string): boolean => segment.length === 2 && drive.test(segment)
|
||||
|
||||
// the root of an absolute path: `""` or a drive such as `C:/`
|
||||
const isRoot = (name: string): boolean => name === "" || (name.length === 3 && name[2] === "/" && drive.test(name))
|
||||
|
||||
const isAbsolute = (path: string): boolean => path.startsWith("/") || (path[2] === "/" && drive.test(path))
|
||||
|
||||
// Preserve absolute roots and a lone `.`; trailing `/` or `/.` marks a directory.
|
||||
const normalize = (raw: ReadonlyArray<string>): {
|
||||
readonly segments: Array<string>
|
||||
readonly directory: boolean
|
||||
} => {
|
||||
const segments: Array<string> = []
|
||||
let i = 0
|
||||
if (raw.length > 1 && (raw[0] === "" || isDrive(raw[0]))) {
|
||||
segments.push(raw[0] === "" ? "" : `${raw[0]}/`)
|
||||
i = 1
|
||||
}
|
||||
let directory = false
|
||||
for (; i < raw.length; i++) {
|
||||
const segment = raw[i]
|
||||
if (segment === "" || segment === ".") {
|
||||
directory = i === raw.length - 1 && segments.length > 0
|
||||
} else {
|
||||
segments.push(segment)
|
||||
directory = false
|
||||
}
|
||||
}
|
||||
if (segments.length === 0 && raw.includes(".")) {
|
||||
segments.push(".")
|
||||
}
|
||||
return { segments, directory }
|
||||
}
|
||||
|
||||
const compileSegment = (chars: ReadonlyArray<string>): Node => {
|
||||
const tokens: Array<Token> = []
|
||||
let literal = ""
|
||||
let magic = false
|
||||
// once a class fails to close, every later `[` in the segment is literal
|
||||
let classes = true
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const char = chars[i]
|
||||
if (char === "\\" && i + 1 < chars.length) {
|
||||
literal += chars[++i]
|
||||
tokens.push({ _tag: "Char", value: chars[i] })
|
||||
} else if (char === "*") {
|
||||
magic = true
|
||||
if (tokens[tokens.length - 1]?._tag !== "Star") {
|
||||
tokens.push({ _tag: "Star" })
|
||||
}
|
||||
} else if (char === "?") {
|
||||
magic = true
|
||||
tokens.push({ _tag: "Any" })
|
||||
} else if (char === "[" && classes) {
|
||||
const parsed = parseClass(chars, i)
|
||||
if (parsed === undefined) {
|
||||
classes = false
|
||||
literal += char
|
||||
tokens.push({ _tag: "Char", value: char })
|
||||
} else {
|
||||
magic = true
|
||||
tokens.push(parsed.token)
|
||||
i = parsed.end
|
||||
}
|
||||
} else {
|
||||
literal += char
|
||||
tokens.push({ _tag: "Char", value: char })
|
||||
}
|
||||
}
|
||||
if (!magic) {
|
||||
return { _tag: "Literal", value: literal }
|
||||
}
|
||||
const first = tokens[0]
|
||||
return { _tag: "Wildcard", tokens, leadingDot: first._tag === "Char" && first.value === "." }
|
||||
}
|
||||
|
||||
const range = (from: string, to: string): Array<number> => [from.codePointAt(0)!, to.codePointAt(0)!]
|
||||
|
||||
const posixClasses: Record<string, ReadonlyArray<number>> = {
|
||||
alnum: [...range("0", "9"), ...range("A", "Z"), ...range("a", "z")],
|
||||
alpha: [...range("A", "Z"), ...range("a", "z")],
|
||||
blank: [0x09, 0x09, 0x20, 0x20],
|
||||
cntrl: [0x00, 0x1f, 0x7f, 0x7f],
|
||||
digit: range("0", "9"),
|
||||
graph: [0x21, 0x7e],
|
||||
lower: range("a", "z"),
|
||||
print: [0x20, 0x7e],
|
||||
punct: [0x21, 0x2f, 0x3a, 0x40, 0x5b, 0x60, 0x7b, 0x7e],
|
||||
space: [0x09, 0x0d, 0x20, 0x20],
|
||||
upper: range("A", "Z"),
|
||||
word: [...range("0", "9"), ...range("A", "Z"), 0x5f, 0x5f, ...range("a", "z")],
|
||||
xdigit: [...range("0", "9"), ...range("A", "F"), ...range("a", "f")]
|
||||
}
|
||||
|
||||
// POSIX class names are at most six characters.
|
||||
const parsePosixClass = (
|
||||
chars: ReadonlyArray<string>,
|
||||
open: number
|
||||
): { readonly ranges: ReadonlyArray<number>; readonly end: number } | undefined => {
|
||||
for (let i = open + 2; i < chars.length && i <= open + 8; i++) {
|
||||
if (chars[i] === ":" && chars[i + 1] === "]") {
|
||||
const ranges = posixClasses[chars.slice(open + 2, i).join("")]
|
||||
return ranges === undefined ? undefined : { ranges, end: i + 1 }
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// Share class boundaries between brace expansion and segment compilation.
|
||||
const parseClass = (
|
||||
chars: ReadonlyArray<string>,
|
||||
open: number
|
||||
): { readonly token: Token; readonly end: number } | undefined => {
|
||||
let i = open + 1
|
||||
const negated = chars[i] === "!" || chars[i] === "^"
|
||||
if (negated) {
|
||||
i++
|
||||
}
|
||||
const ranges: Array<number> = []
|
||||
for (let first = true; i < chars.length; i++, first = false) {
|
||||
let char = chars[i]
|
||||
if (char === "/") {
|
||||
return undefined
|
||||
}
|
||||
if (char === "]" && !first) {
|
||||
return { token: { _tag: "Class", ranges, negated }, end: i }
|
||||
}
|
||||
if (char === "[" && chars[i + 1] === ":") {
|
||||
const posix = parsePosixClass(chars, i)
|
||||
if (posix !== undefined) {
|
||||
ranges.push(...posix.ranges)
|
||||
i = posix.end
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (char === "\\" && i + 1 < chars.length) {
|
||||
char = chars[++i]
|
||||
}
|
||||
if (chars[i + 1] === "-" && i + 2 < chars.length && chars[i + 2] !== "]") {
|
||||
let next = i + 2
|
||||
if (chars[next] === "/") {
|
||||
return undefined
|
||||
}
|
||||
if (chars[next] === "\\" && next + 1 < chars.length) {
|
||||
next++
|
||||
}
|
||||
ranges.push(...range(char, chars[next]))
|
||||
i = next
|
||||
continue
|
||||
}
|
||||
ranges.push(...range(char, char))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
type BraceSequence = ReadonlyArray<string | ReadonlyArray<BraceSequence>>
|
||||
|
||||
interface BraceGroup {
|
||||
readonly commas: ReadonlyArray<number>
|
||||
readonly close: number
|
||||
}
|
||||
|
||||
const expandBraces = (pattern: string): Array<string> => {
|
||||
const chars = Array.from(pattern)
|
||||
const groups = matchBraceGroups(chars)
|
||||
if (groups.size === 0) {
|
||||
return [pattern]
|
||||
}
|
||||
const sequence = parseBraceSequence(chars, 0, chars.length, groups, 0)
|
||||
if (sequence === undefined) {
|
||||
return [pattern]
|
||||
}
|
||||
const count = countExpansions(sequence)
|
||||
return count > maxExpansions || count * pattern.length > maxExpandedLength ? [pattern] : expandSequence(sequence)
|
||||
}
|
||||
|
||||
// Index expandable brace groups by opening position, ignoring bracket classes.
|
||||
const matchBraceGroups = (chars: ReadonlyArray<string>): Map<number, BraceGroup> => {
|
||||
const groups = new Map<number, BraceGroup>()
|
||||
const stack: Array<{ readonly open: number; readonly commas: Array<number> }> = []
|
||||
let classes = true
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const char = chars[i]
|
||||
if (char === "\\") {
|
||||
i++
|
||||
} else if (char === "/") {
|
||||
classes = true
|
||||
} else if (char === "[" && classes) {
|
||||
const parsed = parseClass(chars, i)
|
||||
if (parsed === undefined) {
|
||||
classes = false
|
||||
} else {
|
||||
i = parsed.end
|
||||
}
|
||||
} else if (char === "{") {
|
||||
stack.push({ open: i, commas: [] })
|
||||
} else if (char === ",") {
|
||||
stack[stack.length - 1]?.commas.push(i)
|
||||
} else if (char === "}") {
|
||||
const group = stack.pop()
|
||||
if (group !== undefined && group.commas.length > 0) {
|
||||
groups.set(group.open, { commas: group.commas, close: i })
|
||||
}
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
const parseBraceSequence = (
|
||||
chars: ReadonlyArray<string>,
|
||||
start: number,
|
||||
end: number,
|
||||
groups: Map<number, BraceGroup>,
|
||||
depth: number
|
||||
): BraceSequence | undefined => {
|
||||
if (depth > maxBraceDepth) {
|
||||
return undefined
|
||||
}
|
||||
const parts: Array<string | ReadonlyArray<BraceSequence>> = []
|
||||
let text = ""
|
||||
for (let i = start; i < end; i++) {
|
||||
const group = groups.get(i)
|
||||
if (group === undefined) {
|
||||
if (chars[i] === "\\" && i + 1 < end) {
|
||||
text += chars[i++]
|
||||
}
|
||||
text += chars[i]
|
||||
continue
|
||||
}
|
||||
const alternatives: Array<BraceSequence> = []
|
||||
let from = i + 1
|
||||
for (const to of [...group.commas, group.close]) {
|
||||
const alternative = parseBraceSequence(chars, from, to, groups, depth + 1)
|
||||
if (alternative === undefined) {
|
||||
return undefined
|
||||
}
|
||||
alternatives.push(alternative)
|
||||
from = to + 1
|
||||
}
|
||||
if (text !== "") {
|
||||
parts.push(text)
|
||||
text = ""
|
||||
}
|
||||
parts.push(alternatives)
|
||||
i = group.close
|
||||
}
|
||||
if (text !== "") {
|
||||
parts.push(text)
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
const countExpansions = (sequence: BraceSequence): number => {
|
||||
let count = 1
|
||||
for (const part of sequence) {
|
||||
if (typeof part !== "string") {
|
||||
let sum = 0
|
||||
for (const alternative of part) {
|
||||
sum += countExpansions(alternative)
|
||||
}
|
||||
count *= sum
|
||||
if (count > maxExpansions) {
|
||||
return Infinity
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
const expandSequence = (sequence: BraceSequence): Array<string> => {
|
||||
let out = [""]
|
||||
for (const part of sequence) {
|
||||
if (typeof part === "string") {
|
||||
out = out.map((prefix) => prefix + part)
|
||||
} else {
|
||||
const alternatives = part.flatMap(expandSequence)
|
||||
out = out.flatMap((prefix) => alternatives.map((alternative) => prefix + alternative))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// matching
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
const matchToken = (token: Token, char: string): boolean => {
|
||||
switch (token._tag) {
|
||||
case "Char":
|
||||
return token.value === char
|
||||
case "Any":
|
||||
return true
|
||||
case "Star":
|
||||
return false
|
||||
case "Class": {
|
||||
const code = char.codePointAt(0)!
|
||||
let found = false
|
||||
for (let i = 0; i < token.ranges.length && !found; i += 2) {
|
||||
found = code >= token.ranges[i] && code <= token.ranges[i + 1]
|
||||
}
|
||||
return found !== token.negated
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backtrack only to the last `*`, bounding retries by tokens × characters.
|
||||
const matchWildcard = (
|
||||
node: Extract<Node, { _tag: "Wildcard" }>,
|
||||
name: string,
|
||||
chars: ReadonlyArray<string>,
|
||||
dot: boolean
|
||||
): boolean => {
|
||||
if (name === "." || name === ".." || (name.startsWith(".") && !dot && !node.leadingDot)) {
|
||||
return false
|
||||
}
|
||||
const { tokens } = node
|
||||
let t = 0
|
||||
let c = 0
|
||||
let star = -1
|
||||
let resume = 0
|
||||
while (c < chars.length) {
|
||||
if (tokens[t]?._tag === "Star") {
|
||||
star = t++
|
||||
resume = c
|
||||
} else if (t < tokens.length && matchToken(tokens[t], chars[c])) {
|
||||
t++
|
||||
c++
|
||||
} else if (star !== -1) {
|
||||
t = star + 1
|
||||
c = ++resume
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
while (tokens[t]?._tag === "Star") {
|
||||
t++
|
||||
}
|
||||
return t === tokens.length
|
||||
}
|
||||
|
||||
// `**` also matches zero segments, so its successor is reachable too
|
||||
const closure = (nodes: ReadonlyArray<Node>, states: Set<number>): Set<number> => {
|
||||
for (const state of states) {
|
||||
if (nodes[state]._tag === "Globstar") {
|
||||
states.add(state + 1)
|
||||
}
|
||||
}
|
||||
return states
|
||||
}
|
||||
|
||||
interface Step {
|
||||
/** States reached by matching a literal or wildcard segment. */
|
||||
readonly explicit: States
|
||||
/** States reached by a `**` consuming the name. */
|
||||
readonly globstar: States
|
||||
}
|
||||
|
||||
const step = (compiled: Compiled, states: States, name: string): Step => {
|
||||
const explicit = new Set<number>()
|
||||
const viaGlobstar = new Set<number>()
|
||||
// only a literal segment can name the root of an absolute path
|
||||
const root = isRoot(name)
|
||||
let chars: ReadonlyArray<string> | undefined
|
||||
for (const state of states) {
|
||||
const node = compiled.nodes[state]
|
||||
switch (node._tag) {
|
||||
case "Globstar": {
|
||||
if (!root && name !== "." && name !== ".." && (compiled.dot || !name.startsWith("."))) {
|
||||
viaGlobstar.add(state)
|
||||
}
|
||||
break
|
||||
}
|
||||
case "Literal": {
|
||||
if (node.value === name) {
|
||||
explicit.add(state + 1)
|
||||
}
|
||||
break
|
||||
}
|
||||
case "Wildcard": {
|
||||
if (!root && matchWildcard(node, name, chars ??= Array.from(name), compiled.dot)) {
|
||||
explicit.add(state + 1)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return { explicit: closure(compiled.nodes, explicit), globstar: closure(compiled.nodes, viaGlobstar) }
|
||||
}
|
||||
|
||||
const union = (step: Step): States => {
|
||||
if (step.globstar.size === 0) {
|
||||
return step.explicit
|
||||
}
|
||||
const states = new Set(step.explicit)
|
||||
for (const state of step.globstar) {
|
||||
states.add(state)
|
||||
}
|
||||
return states
|
||||
}
|
||||
|
||||
const accepts = (compiled: Compiled, states: States, isDirectory: boolean): boolean => {
|
||||
for (const state of states) {
|
||||
const node = compiled.nodes[state]
|
||||
if (node._tag === "End" && (isDirectory || !node.directoryOnly)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const canDescend = (compiled: Compiled, states: States): boolean => {
|
||||
for (const state of states) {
|
||||
if (compiled.nodes[state]._tag !== "End") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const needsDirectory = (compiled: Compiled, states: States): boolean => {
|
||||
for (const state of states) {
|
||||
const node = compiled.nodes[state]
|
||||
if (node._tag === "End" && node.directoryOnly) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const match = (compiled: Compiled, path: string): boolean => {
|
||||
if (path === "" || isUnc(path)) {
|
||||
return false
|
||||
}
|
||||
const { directory, segments } = normalize(path.split("/"))
|
||||
let states = compiled.initial
|
||||
for (const name of segments) {
|
||||
states = union(step(compiled, states, name))
|
||||
if (states.size === 0) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return accepts(compiled, states, directory)
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// file system walk
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
const join = (parent: string, name: string): string => {
|
||||
if (parent === "") {
|
||||
return name === "" ? "/" : name
|
||||
}
|
||||
return parent.endsWith("/") ? parent + name : `${parent}/${name}`
|
||||
}
|
||||
|
||||
const isMissing = (error: PlatformError): boolean =>
|
||||
error.reason._tag === "NotFound" || error.reason._tag === "BadResource"
|
||||
|
||||
const isIgnorable = (error: PlatformError): boolean => isMissing(error) || error.reason._tag === "PermissionDenied"
|
||||
|
||||
// Node and Deno report `readLink` on a path that is not a link as "Unknown"
|
||||
const isNotLink = (error: PlatformError): boolean => isIgnorable(error) || error.reason._tag === "Unknown"
|
||||
|
||||
const byName = Order.mapInput(Order.String, (entry: FileSystem.DirectoryEntry) => entry.name)
|
||||
|
||||
/** @internal */
|
||||
export const make = (
|
||||
fs: Pick<FileSystem.FileSystem, "readDirectoryEntries" | "stat" | "readLink">
|
||||
): FileSystem.FileSystem["glob"] =>
|
||||
(pattern, options) => walk(fs, compile([pattern], options?.dot ?? false), options)
|
||||
|
||||
// Named directories (the root and those reached only through leading literal
|
||||
// segments) must be readable; unreadable wildcard-reached ones are skipped.
|
||||
const walk = Effect.fnUntraced(function*(
|
||||
fs: Pick<FileSystem.FileSystem, "readDirectoryEntries" | "stat" | "readLink">,
|
||||
compiled: Compiled,
|
||||
options?: {
|
||||
readonly root?: string | undefined
|
||||
readonly exclude?: ReadonlyArray<string> | undefined
|
||||
}
|
||||
): Effect.fn.Return<Array<string>, PlatformError> {
|
||||
if (compiled.initial.size === 0) {
|
||||
return []
|
||||
}
|
||||
const root = options?.root ?? ""
|
||||
const excludes = compile(options?.exclude ?? [], true)
|
||||
const excludeNeedsDirectory = excludes.nodes.some((node) => node._tag === "End" && node.directoryOnly)
|
||||
|
||||
const toFsPath = (relative: string): string =>
|
||||
isAbsolute(relative) ? relative : relative === "" ? (root === "" ? "." : root) : join(root, relative)
|
||||
|
||||
// Listings never contain `.`, `..`, or the root of an absolute pattern
|
||||
const isUnlisted = (value: string): boolean => value === "." || value === ".." || isRoot(value)
|
||||
|
||||
// Keep broken links so literal probes agree with directory listings.
|
||||
const probe = (
|
||||
parent: string,
|
||||
name: string,
|
||||
named: boolean
|
||||
): Effect.Effect<FileSystem.DirectoryEntry | undefined, PlatformError> => {
|
||||
const path = toFsPath(join(parent, name))
|
||||
return fs.stat(path).pipe(
|
||||
Effect.map((info) => info.type),
|
||||
Effect.catchReason("PlatformError", "NotFound", () =>
|
||||
fs.readLink(path).pipe(
|
||||
Effect.as("SymbolicLink" as const),
|
||||
Effect.catchIf(isNotLink, () => Effect.succeed(undefined))
|
||||
)),
|
||||
Effect.catchIf(named ? isMissing : isIgnorable, () => Effect.succeed(undefined)),
|
||||
Effect.map((type) => type === undefined ? undefined : { name, type })
|
||||
)
|
||||
}
|
||||
|
||||
// Probe leading literals without requiring permission to list their parent.
|
||||
const entries = (
|
||||
relative: string,
|
||||
states: States,
|
||||
named: boolean
|
||||
): Effect.Effect<{ readonly entries: Array<FileSystem.DirectoryEntry>; readonly named: boolean }, PlatformError> => {
|
||||
const literals = new Set<string>()
|
||||
let listed = !named
|
||||
for (const state of states) {
|
||||
const node = compiled.nodes[state]
|
||||
if (node._tag === "Literal") {
|
||||
literals.add(node.value)
|
||||
} else if (node._tag !== "End") {
|
||||
listed = true
|
||||
}
|
||||
}
|
||||
const probed = listed ? [...literals].filter(isUnlisted) : [...literals]
|
||||
return Effect.zipWith(
|
||||
listed
|
||||
? Effect.catchIf(
|
||||
fs.readDirectoryEntries(toFsPath(relative)),
|
||||
named ? isMissing : isIgnorable,
|
||||
() => Effect.succeed([])
|
||||
)
|
||||
: Effect.succeed([]),
|
||||
Effect.forEach(probed, (name) => probe(relative, name, named), { concurrency: 16 }),
|
||||
(listing, found) => ({
|
||||
entries: Arr.sort([...listing, ...found.filter(Predicate.isNotUndefined)], byName),
|
||||
named: named && !listed
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
interface Child {
|
||||
readonly relative: string
|
||||
readonly accepted: boolean
|
||||
readonly excluded: States
|
||||
readonly next: States | undefined
|
||||
}
|
||||
|
||||
const visit = Effect.fnUntraced(function*(
|
||||
{ name, type }: FileSystem.DirectoryEntry,
|
||||
parent: string,
|
||||
states: States,
|
||||
excluded: States
|
||||
): Effect.fn.Return<Child | undefined, PlatformError> {
|
||||
const result = step(compiled, states, name)
|
||||
const next = union(result)
|
||||
if (next.size === 0) {
|
||||
return undefined
|
||||
}
|
||||
const relative = join(parent, name)
|
||||
const nextExcluded = union(step(excludes, excluded, name))
|
||||
const descend = canDescend(compiled, next)
|
||||
const isDirectory = !descend && !needsDirectory(compiled, next) && !excludeNeedsDirectory
|
||||
? false
|
||||
: type !== "Unknown" && type !== "SymbolicLink"
|
||||
? type === "Directory"
|
||||
: yield* fs.stat(toFsPath(relative)).pipe(
|
||||
Effect.map((info) => info.type === "Directory"),
|
||||
Effect.catchIf(isIgnorable, () => Effect.succeed(false))
|
||||
)
|
||||
const accepted = accepts(compiled, next, isDirectory)
|
||||
if ((!accepted && (!isDirectory || !descend)) || accepts(excludes, nextExcluded, isDirectory)) {
|
||||
return undefined
|
||||
}
|
||||
const child = (next: States | undefined): Child => ({ relative, accepted, excluded: nextExcluded, next })
|
||||
if (!isDirectory || !descend) {
|
||||
return child(undefined)
|
||||
}
|
||||
if (result.globstar.size === 0) {
|
||||
return child(next)
|
||||
}
|
||||
// Follow symlinks only through explicit segments, not `**`.
|
||||
const followed = canDescend(compiled, result.explicit) ? result.explicit : undefined
|
||||
if (type !== "Unknown") {
|
||||
return child(type === "SymbolicLink" ? followed : next)
|
||||
}
|
||||
return yield* fs.readLink(toFsPath(relative)).pipe(
|
||||
Effect.as(child(followed)),
|
||||
Effect.catchIf(isNotLink, () => Effect.succeed(child(next)))
|
||||
)
|
||||
})
|
||||
|
||||
const directory = Effect.fnUntraced(function*(
|
||||
relative: string,
|
||||
states: States,
|
||||
excluded: States,
|
||||
named: boolean,
|
||||
out: Array<string>
|
||||
): Effect.fn.Return<void, PlatformError> {
|
||||
const listing = yield* entries(relative, states, named)
|
||||
const children = yield* Effect.forEach(
|
||||
listing.entries,
|
||||
(entry) => visit(entry, relative, states, excluded),
|
||||
{ concurrency: 16 }
|
||||
)
|
||||
for (const child of children) {
|
||||
if (child === undefined) {
|
||||
continue
|
||||
}
|
||||
if (child.accepted) {
|
||||
out.push(child.relative)
|
||||
}
|
||||
if (child.next !== undefined) {
|
||||
yield* directory(child.relative, child.next, child.excluded, listing.named, out)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const out: Array<string> = []
|
||||
yield* directory("", compiled.initial, excludes.initial, true, out)
|
||||
return out
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import { assert, expect, it } from "@effect/vitest"
|
||||
import { Array, ByteSize, Cause, Option, Result } from "effect"
|
||||
import * as Effect from "effect/Effect"
|
||||
import * as Fs from "effect/FileSystem"
|
||||
import * as Glob from "effect/Glob"
|
||||
import type * as Layer from "effect/Layer"
|
||||
import * as Stream from "effect/Stream"
|
||||
|
||||
@@ -14,11 +15,11 @@ export interface TestLayerOptions {
|
||||
readonly noFollow?: boolean
|
||||
}
|
||||
|
||||
const runWith = <E>(layer: Layer.Layer<Fs.FileSystem, E>) => <E2, A>(self: Effect.Effect<A, E2, Fs.FileSystem>) =>
|
||||
Effect.runPromise(Effect.provide(self, layer))
|
||||
|
||||
export const testLayer = <E>(layer: Layer.Layer<Fs.FileSystem, E>, options: TestLayerOptions = {}) => {
|
||||
const runPromise = <E2, A>(self: Effect.Effect<A, E2, Fs.FileSystem>) =>
|
||||
Effect.runPromise(
|
||||
Effect.provide(self, layer)
|
||||
)
|
||||
const runPromise = runWith(layer)
|
||||
|
||||
it("readFile", () =>
|
||||
runPromise(Effect.gen(function*() {
|
||||
@@ -625,4 +626,142 @@ export const testLayer = <E>(layer: Layer.Layer<Fs.FileSystem, E>, options: Test
|
||||
}).pipe(Effect.scoped)
|
||||
)
|
||||
)
|
||||
|
||||
it("readDirectoryEntries reports the type of each entry itself", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const dir = yield* fs.makeTempDirectoryScoped()
|
||||
yield* fs.makeDirectory(`${dir}/directory`)
|
||||
yield* fs.writeFileString(`${dir}/file`, "")
|
||||
yield* fs.symlink(`${dir}/directory`, `${dir}/link`)
|
||||
const entries = yield* fs.readDirectoryEntries(dir)
|
||||
expect([...entries].sort((a, b) => a.name.localeCompare(b.name))).toEqual([
|
||||
{ name: "directory", type: "Directory" },
|
||||
{ name: "file", type: "File" },
|
||||
{ name: "link", type: "SymbolicLink" }
|
||||
])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
testGlob(layer)
|
||||
}
|
||||
|
||||
export const testGlob = <E>(layer: Layer.Layer<Fs.FileSystem, E>) => {
|
||||
const runPromise = runWith(layer)
|
||||
|
||||
const globFixture = Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* fs.makeTempDirectoryScoped()
|
||||
for (const directory of ["src/sub", "a", "b", ".hidden", "node_modules/pkg"]) {
|
||||
yield* fs.makeDirectory(`${root}/${directory}`, { recursive: true })
|
||||
}
|
||||
for (
|
||||
const file of [
|
||||
"README.md",
|
||||
".env",
|
||||
"src/index.ts",
|
||||
"src/sub/deep.ts",
|
||||
"src/sub/deep.js",
|
||||
"a/x.ts",
|
||||
"b/y.ts",
|
||||
".hidden/secret.ts",
|
||||
"node_modules/pkg/index.ts"
|
||||
]
|
||||
) {
|
||||
yield* fs.writeFileString(`${root}/${file}`, "")
|
||||
}
|
||||
return root
|
||||
})
|
||||
|
||||
it.each<{
|
||||
readonly pattern: string
|
||||
readonly exclude?: ReadonlyArray<string>
|
||||
readonly dot?: boolean
|
||||
readonly expected: ReadonlyArray<string>
|
||||
}>([
|
||||
{
|
||||
pattern: "**/*.ts",
|
||||
expected: ["a/x.ts", "b/y.ts", "node_modules/pkg/index.ts", "src/index.ts", "src/sub/deep.ts"]
|
||||
},
|
||||
{ pattern: ".*", expected: [".env", ".hidden"] },
|
||||
{ pattern: "src/**", expected: ["src", "src/index.ts", "src/sub", "src/sub/deep.js", "src/sub/deep.ts"] },
|
||||
{ pattern: "*/", expected: ["a", "b", "node_modules", "src"] },
|
||||
{ pattern: "{a,b}/*.ts", expected: ["a/x.ts", "b/y.ts"] },
|
||||
{ pattern: "src/index.ts", expected: ["src/index.ts"] },
|
||||
{ pattern: "readme.*", expected: [] },
|
||||
{ pattern: "**/.", expected: [] },
|
||||
{ pattern: "src/index.ts/.", expected: [] },
|
||||
{ pattern: "src/.", expected: ["src"] },
|
||||
{
|
||||
pattern: "**/*.ts",
|
||||
exclude: ["node_modules"],
|
||||
dot: true,
|
||||
expected: [".hidden/secret.ts", "a/x.ts", "b/y.ts", "src/index.ts", "src/sub/deep.ts"]
|
||||
},
|
||||
{ pattern: "*", exclude: ["**/src/", "**/README.md/"], expected: ["README.md", "a", "b", "node_modules"] }
|
||||
])("glob $pattern (exclude: $exclude, dot: $dot)", ({ dot, exclude, expected, pattern }) =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* globFixture
|
||||
expect(yield* fs.glob(pattern, { root, exclude, dot })).toEqual(expected)
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
it("glob returns absolute paths for an absolute pattern", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = (yield* globFixture).replaceAll("\\", "/")
|
||||
expect(yield* fs.glob(`${Glob.escape(root)}/src/**/*.ts`)).toEqual([
|
||||
`${root}/src/index.ts`,
|
||||
`${root}/src/sub/deep.ts`
|
||||
])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
it("glob resolves .. segments against root", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* globFixture
|
||||
expect(yield* fs.glob("../a/*.ts", { root: `${root}/src` })).toEqual(["../a/x.ts"])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
it("glob returns an empty array for a missing root", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* fs.makeTempDirectoryScoped()
|
||||
expect(yield* fs.glob("**", { root: `${root}/missing` })).toEqual([])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
it("glob includes a dangling symlink named by a literal or wildcard", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* fs.makeTempDirectoryScoped()
|
||||
yield* fs.symlink(`${root}/missing`, `${root}/dangling`)
|
||||
assert.deepStrictEqual(yield* fs.glob("dangling", { root }), ["dangling"])
|
||||
assert.deepStrictEqual(yield* fs.glob("dang*", { root }), ["dangling"])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
|
||||
it("glob follows a named symlink but not through **", () =>
|
||||
runPromise(
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* Fs.FileSystem
|
||||
const root = yield* fs.makeTempDirectoryScoped()
|
||||
yield* fs.makeDirectory(`${root}/target`)
|
||||
yield* fs.writeFileString(`${root}/target/file.ts`, "")
|
||||
yield* fs.symlink(`${root}/target`, `${root}/link`)
|
||||
// a link back to the root would loop if `**` followed it
|
||||
yield* fs.symlink(root, `${root}/target/loop`)
|
||||
expect(yield* fs.glob("**", { root })).toEqual(["link", "target", "target/file.ts", "target/loop"])
|
||||
expect(yield* fs.glob("link/*.ts", { root })).toEqual(["link/file.ts"])
|
||||
}).pipe(Effect.scoped)
|
||||
))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { assert, describe, it } from "@effect/vitest"
|
||||
import { ByteSize, Effect, Exit, FileSystem, Option, PlatformError } from "effect"
|
||||
|
||||
const info = (type: FileSystem.File.Type): FileSystem.File.Info => ({
|
||||
type,
|
||||
mtime: Option.none(),
|
||||
atime: Option.none(),
|
||||
birthtime: Option.none(),
|
||||
dev: 0n,
|
||||
ino: Option.none(),
|
||||
mode: 0,
|
||||
nlink: Option.none(),
|
||||
uid: Option.none(),
|
||||
gid: Option.none(),
|
||||
rdev: Option.none(),
|
||||
size: ByteSize.bytes(0),
|
||||
blksize: Option.none(),
|
||||
blocks: Option.none()
|
||||
})
|
||||
|
||||
const failure = (_tag: PlatformError.SystemErrorTag, method: string, path: string) =>
|
||||
PlatformError.systemError({ _tag, module: "FileSystem", method, pathOrDescriptor: path })
|
||||
|
||||
// Each directory holds the file `x.ts`. Listings report every entry as
|
||||
// `"Unknown"`, so `glob` learns entry types from `stat` and `readLink`.
|
||||
const makeFileSystem = (overrides: {
|
||||
readonly directories?: Record<string, ReadonlyArray<string>>
|
||||
readonly readDirectory?: (path: string) => Effect.Effect<Array<string>, PlatformError.PlatformError> | undefined
|
||||
readonly stat?: (path: string) => Effect.Effect<FileSystem.File.Info, PlatformError.PlatformError> | undefined
|
||||
readonly readLink?: (path: string) => Effect.Effect<string, PlatformError.PlatformError>
|
||||
}) => {
|
||||
const directories = overrides.directories ?? { ".": ["a"], "a": ["x.ts"] }
|
||||
const readDirectory = (path: string) =>
|
||||
overrides.readDirectory?.(path) ??
|
||||
(path in directories
|
||||
? Effect.succeed([...directories[path]])
|
||||
: Effect.fail(failure("NotFound", "readDirectory", path)))
|
||||
return FileSystem.make({
|
||||
...FileSystem.makeNoop({}),
|
||||
readDirectory,
|
||||
readDirectoryEntries: (path) =>
|
||||
Effect.map(readDirectory(path), (names) => names.map((name) => ({ name, type: "Unknown" as const }))),
|
||||
stat: (path) =>
|
||||
overrides.stat?.(path) ??
|
||||
(path in directories
|
||||
? Effect.succeed(info("Directory"))
|
||||
: path.endsWith("/x.ts") && path.slice(0, -5) in directories
|
||||
? Effect.succeed(info("File"))
|
||||
: Effect.fail(failure("NotFound", "stat", path))),
|
||||
// Node and Deno report EINVAL as "Unknown" for a path that is not a link
|
||||
readLink: overrides.readLink ?? ((path) => Effect.fail(failure("Unknown", "readLink", path)))
|
||||
})
|
||||
}
|
||||
|
||||
// `secret` and `src` are named by literal pattern segments below, and `open`
|
||||
// is only reached through wildcards
|
||||
const permissionTree = {
|
||||
".": ["open", "secret", "src"],
|
||||
"open": ["x.ts"],
|
||||
"secret": ["x.ts"],
|
||||
"src": ["x.ts"]
|
||||
}
|
||||
|
||||
describe("FileSystem", () => {
|
||||
describe("derived glob", () => {
|
||||
it.effect("traverses directories whose readLink reports that they are not links", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({})
|
||||
assert.deepStrictEqual(yield* fs.glob("**"), ["a", "a/x.ts"])
|
||||
}))
|
||||
|
||||
it.effect.each([".", "../*", "/x"])(
|
||||
"fails when probing %s fails unexpectedly",
|
||||
(pattern) =>
|
||||
Effect.gen(function*() {
|
||||
const error = failure("Unknown", "stat", pattern)
|
||||
const fs = makeFileSystem({
|
||||
stat: (path) => [".", "..", "/"].includes(path) ? Effect.fail(error) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* Effect.exit(fs.glob(pattern)), Exit.fail(error))
|
||||
})
|
||||
)
|
||||
|
||||
it.effect("fails when readLink fails unexpectedly", () =>
|
||||
Effect.gen(function*() {
|
||||
const error = failure("Busy", "readLink", "a")
|
||||
const fs = makeFileSystem({ readLink: () => Effect.fail(error) })
|
||||
assert.deepStrictEqual(yield* Effect.exit(fs.glob("**")), Exit.fail(error))
|
||||
}))
|
||||
|
||||
it.effect("propagates defects from probing stat", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({ stat: (path) => path === "." ? Effect.die("boom") : undefined })
|
||||
assert.isTrue(Exit.hasDies(yield* Effect.exit(fs.glob("."))))
|
||||
}))
|
||||
|
||||
it.effect.each<{ readonly pattern: string; readonly root?: string }>([
|
||||
{ pattern: "**", root: "secret" },
|
||||
{ pattern: "secret/**" },
|
||||
{ pattern: "secret/*.ts" }
|
||||
])(
|
||||
"fails when a directory named by $pattern (root: $root) cannot be read",
|
||||
({ pattern, root }) =>
|
||||
Effect.gen(function*() {
|
||||
const error = failure("PermissionDenied", "readDirectory", "secret")
|
||||
const fs = makeFileSystem({
|
||||
directories: permissionTree,
|
||||
readDirectory: (path) => path === "secret" ? Effect.fail(error) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* Effect.exit(fs.glob(pattern, { root })), Exit.fail(error))
|
||||
})
|
||||
)
|
||||
|
||||
it.effect("fails when stat denies access to a leading literal", () =>
|
||||
Effect.gen(function*() {
|
||||
const error = failure("PermissionDenied", "stat", "a")
|
||||
const fs = makeFileSystem({
|
||||
stat: (path) => path === "a" ? Effect.fail(error) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* Effect.exit(fs.glob("a/*.ts")), Exit.fail(error))
|
||||
}))
|
||||
|
||||
it.effect("returns an empty array when the root is a file", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({
|
||||
readDirectory: (path) =>
|
||||
path === "a/x.ts" ? Effect.fail(failure("BadResource", "readDirectory", path)) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* fs.glob("**", { root: "a/x.ts" }), [])
|
||||
}))
|
||||
|
||||
it.effect("reads a literal prefix whose parent cannot be listed", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({
|
||||
directories: permissionTree,
|
||||
readDirectory: (path) =>
|
||||
path === "." ? Effect.fail(failure("PermissionDenied", "readDirectory", path)) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* fs.glob("src/*.ts"), ["src/x.ts"])
|
||||
}))
|
||||
|
||||
it.effect("skips unreadable directories reached through wildcards and missing literal prefixes", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({
|
||||
directories: permissionTree,
|
||||
readDirectory: (path) =>
|
||||
path === "secret" ? Effect.fail(failure("PermissionDenied", "readDirectory", path)) : undefined
|
||||
})
|
||||
assert.deepStrictEqual(yield* fs.glob("*/x.ts"), ["open/x.ts", "src/x.ts"])
|
||||
assert.deepStrictEqual(yield* fs.glob("missing/**"), [])
|
||||
}))
|
||||
|
||||
it.effect("propagates defects from readLink", () =>
|
||||
Effect.gen(function*() {
|
||||
const fs = makeFileSystem({ readLink: () => Effect.die("boom") })
|
||||
assert.isTrue(Exit.hasDies(yield* Effect.exit(fs.glob("**"))))
|
||||
}))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it } from "@effect/vitest"
|
||||
import { assertFalse, assertTrue } from "@effect/vitest/utils"
|
||||
import { Glob } from "effect"
|
||||
|
||||
const cases: ReadonlyArray<{
|
||||
readonly pattern: string
|
||||
readonly dot?: boolean
|
||||
readonly matches: ReadonlyArray<string>
|
||||
readonly rejects: ReadonlyArray<string>
|
||||
}> = [
|
||||
{ pattern: "a.ts", matches: ["a.ts", "./a.ts"], rejects: ["b.ts", "dir/a.ts"] },
|
||||
{ pattern: "*.ts", matches: ["a.ts", "a.b.ts"], rejects: [".a.ts", "dir/a.ts", "a.js"] },
|
||||
{ pattern: "?.ts", matches: ["a.ts"], rejects: ["ab.ts", ".ts"] },
|
||||
{ pattern: "**/*.ts", matches: ["a.ts", "a/b/c.ts"], rejects: [".a.ts", "a/.b/c.ts"] },
|
||||
{ pattern: "a/**", matches: ["a", "a/b/c"], rejects: ["ab"] },
|
||||
{ pattern: "a/**/b", matches: ["a/b", "a/x/y/b"], rejects: ["a/x"] },
|
||||
{ pattern: ".*", matches: [".env"], rejects: ["env", ".", ".."] },
|
||||
{ pattern: "*", dot: true, matches: [".env", "a"], rejects: [".", "..", "a/b"] },
|
||||
{ pattern: "[!a-c]x", matches: ["dx"], rejects: ["ax", "/x"] },
|
||||
{ pattern: "[[:digit:]]x", matches: ["1x"], rejects: ["ax"] },
|
||||
{ pattern: "[😀-😂]x", matches: ["😁x"], rejects: ["😃x"] },
|
||||
{ pattern: "{a,{b,c}d}", matches: ["a", "bd", "cd"], rejects: ["b", "d"] },
|
||||
{ pattern: "{a,b/c}/x", matches: ["a/x", "b/c/x"], rejects: ["b/x"] },
|
||||
{ pattern: "{a}", matches: ["{a}"], rejects: ["a"] },
|
||||
{ pattern: "[{a,b}]", matches: ["{", ",", "}", "a", "b"], rejects: ["[a]", "c"] },
|
||||
{ pattern: "[]{a,b}]", matches: ["]", "{", "b"], rejects: ["[]a]", "c"] },
|
||||
{ pattern: "{[,]x,b}", matches: [",x", "b"], rejects: ["[", "]x"] },
|
||||
{ pattern: "[ab", matches: ["[ab"], rejects: ["a"] },
|
||||
{ pattern: "\\*.ts", matches: ["*.ts"], rejects: ["a.ts"] },
|
||||
{ pattern: "!(a)", matches: ["!(a)"], rejects: ["b"] },
|
||||
{ pattern: "dir/", matches: ["dir/"], rejects: ["dir", "dir/a"] },
|
||||
{ pattern: "a/.", matches: ["a/"], rejects: ["a"] },
|
||||
{ pattern: "**/.", matches: [], rejects: ["a", "a/", "a/b"] },
|
||||
{ pattern: "**/..", matches: [], rejects: ["..", "a/.."] },
|
||||
{ pattern: "/abs/*.ts", matches: ["/abs/a.ts"], rejects: ["abs/a.ts"] },
|
||||
{ pattern: "C:/x/*", matches: ["C:/x/a"], rejects: ["x/a"] },
|
||||
{ pattern: "//server/share/*", matches: [], rejects: ["//server/share/a", "/server/share/a"] },
|
||||
{ pattern: "/server/share/*", matches: ["/server/share/a"], rejects: ["//server/share/a"] },
|
||||
{ pattern: "**", matches: ["a/b"], rejects: ["/a", "C:/a"] }
|
||||
]
|
||||
|
||||
describe("Glob", () => {
|
||||
describe("match", () => {
|
||||
for (const { dot, matches, pattern, rejects } of cases) {
|
||||
it(`${pattern}${dot ? " (dot)" : ""}`, () => {
|
||||
const glob = Glob.make(pattern, { dot })
|
||||
for (const path of matches) {
|
||||
assertTrue(Glob.match(glob, path), `expected ${pattern} to match ${path}`)
|
||||
}
|
||||
for (const path of rejects) {
|
||||
assertFalse(Glob.match(glob, path), `expected ${pattern} not to match ${path}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
it("matches braces literally when they expand to more than 10,000 alternatives", () => {
|
||||
assertTrue(Glob.match(Glob.make("{a,b}".repeat(13)), "b".repeat(13)))
|
||||
const pattern = "{a,b}".repeat(20)
|
||||
const glob = Glob.make(pattern)
|
||||
assertFalse(Glob.match(glob, "a".repeat(20)))
|
||||
assertTrue(Glob.match(glob, pattern))
|
||||
})
|
||||
|
||||
it("matches repeated wildcards without exponential backtracking", () => {
|
||||
const glob = Glob.make("*a".repeat(15) + "b")
|
||||
const start = performance.now()
|
||||
assertFalse(Glob.match(glob, "a".repeat(30)))
|
||||
assertTrue(performance.now() - start < 500)
|
||||
})
|
||||
|
||||
it("compiles adversarial patterns without overflowing", () => {
|
||||
const brackets = "[{".repeat(20_000)
|
||||
assertTrue(Glob.match(Glob.make(brackets), brackets))
|
||||
const nested = "{a,".repeat(100) + "b" + "}".repeat(100)
|
||||
assertTrue(Glob.match(Glob.make(nested), nested))
|
||||
})
|
||||
})
|
||||
|
||||
it("escape makes special characters literal", () => {
|
||||
const input = "a*b?c[d]{e,f}\\g"
|
||||
const glob = Glob.make(Glob.escape(input))
|
||||
assertTrue(Glob.match(glob, input))
|
||||
assertFalse(Glob.match(glob, "axbxcdeg"))
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@
|
||||
* @stability unstable
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import { copy as denoCopy, expandGlob, walk } from "@std/fs"
|
||||
import { copy as denoCopy, walk } from "@std/fs"
|
||||
import { relative } from "@std/path"
|
||||
import * as ByteSize from "effect/ByteSize"
|
||||
import * as Effect from "effect/Effect"
|
||||
@@ -77,16 +77,6 @@ const chmod: FileSystem.FileSystem["chmod"] = (path, mode) => tryPromise("chmod"
|
||||
const chown: FileSystem.FileSystem["chown"] = (path, uid, gid) =>
|
||||
tryPromise("chown", path, () => Deno.chown(path, uid, gid))
|
||||
|
||||
const glob: FileSystem.FileSystem["glob"] = (pattern, options) =>
|
||||
Effect.map(
|
||||
collectAsyncIterable("glob", pattern, () =>
|
||||
expandGlob(pattern, {
|
||||
root: options?.root ?? Deno.cwd(),
|
||||
exclude: options?.exclude ? [...options.exclude] : []
|
||||
})),
|
||||
(entries) => entries.map((entry) => entry.path)
|
||||
)
|
||||
|
||||
const link: FileSystem.FileSystem["link"] = (existingPath, newPath) =>
|
||||
tryPromise("link", existingPath, () => Deno.link(existingPath, newPath))
|
||||
|
||||
@@ -151,22 +141,28 @@ const openOptions = (flag: FileSystem.OpenFlag = "r", mode?: number): Deno.OpenO
|
||||
}
|
||||
}
|
||||
|
||||
const makeFileInfo = (info: Deno.FileInfo): FileSystem.File.Info => ({
|
||||
type: info.isFile ?
|
||||
// `Deno.DirEntry` only reports the first three flags
|
||||
const fileType = (info: Deno.DirEntry | Deno.FileInfo): FileSystem.File.Type => {
|
||||
const flags: Partial<Deno.FileInfo> = info
|
||||
return info.isFile ?
|
||||
"File" :
|
||||
info.isDirectory ?
|
||||
"Directory" :
|
||||
info.isSymlink ?
|
||||
"SymbolicLink" :
|
||||
info.isBlockDevice ?
|
||||
flags.isBlockDevice ?
|
||||
"BlockDevice" :
|
||||
info.isCharDevice ?
|
||||
flags.isCharDevice ?
|
||||
"CharacterDevice" :
|
||||
info.isFifo ?
|
||||
flags.isFifo ?
|
||||
"FIFO" :
|
||||
info.isSocket ?
|
||||
flags.isSocket ?
|
||||
"Socket" :
|
||||
"Unknown",
|
||||
"Unknown"
|
||||
}
|
||||
|
||||
const makeFileInfo = (info: Deno.FileInfo): FileSystem.File.Info => ({
|
||||
type: fileType(info),
|
||||
mtime: Option.fromNullishOr(info.mtime),
|
||||
atime: Option.fromNullishOr(info.atime),
|
||||
birthtime: Option.fromNullishOr(info.birthtime),
|
||||
@@ -412,6 +408,12 @@ const readDirectory: FileSystem.FileSystem["readDirectory"] = (path, options) =>
|
||||
)
|
||||
}
|
||||
|
||||
const readDirectoryEntries = (path: string) =>
|
||||
Effect.map(
|
||||
collectAsyncIterable("readDirectoryEntries", path, () => Deno.readDir(path)),
|
||||
(entries) => entries.map((entry): FileSystem.DirectoryEntry => ({ name: entry.name, type: fileType(entry) }))
|
||||
)
|
||||
|
||||
const readFile: FileSystem.FileSystem["readFile"] = (path) =>
|
||||
tryPromise("readFile", path, (signal) => Deno.readFile(path, { signal }))
|
||||
|
||||
@@ -519,7 +521,6 @@ const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend),
|
||||
chown,
|
||||
copy,
|
||||
copyFile,
|
||||
glob,
|
||||
link,
|
||||
makeDirectory,
|
||||
makeTempDirectory,
|
||||
@@ -528,6 +529,7 @@ const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend),
|
||||
makeTempFileScoped,
|
||||
open,
|
||||
readDirectory,
|
||||
readDirectoryEntries,
|
||||
readFile,
|
||||
readLink,
|
||||
realPath,
|
||||
|
||||
@@ -129,21 +129,6 @@ const chown = (() => {
|
||||
return (path: string, uid: number, gid: number) => nodeChown(path, uid, gid)
|
||||
})()
|
||||
|
||||
// == glob
|
||||
|
||||
const glob = ((): FileSystem.FileSystem["glob"] => {
|
||||
const nodeGlob = effectify(
|
||||
NFS.glob,
|
||||
handleErrnoException("FileSystem", "glob"),
|
||||
handleBadArgument("glob")
|
||||
)
|
||||
return (pattern: string, options) =>
|
||||
nodeGlob(pattern, {
|
||||
cwd: options?.root,
|
||||
exclude: options?.exclude
|
||||
})
|
||||
})()
|
||||
|
||||
// == link
|
||||
|
||||
const link = (() => {
|
||||
@@ -526,6 +511,16 @@ const readDirectory: FileSystem.FileSystem["readDirectory"] = (path, options) =>
|
||||
catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err as any, [path])
|
||||
})
|
||||
|
||||
const readDirectoryEntries = (path: string) =>
|
||||
Effect.tryPromise({
|
||||
try: () => NFS.promises.readdir(path, { withFileTypes: true }),
|
||||
catch: (err) => handleErrnoException("FileSystem", "readDirectoryEntries")(err as any, [path])
|
||||
}).pipe(
|
||||
Effect.map((entries) =>
|
||||
entries.map((entry): FileSystem.DirectoryEntry => ({ name: entry.name, type: fileType(entry) }))
|
||||
)
|
||||
)
|
||||
|
||||
// == readFile
|
||||
|
||||
const readFile = (path: string) =>
|
||||
@@ -578,24 +573,27 @@ const rename = (() => {
|
||||
|
||||
// == stat
|
||||
|
||||
const fileType = (stat: NFS.BigIntStats | NFS.Dirent): FileSystem.File.Type =>
|
||||
stat.isFile() ?
|
||||
"File" :
|
||||
stat.isDirectory() ?
|
||||
"Directory" :
|
||||
stat.isSymbolicLink() ?
|
||||
"SymbolicLink" :
|
||||
stat.isBlockDevice() ?
|
||||
"BlockDevice" :
|
||||
stat.isCharacterDevice() ?
|
||||
"CharacterDevice" :
|
||||
stat.isFIFO() ?
|
||||
"FIFO" :
|
||||
stat.isSocket() ?
|
||||
"Socket" :
|
||||
"Unknown"
|
||||
|
||||
const makeFileInfo = (stat: NFS.BigIntStats): Effect.Effect<FileSystem.File.Info, Error.PlatformError> =>
|
||||
Effect.try({
|
||||
try: (): FileSystem.File.Info => ({
|
||||
type: stat.isFile() ?
|
||||
"File" :
|
||||
stat.isDirectory() ?
|
||||
"Directory" :
|
||||
stat.isSymbolicLink() ?
|
||||
"SymbolicLink" :
|
||||
stat.isBlockDevice() ?
|
||||
"BlockDevice" :
|
||||
stat.isCharacterDevice() ?
|
||||
"CharacterDevice" :
|
||||
stat.isFIFO() ?
|
||||
"FIFO" :
|
||||
stat.isSocket() ?
|
||||
"Socket" :
|
||||
"Unknown",
|
||||
type: fileType(stat),
|
||||
mtime: Option.fromNullishOr(stat.mtime),
|
||||
atime: Option.fromNullishOr(stat.atime),
|
||||
birthtime: Option.fromNullishOr(stat.birthtime),
|
||||
@@ -745,7 +743,6 @@ const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend),
|
||||
chown,
|
||||
copy,
|
||||
copyFile,
|
||||
glob,
|
||||
link,
|
||||
makeDirectory,
|
||||
makeTempDirectory,
|
||||
@@ -754,6 +751,7 @@ const makeFileSystem = Effect.map(Effect.serviceOption(FileSystem.WatchBackend),
|
||||
makeTempFileScoped,
|
||||
open,
|
||||
readDirectory,
|
||||
readDirectoryEntries,
|
||||
readFile,
|
||||
readLink,
|
||||
realPath,
|
||||
|
||||
@@ -5,13 +5,14 @@ import * as Deferred from "effect/Deferred"
|
||||
import * as Effect from "effect/Effect"
|
||||
import * as Fiber from "effect/Fiber"
|
||||
import * as FileSystem from "effect/FileSystem"
|
||||
import * as Layer from "effect/Layer"
|
||||
import * as Option from "effect/Option"
|
||||
import * as Stream from "effect/Stream"
|
||||
import * as TestClock from "effect/testing/TestClock"
|
||||
import * as NFS from "node:fs"
|
||||
import * as Path from "node:path"
|
||||
import { afterEach, beforeEach, vi } from "vitest"
|
||||
import { testLayer } from "../../../effect/test/FileSystem.test-utils.ts"
|
||||
import { testGlob, testLayer } from "../../../effect/test/FileSystem.test-utils.ts"
|
||||
|
||||
const startWatch = Effect.fnUntraced(function*<E, R>(
|
||||
fs: FileSystem.FileSystem,
|
||||
@@ -45,6 +46,24 @@ const startWatch = Effect.fnUntraced(function*<E, R>(
|
||||
return fiber
|
||||
})
|
||||
|
||||
// A file system whose listings report every entry as `"Unknown"`, so `glob`
|
||||
// learns entry types from `stat` and `readLink` alone.
|
||||
const untypedLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function*() {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
return FileSystem.make({
|
||||
...fs,
|
||||
readDirectoryEntries: (path) =>
|
||||
Effect.map(fs.readDirectory(path), (names) => names.map((name) => ({ name, type: "Unknown" as const })))
|
||||
})
|
||||
})
|
||||
).pipe(Layer.provide(NodeFileSystem.layer))
|
||||
|
||||
describe("FileSystem without typed directory listings", { concurrent: false }, () => {
|
||||
testGlob(untypedLayer)
|
||||
})
|
||||
|
||||
describe("FileSystem", { concurrent: false }, () => {
|
||||
testLayer(NodeFileSystem.layer, { noFollow: process.platform !== "win32" })
|
||||
|
||||
|
||||
Reference in New Issue
Block a user