Skip to content

Commit 4baadb1

Browse files
committed
fix: handle dotenv comments
1 parent b0fda39 commit 4baadb1

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

src/util.ts

+21-8
Original file line numberDiff line numberDiff line change
@@ -365,23 +365,36 @@ export const parseDotenv = (content: string): NodeJS.ProcessEnv => {
365365
let k = ''
366366
let c = ''
367367
let q = ''
368+
let i = false
368369
const cap = () => { if (c && k) {
369370
if (!r.test(k)) throw new Error(`Invalid identifier: ${k}`)
370371
e[k] = c; c = ''; k = ''
371372
}}
372373

373374
for (const s of content) {
374-
if (s === ' ' && !q) {
375-
if (!k && c === 'export') c = ''
375+
if (i) {
376+
if (s === '\n') i = false
376377
continue
377378
}
378-
if (s === '=' && !q) {
379-
if (!k) { k = c; c = ''; continue }
380-
}
381-
if (s === '\n' && !q) {
382-
cap()
383-
continue
379+
if (!q) {
380+
if (s === '#') {
381+
i = true
382+
continue
383+
}
384+
if (s === ' ') {
385+
if (!k && c === 'export') c = ''
386+
continue
387+
}
388+
if (s === '=') {
389+
if (!k) { k = c; c = ''; continue }
390+
}
391+
if (s === '\n') {
392+
i = false
393+
cap()
394+
continue
395+
}
384396
}
397+
385398
if (s === '"' || s === "'") {
386399
if (q === s) {
387400
q = ''

test/util.test.js

+7-4
Original file line numberDiff line numberDiff line change
@@ -141,24 +141,27 @@ describe('util', () => {
141141
assert.equal(toCamelCase('kebab-input-str'), 'kebabInputStr')
142142
})
143143

144-
test('parseDotenv()', () => {
144+
test.only('parseDotenv()', () => {
145145
const multiline = `SIMPLE=xyz123
146-
NON_INTERPOLATED='raw text without variable interpolation'
146+
# comment ###
147+
NON_INTERPOLATED='raw text without variable interpolation'
147148
MULTILINE = """
148-
long text here,
149+
long text here, # not-comment
149150
e.g. a private SSH key
150151
"""
151152
ENV=v1\nENV2=v2\n\n\n ENV3 = v3 \n export ENV4=v4
153+
ENV5=v5 # comment
152154
`
153155

154156
assert.deepEqual(parseDotenv(multiline), {
155157
SIMPLE: 'xyz123',
156158
NON_INTERPOLATED: 'raw text without variable interpolation',
157-
MULTILINE: '\nlong text here,\ne.g. a private SSH key\n',
159+
MULTILINE: '\nlong text here, # not-comment\ne.g. a private SSH key\n',
158160
ENV: 'v1',
159161
ENV2: 'v2',
160162
ENV3: 'v3',
161163
ENV4: 'v4',
164+
ENV5: 'v5',
162165
})
163166

164167
assert.deepEqual(

0 commit comments

Comments
 (0)