Skip to content

Commit

Permalink
feat: handle multilines in env files
Browse files Browse the repository at this point in the history
continues #974
  • Loading branch information
antongolub committed Dec 24, 2024
1 parent 759dcf6 commit 93691d6
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 24 deletions.
4 changes: 2 additions & 2 deletions .size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
{
"name": "zx/index",
"path": "build/*.{js,cjs}",
"limit": "805 kB",
"limit": "805.5 kB",
"brotli": false,
"gzip": false
},
Expand All @@ -30,7 +30,7 @@
{
"name": "all",
"path": "build/*",
"limit": "842 kB",
"limit": "842.5 kB",
"brotli": false,
"gzip": false
}
Expand Down
43 changes: 34 additions & 9 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,15 +358,40 @@ export const toCamelCase = (str: string) =>
export const parseBool = (v: string): boolean | string =>
({ true: true, false: false })[v] ?? v

export const parseDotenv = (content: string): NodeJS.ProcessEnv =>
content.split(/\r?\n/).reduce<NodeJS.ProcessEnv>((r, line) => {
if (line.startsWith('export ')) line = line.slice(7)
const i = line.indexOf('=')
const k = line.slice(0, i).trim()
const v = line.slice(i + 1).trim()
if (k && v) r[k] = v
return r
}, {})
// prettier-ignore
export const parseDotenv = (content: string): NodeJS.ProcessEnv => {
const e: Record<string, string> = {}
let k = ''
let c = ''
let q = ''
const cap = () => {if (c && k) { e[k] = c; c = ''; k = '' }}

for (const s of content) {
if (s === ' ' && !q) {
if (!k && c === 'export') c = ''
continue
}
if (s === '=' && !q) {
if (!k) { k = c; c = ''; continue }
}
if (s === '\n' && !q) {
cap()
continue
}
if (s === '"' || s === "'") {
if (q === s) {
q = ''
cap()
continue
}
q = s
continue
}
c += s
}

return e
}

export const readEnvFromFile = (
filepath: string,
Expand Down
26 changes: 13 additions & 13 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,24 +143,24 @@ describe('util', () => {
})

test('parseDotenv()', () => {
assert.deepEqual(
parseDotenv('ENV=v1\nENV2=v2\n\n\n ENV3 = v3 \nexport ENV4=v4'),
{
ENV: 'v1',
ENV2: 'v2',
ENV3: 'v3',
ENV4: 'v4',
}
)
assert.deepEqual(parseDotenv(''), {})

// TBD: multiline
const multiline = `SIMPLE=xyz123
NON_INTERPOLATED='raw text without variable interpolation'
MULTILINE = """
long text here,
e.g. a private SSH key
"""`
"""
ENV=v1\nENV2=v2\n\n\n ENV3 = v3 \n export ENV4=v4
`

assert.deepEqual(parseDotenv(multiline), {
SIMPLE: 'xyz123',
NON_INTERPOLATED: 'raw text without variable interpolation',
MULTILINE: '\nlong text here,\ne.g. a private SSH key\n',
ENV: 'v1',
ENV2: 'v2',
ENV3: 'v3',
ENV4: 'v4',
})
})

describe('readEnvFromFile()', () => {
Expand Down

0 comments on commit 93691d6

Please sign in to comment.