From e4a0eddb441a2c9ed880d9d28ee0ad507776848a Mon Sep 17 00:00:00 2001 From: mrmlnc Date: Mon, 9 Sep 2019 09:19:35 +0300 Subject: [PATCH] feat: add `flipBackslashes` option to avoid auto conversion of slashes --- README.md | 11 ++++++++++- index.js | 11 +++++++++-- test/index.test.js | 13 ++++++++++++- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c7fbe32..36a2793 100644 --- a/README.md +++ b/README.md @@ -36,10 +36,19 @@ globParent('path/foo'); // 'path' (see issue #3 for details) ## API -### `globParent(maybeGlobString)` +### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true +} +``` + ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: diff --git a/index.js b/index.js index 900d3fb..2ded6ea 100644 --- a/index.js +++ b/index.js @@ -10,9 +10,16 @@ var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g; -module.exports = function globParent(str) { +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + // flip windows path separators - if (isWin32 && str.indexOf(slash) < 0) { + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } diff --git a/test/index.test.js b/test/index.test.js index 33f26f6..d3e7a71 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -84,7 +84,12 @@ describe('glob-parent', function() { assert.equal(gp('\\{foo,bar}/'), '{foo,bar}'); assert.equal(gp('\\{foo,bar\\}/'), '{foo,bar}'); assert.equal(gp('{foo,bar\\}/'), '.'); - if (!isWin32) { + + if (isWin32) { + // On Windows we are trying to flip backslashes foo-\\( → foo-/( + assert.equal(gp('foo-\\(bar\\).md'), 'foo-'); + } else { + assert.equal(gp('foo-\\(bar\\).md'), '.'); assert.equal(gp('\\[bar]'), '[bar]'); assert.equal(gp('[bar\\]'), '.'); assert.equal(gp('\\{foo,bar\\}'), '{foo,bar}'); @@ -135,6 +140,12 @@ describe('glob-parent', function() { done(); }); + + it('should respect disabled auto flip backslashes', function(done) { + assert.equal(gp('foo-\\(bar\\).md', { flipBackslashes: false }), '.'); + + done(); + }); }); describe('glob2base test patterns', function() {