From 355882c72377e1ca12411e9661963e6d23cf8067 Mon Sep 17 00:00:00 2001 From: Nam PHAM Date: Fri, 15 Mar 2024 15:06:23 +0100 Subject: [PATCH] fix: preserve quotes inside quotes in value (#234) --- source/index.ts | 15 ++++++++++++++- source/test.ts | 13 +++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/source/index.ts b/source/index.ts index 40203a7..51cbb3c 100644 --- a/source/index.ts +++ b/source/index.ts @@ -6,6 +6,19 @@ export type Input = Record // perhaps in the future we can use @bevry/json's toJSON and parseJSON and JSON.stringify to support more advanced types +function removeQuotes(str: string) { + // Check if the string starts and ends with single or double quotes + if ( + (str.startsWith('"') && str.endsWith('"')) || + (str.startsWith("'") && str.endsWith("'")) + ) { + // Remove the quotes + return str.slice(1, -1) + } + // If the string is not wrapped in quotes, return it as is + return str +} + /** Parse an envfile string. */ export function parse(src: string): Data { const result: Data = {} @@ -14,7 +27,7 @@ export function parse(src: string): Data { const match = line.match(/^([^=:#]+?)[=:]((.|\n)*)/) if (match) { const key = match[1].trim() - const value = match[2].trim().replace(/['"]+/g, '') + const value = removeQuotes(match[2].trim()) result[key] = value } } diff --git a/source/test.ts b/source/test.ts index da81384..a53448f 100644 --- a/source/test.ts +++ b/source/test.ts @@ -73,4 +73,17 @@ kava.suite('envfile', function (suite, test) { deepEqual(result, expected) done() }) + + test('quotes inside quotes should be preserved', function (done) { + const str = `name="[{"key":"foo"},{"key":"bar"}]"\nplanet="earth"\nrace='human'` + const expected = { + name: '[{"key":"foo"},{"key":"bar"}]', + planet: 'earth', + race: 'human', + } + const result = parse(str) + + deepEqual(result, expected) + done() + }) })