Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,3 @@ jobs:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
- run: npm run test:coverage
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<a href="https://dotenvx.com/?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=banner"><img src="https://dotenvx.com/dotenv-banner.png" alt="dotenvx" /></a>
> [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)

Expand Down Expand Up @@ -153,6 +153,29 @@ const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```

</details>
<details><summary>Run</summary><br>

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
```

</details>
<details><summary>Preload</summary><br>

Expand Down
167 changes: 167 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -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 <path>] -- <command>',
'',
'Run a command with environment variables from a .env file.',
'',
'Options:',
' -f <path> 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))
28 changes: 1 addition & 27 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,13 @@ 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())
}
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
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading