Debian Codegraph @

fast-glob/src/providers/filters/entry.ts

raw
1 import Settings from '../../settings';
2 import { Entry, EntryFilterFunction, MicromatchOptions, Pattern, PatternRe } from '../../types';
3 import * as utils from '../../utils';
4
5 export default class EntryFilter {
6 public readonly index: Map<string, undefined> = new Map();
7
8 constructor(private readonly _settings: Settings, private readonly _micromatchOptions: MicromatchOptions) {}
9
10 public getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction {
11 const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions);
12 const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions);
13
14 return (entry) => this._filter(entry, positiveRe, negativeRe);
15 }
16
17 private _filter(entry: Entry, positiveRe: PatternRe[], negativeRe: PatternRe[]): boolean {
18 if (this._settings.unique && this._isDuplicateEntry(entry)) {
19 return false;
20 }
21
22 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
23 return false;
24 }
25
26 if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
27 return false;
28 }
29
30 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
31 const isDirectory = entry.dirent.isDirectory();
32
33 const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(entry.path, negativeRe, isDirectory);
34
35 if (this._settings.unique && isMatched) {
36 this._createIndexRecord(entry);
37 }
38
39 return isMatched;
40 }
41
42 private _isDuplicateEntry(entry: Entry): boolean {
43 return this.index.has(entry.path);
44 }
45
46 private _createIndexRecord(entry: Entry): void {
47 this.index.set(entry.path, undefined);
48 }
49
50 private _onlyFileFilter(entry: Entry): boolean {
51 return this._settings.onlyFiles && !entry.dirent.isFile();
52 }
53
54 private _onlyDirectoryFilter(entry: Entry): boolean {
55 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
56 }
57
58 private _isSkippedByAbsoluteNegativePatterns(entryPath: string, patternsRe: PatternRe[]): boolean {
59 if (!this._settings.absolute) {
60 return false;
61 }
62
63 const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath);
64
65 return utils.pattern.matchAny(fullpath, patternsRe);
66 }
67
68 private _isMatchToPatterns(entryPath: string, patternsRe: PatternRe[], isDirectory: boolean): boolean {
69 const filepath = utils.path.removeLeadingDotSegment(entryPath);
70
71 // Trying to match files and directories by patterns.
72 const isMatched = utils.pattern.matchAny(filepath, patternsRe);
73
74 // A pattern with a trailling slash can be used for directory matching.
75 // To apply such pattern, we need to add a tralling slash to the path.
76 if (!isMatched && isDirectory) {
77 return utils.pattern.matchAny(filepath + '/', patternsRe);
78 }
79
80 return isMatched;
81 }
82 }