path: add `matchesGlob` method · nodejs/node@57b8b8e
1+'use strict';
2+3+require('../common');
4+const assert = require('assert');
5+const path = require('path');
6+7+const globs = {
8+win32: [
9+['foo\\bar\\baz', 'foo\\[bcr]ar\\baz', true], // Matches 'bar' or 'car' in 'foo\\bar'
10+['foo\\bar\\baz', 'foo\\[!bcr]ar\\baz', false], // Matches anything except 'bar' or 'car' in 'foo\\bar'
11+['foo\\bar\\baz', 'foo\\[bc-r]ar\\baz', true], // Matches 'bar' or 'car' using range in 'foo\\bar'
12+['foo\\bar\\baz', 'foo\\*\\!bar\\*\\baz', false], // Matches anything with 'foo' and 'baz' but not 'bar' in between
13+['foo\\bar1\\baz', 'foo\\bar[0-9]\\baz', true], // Matches 'bar' followed by any digit in 'foo\\bar1'
14+['foo\\bar5\\baz', 'foo\\bar[0-9]\\baz', true], // Matches 'bar' followed by any digit in 'foo\\bar5'
15+['foo\\barx\\baz', 'foo\\bar[a-z]\\baz', true], // Matches 'bar' followed by any lowercase letter in 'foo\\barx'
16+['foo\\bar\\baz\\boo', 'foo\\[bc-r]ar\\baz\\*', true], // Matches 'bar' or 'car' in 'foo\\bar'
17+['foo\\bar\\baz', 'foo/**', true], // Matches anything in 'foo'
18+['foo\\bar\\baz', '*', false], // No match
19+],
20+posix: [
21+['foo/bar/baz', 'foo/[bcr]ar/baz', true], // Matches 'bar' or 'car' in 'foo/bar'
22+['foo/bar/baz', 'foo/[!bcr]ar/baz', false], // Matches anything except 'bar' or 'car' in 'foo/bar'
23+['foo/bar/baz', 'foo/[bc-r]ar/baz', true], // Matches 'bar' or 'car' using range in 'foo/bar'
24+['foo/bar/baz', 'foo/*/!bar/*/baz', false], // Matches anything with 'foo' and 'baz' but not 'bar' in between
25+['foo/bar1/baz', 'foo/bar[0-9]/baz', true], // Matches 'bar' followed by any digit in 'foo/bar1'
26+['foo/bar5/baz', 'foo/bar[0-9]/baz', true], // Matches 'bar' followed by any digit in 'foo/bar5'
27+['foo/barx/baz', 'foo/bar[a-z]/baz', true], // Matches 'bar' followed by any lowercase letter in 'foo/barx'
28+['foo/bar/baz/boo', 'foo/[bc-r]ar/baz/*', true], // Matches 'bar' or 'car' in 'foo/bar'
29+['foo/bar/baz', 'foo/**', true], // Matches anything in 'foo'
30+['foo/bar/baz', '*', false], // No match
31+],
32+};
33+34+35+for (const [platform, platformGlobs] of Object.entries(globs)) {
36+for (const [pathStr, glob, expected] of platformGlobs) {
37+const actual = path[platform].matchesGlob(pathStr, glob);
38+assert.strictEqual(actual, expected, `Expected ${pathStr} to ` + (expected ? '' : 'not ') + `match ${glob} on ${platform}`);
39+}
40+}
41+42+// Test for non-string input
43+assert.throws(() => path.matchesGlob(123, 'foo/bar/baz'), /.*must be of type string.*/);
44+assert.throws(() => path.matchesGlob('foo/bar/baz', 123), /.*must be of type string.*/);