Skip to content

Commit

Permalink
feat(matcher): ignore patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
LuciNyan committed Sep 11, 2022
1 parent f3fc6b5 commit 6738d18
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-phones-jog.md
@@ -0,0 +1,5 @@
---
"@pnpm/matcher": major
---

feat(matcher): ignore patterns
37 changes: 31 additions & 6 deletions packages/matcher/src/index.ts
@@ -1,16 +1,31 @@
import escapeStringRegexp from 'escape-string-regexp'

export default function matcher (patterns: string[] | string) {
if (typeof patterns === 'string') return matcherFromPattern(patterns)
type Matcher = (input: string) => boolean

export default function matcher (patterns: string[] | string): Matcher {
if (typeof patterns === 'string') return matcherWhenOnlyOnePattern(patterns)
switch (patterns.length) {
case 0: return () => false
case 1: return matcherFromPattern(patterns[0])
case 1: return matcherWhenOnlyOnePattern(patterns[0])
}
const matchArr = patterns.map(matcherFromPattern)
return (input: string) => matchArr.some((match) => match(input))
return (input: string) => patterns.reduce((result, pattern) => {
if (isIgnorePattern(pattern)) {
const match = matcherFromPattern(pattern.substring(1))
if (match(input)) {
return false
}
} else {
const match = matcherFromPattern(pattern)
if (match(input)) {
return true
}
}

return result
}, false)
}

function matcherFromPattern (pattern: string) {
function matcherFromPattern (pattern: string): Matcher {
if (pattern === '*') {
return () => true
}
Expand All @@ -23,3 +38,13 @@ function matcherFromPattern (pattern: string) {
const regexp = new RegExp(`^${escapedPattern}$`)
return (input: string) => regexp.test(input)
}

function isIgnorePattern (pattern: string): boolean {
return pattern.startsWith('!')
}

function matcherWhenOnlyOnePattern (pattern: string): Matcher {
return isIgnorePattern(pattern)
? () => false
: matcherFromPattern(pattern)
}
11 changes: 11 additions & 0 deletions packages/matcher/test/index.ts
Expand Up @@ -30,4 +30,15 @@ test('matcher()', () => {
expect(match('bar')).toBe(true)
expect(match('express')).toBe(false)
}
{
const match = matcher(['eslint-*', '!eslint-plugin-bar'])
expect(match('eslint-plugin-foo')).toBe(true)
expect(match('eslint-plugin-bar')).toBe(false)
}
{
const match = matcher(['eslint-*', '!eslint-plugin-*', 'eslint-plugin-bar'])
expect(match('eslint-config-foo')).toBe(true)
expect(match('eslint-plugin-foo')).toBe(false)
expect(match('eslint-plugin-bar')).toBe(true)
}
})

0 comments on commit 6738d18

Please sign in to comment.