diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c131636..28f3144c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,4 +22,3 @@ jobs: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test - - run: npm run test:coverage diff --git a/README.md b/README.md index 29d6f253..e21f47fe 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -dotenvx +> [dotenvx](https://dotenvx.com/?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=banner) — a secure dotenv, from the creator of `dotenv` for the agentic age. Run anywhere, encrypt secrets, and commit safely. # dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv) [![downloads](https://img.shields.io/npm/dw/dotenv)](https://www.npmjs.com/package/dotenv) @@ -153,6 +153,29 @@ const config = dotenv.parse(buf) // will return an object console.log(typeof config, config) // object { BASIC : 'basic' } ``` + +
Run
+ +Use `dotenv run --` to run a command with environment variables from your `.env` file. + +```bash +$ dotenv run -- node index.js +◇ injected env (2) from .env +``` + +Use `-f` to select one or more `.env` files. + +```bash +$ dotenv run -f .env.local -f .env -- node index.js +◇ injected env (2) from .env.local, .env +``` + +Use `--quiet` to suppress the injected env message. + +```bash +$ dotenv run --quiet -- node index.js +``` +
Preload
diff --git a/cli.js b/cli.js new file mode 100755 index 00000000..304debc0 --- /dev/null +++ b/cli.js @@ -0,0 +1,167 @@ +#!/usr/bin/env node + +const fs = require('fs') +const path = require('path') +const cp = require('child_process') + +const dotenv = require('./lib/main') + +function printHelp () { + console.log([ + 'Usage: dotenv run [--help] [--quiet] [-f ] -- ', + '', + 'Run a command with environment variables from a .env file.', + '', + 'Options:', + ' -f path to your .env file (default: .env)', + ' --quiet suppress the injected env message' + ].join('\n')) +} + +function parseRunArgs (args) { + const paths = [] + let defaultPath = true + let quiet = false + let commandIndex = -1 + + for (let i = 0; i < args.length; i++) { + const arg = args[i] + + if (arg === '--') { + commandIndex = i + 1 + break + } + + if (arg === '--help' || arg === '-h') { + return { help: true } + } + + if (arg === '--quiet') { + quiet = true + continue + } + + if (arg === '-f') { + const filepath = args[i + 1] + if (!filepath || filepath === '--') { + return { error: '-f requires a path' } + } + + paths.push(filepath) + defaultPath = false + i++ + continue + } + + if (arg.startsWith('-f=')) { + const filepath = arg.slice(3) + if (!filepath) { + return { error: '-f requires a path' } + } + + paths.push(filepath) + defaultPath = false + continue + } + + return { error: `unknown option: ${arg}` } + } + + const command = commandIndex === -1 ? [] : args.slice(commandIndex) + return { + paths: paths.length > 0 ? paths : ['.env'], + defaultPath, + quiet, + command + } +} + +function loadEnvFiles (paths, defaultPath) { + const parsedAll = {} + const loadedPaths = [] + + for (const filepath of paths) { + const resolvedPath = path.resolve(process.cwd(), filepath) + try { + const parsed = dotenv.parse(fs.readFileSync(resolvedPath, { encoding: 'utf8' })) + dotenv.populate(parsedAll, parsed) + loadedPaths.push(filepath) + } catch (e) { + if (!(defaultPath && e.code === 'ENOENT')) { + throw e + } + } + } + + const injected = dotenv.populate(process.env, parsedAll) + return { injected, loadedPaths } +} + +function run (argv) { + const command = argv[0] + + if (command === '--help' || command === '-h') { + printHelp() + return + } + + if (command !== 'run') { + printHelp() + process.exitCode = 1 + return + } + + const parsed = parseRunArgs(argv.slice(1)) + if (parsed.help) { + printHelp() + return + } + + if (parsed.error) { + console.error(`dotenv: ${parsed.error}`) + printHelp() + process.exitCode = 1 + return + } + + if (parsed.command.length === 0) { + printHelp() + process.exitCode = 1 + return + } + + try { + const result = loadEnvFiles(parsed.paths, parsed.defaultPath) + if (!parsed.quiet) { + let message = `◇ injected env (${Object.keys(result.injected).length})` + if (result.loadedPaths.length > 0) { + message += ` from ${result.loadedPaths.join(', ')}` + } + console.log(message) + } + } catch (e) { + console.error(`dotenv: ${e.message}`) + process.exitCode = 1 + return + } + + const child = cp.spawn(parsed.command[0], parsed.command.slice(1), { + stdio: 'inherit', + shell: process.platform === 'win32' + }) + + child.on('error', function (e) { + console.error(`dotenv: ${e.message}`) + process.exitCode = 1 + }) + + child.on('exit', function (exitCode, signal) { + if (typeof exitCode === 'number') { + process.exit(exitCode) + } else { + process.kill(process.pid, signal) + } + }) +} + +run(process.argv.slice(2)) diff --git a/lib/main.js b/lib/main.js index 8541f359..7ab59a32 100644 --- a/lib/main.js +++ b/lib/main.js @@ -3,24 +3,6 @@ const path = require('path') const os = require('os') const crypto = require('crypto') -// Array of tips to display randomly -const TIPS = [ - '◈ encrypted .env [www.dotenvx.com]', - '◈ secrets for agents [www.dotenvx.com]', - '✦ add agent skills [npx skills add motdotla/dotenv]', - '⌁ auth for agents [www.vestauth.com]', - '⌘ custom filepath { path: \'/custom/path/.env\' }', - '⌘ enable debugging { debug: true }', - '⌘ override existing { override: true }', - '⌘ suppress logs { quiet: true }', - '⌘ multiple files { path: [\'.env.local\', \'.env\'] }' -] - -// Get a random tip from the tips array -function _getRandomTip () { - return TIPS[Math.floor(Math.random() * TIPS.length)] -} - function parseBoolean (value) { if (typeof value === 'string') { return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase()) @@ -28,14 +10,6 @@ function parseBoolean (value) { return Boolean(value) } -function supportsAnsi () { - return process.stdout.isTTY // && process.env.TERM !== 'dumb' -} - -function dim (text) { - return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text -} - const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg // Parse src into an Object @@ -307,7 +281,7 @@ function configDotenv (options) { } } - _log(`injected env (${keysCount}) from ${shortPaths.join(',')} ${dim(`// tip: ${_getRandomTip()}`)}`) + _log(`injected env (${keysCount}) from ${shortPaths.join(',')}`) } if (lastError) { diff --git a/package-lock.json b/package-lock.json index f426b2bb..9de030d6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "dotenv", "version": "17.4.2", "license": "BSD-2-Clause", + "bin": { + "dotenv": "cli.js" + }, "devDependencies": { "@types/node": "^18.11.3", "decache": "^4.6.2", @@ -1070,6 +1073,7 @@ "integrity": "sha512-NYMp0bl52DxXfcLmivMKvOIE14aaB9qJjdHeUbs6GZ9yxgD5w0yeiOT+gWEL+1PzZgGWRxSFEpghID1YfXAc4w==", "dev": true, "license": "BlueOak-1.0.0", + "peer": true, "dependencies": { "@tapjs/processinfo": "^3.1.8", "@tapjs/stack": "2.0.1", @@ -1962,7 +1966,8 @@ "version": "18.11.3", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.3.tgz", "integrity": "sha512-fNjDQzzOsZeKZu5NATgXUPsaFaTxeRgFXoosrHivTl8RGeV733OLawXsGfEk9a8/tySyZUyiZ6E8LcjPFZ2y1A==", - "dev": true + "dev": true, + "peer": true }, "node_modules/@types/normalize-package-data": { "version": "2.4.1", @@ -1986,6 +1991,7 @@ "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3554,6 +3560,7 @@ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.25.0.tgz", "integrity": "sha512-DVlJOZ4Pn50zcKW5bYH7GQK/9MsoQG2d5eDH0ebEkE8PbgzTTmtt/VTH9GGJ4BfeZCpBLqFfvsjX35UacUL83A==", "dev": true, + "peer": true, "dependencies": { "@eslint/eslintrc": "^1.3.3", "@humanwhocodes/config-array": "^0.10.5", @@ -3747,6 +3754,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", "dev": true, + "peer": true, "dependencies": { "array-includes": "^3.1.4", "array.prototype.flat": "^1.2.5", @@ -3801,6 +3809,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-n/-/eslint-plugin-n-15.3.0.tgz", "integrity": "sha512-IyzPnEWHypCWasDpxeJnim60jhlumbmq0pubL6IOcnk8u2y53s5QfT8JnXy7skjHJ44yWHRb11PLtDHuu1kg/Q==", "dev": true, + "peer": true, "dependencies": { "builtins": "^5.0.1", "eslint-plugin-es": "^4.1.0", @@ -3839,6 +3848,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-6.1.1.tgz", "integrity": "sha512-tjqWDwVZQo7UIPMeDReOpUgHCmCiH+ePnVT+5zVapL0uuHnegBUs2smM13CzOs2Xb5+MHMRFTs9v24yjba4Oig==", "dev": true, + "peer": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -3851,6 +3861,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.31.10.tgz", "integrity": "sha512-e4N/nc6AAlg4UKW/mXeYWd3R++qUano5/o+t+wnWxIf+bLsOaH3a4q74kX3nDjYym3VBN4HyO9nEn1GcAqgQOA==", "dev": true, + "peer": true, "dependencies": { "array-includes": "^3.1.5", "array.prototype.flatmap": "^1.3.0", @@ -7476,6 +7487,7 @@ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -9346,6 +9358,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -9732,6 +9745,7 @@ "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", "dev": true, "license": "ISC", + "peer": true, "bin": { "yaml": "bin.mjs" }, @@ -10487,6 +10501,7 @@ "resolved": "https://registry.npmjs.org/@tapjs/core/-/core-2.1.6.tgz", "integrity": "sha512-NYMp0bl52DxXfcLmivMKvOIE14aaB9qJjdHeUbs6GZ9yxgD5w0yeiOT+gWEL+1PzZgGWRxSFEpghID1YfXAc4w==", "dev": true, + "peer": true, "requires": { "@tapjs/processinfo": "^3.1.8", "@tapjs/stack": "2.0.1", @@ -11053,7 +11068,8 @@ "version": "18.11.3", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.3.tgz", "integrity": "sha512-fNjDQzzOsZeKZu5NATgXUPsaFaTxeRgFXoosrHivTl8RGeV733OLawXsGfEk9a8/tySyZUyiZ6E8LcjPFZ2y1A==", - "dev": true + "dev": true, + "peer": true }, "@types/normalize-package-data": { "version": "2.4.1", @@ -11071,7 +11087,8 @@ "version": "8.14.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", - "dev": true + "dev": true, + "peer": true }, "acorn-jsx": { "version": "5.3.2", @@ -12204,6 +12221,7 @@ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.25.0.tgz", "integrity": "sha512-DVlJOZ4Pn50zcKW5bYH7GQK/9MsoQG2d5eDH0ebEkE8PbgzTTmtt/VTH9GGJ4BfeZCpBLqFfvsjX35UacUL83A==", "dev": true, + "peer": true, "requires": { "@eslint/eslintrc": "^1.3.3", "@humanwhocodes/config-array": "^0.10.5", @@ -12356,6 +12374,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.26.0.tgz", "integrity": "sha512-hYfi3FXaM8WPLf4S1cikh/r4IxnO6zrhZbEGz2b660EJRbuxgpDS5gkCuYgGWg2xxh2rBuIr4Pvhve/7c31koA==", "dev": true, + "peer": true, "requires": { "array-includes": "^3.1.4", "array.prototype.flat": "^1.2.5", @@ -12403,6 +12422,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-n/-/eslint-plugin-n-15.3.0.tgz", "integrity": "sha512-IyzPnEWHypCWasDpxeJnim60jhlumbmq0pubL6IOcnk8u2y53s5QfT8JnXy7skjHJ44yWHRb11PLtDHuu1kg/Q==", "dev": true, + "peer": true, "requires": { "builtins": "^5.0.1", "eslint-plugin-es": "^4.1.0", @@ -12427,6 +12447,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-6.1.1.tgz", "integrity": "sha512-tjqWDwVZQo7UIPMeDReOpUgHCmCiH+ePnVT+5zVapL0uuHnegBUs2smM13CzOs2Xb5+MHMRFTs9v24yjba4Oig==", "dev": true, + "peer": true, "requires": {} }, "eslint-plugin-react": { @@ -12434,6 +12455,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.31.10.tgz", "integrity": "sha512-e4N/nc6AAlg4UKW/mXeYWd3R++qUano5/o+t+wnWxIf+bLsOaH3a4q74kX3nDjYym3VBN4HyO9nEn1GcAqgQOA==", "dev": true, + "peer": true, "requires": { "array-includes": "^3.1.5", "array.prototype.flatmap": "^1.3.0", @@ -14994,6 +15016,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "dev": true, + "peer": true, "requires": { "loose-envify": "^1.1.0" } @@ -16299,7 +16322,8 @@ "version": "4.8.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.8.4.tgz", "integrity": "sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==", - "dev": true + "dev": true, + "peer": true }, "uglify-js": { "version": "3.17.3", @@ -16570,7 +16594,8 @@ "version": "2.6.1", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz", "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", - "dev": true + "dev": true, + "peer": true }, "yaml-types": { "version": "0.3.0", diff --git a/package.json b/package.json index 1efa8e64..ec386733 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "version": "17.4.2", "description": "Loads environment variables from .env file", "main": "lib/main.js", + "bin": { + "dotenv": "./cli.js" + }, "types": "lib/main.d.ts", "exports": { ".": { @@ -22,7 +25,6 @@ "dts-check": "tsc --project tests/types/tsconfig.json", "lint": "standard", "test": "npm run lint && npm run dts-check && tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000", - "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov", "prerelease": "npm test", "release": "standard-version" }, diff --git a/tests/test-cli.js b/tests/test-cli.js new file mode 100644 index 00000000..3caaef3f --- /dev/null +++ b/tests/test-cli.js @@ -0,0 +1,263 @@ +const cp = require('child_process') +const fs = require('fs') +const os = require('os') +const path = require('path') + +const t = require('tap') + +function spawn (args, options = {}) { + return cp.spawnSync( + process.argv[0], + [path.resolve(__dirname, '../cli.js')].concat(args), + Object.assign( + {}, + { + cwd: path.resolve(__dirname, '..'), + timeout: 5000, + encoding: 'utf8', + env: Object.assign({}, process.env) + }, + options + ) + ) +} + +function removeDir (dir) { + if (fs.rmSync) { + fs.rmSync(dir, { recursive: true, force: true }) + } else { + fs.rmdirSync(dir, { recursive: true }) + } +} + +t.test('dotenv run loads .env by default', ct => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'dotenv-run-')) + fs.writeFileSync(path.join(cwd, '.env'), 'BASIC=basic\n') + + const result = spawn([ + 'run', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ], { + cwd + }) + + removeDir(cwd) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (1) from .env\nbasic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run continues when default .env is missing', ct => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'dotenv-run-')) + + const result = spawn([ + 'run', + '--', + process.argv[0], + '-e', + 'console.log("ok")' + ], { + cwd + }) + + removeDir(cwd) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (0)\nok\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run supports -f path', ct => { + const result = spawn([ + 'run', + '-f', + './tests/.env.local', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ]) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (2) from ./tests/.env.local\nlocal_basic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run supports -f=path', ct => { + const result = spawn([ + 'run', + '-f=./tests/.env.local', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ]) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (2) from ./tests/.env.local\nlocal_basic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run supports multiple -f paths without override', ct => { + const result = spawn([ + 'run', + '-f', + './tests/.env.local', + '-f', + './tests/.env', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ]) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (41) from ./tests/.env.local, ./tests/.env\nlocal_basic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run does not override existing environment variables', ct => { + const result = spawn( + [ + 'run', + '-f', + './tests/.env', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ], + { + env: Object.assign({}, process.env, { BASIC: 'existing' }) + } + ) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (39) from ./tests/.env\nexisting\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run ignores DOTENV_KEY vault behavior', ct => { + const result = spawn( + [ + 'run', + '-f', + './tests/.env', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ], + { + env: Object.assign({}, process.env, { DOTENV_KEY: 'dotenv://:bad@dotenvx.com/vault/.env.vault?environment=production' }) + } + ) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (40) from ./tests/.env\nbasic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run does not expand variables', ct => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'dotenv-run-')) + fs.writeFileSync(path.join(cwd, '.env'), 'BASIC=basic\nEXPANDED=$BASIC\n') + + const result = spawn([ + 'run', + '--', + process.argv[0], + '-e', + 'console.log(process.env.EXPANDED)' + ], { + cwd + }) + + removeDir(cwd) + + ct.equal(result.status, 0) + ct.equal(result.stdout, '◇ injected env (2) from .env\n$BASIC\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run exits with child status', ct => { + const result = spawn([ + 'run', + '--', + process.argv[0], + '-e', + 'process.exit(7)' + ]) + + ct.equal(result.status, 7) + ct.end() +}) + +t.test('dotenv run supports --quiet', ct => { + const result = spawn([ + 'run', + '--quiet', + '-f', + './tests/.env.local', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ]) + + ct.equal(result.status, 0) + ct.equal(result.stdout, 'local_basic\n') + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run requires -- before command', ct => { + const result = spawn([ + 'run', + process.argv[0], + '-e', + 'console.log("nope")' + ]) + + ct.equal(result.status, 1) + ct.match(result.stdout, /Usage: dotenv run/) + ct.equal(result.stderr, 'dotenv: unknown option: ' + process.argv[0] + '\n') + ct.end() +}) + +t.test('dotenv run requires a command', ct => { + const result = spawn(['run', '--']) + + ct.equal(result.status, 1) + ct.match(result.stdout, /Usage: dotenv run/) + ct.equal(result.stderr, '') + ct.end() +}) + +t.test('dotenv run exits when selected env file is missing', ct => { + const result = spawn([ + 'run', + '-f', + './tests/.env.missing', + '--', + process.argv[0], + '-e', + 'console.log(process.env.BASIC)' + ]) + + ct.equal(result.status, 1) + ct.equal(result.stdout, '') + ct.match(result.stderr, /ENOENT/) + ct.end() +}) diff --git a/tests/test-config.js b/tests/test-config.js index 2c58f9e5..93889f97 100644 --- a/tests/test-config.js +++ b/tests/test-config.js @@ -301,117 +301,14 @@ t.test('path.relative fails somehow', ct => { ct.end() }) -t.test('displays random tips from the tips array', ct => { - ct.plan(2) - - const originalTTY = process.stdout.isTTY - process.stdout.isTTY = true - - logStub = sinon.stub(console, 'log') - const testPath = 'tests/.env' - - // Test that tips are displayed (run config multiple times to see variation) - dotenv.config({ path: testPath }) - dotenv.config({ path: testPath }) - dotenv.config({ path: testPath }) - - // Should have at least one call that contains a tip - let foundTip = false - for (const call of logStub.getCalls()) { - if (call.args[0] && call.args[0].includes('tip:')) { - foundTip = true - break - } - } - - ct.ok(foundTip, 'Should display a tip') - - // Test that the tip contains one of our expected tip messages - let foundExpectedTip = false - const expectedTips = [ - '◈ encrypted .env [www.dotenvx.com]', - '◈ secrets for agents [www.dotenvx.com]', - '✦ add agent skills [npx skills add motdotla/dotenv]', - '⌁ auth for agents [www.vestauth.com]', - '⌘ custom filepath { path: \'/custom/path/.env\' }', - '⌘ enable debugging { debug: true }', - '⌘ override existing { override: true }', - '⌘ suppress logs { quiet: true }', - '⌘ multiple files { path: [\'.env.local\', \'.env\'] }' - ] - - for (const call of logStub.getCalls()) { - if (call.args[0] && call.args[0].includes('tip:')) { - for (const expectedTip of expectedTips) { - if (call.args[0].includes(expectedTip)) { - foundExpectedTip = true - break - } - } - } - } - - ct.ok(foundExpectedTip, 'Should display one of the expected tips') - - // Restore - process.stdout.isTTY = originalTTY - ct.end() -}) - -t.test('displays random tips from the tips array with fallback for isTTY false', ct => { - ct.plan(2) - - const originalTTY = process.stdout.isTTY - process.stdout.isTTY = undefined - +t.test('displays the injected env message without tips', ct => { + ct.plan(1) logStub = sinon.stub(console, 'log') const testPath = 'tests/.env' - // Test that tips are displayed (run config multiple times to see variation) - dotenv.config({ path: testPath }) - dotenv.config({ path: testPath }) dotenv.config({ path: testPath }) - // Should have at least one call that contains a tip - let foundTip = false - for (const call of logStub.getCalls()) { - if (call.args[0] && call.args[0].includes('tip:')) { - foundTip = true - break - } - } - - ct.ok(foundTip, 'Should display a tip') - - // Test that the tip contains one of our expected tip messages - let foundExpectedTip = false - const expectedTips = [ - '◈ encrypted .env [www.dotenvx.com]', - '◈ secrets for agents [www.dotenvx.com]', - '✦ add agent skills [npx skills add motdotla/dotenv]', - '⌁ auth for agents [www.vestauth.com]', - '⌘ custom filepath { path: \'/custom/path/.env\' }', - '⌘ enable debugging { debug: true }', - '⌘ override existing { override: true }', - '⌘ suppress logs { quiet: true }', - '⌘ multiple files { path: [\'.env.local\', \'.env\'] }' - ] - - for (const call of logStub.getCalls()) { - if (call.args[0] && call.args[0].includes('tip:')) { - for (const expectedTip of expectedTips) { - if (call.args[0].includes(expectedTip)) { - foundExpectedTip = true - break - } - } - } - } - - ct.ok(foundExpectedTip, 'Should display one of the expected tips') - - // Restore - process.stdout.isTTY = originalTTY + ct.match(logStub.firstCall.args[0], /^◇ injected env \(\d+\) from tests\/\.env$/) ct.end() })