Skip to content

Commit

Permalink
Fix #199 – Allow regexes in array
Browse files Browse the repository at this point in the history
  • Loading branch information
adamreisnz committed Sep 22, 2024
1 parent 8d77abc commit fc5af6d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "replace-in-file",
"type": "module",
"version": "8.1.0",
"version": "8.2.0",
"description": "A simple utility to quickly replace text in one or more files.",
"homepage": "https://github.com/adamreisnz/replace-in-file#readme",
"author": {
Expand Down
30 changes: 25 additions & 5 deletions src/helpers/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,30 @@ export async function loadConfig(file) {
return JSON.parse(json)
}

/**
* Helper to convert a string to Regex if it matches the pattern
*/
export function stringToRegex(str) {

//Array given
if (Array.isArray(str)) {
return str.map(stringToRegex)
}

//Not a string, or no match
const regexMatch = /.*\/([gimyus]*)$/
if (typeof str !== 'string' || !str.match(regexMatch)) {
return str
}

//Extract flags and pattern
const flags = str.replace(/.*\/([gimyus]*)$/, '$1')
const pattern = str.replace(new RegExp(`^/(.*?)/${flags}$`), '$1')

//Return regex
return new RegExp(pattern, flags)
}

/**
* Parse config
*/
Expand Down Expand Up @@ -66,11 +90,7 @@ export function parseConfig(config) {
}

//Since we can't store Regexp in JSON, convert from string if needed
if (typeof from === 'string' && from.match(/.*\/([gimyus]*)$/)) {
const flags = from.replace(/.*\/([gimyus]*)$/, '$1')
const pattern = from.replace(new RegExp(`^/(.*?)/${flags}$`), '$1')
config.from = new RegExp(pattern, flags)
}
config.from = stringToRegex(from)

//Use default encoding if invalid
if (typeof encoding !== 'string' || encoding === '') {
Expand Down
12 changes: 12 additions & 0 deletions src/helpers/config.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,18 @@ describe('helpers/config.js', () => {
expect(parsed.from).to.be.an.instanceof(RegExp)
})

it('should convert from an array of regexes if provided in JSON', async () => {
const parsed = parseConfig({
files: ['file.txt'],
from: ['/foo/g', '/baz/g', 'plain'],
to: 'bar',
})
expect(parsed.from).to.be.an.instanceof(Array)
expect(parsed.from[0]).to.be.an.instanceof(RegExp)
expect(parsed.from[1]).to.be.an.instanceof(RegExp)
expect(parsed.from[2]).to.equal('plain')
})

it('should not convert from regex if it is a regular string', async () => {
const parsed = parseConfig({
files: ['file.txt'],
Expand Down

0 comments on commit fc5af6d

Please sign in to comment.