| 1 | import { Pattern, MicromatchOptions, PatternRe } from '../../types'; |
| 2 | import * as utils from '../../utils'; |
| 3 | import Settings from '../../settings'; |
| 4 | |
| 5 | export type PatternSegment = StaticPatternSegment | DynamicPatternSegment; |
| 6 | |
| 7 | type StaticPatternSegment = { |
| 8 | dynamic: false; |
| 9 | pattern: Pattern; |
| 10 | }; |
| 11 | |
| 12 | type DynamicPatternSegment = { |
| 13 | dynamic: true; |
| 14 | pattern: Pattern; |
| 15 | patternRe: PatternRe; |
| 16 | }; |
| 17 | |
| 18 | export type PatternSection = PatternSegment[]; |
| 19 | |
| 20 | export type PatternInfo = { |
| 21 | /** |
| 22 | * Indicates that the pattern has a globstar (more than a single section). |
| 23 | */ |
| 24 | complete: boolean; |
| 25 | pattern: Pattern; |
| 26 | segments: PatternSegment[]; |
| 27 | sections: PatternSection[]; |
| 28 | }; |
| 29 | |
| 30 | export default abstract class Matcher { |
| 31 | protected readonly _storage: PatternInfo[] = []; |
| 32 | |
| 33 | constructor(private readonly _patterns: Pattern[], private readonly _settings: Settings, private readonly _micromatchOptions: MicromatchOptions) { |
| 34 | this._fillStorage(); |
| 35 | } |
| 36 | |
| 37 | private _fillStorage(): void { |
| 38 | /** |
| 39 | * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). |
| 40 | * So, before expand patterns with brace expansion into separated patterns. |
| 41 | */ |
| 42 | const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns); |
| 43 | |
| 44 | for (const pattern of patterns) { |
| 45 | const segments = this._getPatternSegments(pattern); |
| 46 | const sections = this._splitSegmentsIntoSections(segments); |
| 47 | |
| 48 | this._storage.push({ |
| 49 | complete: sections.length <= 1, |
| 50 | pattern, |
| 51 | segments, |
| 52 | sections |
| 53 | }); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private _getPatternSegments(pattern: Pattern): PatternSegment[] { |
| 58 | const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); |
| 59 | |
| 60 | return parts.map((part) => { |
| 61 | const dynamic = utils.pattern.isDynamicPattern(part, this._settings); |
| 62 | |
| 63 | if (!dynamic) { |
| 64 | return { |
| 65 | dynamic: false, |
| 66 | pattern: part |
| 67 | }; |
| 68 | } |
| 69 | |
| 70 | return { |
| 71 | dynamic: true, |
| 72 | pattern: part, |
| 73 | patternRe: utils.pattern.makeRe(part, this._micromatchOptions) |
| 74 | }; |
| 75 | }); |
| 76 | } |
| 77 | |
| 78 | private _splitSegmentsIntoSections(segments: PatternSegment[]): PatternSection[] { |
| 79 | return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); |
| 80 | } |
| 81 | } |