From fc5af6d35f046a9d70d68795a89c0afbca4511a2 Mon Sep 17 00:00:00 2001 From: Adam Reis Date: Sun, 22 Sep 2024 19:01:20 +1200 Subject: [PATCH] =?UTF-8?q?Fix=20#199=20=E2=80=93=20Allow=20regexes=20in?= =?UTF-8?q?=20array?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/helpers/config.js | 30 +++++++++++++++++++++++++----- src/helpers/config.spec.js | 12 ++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index b6a4915..642b123 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/helpers/config.js b/src/helpers/config.js index 123eac7..ddebeaa 100644 --- a/src/helpers/config.js +++ b/src/helpers/config.js @@ -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 */ @@ -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 === '') { diff --git a/src/helpers/config.spec.js b/src/helpers/config.spec.js index 2607dc4..704f638 100644 --- a/src/helpers/config.spec.js +++ b/src/helpers/config.spec.js @@ -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'],