@karmaniverous/get-dotenv 2.6.7 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,24 +3,21 @@
3
3
  Load environment variables with a cascade of environment-aware dotenv files. You can:
4
4
 
5
5
  - Load dotenv files synchronously or asynchronously.
6
- - Specify the directory containing your dotenv files.
7
- - Specify the token that identifies dotenv files (e.g. '.env').
8
- - Specify the token that identifies private vatiables (e.g. 'local').
9
- - Define dynamic variables progressively in terms of other variables and other logic.
10
6
  - Load variables for a specific environment or none.
11
- - Exclude public or private variables.
12
- - Extract variables to an object, to `process.env`, or both.
13
- - Log the result to the console.
14
-
15
- The command-line version can pull the environment designator from a number of sources, populate `process.env`, and execute a shell command.
7
+ - Define dynamic variables progressively in terms of other variables and other logic.
8
+ - Exclude public, private, global, environment-specific, or dynamic variables.
9
+ - Extract the resulting variables to an object, `process.env`, a dotenv file, or a logger, in any combination.
10
+ - Specify the directories containing your dotenv files.
11
+ - Specify the filename token that identifies dotenv files (e.g. '.env').
12
+ - Specify the filename extension that identifies private variables (e.g. 'local').
16
13
 
17
14
  `getdotenv` relies on the excellent [`dotenv`](https://www.npmjs.com/package/dotenv) parser and uses [`dotenv-expand`](https://www.npmjs.com/package/dotenv-expand) for recursive variable expansion.
18
15
 
19
- **So why not just use the very popular [`dotenv-cli`](https://www.npmjs.com/package/dotenv-cli) package to load dotenv file cascades?** A couple of reasons:
16
+ The command-line version populates `process.env` from your dotenv files (you can also specify values inline) and can then execute a shell command within that context. The executing shell is configurable. Any child `getdotenv` instances will inherit as defaults the parent shell's environment and optionally its `getdotenv` settings.
20
17
 
21
- - `dotenv-cli` assumes all your `.env` files are located in your root directory. If you have a lot of environments, you probably want to sequester them into their own directory.
18
+ You can always use `getdotenv` directly on the command line, but its REAL power comes into play when you use it as the foundation of your own CLI. This lets you set defaults globally and configure pre- and post-hooks that mutate your `getdotenv` context and do useful things like grab an AWS session from your dev environment and add it to the command execution context.
22
19
 
23
- - The `dotenv-cli` syntax requires the environment to be set (the `-c` argument) _before_ the shell command is articulated (after the `--`). This doesn't work if you want to write an NPM script that takes the environment as an argument, since in that case it would have to go at the end.
20
+ When you plug your own [`commander`](https://www.npmjs.com/package/commander) CLI commands into the `getdotenv` base, they will execute within all of the environmental context created above!
24
21
 
25
22
  ## Installation
26
23
 
@@ -61,55 +58,63 @@ This function should take the expanded `dotenv` object as an argument and return
61
58
  If the corresponding value is a function, it will be executed with the current state of `dotenv` as its single argument and the result applied back to the `dotenv` object. Otherwise, the value will just be applied back to `dotenv`.
62
59
 
63
60
  Since keys will be evaluated progressively, each successive key function will have access to any previous ones. These keys can also override existing variables.
61
+
62
+ ## More to Come!
63
+
64
+ Implementation always runs a little behind documentation. These topics & improvements are coming soon:
65
+
66
+ - Rationalize the package's JSDOC to improve the API documentation below.
67
+ - An example of dotenv-based environment config.
68
+ - Integrating `getdotenv` into your npm scripts.
69
+ - Creating a `getdotenv`-based CLI.
70
+ - Some gotchas & tips around managing your shell execution context.
64
71
 
65
72
  # Command Line Interface
66
73
 
74
+ Note that the defaults below can be changed in your own environment by deriving your base CLI using the `getCli` function.
75
+
67
76
  ```text
68
- Usage: getdotenv [options] [-- [command]]
69
-
70
- Load environment variables with a cascade of environment-aware
71
- dotenv files. You can:
72
-
73
- * Specify the directories containing your dotenv files.
74
- * Define dynamic variables progressively in terms of other variables and
75
- other logic.
76
- * Specify a consolidated output file path.
77
- * Load variables for a specific environment or none.
78
- * Specify a default environment, override the default with an existing
79
- environment variable, and override both with a direct setting.
80
- * Derive the default environment from the current git branch
81
- * Exclude public, private, global, environment-specific, or dynamic variables.
82
- * Execute a &&-delimited series of shell commands after loading variables,
83
- optionally ignoring errors.
84
- * Place the shell commands inside the invocation to support npm script
85
- arguments for other options.
86
- * Specify the token that identifies dotenv files (e.g. '.env').
87
- * Specify the token that identifies private vatiables (e.g. '.local').
88
- * Load AWS SSO session credentials from an AWS Toolkit profile.
77
+ Usage: getdotenv [options] [command]
78
+
79
+ Base CLI. All options except delimiters follow dotenv-expand rules.
89
80
 
90
81
  Options:
91
- -p, --paths <strings...> space-delimited paths to dotenv directory (default './')
92
- -y, --dynamic-path <string> dynamic variables path
93
- -o, --output-path <string> consolidated output file (follows dotenv-expand rules using loaded env vars)
94
- -d, --default-environment <string> default environment (prefix with $ to use environment variable)
95
- -b, --branch-to-default derive default environment from the current git branch (default: false)
96
- -e, --environment <string> designated environment (prefix with $ to use environment variable)
97
- -n, --exclude-env exclude environment-specific variables (default: false)
98
- -g, --exclude-global exclude global & dynamic variables (default: false)
99
- -r, --exclude-private exclude private variables (default: false)
100
- -u, --exclude-public exclude public variables (default: false)
101
- -z, --exclude-dynamic exclude dynamic variables (default: false)
102
- -c, --command <string> shell command string
103
- -l, --log log extracted variables (default: false)
104
- -t, --dotenv-token <string> token indicating a dotenv file (default: '.env')
105
- -i, --private-token <string> token indicating private variables (default: 'local')
106
- -q, --quit-on-error terminate sequential process on error (default: false)
107
- -a, --aws-sso-profile <string> local AWS SSO profile (follows dotenv-expand rules)
108
- -h, --help display help for command
82
+ -e, --env <string> environment name
83
+ -p, --paths <string> delimited list of paths to dotenv directory (default: "./")
84
+ --paths-delimiter <string> regex paths delimiter (default: "\\s+")
85
+ -v, --vars <string> delimited list KEY=VALUE pairs
86
+ --vars-delimiter <string> regex vars delimiter (default: "\\s+")
87
+ --vars-assignor <string> regex vars assignment operator (default: "=")
88
+ -y, --dynamic-path <string> dynamic variables path
89
+ -o, --output-path <string> consolidated output file, follows dotenv-expand rules using loaded env vars
90
+ -n, --exclude-env [bool] exclude environment-specific variables (default: false)
91
+ -g, --exclude-global [bool] exclude global & dynamic variables (default: false)
92
+ -r, --exclude-private [bool] exclude private variables (default: false)
93
+ -u, --exclude-public [bool] exclude public variables (default: false)
94
+ -z, --exclude-dynamic [bool] exclude dynamic variables (default: false)
95
+ -l, --log [bool] console log extracted variables (default: false)
96
+ -x, --suppress-dotenv suppress dotenv loading (default: false)
97
+ -c, --command <string> shell command string
98
+ -s, --shell <string> execa shell option
99
+ --dotenv-token <string> token indicating a dotenv file (default: ".env")
100
+ --private-token <string> token indicating private variables (default: "local")
101
+ -h, --help display help for command
102
+
103
+ Commands:
104
+ cmd execute shell command string (default command)
105
+ help [command] display help for command
109
106
  ```
110
107
 
111
108
  # API Documentation
112
109
 
110
+ ## Constants
111
+
112
+ <dl>
113
+ <dt><a href="#getCli">getCli</a> ⇒ <code>object</code></dt>
114
+ <dd><p>Generate a CLI for get-dotenv.</p>
115
+ </dd>
116
+ </dl>
117
+
113
118
  ## Functions
114
119
 
115
120
  <dl>
@@ -124,11 +129,35 @@ Options:
124
129
  ## Typedefs
125
130
 
126
131
  <dl>
132
+ <dt><a href="#GetDotenvCliOptions">GetDotenvCliOptions</a> : <code>Object</code></dt>
133
+ <dd><p>GetDotenv CLI Options type</p>
134
+ </dd>
135
+ <dt><a href="#GetDotenvPreHookCallback">GetDotenvPreHookCallback</a> ⇒ <code><a href="#GetDotenvCliOptions">GetDotenvCliOptions</a></code></dt>
136
+ <dd><p>GetDotenv CLI Pre-hook Callback type. Transforms inbound options &amp; executes side effects.</p>
137
+ </dd>
138
+ <dt><a href="#GetDotenvPostHookCallback">GetDotenvPostHookCallback</a> : <code>function</code></dt>
139
+ <dd><p>GetDotenv CLI Post-hook Callback type. Executes side effects within getdotenv context.</p>
140
+ </dd>
141
+ <dt><a href="#GetDotenvCliConfig">GetDotenvCliConfig</a> : <code>Object</code></dt>
142
+ <dd><p>GetDotenv CLI Config type</p>
143
+ </dd>
127
144
  <dt><a href="#OptionsType">OptionsType</a> : <code>Object</code></dt>
128
145
  <dd><p>get-dotenv options type</p>
129
146
  </dd>
130
147
  </dl>
131
148
 
149
+ <a name="getCli"></a>
150
+
151
+ ## getCli ⇒ <code>object</code>
152
+ Generate a CLI for get-dotenv.
153
+
154
+ **Kind**: global constant
155
+ **Returns**: <code>object</code> - The CLI command.
156
+
157
+ | Param | Type | Description |
158
+ | --- | --- | --- |
159
+ | [config] | [<code>GetDotenvCliConfig</code>](#GetDotenvCliConfig) | config object |
160
+
132
161
  <a name="getDotenv"></a>
133
162
 
134
163
  ## getDotenv([options]) ⇒ <code>Promise.&lt;object&gt;</code>
@@ -153,6 +182,72 @@ Synchronously process dotenv files of the form .env[.<ENV>][.<PRIVATETOKEN>]
153
182
  | --- | --- | --- |
154
183
  | [options] | [<code>OptionsType</code>](#OptionsType) | options object |
155
184
 
185
+ <a name="GetDotenvCliOptions"></a>
186
+
187
+ ## GetDotenvCliOptions : <code>Object</code>
188
+ GetDotenv CLI Options type
189
+
190
+ **Kind**: global typedef
191
+ **Properties**
192
+
193
+ | Name | Type | Description |
194
+ | --- | --- | --- |
195
+ | [cliInvocation] | <code>string</code> | cli invocation string (used for cli help) |
196
+ | [dotenvToken] | <code>string</code> | token indicating a dotenv file |
197
+ | [dynamicPath] | <code>string</code> | path to file exporting an object keyed to dynamic variable functions |
198
+ | [env] | <code>string</code> | target environment |
199
+ | [excludeDynamic] | <code>bool</code> | exclude dynamic variables |
200
+ | [excludeEnv] | <code>bool</code> | exclude environment-specific variables |
201
+ | [excludeGlobal] | <code>bool</code> | exclude global & dynamic variables |
202
+ | [excludePrivate] | <code>bool</code> | exclude private variables |
203
+ | [excludePublic] | <code>bool</code> | exclude public variables |
204
+ | [log] | <code>bool</code> | log result to console |
205
+ | [logger] | <code>function</code> | logger function |
206
+ | [outputPath] | <code>string</code> | if populated, writes consolidated .env file to this path (follows [dotenv-expand rules](https://github.com/motdotla/dotenv-expand/blob/master/tests/.env)) |
207
+ | [paths] | <code>string</code> | space-delimited list of input directory paths |
208
+ | [privateToken] | <code>string</code> | token indicating private variables. |
209
+ | [shell] | <code>bool</code> \| <code>string</code> | execa shell option |
210
+ | [suppressDotenv] | <code>bool</code> | suppress dotenv loading |
211
+
212
+ <a name="GetDotenvPreHookCallback"></a>
213
+
214
+ ## GetDotenvPreHookCallback ⇒ [<code>GetDotenvCliOptions</code>](#GetDotenvCliOptions)
215
+ GetDotenv CLI Pre-hook Callback type. Transforms inbound options & executes side effects.
216
+
217
+ **Kind**: global typedef
218
+ **Returns**: [<code>GetDotenvCliOptions</code>](#GetDotenvCliOptions) - transformed GetDotenv CLI Options object (undefined return value is ignored)
219
+
220
+ | Param | Type | Description |
221
+ | --- | --- | --- |
222
+ | options | [<code>GetDotenvCliOptions</code>](#GetDotenvCliOptions) | inbound GetDotenv CLI Options object |
223
+
224
+ <a name="GetDotenvPostHookCallback"></a>
225
+
226
+ ## GetDotenvPostHookCallback : <code>function</code>
227
+ GetDotenv CLI Post-hook Callback type. Executes side effects within getdotenv context.
228
+
229
+ **Kind**: global typedef
230
+
231
+ | Param | Type | Description |
232
+ | --- | --- | --- |
233
+ | options | [<code>GetDotenvCliOptions</code>](#GetDotenvCliOptions) | GetDotenv CLI Options object |
234
+ | dotenv | <code>object</code> | dotenv object |
235
+
236
+ <a name="GetDotenvCliConfig"></a>
237
+
238
+ ## GetDotenvCliConfig : <code>Object</code>
239
+ GetDotenv CLI Config type
240
+
241
+ **Kind**: global typedef
242
+ **Properties**
243
+
244
+ | Name | Type | Description |
245
+ | --- | --- | --- |
246
+ | [config] | <code>object</code> | config options |
247
+ | [config.defaultOptions] | [<code>GetDotenvCliOptions</code>](#GetDotenvCliOptions) | default options |
248
+ | [config.preHook] | [<code>GetDotenvPreHookCallback</code>](#GetDotenvPreHookCallback) | transforms inbound options & executes side effects |
249
+ | [config.postHook] | [<code>GetDotenvPostHookCallback</code>](#GetDotenvPostHookCallback) | executes side effects within getdotenv context |
250
+
156
251
  <a name="OptionsType"></a>
157
252
 
158
253
  ## OptionsType : <code>Object</code>
@@ -163,19 +258,20 @@ get-dotenv options type
163
258
 
164
259
  | Name | Type | Description |
165
260
  | --- | --- | --- |
166
- | [dotenvToken] | <code>string</code> | token indicating a dotenv file (default: '.env') |
261
+ | [dotenvToken] | <code>string</code> | token indicating a dotenv file |
167
262
  | [dynamicPath] | <code>string</code> | path to file exporting an object keyed to dynamic variable functions |
168
263
  | [env] | <code>string</code> | target environment |
169
- | [excludeDynamic] | <code>bool</code> | exclude dynamic variables (default: false) |
170
- | [excludeEnv] | <code>bool</code> | exclude environment-specific variables (default: false) |
171
- | [excludeGlobal] | <code>bool</code> | exclude global & dynamic variables (default: false) |
172
- | [excludePrivate] | <code>bool</code> | exclude private variables (default: false) |
173
- | [excludePublic] | <code>bool</code> | exclude public variables (default: false) |
174
- | [loadProcess] | <code>bool</code> | load dotenv to process.env (default: false) |
175
- | [log] | <code>bool</code> | log result to console (default: false) |
264
+ | [excludeDynamic] | <code>bool</code> | exclude dynamic variables |
265
+ | [excludeEnv] | <code>bool</code> | exclude environment-specific variables |
266
+ | [excludeGlobal] | <code>bool</code> | exclude global & dynamic variables |
267
+ | [excludePrivate] | <code>bool</code> | exclude private variables |
268
+ | [excludePublic] | <code>bool</code> | exclude public variables |
269
+ | [loadProcess] | <code>bool</code> | load dotenv to process.env |
270
+ | [log] | <code>bool</code> | log result to logger |
271
+ | [logger] | <code>function</code> | logger function |
176
272
  | [outputPath] | <code>string</code> | if populated, writes consolidated .env file to this path (follows [dotenv-expand rules](https://github.com/motdotla/dotenv-expand/blob/master/tests/.env)) |
177
- | [paths] | <code>Array.&lt;string&gt;</code> | array of input directory paths (default ['./']) |
178
- | [privateToken] | <code>string</code> | token indicating private variables (default: 'local'). |
273
+ | [paths] | <code>Array.&lt;string&gt;</code> | array of input directory paths |
274
+ | [privateToken] | <code>string</code> | token indicating private variables |
179
275
 
180
276
 
181
277
  ---
@@ -1,164 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // Import npm packages.
4
- import spawn from 'cross-spawn';
5
- import { parseArgsStringToArgv } from 'string-argv';
3
+ // lib imports
4
+ import { getCli } from '../../lib/getCli.js';
6
5
 
7
- // Import package exports.
8
- import {
9
- dotenvExpand,
10
- getAwsSsoCredentials,
11
- getDotenv,
12
- parseBranch,
13
- } from '../../lib/index.js';
6
+ const cli = getCli();
14
7
 
15
- // Create CLI.
16
- import { program } from 'commander';
17
-
18
- // CLI description.
19
- program
20
- .name('getdotenv')
21
- .usage('[options] [-- [command]]')
22
- .description(
23
- [
24
- `Load environment variables with a cascade of environment-aware`,
25
- `dotenv files. You can:`,
26
- ``,
27
- `* Specify the directories containing your dotenv files.`,
28
- `* Define dynamic variables progressively in terms of other variables and`,
29
- ` other logic.`,
30
- `* Specify a consolidated output file path.`,
31
- `* Load variables for a specific environment or none.`,
32
- `* Specify a default environment, override the default with an existing`,
33
- ` environment variable, and override both with a direct setting.`,
34
- `* Derive the default environment from the current git branch`,
35
- `* Exclude public, private, global, environment-specific, or dynamic variables.`,
36
- `* Execute a &&-delimited series of shell commands after loading variables,`,
37
- ` optionally ignoring errors.`,
38
- `* Place the shell commands inside the invocation to support npm script`,
39
- ` arguments for other options.`,
40
- `* Specify the token that identifies dotenv files (e.g. '.env').`,
41
- `* Specify the token that identifies private vatiables (e.g. '.local').`,
42
- `* Load AWS SSO session credentials from an AWS Toolkit profile.`,
43
- ].join('\n')
44
- );
45
-
46
- // CLI options.
47
- program
48
- .option(
49
- '-p, --paths <strings...>',
50
- "space-delimited paths to dotenv directory (default './')"
51
- )
52
- .option('-y, --dynamic-path <string>', 'dynamic variables path')
53
- .option(
54
- '-o, --output-path <string>',
55
- 'consolidated output file (follows dotenv-expand rules using loaded env vars)'
56
- )
57
- .option(
58
- '-d, --default-environment <string>',
59
- 'default environment (prefix with $ to use environment variable)',
60
- dotenvExpand
61
- )
62
- .option(
63
- '-b, --branch-to-default',
64
- 'derive default environment from the current git branch (default: false)',
65
- dotenvExpand
66
- )
67
- .option(
68
- '-e, --environment <string>',
69
- 'designated environment (prefix with $ to use environment variable)',
70
- dotenvExpand
71
- )
72
- .option(
73
- '-n, --exclude-env',
74
- 'exclude environment-specific variables (default: false)'
75
- )
76
- .option(
77
- '-g, --exclude-global',
78
- 'exclude global & dynamic variables (default: false)'
79
- )
80
- .option('-r, --exclude-private', 'exclude private variables (default: false)')
81
- .option('-u, --exclude-public', 'exclude public variables (default: false)')
82
- .option('-z, --exclude-dynamic', 'exclude dynamic variables (default: false)')
83
- .option('-c, --command <string>', 'shell command string')
84
- .option('-l, --log', 'log extracted variables (default: false)')
85
- .option(
86
- '-t, --dotenv-token <string>',
87
- "token indicating a dotenv file (default: '.env')"
88
- )
89
- .option(
90
- '-i, --private-token <string>',
91
- "token indicating private variables (default: 'local')"
92
- )
93
- .option(
94
- '-q, --quit-on-error',
95
- 'terminate sequential process on error (default: false)'
96
- )
97
- .option(
98
- '-a, --aws-sso-profile <string>',
99
- 'local AWS SSO profile (follows dotenv-expand rules)'
100
- );
101
-
102
- // Parse CLI options from command line.
103
- program.parse();
104
- const {
105
- awsSsoProfile,
106
- branchToDefault,
107
- command,
108
- defaultEnvironment,
109
- dotenvToken,
110
- dynamicPath,
111
- environment,
112
- excludeEnv,
113
- excludeGlobal,
114
- excludePrivate,
115
- excludePublic,
116
- log,
117
- outputPath,
118
- paths,
119
- privateToken,
120
- quitOnError,
121
- } = program.opts();
122
-
123
- if (command && program.args.length) program.error('command specified twice');
124
-
125
- if (branchToDefault) {
126
- var { envToken } = parseBranch();
127
- }
128
-
129
- // Get environment.
130
- const env = environment ?? envToken ?? defaultEnvironment;
131
-
132
- // Load dotenvs.
133
- await getDotenv({
134
- dotenvToken,
135
- env,
136
- excludeEnv,
137
- excludeGlobal,
138
- excludePrivate,
139
- excludePublic,
140
- loadProcess: true,
141
- dynamicPath,
142
- log,
143
- outputPath,
144
- paths,
145
- privateToken,
146
- });
147
-
148
- // Get AWS SSO credentials.
149
- if (awsSsoProfile) getAwsSsoCredentials(dotenvExpand(awsSsoProfile));
150
-
151
- // Execute shell command.
152
- if (command || program.args.length) {
153
- const argvs = (command ?? program.args.join(' '))
154
- .split('&&')
155
- .map((c) => parseArgsStringToArgv(c));
156
-
157
- for (const argv of argvs) {
158
- const { status } = spawn.sync(argv[0], argv.slice(1), {
159
- stdio: 'inherit',
160
- });
161
-
162
- if (status && quitOnError) process.exit(status);
163
- }
164
- }
8
+ await cli.parseAsync();
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.dotenvDefaults = void 0;
7
+ const dotenvDefaults = {
8
+ dotenvToken: '.env',
9
+ excludeDynamic: false,
10
+ excludeEnv: false,
11
+ excludeGlobal: false,
12
+ excludePrivate: false,
13
+ excludePublic: false,
14
+ loadProcess: false,
15
+ log: false,
16
+ logger: console.log,
17
+ paths: ['./'],
18
+ privateToken: 'local'
19
+ };
20
+ exports.dotenvDefaults = dotenvDefaults;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getCli = void 0;
7
+ var _boolean = require("boolean");
8
+ var _commander = require("commander");
9
+ var _execa = require("execa");
10
+ var _lodash = _interopRequireDefault(require("lodash.frompairs"));
11
+ var _lodash2 = _interopRequireDefault(require("lodash.isstring"));
12
+ var _dotenvDefaults = require("./dotenvDefaults.js");
13
+ var _dotenvExpand = require("./dotenvExpand.js");
14
+ var _getDotenv = require("./getDotenv.js");
15
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
+ // npm imports
17
+
18
+ // lib imports
19
+
20
+ const booleanExpand = value => (0, _boolean.boolean)((0, _dotenvExpand.dotenvExpand)(value));
21
+
22
+ /**
23
+ * GetDotenv CLI Options type
24
+ *
25
+ * @typedef {Object} GetDotenvCliOptions
26
+ * @property {string} [cliInvocation] - cli invocation string (used for cli help)
27
+ * @property {string} [dotenvToken] - token indicating a dotenv file
28
+ * @property {string} [dynamicPath] - path to file exporting an object keyed to dynamic variable functions
29
+ * @property {string} [env] - target environment
30
+ * @property {bool} [excludeDynamic] - exclude dynamic variables
31
+ * @property {bool} [excludeEnv] - exclude environment-specific variables
32
+ * @property {bool} [excludeGlobal] - exclude global & dynamic variables
33
+ * @property {bool} [excludePrivate] - exclude private variables
34
+ * @property {bool} [excludePublic] - exclude public variables
35
+ * @property {bool} [log] - log result to console
36
+ * @property {function} [logger] - logger function
37
+ * @property {string} [outputPath] - if populated, writes consolidated .env file to this path (follows {@link https://github.com/motdotla/dotenv-expand/blob/master/tests/.env dotenv-expand rules})
38
+ * @property {string} [paths] - space-delimited list of input directory paths
39
+ * @property {string} [privateToken] - token indicating private variables.
40
+ * @property {bool|string} [shell] - execa shell option
41
+ * @property {bool} [suppressDotenv] - suppress dotenv loading
42
+ */
43
+
44
+ /**
45
+ * GetDotenv CLI Pre-hook Callback type. Transforms inbound options & executes side effects.
46
+ *
47
+ * @async
48
+ * @callback GetDotenvPreHookCallback
49
+ * @param {GetDotenvCliOptions} options - inbound GetDotenv CLI Options object
50
+ * @returns {GetDotenvCliOptions} transformed GetDotenv CLI Options object (undefined return value is ignored)
51
+ */
52
+
53
+ /**
54
+ * GetDotenv CLI Post-hook Callback type. Executes side effects within getdotenv context.
55
+ *
56
+ * @async
57
+ * @callback GetDotenvPostHookCallback
58
+ * @param {GetDotenvCliOptions} options - GetDotenv CLI Options object
59
+ * @param {object} dotenv - dotenv object
60
+ */
61
+
62
+ /**
63
+ * GetDotenv CLI Config type
64
+ *
65
+ * @typedef {Object} GetDotenvCliConfig
66
+ * @property {object} [config] - config options
67
+ * @property {GetDotenvCliOptions} [config.defaultOptions] - default options
68
+ * @property {GetDotenvPreHookCallback} [config.preHook] - transforms inbound options & executes side effects
69
+ * @property {GetDotenvPostHookCallback} [config.postHook] - executes side effects within getdotenv context
70
+ */
71
+
72
+ /**
73
+ * Generate a CLI for get-dotenv.
74
+ *
75
+ * @param {GetDotenvCliConfig} [config] - config object
76
+ * @returns {object} The CLI command.
77
+ */
78
+ const getCli = function () {
79
+ let {
80
+ defaultOptions = {},
81
+ preHook,
82
+ postHook
83
+ } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
84
+ let {
85
+ cliInvocation = 'getdotenv',
86
+ command,
87
+ dotenvToken,
88
+ dynamicPath,
89
+ env,
90
+ excludeDynamic,
91
+ excludeEnv,
92
+ excludeGlobal,
93
+ excludePrivate,
94
+ excludePublic,
95
+ log,
96
+ outputPath,
97
+ paths,
98
+ pathsDelimiter = '\\s+',
99
+ privateToken,
100
+ shell,
101
+ suppressDotenv,
102
+ vars,
103
+ varsAssignor = '=',
104
+ varsDelimiter = '\\s+'
105
+ } = {
106
+ ..._dotenvDefaults.dotenvDefaults,
107
+ ...defaultOptions
108
+ };
109
+ if (Array.isArray(paths)) paths = paths.join(' ');
110
+ return new _commander.Command().name(cliInvocation)
111
+ // .usage('[options] [command] [command options] [commad args]')
112
+ .description('Base CLI. All options except delimiters follow dotenv-expand rules.').enablePositionalOptions().passThroughOptions().option('-e, --env <string>', 'environment name', _dotenvExpand.dotenvExpand, env).option('-p, --paths <string>', 'delimited list of paths to dotenv directory', _dotenvExpand.dotenvExpand, paths).option('--paths-delimiter <string>', 'regex paths delimiter', pathsDelimiter).option('-v, --vars <string>', 'delimited list KEY=VALUE pairs', _dotenvExpand.dotenvExpand, vars).option('--vars-delimiter <string>', 'regex vars delimiter', varsDelimiter).option('--vars-assignor <string>', 'regex vars assignment operator', varsAssignor).option('-y, --dynamic-path <string>', 'dynamic variables path', _dotenvExpand.dotenvExpand, dynamicPath).option('-o, --output-path <string>', 'consolidated output file, follows dotenv-expand rules using loaded env vars', _dotenvExpand.dotenvExpand, outputPath).option('-n, --exclude-env [bool]', 'exclude environment-specific variables', booleanExpand, excludeEnv ?? false).option('-g, --exclude-global [bool]', 'exclude global & dynamic variables', booleanExpand, excludeGlobal ?? false).option('-r, --exclude-private [bool]', 'exclude private variables', booleanExpand, excludePrivate ?? false).option('-u, --exclude-public [bool]', 'exclude public variables', booleanExpand, excludePublic ?? false).option('-z, --exclude-dynamic [bool]', 'exclude dynamic variables', booleanExpand, excludeDynamic ?? false).option('-l, --log [bool]', 'console log extracted variables', booleanExpand, log ?? false).option('-x, --suppress-dotenv', 'suppress dotenv loading', booleanExpand, suppressDotenv ?? false).option('-c, --command <string>', 'shell command string', _dotenvExpand.dotenvExpand, command).option('-s, --shell <string>', 'execa shell option', _dotenvExpand.dotenvExpand, shell).option('--dotenv-token <string>', 'token indicating a dotenv file', _dotenvExpand.dotenvExpand, dotenvToken).option('--private-token <string>', 'token indicating private variables', _dotenvExpand.dotenvExpand, privateToken).addCommand(new _commander.Command().name('cmd').description('execute shell command string (default command)').configureHelp({
113
+ showGlobalOptions: true
114
+ }).enablePositionalOptions().passThroughOptions().action(async (options, _ref) => {
115
+ let {
116
+ args,
117
+ parent
118
+ } = _ref;
119
+ if (args.length) await (0, _execa.execaCommand)(args.join(' '), {
120
+ stdio: 'inherit',
121
+ shell: parent.opts().shell
122
+ });
123
+ }), {
124
+ isDefault: true
125
+ }).hook('preSubcommand', async thisCommand => {
126
+ var _paths;
127
+ // Inherit options from parent command.
128
+ let options = {
129
+ ...(process.env['getdotenvOptions'] ? JSON.parse(process.env['getdotenvOptions']) : {}),
130
+ ...thisCommand.opts()
131
+ };
132
+
133
+ // Execute pre-hook.
134
+ if (preHook) options = (await preHook(options)) ?? options;
135
+
136
+ // Get options.
137
+ let {
138
+ command,
139
+ paths,
140
+ pathsDelimiter,
141
+ suppressDotenv,
142
+ vars,
143
+ varsDelimiter,
144
+ varsAssignor,
145
+ ...rest
146
+ } = options;
147
+
148
+ // Parse vars.
149
+ if (vars !== null && vars !== void 0 && vars.length) Object.assign(process.env, (0, _lodash.default)(vars.split(new RegExp(varsDelimiter)).map(v => v.split(new RegExp(varsAssignor)))));
150
+
151
+ // Execute getdotenv.
152
+ if ((_paths = paths) !== null && _paths !== void 0 && _paths.length && !suppressDotenv) {
153
+ var _paths2;
154
+ if ((0, _lodash2.default)(paths)) paths = (_paths2 = paths) === null || _paths2 === void 0 ? void 0 : _paths2.split(new RegExp(pathsDelimiter));
155
+ var dotenv = await (0, _getDotenv.getDotenv)({
156
+ ...rest,
157
+ loadProcess: true,
158
+ paths
159
+ });
160
+ }
161
+
162
+ // Execute post-hook.
163
+ if (postHook) await postHook(options, dotenv);
164
+
165
+ // Execute shell command.
166
+ if (command) await (0, _execa.execaCommand)(command, {
167
+ stdio: 'inherit',
168
+ shell
169
+ });
170
+ });
171
+ };
172
+ exports.getCli = getCli;