|
| 1 | +import fs from 'node:fs' |
| 2 | +import fsp from 'node:fs/promises' |
| 3 | +import Path from 'node:path' |
| 4 | +import glob from 'it-glob' |
| 5 | +import { InvalidParametersError } from '../errors.js' |
| 6 | +import type { MtimeLike } from 'ipfs-unixfs' |
| 7 | +import type { ImportCandidateStream } from 'ipfs-unixfs-importer' |
| 8 | + |
| 9 | +export interface GlobSourceOptions { |
| 10 | + /** |
| 11 | + * Include .dot files in matched paths |
| 12 | + */ |
| 13 | + hidden?: boolean |
| 14 | + |
| 15 | + /** |
| 16 | + * follow symlinks |
| 17 | + */ |
| 18 | + followSymlinks?: boolean |
| 19 | + |
| 20 | + /** |
| 21 | + * Preserve mode |
| 22 | + */ |
| 23 | + preserveMode?: boolean |
| 24 | + |
| 25 | + /** |
| 26 | + * Preserve mtime |
| 27 | + */ |
| 28 | + preserveMtime?: boolean |
| 29 | + |
| 30 | + /** |
| 31 | + * mode to use - if preserveMode is true this will be ignored |
| 32 | + */ |
| 33 | + mode?: number |
| 34 | + |
| 35 | + /** |
| 36 | + * mtime to use - if preserveMtime is true this will be ignored |
| 37 | + */ |
| 38 | + mtime?: MtimeLike |
| 39 | +} |
| 40 | + |
| 41 | +export interface GlobSourceResult { |
| 42 | + path: string |
| 43 | + content: AsyncIterable<Uint8Array> | undefined |
| 44 | + mode: number | undefined |
| 45 | + mtime: MtimeLike | undefined |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Create an async iterator that yields paths that match requested glob pattern |
| 50 | + */ |
| 51 | +export async function * globSource (cwd: string, pattern: string, options: GlobSourceOptions = {}): ImportCandidateStream { |
| 52 | + if (typeof pattern !== 'string') { |
| 53 | + throw new InvalidParametersError('Pattern must be a string') |
| 54 | + } |
| 55 | + |
| 56 | + if (!Path.isAbsolute(cwd)) { |
| 57 | + cwd = Path.resolve(process.cwd(), cwd) |
| 58 | + } |
| 59 | + |
| 60 | + const globOptions = Object.assign({}, { |
| 61 | + nodir: false, |
| 62 | + realpath: false, |
| 63 | + absolute: true, |
| 64 | + dot: Boolean(options.hidden), |
| 65 | + follow: options.followSymlinks != null ? options.followSymlinks : true |
| 66 | + }) |
| 67 | + |
| 68 | + for await (const p of glob(cwd, pattern, globOptions)) { |
| 69 | + const stat = await fsp.stat(p) |
| 70 | + |
| 71 | + let mode = options.mode |
| 72 | + |
| 73 | + if (options.preserveMode === true) { |
| 74 | + mode = stat.mode |
| 75 | + } |
| 76 | + |
| 77 | + let mtime = options.mtime |
| 78 | + |
| 79 | + if (options.preserveMtime === true) { |
| 80 | + mtime = stat.mtime |
| 81 | + } |
| 82 | + |
| 83 | + yield { |
| 84 | + path: toPosix(p.replace(cwd, '')), |
| 85 | + content: stat.isFile() ? fs.createReadStream(p) : undefined, |
| 86 | + mode, |
| 87 | + mtime |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +const toPosix = (path: string): string => path.replace(/\\/g, '/') |
0 commit comments