Skip to content

src: extend --env-file to also accept sections #58782

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
23 changes: 23 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,29 @@ Export keyword before a key is ignored:
export USERNAME="nodejs" # will result in `nodejs` as the value.
```

Additionally sections can be used to have a more granular control of
the environment variables within a single file.

Sections can be defined in the file and then targeted by including a hash character
followed by their name as the flag's argument. Multiple sections can be specified and
if a variable is defined in multiple sections the latest instance of the variable in
the file overrides the others.

For example given the following file:

```text
MY_VAR = 'my top-level variable'

[dev]
MY_VAR = 'my variable for development'

[prod]
MY_VAR = 'my variable for production'
```

`--env-file=config#dev` will make it so that the variable's value being used is
taken from the `dev` section.

If you want to load environment variables from a file that may not exist, you
can use the [`--env-file-if-exists`][] flag instead.

Expand Down
4 changes: 4 additions & 0 deletions doc/api/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -2791,6 +2791,10 @@ added:

* `path` {string | URL | Buffer | undefined}. **Default:** `'./.env'`

* `options`

* `sections` {string\[]} (optional) The sections to use.

Loads the `.env` file into `process.env`. Usage of `NODE_OPTIONS`
in the `.env` file will not have any effect on Node.js.

Expand Down
56 changes: 50 additions & 6 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -2133,7 +2133,7 @@ $ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
```

## `util.parseEnv(content)`
## `util.parseEnv(content, sections)`

<!-- YAML
added:
Expand All @@ -2143,28 +2143,72 @@ added:

> Stability: 1.1 - Active development

* `content` {string}
* `content` {string} The con
The raw contents of a `.env` file.

The raw contents of a `.env` file.
* `options`

* `sections` {string\[]} (optional)
The sections to take from the content

* Returns: {Object}

Given an example `.env` file:
Examples:

```cjs
const { parseEnv } = require('node:util');

parseEnv('HELLO=world\nHELLO=oh my\n');
parseEnv(`
HELLO=world
HELLO=oh my
`);
// Returns: { HELLO: 'oh my' }
```

```mjs
import { parseEnv } from 'node:util';

parseEnv('HELLO=world\nHELLO=oh my\n');
parseEnv(`
HELLO=world
HELLO=oh my
`);
// Returns: { HELLO: 'oh my' }
```

```cjs
const { parseEnv } = require('node:util');

parseEnv(`
X = x
Y = y

[section-a]
X = x_a

[section-b]
Y = y_b
Z = z_b
`, { sections: ['section-b'] });
// Returns: { X: 'x', Y: 'y_b', Z: 'z_b' }
```

```mjs
import { parseEnv } from 'node:util';

parseEnv(`
X = x
Y = y

[section-a]
X = x_a

[section-b]
Y = y_b
Z = z_b
`, { sections: ['section-b'] });
// Returns: { X: 'x', Y: 'y_b', Z: 'z_b' }
```

## `util.promisify(original)`

<!-- YAML
Expand Down
15 changes: 8 additions & 7 deletions lib/internal/process/per_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const {
validateNumber,
validateObject,
validateString,
validateStringArray,
} = require('internal/validators');

const dc = require('diagnostics_channel');
Expand Down Expand Up @@ -354,15 +355,15 @@ function wrapProcessMethods(binding) {
/**
* Loads the `.env` file to process.env.
* @param {string | URL | Buffer | undefined} path
* @param {{ sections?: string[] }} [options]
*/
function loadEnvFile(path = undefined) { // Provide optional value so that `loadEnvFile.length` returns 0
if (path != null) {
getValidatedPath ??= require('internal/fs/utils').getValidatedPath;
path = getValidatedPath(path);
_loadEnvFile(path);
} else {
_loadEnvFile();
function loadEnvFile(path = '.env', options = {}) {
getValidatedPath ??= require('internal/fs/utils').getValidatedPath;
path = getValidatedPath(path);
if ('sections' in options) {
validateStringArray(options.sections, 'options.section');
}
_loadEnvFile(path, options.sections ?? []);
}

return {
Expand Down
9 changes: 7 additions & 2 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const {
validateFunction,
validateNumber,
validateString,
validateStringArray,
validateOneOf,
validateObject,
} = require('internal/validators');
Expand Down Expand Up @@ -316,11 +317,15 @@ function _exceptionWithHostPort(...args) {
/**
* Parses the content of a `.env` file.
* @param {string} content
* @param {{ sections?: string[] }} [options]
* @returns {Record<string, string>}
*/
function parseEnv(content) {
function parseEnv(content, options = {}) {
validateString(content, 'content');
return binding.parseEnv(content);
if ('sections' in options.sections) {
validateStringArray(options.sections, 'options.section');
}
return binding.parseEnv(content, options.sections ?? []);
}

const lazySourceMap = getLazy(() => require('internal/source_map/source_map_cache'));
Expand Down
3 changes: 2 additions & 1 deletion src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,8 @@ static ExitCode InitializeNodeWithArgsInternal(
CHECK(!per_process::v8_initialized);

for (const auto& file_data : env_files) {
switch (per_process::dotenv_file.ParsePath(file_data.path)) {
switch (per_process::dotenv_file.ParsePath(file_data.path,
file_data.sections)) {
case Dotenv::ParseResult::Valid:
break;
case Dotenv::ParseResult::InvalidContent:
Expand Down
Loading
Loading