Skip to content

Commit

Permalink
path: add path.glob and path.globToRegExp
Browse files Browse the repository at this point in the history
  • Loading branch information
MoLow committed Apr 8, 2023
1 parent 37d1fe8 commit ec4c561
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ const {
validateString,
} = require('internal/validators');


let minimatch;
function lazyMinimatch() {
minimatch ??= require('internal/deps/minimatch/index');
return minimatch;
}

const platformIsWin32 = (process.platform === 'win32');

function isPathSeparator(code) {
Expand Down Expand Up @@ -153,6 +160,23 @@ function _format(sep, pathObject) {
return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
}


/**
* @param {string} path
* @returns {Function}
*/
function glob(pattern) {
return lazyMinimatch().filter(pattern);
}

/**
* @param {string} path
* @returns {RegExp}
*/
function globToRegExp(pattern) {
return lazyMinimatch().makeRe(pattern);
}

const win32 = {
/**
* path.resolve([from ...], to)
Expand Down Expand Up @@ -1064,6 +1088,8 @@ const win32 = {

return ret;
},
glob,
globToRegExp,

sep: '\\',
delimiter: ';',
Expand Down Expand Up @@ -1530,6 +1556,8 @@ const posix = {

return ret;
},
glob,
globToRegExp,

sep: '/',
delimiter: ':',
Expand Down
25 changes: 25 additions & 0 deletions test/parallel/test-path-glob.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, it } from 'node:test';
import * as assert from 'node:assert';
import * as path from 'node:path';

describe('path.glob', () => {
it('should return a filter function', () => {
const fn = path.glob('*.js');
assert.strictEqual(typeof fn, 'function');
});
it('should return a filter function that matches the glob', () => {
const fn = path.glob('*.js');
assert.strictEqual(fn('foo.js'), true);
});
});

describe('path.globToRegExp', () => {
it('should return a RegExp', () => {
const re = path.globToRegExp('foo');
assert.strictEqual(re instanceof RegExp, true);
});
it('should return a RegExp that matches the glob', () => {
const re = path.globToRegExp('*.js');
assert.strictEqual(re.test('foo.js'), true);
})
});

0 comments on commit ec4c561

Please sign in to comment.