Skip to content

Commit

Permalink
fix: handle dotenv comments
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Dec 24, 2024
1 parent b0fda39 commit 4baadb1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
29 changes: 21 additions & 8 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,23 +365,36 @@ export const parseDotenv = (content: string): NodeJS.ProcessEnv => {
let k = ''
let c = ''
let q = ''
let i = false
const cap = () => { if (c && k) {
if (!r.test(k)) throw new Error(`Invalid identifier: ${k}`)
e[k] = c; c = ''; k = ''
}}

for (const s of content) {
if (s === ' ' && !q) {
if (!k && c === 'export') c = ''
if (i) {
if (s === '\n') i = false
continue
}
if (s === '=' && !q) {
if (!k) { k = c; c = ''; continue }
}
if (s === '\n' && !q) {
cap()
continue
if (!q) {
if (s === '#') {
i = true
continue
}
if (s === ' ') {
if (!k && c === 'export') c = ''
continue
}
if (s === '=') {
if (!k) { k = c; c = ''; continue }
}
if (s === '\n') {
i = false
cap()
continue
}
}

if (s === '"' || s === "'") {
if (q === s) {
q = ''
Expand Down
11 changes: 7 additions & 4 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,24 +141,27 @@ describe('util', () => {
assert.equal(toCamelCase('kebab-input-str'), 'kebabInputStr')
})

test('parseDotenv()', () => {
test.only('parseDotenv()', () => {
const multiline = `SIMPLE=xyz123
NON_INTERPOLATED='raw text without variable interpolation'
# comment ###
NON_INTERPOLATED='raw text without variable interpolation'
MULTILINE = """
long text here,
long text here, # not-comment
e.g. a private SSH key
"""
ENV=v1\nENV2=v2\n\n\n ENV3 = v3 \n export ENV4=v4
ENV5=v5 # comment
`

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

assert.deepEqual(
Expand Down

0 comments on commit 4baadb1

Please sign in to comment.