2020-05-21 00:31:16 +02:00
|
|
|
import * as jsyaml from 'js-yaml'
|
|
|
|
import * as minimatch from 'minimatch'
|
|
|
|
|
|
|
|
export default class Filter {
|
|
|
|
rules: {[key: string]: minimatch.IMinimatch[]} = {}
|
|
|
|
|
|
|
|
constructor(yaml: string) {
|
|
|
|
const doc = jsyaml.safeLoad(yaml)
|
|
|
|
if (typeof doc !== 'object') {
|
|
|
|
this.throwInvalidFormatError()
|
|
|
|
}
|
|
|
|
|
2020-05-21 13:46:48 +02:00
|
|
|
const opts: minimatch.IOptions = {
|
|
|
|
dot: true
|
|
|
|
}
|
|
|
|
|
2020-05-21 00:31:16 +02:00
|
|
|
for (const name of Object.keys(doc)) {
|
2020-06-19 23:39:06 +02:00
|
|
|
const patternsNode = doc[name]
|
|
|
|
if (!Array.isArray(patternsNode)) {
|
2020-05-21 00:31:16 +02:00
|
|
|
this.throwInvalidFormatError()
|
|
|
|
}
|
2020-06-19 23:39:06 +02:00
|
|
|
const patterns = flat(patternsNode) as string[]
|
2020-05-21 00:31:16 +02:00
|
|
|
if (!patterns.every(x => typeof x === 'string')) {
|
|
|
|
this.throwInvalidFormatError()
|
|
|
|
}
|
2020-05-21 13:46:48 +02:00
|
|
|
this.rules[name] = patterns.map(x => new minimatch.Minimatch(x, opts))
|
2020-05-21 00:31:16 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns dictionary with match result per rules group
|
|
|
|
match(paths: string[]): {[key: string]: boolean} {
|
|
|
|
const result: {[key: string]: boolean} = {}
|
|
|
|
for (const [key, patterns] of Object.entries(this.rules)) {
|
|
|
|
const match = paths.some(fileName => patterns.some(rule => rule.match(fileName)))
|
|
|
|
result[key] = match
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
private throwInvalidFormatError(): never {
|
|
|
|
throw new Error('Invalid filter YAML format: Expected dictionary of string arrays')
|
|
|
|
}
|
|
|
|
}
|
2020-06-19 23:39:06 +02:00
|
|
|
|
|
|
|
// Creates a new array with all sub-array elements recursively concatenated
|
|
|
|
// In future could be replaced by Array.prototype.flat (supported on Node.js 11+)
|
|
|
|
function flat(arr: any[]): any[] {
|
|
|
|
return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flat(val) : val), [])
|
|
|
|
}
|