@@ -5,12 +5,14 @@ import type {
5
5
import type {
6
6
Application
7
7
} from "@aedart/contracts/core" ;
8
+ import type { ParseArgsConfig } from "node:util" ;
8
9
import { Application as CoreApplication } from "@aedart/core" ;
9
10
import { CallbackWrapper } from "@aedart/support" ;
10
11
import { Command as CommanderJs } from "commander" ;
11
12
import SkipProcessExitError from "./exceptions/SkipProcessExitError" ;
12
13
import { version } from "../package.json" ;
13
14
import * as process from "node:process" ;
15
+ import { parseArgs } from "node:util" ;
14
16
15
17
/**
16
18
* Cli Application
@@ -149,13 +151,15 @@ export default class CliApplication
149
151
*/
150
152
public async run ( argv ?: readonly string [ ] , options ?: ParseOptions ) : Promise < boolean >
151
153
{
154
+ this . processEnvOption ( argv ) ;
155
+
152
156
return await this . core . run ( CallbackWrapper . makeFor (
153
157
this ,
154
158
this . parse ,
155
159
[ argv , options ]
156
160
) ) ;
157
161
}
158
-
162
+
159
163
// TODO:
160
164
protected async parse ( argv ?: readonly string [ ] , options ?: ParseOptions ) : Promise < boolean >
161
165
{
@@ -232,7 +236,11 @@ export default class CliApplication
232
236
{
233
237
return ( new CommanderJs ( ) )
234
238
. version ( this . version )
235
- . description ( this . description ) ;
239
+ . description ( this . description )
240
+
241
+ // This option will be processed outside the "driver's" usual way of dealing with options!
242
+ // @see processEnvOption()
243
+ . option ( '--env <file>' , 'set environment variables from supplied file.' ) ;
236
244
}
237
245
238
246
/**
@@ -267,4 +275,44 @@ export default class CliApplication
267
275
throw err ;
268
276
} )
269
277
}
278
+
279
+ /**
280
+ * Processes the `--env` option for the cli application
281
+ *
282
+ * @param {readonly string[] } [argv] Defaults to `process.argv` when no arguments given.
283
+ *
284
+ * @protected
285
+ */
286
+ protected processEnvOption ( argv ?: readonly string [ ] ) : void
287
+ {
288
+ // Prepare options for the `parseArgs`.
289
+ const argsOptions : ParseArgsConfig = {
290
+ args : ( argv as string [ ] | undefined ) ,
291
+
292
+ // Define the '--env' option
293
+ options : {
294
+ 'env' : {
295
+ type : 'string' ,
296
+ //default: '.env'
297
+ }
298
+ } ,
299
+
300
+ // Ignore any other arguments and options...
301
+ strict : false ,
302
+ }
303
+
304
+ // Parse the arguments and extract the values
305
+ const { values } = parseArgs ( argsOptions ) ;
306
+
307
+ // Resolve path to `.env` file.
308
+ const path = Reflect . has ( values , 'env' )
309
+ ? values [ 'env' ]
310
+ : undefined ;
311
+
312
+ // Load environment variables into `process.env`, if a path has been provided.
313
+ // If nothing was specified, then avoid doing anything.
314
+ if ( typeof path === 'string' && path . length > 0 ) {
315
+ process . loadEnvFile ( path ) ;
316
+ }
317
+ }
270
318
}
0 commit comments