Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support env files #1022

Merged
merged 20 commits into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
{
"name": "zx/core",
"path": ["build/core.cjs", "build/util.cjs", "build/vendor-core.cjs"],
"limit": "76 kB",
"limit": "77 kB",
"brotli": false,
"gzip": false
},
{
"name": "zx/index",
"path": "build/*.{js,cjs}",
"limit": "804 kB",
"limit": "805 kB",
"brotli": false,
"gzip": false
},
Expand All @@ -30,7 +30,7 @@
{
"name": "all",
"path": "build/*",
"limit": "841 kB",
"limit": "842 kB",
"brotli": false,
"gzip": false
}
Expand Down
2 changes: 2 additions & 0 deletions man/zx.1
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ install dependencies
npm registry, defaults to https://registry.npmjs.org/
.SS --repl
start repl
.SS --env=<path>
path to env file
.SS --version, -v
print current zx version
.SS --help, -h
Expand Down
9 changes: 7 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
parseArgv,
} from './index.js'
import { installDeps, parseDeps } from './deps.js'
import { randomId } from './util.js'
import { readEnvFromFile, randomId } from './util.js'
import { createRequire } from './vendor.js'

const EXT = '.mjs'
Expand Down Expand Up @@ -66,6 +66,7 @@ export function printUsage() {
--version, -v print current zx version
--help, -h print help
--repl start repl
--env=<path> path to env file
--experimental enables experimental features (deprecated)

${chalk.italic('Full documentation:')} ${chalk.underline('https://google.github.io/zx/')}
Expand All @@ -74,7 +75,7 @@ export function printUsage() {

// prettier-ignore
export const argv = parseArgv(process.argv.slice(2), {
string: ['shell', 'prefix', 'postfix', 'eval', 'cwd', 'ext', 'registry'],
string: ['shell', 'prefix', 'postfix', 'eval', 'cwd', 'ext', 'registry', 'env'],
boolean: ['version', 'help', 'quiet', 'verbose', 'install', 'repl', 'experimental', 'prefer-local'],
alias: { e: 'eval', i: 'install', v: 'version', h: 'help', l: 'prefer-local' },
stopEarly: true,
Expand All @@ -86,6 +87,10 @@ export async function main() {
await import('./globals.js')
argv.ext = normalizeExt(argv.ext)
if (argv.cwd) $.cwd = argv.cwd
if (argv.env) {
const envPath = path.resolve($.cwd ?? process.cwd(), argv.env)
$.env = readEnvFromFile(envPath, process.env)
}
if (argv.verbose) $.verbose = true
if (argv.quiet) $.quiet = true
if (argv.shell) $.shell = argv.shell
Expand Down
27 changes: 27 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,3 +357,30 @@ export const toCamelCase = (str: string) =>

export const parseBool = (v: string): boolean | string =>
({ true: true, false: false })[v] ?? v

// prettier-ignore
easymikey marked this conversation as resolved.
Show resolved Hide resolved
export const parseDotenv = (
content: string,
): NodeJS.ProcessEnv => {
return content
.split(/\r?\n/)
.reduce<NodeJS.ProcessEnv>((acc, line) => {
const [k,v] = line.trim().split('=', 2)
easymikey marked this conversation as resolved.
Show resolved Hide resolved
if (k && v) acc[k] = v
return acc;
}, {});
};

export const readEnvFromFile = (
filepath: string,
env: NodeJS.ProcessEnv = process.env
): NodeJS.ProcessEnv => {
const content = fs.readFileSync(path.resolve(filepath), {
encoding: 'utf8',
})
easymikey marked this conversation as resolved.
Show resolved Hide resolved

return {
...env,
...parseDotenv(content),
}
}
35 changes: 35 additions & 0 deletions test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,41 @@ describe('cli', () => {
assert.ok(p.stderr.endsWith(cwd + '\n'))
})

test('supports `--env` options with file', async () => {
const env = tmpfile(
'.env',
`FOO=BAR
BAR=FOO+`
)
const file = `
console.log((await $\`echo $FOO\`).stdout);
console.log((await $\`echo $BAR\`).stdout)
`

const out = await $`node build/cli.js --env=${env} <<< ${file}`
fs.remove(env)
assert.equal(out.stdout, 'BAR\n\nFOO+\n\n')
})

test('supports `--env` and `--cwd` options and with file', async () => {
const env = tmpfile(
'.env',
`FOO=BAR
BAR=FOO+`
)
const dir = tmpdir()
const file = `
console.log((await $\`echo $FOO\`).stdout);
console.log((await $\`echo $BAR\`).stdout)
`

const out =
await $`node build/cli.js --cwd=${dir} --env=${env} <<< ${file}`
fs.remove(env)
fs.remove(dir)
assert.equal(out.stdout, 'BAR\n\nFOO+\n\n')
})

test('scripts from https 200', async () => {
const resp = await fs.readFile(path.resolve('test/fixtures/echo.http'))
const port = await getPort()
Expand Down
29 changes: 29 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
tempfile,
preferLocalBin,
toCamelCase,
parseDotenv,
readEnvFromFile,
} from '../build/util.js'

describe('util', () => {
Expand Down Expand Up @@ -139,3 +141,30 @@ describe('util', () => {
assert.equal(toCamelCase('kebab-input-str'), 'kebabInputStr')
})
})

test('parseDotenv()', () => {
assert.deepEqual(parseDotenv('ENV=value1\nENV2=value24'), {
ENV: 'value1',
ENV2: 'value24',
})
assert.deepEqual(parseDotenv(''), {})
})

describe('readEnvFromFile()', () => {
test('handles correct proccess.env', () => {
const file = tempfile('.env', 'ENV=value1\nENV2=value24')
const env = readEnvFromFile(file)
assert.equal(env.ENV, 'value1')
assert.equal(env.ENV2, 'value24')
assert.ok(env.NODE_VERSION !== '')
})

test('handles correct some env', () => {
const file = tempfile('.env', 'ENV=value1\nENV2=value24')
const env = readEnvFromFile(file, { version: '1.0.0', name: 'zx' })
assert.equal(env.ENV, 'value1')
assert.equal(env.ENV2, 'value24')
assert.equal(env.version, '1.0.0')
assert.equal(env.name, 'zx')
})
})