Skip to content

Commit

Permalink
fix: preserve quotes inside quotes in value (#234)
Browse files Browse the repository at this point in the history
  • Loading branch information
NamPNQ committed Mar 15, 2024
1 parent dc6083d commit 355882c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 14 additions & 1 deletion source/index.ts
Expand Up @@ -6,6 +6,19 @@ export type Input = Record<string, any>

// 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 = {}
Expand All @@ -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
}
}
Expand Down
13 changes: 13 additions & 0 deletions source/test.ts
Expand Up @@ -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()
})
})

0 comments on commit 355882c

Please sign in to comment.