From ea280fe6cfeaa519486d9d1e73f91703813ee665 Mon Sep 17 00:00:00 2001 From: GweesinChan Date: Thu, 6 Feb 2025 22:39:54 +0800 Subject: [PATCH] fix: fix converting glob expression to regex error and add tests --- src/utils.ts | 3 ++- test/utils.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 test/utils.test.ts diff --git a/src/utils.ts b/src/utils.ts index 5fbed05..656cc65 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,7 +3,8 @@ import pm from 'picomatch' export function constructPatternFilter(patterns: string[]): (str: string) => boolean { const matchers = patterns.map((glob) => { if (glob.match(/[\^$*{}]/)) { - const re = pm.toRegex(glob) + const { output } = pm.parse(glob) + const re = pm.toRegex(output) return (str: string) => re.test(str) } else { diff --git a/test/utils.test.ts b/test/utils.test.ts new file mode 100644 index 0000000..6d00548 --- /dev/null +++ b/test/utils.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { constructPatternFilter } from '../src/utils' + +describe('constructPatternFilter', () => { + it('should match exact strings', () => { + const filter = constructPatternFilter(['test', 'example']) + expect(filter('test')).toBe(true) + expect(filter('example')).toBe(true) + expect(filter('other')).toBe(false) + }) + + it('should match patterns with wildcards', () => { + const filter = constructPatternFilter(['*.js', '*.ts']) + expect(filter('file.js')).toBe(true) + expect(filter('file.ts')).toBe(true) + expect(filter('file.txt')).toBe(false) + }) + + it('should match patterns with regex special characters', () => { + const filter = constructPatternFilter(['example*']) + expect(filter('example123')).toBe(true) + expect(filter('test123')).toBe(false) + }) + + it('should handle empty patterns', () => { + const filter = constructPatternFilter([]) + expect(filter('anything')).toBe(false) + }) + + it('should match mixed exact strings and patterns', () => { + const filter = constructPatternFilter(['test', '*.js']) + expect(filter('test')).toBe(true) + expect(filter('file.js')).toBe(true) + expect(filter('example')).toBe(false) + }) +})