Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/unescape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,18 @@ export const unescape = (
magicalBraces = true,
}: Pick<MinimatchOptions, 'windowsPathsNoEscape' | 'magicalBraces'> = {},
) => {
// Skip backslash escapes while finding bracket escapes, without consuming
// the character before a bracket (which may close the previous escape).
if (magicalBraces) {
return windowsPathsNoEscape ?
s.replace(/\[([^/\\])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
.replace(/\\.|\[([^/\\])\]/g, (match, value) => value ?? match)
.replace(/\\([^/])/g, '$1')
}
return windowsPathsNoEscape ?
s.replace(/\[([^/\\{}])\]/g, '$1')
: s
.replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
.replace(/\\.|\[([^/\\{}])\]/g, (match, value) => value ?? match)
.replace(/\\([^/{}])/g, '$1')
}
54 changes: 54 additions & 0 deletions test/unescape-adjacent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import t from 'tap'
import { escape, unescape } from '../src/index.js'

t.test('default mode unescapes adjacent bracket escapes', t => {
for (const magicalBraces of [false, true]) {
const options = { magicalBraces }
for (const value of ['**', '??', '[]', '[a][b]', '*?[]()', '{}{}']) {
const escaped = escape(value, {
windowsPathsNoEscape: true,
magicalBraces,
})
t.equal(
unescape(escaped, options),
value,
JSON.stringify({ value, options }),
)
}
t.equal(unescape('[a][b][c]', options), 'abc')
t.equal(unescape('x[a][b]y', options), 'xaby')
t.equal(unescape('\\\\[a][b]', options), '\\ab')
t.equal(unescape('\\[a][b]', options), '[a]b')
t.equal(unescape('[/][\\]', options), '[/][]')
}
t.end()
})

t.test('backslash and brace options keep their existing behavior', t => {
for (const magicalBraces of [false, true]) {
for (const windowsPathsNoEscape of [false, true]) {
const options = { magicalBraces, windowsPathsNoEscape }
for (const value of [
'**',
'??',
'[]',
'[a][b]',
'*?[]()',
'{}{}',
'a/b',
'a\\b',
]) {
t.equal(unescape(escape(value, options), options), value)
}
t.equal(unescape('[a][b][c]', options), 'abc')
t.equal(unescape('[{][}]', options), magicalBraces ? '{}' : '[{][}]')
t.equal(
unescape('\\{\\}', options),
magicalBraces && !windowsPathsNoEscape ? '{}' : '\\{\\}',
)
t.equal(unescape('[/]', options), '[/]')
t.equal(unescape('\\*', options), windowsPathsNoEscape ? '\\*' : '*')
}
}
t.end()
})