Commit 759dcf6

Anton Golub <antongolub@antongolub.com>
2024-12-24 09:49:07
fix: parseDotenv tweak ups (#1030) tag: 8.3.0
1 parent 36b42d8
Changed files (3)
docs/cli.md
@@ -119,17 +119,14 @@ zx --cwd=/foo/bar script.mjs
 ```
 
 ## --env
-Specify a env file.
+Specify an env file.
 
 ```bash
 zx --env=/path/to/some.env script.mjs
 ```
 
-When cwd option is specified, it will used as base path: `--cwd='/foo/bar' --env='../.env'` → `/foo/.env`
-
-```bash
-zx --cwd=/foo/bar --env=/path/to/some.env script.mjs
-```
+When `cwd` option is specified, it will be used as base path:  
+`--cwd='/foo/bar' --env='../.env'` → `/foo/.env`
 
 ## --ext
 
src/util.ts
@@ -358,14 +358,15 @@ 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 => {
-  return content.split(/\r?\n/).reduce<NodeJS.ProcessEnv>((r, line) => {
-    const [k] = line.trim().split('=', 1)
-    const v = line.trim().slice(k.length + 1)
+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
   }, {})
-}
 
 export const readEnvFromFile = (
   filepath: string,
test/util.test.js
@@ -143,11 +143,24 @@ describe('util', () => {
 })
 
 test('parseDotenv()', () => {
-  assert.deepEqual(parseDotenv('ENV=value1\nENV2=value24'), {
-    ENV: 'value1',
-    ENV2: 'value24',
-  })
+  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
+"""`
 })
 
 describe('readEnvFromFile()', () => {