Skip to content

Commit

Permalink
fix: parseDotenv tweak ups (google#1030)
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub authored Dec 24, 2024
1 parent 36b42d8 commit 759dcf6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 15 deletions.
9 changes: 3 additions & 6 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 6 additions & 5 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
21 changes: 17 additions & 4 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()', () => {
Expand Down

0 comments on commit 759dcf6

Please sign in to comment.