import { statSync, readdirSync, stat, readdir, Stats } from 'fs' import { join } from 'path' import { promisify } from 'util' // TODO: Not sure of a good way to keep the async & sync impls in sync. const statP = promisify(stat) const readdirP = promisify(readdir) export { crawl, crawlSync } type Cache = Map type Predicate = (path: string, stats: Stats) => boolean interface AnyOptions { filter?: Predicate depth?: number } interface Options { filter: Predicate depth: number } const defaultOptions: Options = { filter: () => true, depth: Infinity, } // map of absolute paths -> fs.Stats async function crawl( path: string, options: AnyOptions = {}, currentDepth = 0 ): Promise { const { filter, depth }: Options = { ...defaultOptions, ...options } let cache: Cache = new Map() // Bail if exceed max depth if (currentDepth > depth) { return cache } const stats = await statP(path) const keep = filter(path, stats) if (stats.isFile()) { if (keep) { cache.set(path, stats) } } else if (stats.isDirectory()) { // Don't add enty point dir if (currentDepth > 0 && keep) { cache.set(path, stats) } for (const childPath of await readdirP(path)) { cache = new Map([ ...cache, ...(await crawl( join(path, childPath), options, currentDepth + 1 )), ]) } } return cache } // map of absolute paths -> fs.Stats function crawlSync( path: string, options: AnyOptions = defaultOptions, currentDepth = 0 ): Cache { const { filter, depth }: Options = { ...defaultOptions, ...options } let cache = new Map() // Bail if exceed max depth if (currentDepth > depth) { return cache } const stats = statSync(path) const keep = filter(path, stats) if (stats.isFile()) { if (keep) { cache.set(path, stats) } } else if (stats.isDirectory()) { // Don't add enty point dir if (currentDepth > 0 && keep) { cache.set(path, stats) } for (const childPath of readdirSync(path)) { cache = new Map([ ...cache, ...crawlSync(join(path, childPath), options, currentDepth + 1), ]) } } return cache }