From 759dcf6f16cc517b5ef3fb41f92374aba5d6f60a Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Tue, 24 Dec 2024 11:49:07 +0300 Subject: [PATCH] fix: parseDotenv tweak ups (#1030) --- docs/cli.md | 9 +++------ src/util.ts | 11 ++++++----- test/util.test.js | 21 +++++++++++++++++---- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 43ddbbd9e1..ca558299ad 100644 --- a/docs/cli.md +++ b/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 diff --git a/src/util.ts b/src/util.ts index b3fc5a5938..9fb4fc211e 100644 --- a/src/util.ts +++ b/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((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((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, diff --git a/test/util.test.js b/test/util.test.js index 1ad6f28421..6a98189c62 100644 --- a/test/util.test.js +++ b/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()', () => {