@travetto/cli 3.4.10 → 4.0.0-rc.1
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 +10 -6
- package/__index__.ts +1 -0
- package/bin/trv.js +1 -1
- package/package.json +3 -3
- package/src/color.ts +15 -18
- package/src/decorators.ts +12 -14
- package/src/error.ts +2 -7
- package/src/execute.ts +39 -41
- package/src/help.ts +6 -6
- package/src/module.ts +5 -5
- package/src/parse.ts +7 -6
- package/src/registry.ts +8 -15
- package/src/schema.ts +5 -10
- package/src/scm.ts +17 -17
- package/src/trv.d.ts +15 -0
- package/src/types.ts +21 -2
- package/src/util.ts +28 -41
- package/support/cli.cli_schema.ts +8 -2
- package/support/cli.main.ts +14 -8
- package/support/entry.trv.ts +2 -14
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@ This module also has a tight integration with the [VSCode plugin](https://market
|
|
|
59
59
|
At it's heart, a cli command is the contract defined by what flags, and what arguments the command supports. Within the framework this requires three criteria to be met:
|
|
60
60
|
* The file must be located in the `support/` folder, and have a name that matches `cli.*.ts`
|
|
61
61
|
* The file must be a class that has a main method
|
|
62
|
-
* The class must use the [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#
|
|
62
|
+
* The class must use the [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#L15) decorator
|
|
63
63
|
|
|
64
64
|
**Code: Basic Command**
|
|
65
65
|
```typescript
|
|
@@ -93,7 +93,7 @@ Examples of mappings:
|
|
|
93
93
|
The pattern is that underscores(_) translate to colons (:), and the `cli.` prefix, and `.ts` suffix are dropped.
|
|
94
94
|
|
|
95
95
|
## Binding Flags
|
|
96
|
-
[@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#
|
|
96
|
+
[@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#L15) is a wrapper for [@Schema](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/schema.ts#L14), and so every class that uses the [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#L15) decorator is now a full [@Schema](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/schema.ts#L14) class. The fields of the class represent the flags that are available to the command.
|
|
97
97
|
|
|
98
98
|
**Code: Basic Command with Flag**
|
|
99
99
|
```typescript
|
|
@@ -130,7 +130,7 @@ $ trv basic:flag --loud
|
|
|
130
130
|
HELLO
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
-
The [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#
|
|
133
|
+
The [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#L15) supports the following data types for flags:
|
|
134
134
|
* Boolean values
|
|
135
135
|
* Number values. The [@Integer](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L172), [@Float](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L178), [@Precision](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L166), [@Min](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L107) and [@Max](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L117) decorators help provide additional validation.
|
|
136
136
|
* String values. [@MinLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L107), [@MaxLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L117), [@Match](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L99) and [@Enum](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L78) provide additional constraints
|
|
@@ -388,7 +388,7 @@ npx trv call:db --host localhost --port 3306 --username app --password <custom>
|
|
|
388
388
|
```
|
|
389
389
|
|
|
390
390
|
## VSCode Integration
|
|
391
|
-
By default, cli commands do not expose themselves to the VSCode extension, as the majority of them are not intended for that sort of operation. [RESTful API](https://github.com/travetto/travetto/tree/main/module/rest#readme "Declarative api for RESTful APIs with support for the dependency injection module.") does expose a cli target `run:rest` that will show up, to help run/debug a rest application. Any command can mark itself as being a run target, and will be eligible for running from within the [VSCode plugin](https://marketplace.visualstudio.com/items?itemName=arcsine.travetto-plugin). This is achieved by setting the `runTarget` field on the [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#
|
|
391
|
+
By default, cli commands do not expose themselves to the VSCode extension, as the majority of them are not intended for that sort of operation. [RESTful API](https://github.com/travetto/travetto/tree/main/module/rest#readme "Declarative api for RESTful APIs with support for the dependency injection module.") does expose a cli target `run:rest` that will show up, to help run/debug a rest application. Any command can mark itself as being a run target, and will be eligible for running from within the [VSCode plugin](https://marketplace.visualstudio.com/items?itemName=arcsine.travetto-plugin). This is achieved by setting the `runTarget` field on the [@CliCommand](https://github.com/travetto/travetto/tree/main/module/cli/src/decorators.ts#L15) decorator. This means the target will be visible within the editor tooling.
|
|
392
392
|
|
|
393
393
|
**Code: Simple Run Target**
|
|
394
394
|
```typescript
|
|
@@ -415,6 +415,10 @@ export interface CliCommandShape<T extends unknown[] = unknown[]> {
|
|
|
415
415
|
* Parsed state
|
|
416
416
|
*/
|
|
417
417
|
_parsed?: ParsedState;
|
|
418
|
+
/**
|
|
419
|
+
* Config
|
|
420
|
+
*/
|
|
421
|
+
_cfg?: CliCommandConfig;
|
|
418
422
|
/**
|
|
419
423
|
* Action target of the command
|
|
420
424
|
*/
|
|
@@ -492,12 +496,12 @@ export class RunRestCommand implements CliCommandShape {
|
|
|
492
496
|
}
|
|
493
497
|
```
|
|
494
498
|
|
|
495
|
-
As noted in the example above, `fields` is specified in this execution, with support for `module`, and `env`. These env flag is directly tied to the [
|
|
499
|
+
As noted in the example above, `fields` is specified in this execution, with support for `module`, and `env`. These env flag is directly tied to the [Runtime](https://github.com/travetto/travetto/tree/main/module/base/src/env.ts#L105) `name` defined in the [Base](https://github.com/travetto/travetto/tree/main/module/base#readme "Environment config and common utilities for travetto applications.") module.
|
|
496
500
|
|
|
497
501
|
The `module` field is slightly more complex, but is geared towards supporting commands within a monorepo context. This flag ensures that a module is specified if running from the root of the monorepo, and that the module provided is real, and can run the desired command. When running from an explicit module folder in the monorepo, the module flag is ignored.
|
|
498
502
|
|
|
499
503
|
### Custom Validation
|
|
500
|
-
In addition to dependency injection, the command contract also allows for a custom validation function, which will have access to bound command (flags, and args) as well as the unknown arguments. When a command implements this method, any [CliValidationError](https://github.com/travetto/travetto/tree/main/module/cli/src/types.ts#
|
|
504
|
+
In addition to dependency injection, the command contract also allows for a custom validation function, which will have access to bound command (flags, and args) as well as the unknown arguments. When a command implements this method, any [CliValidationError](https://github.com/travetto/travetto/tree/main/module/cli/src/types.ts#L37) errors that are returned will be shared with the user, and fail to invoke the `main` method.
|
|
501
505
|
|
|
502
506
|
**Code: CliValidationError**
|
|
503
507
|
```typescript
|
package/__index__.ts
CHANGED
package/bin/trv.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
// @ts-check
|
|
4
4
|
import { getEntry } from '@travetto/compiler/bin/common.js';
|
|
5
5
|
|
|
6
|
-
getEntry().then(ops => ops.
|
|
6
|
+
getEntry().then(ops => ops.getLoader()).then(load => load('@travetto/cli/support/entry.trv.js'));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@travetto/cli",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0-rc.1",
|
|
4
4
|
"description": "CLI infrastructure for Travetto framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
"directory": "module/cli"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@travetto/schema": "^
|
|
33
|
-
"@travetto/terminal": "^
|
|
32
|
+
"@travetto/schema": "^4.0.0-rc.1",
|
|
33
|
+
"@travetto/terminal": "^4.0.0-rc.1"
|
|
34
34
|
},
|
|
35
35
|
"travetto": {
|
|
36
36
|
"displayName": "Command Line Interface"
|
package/src/color.ts
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { GlobalTerminal } from '@travetto/terminal';
|
|
1
|
+
import { StyleUtil } from '@travetto/terminal';
|
|
3
2
|
|
|
4
|
-
const
|
|
5
|
-
input: '
|
|
6
|
-
output: '
|
|
7
|
-
path: '
|
|
8
|
-
success: '
|
|
9
|
-
failure: '
|
|
10
|
-
param: ['
|
|
11
|
-
type: '
|
|
12
|
-
description: ['
|
|
13
|
-
title: ['
|
|
14
|
-
identifier: '
|
|
15
|
-
subtitle: ['
|
|
16
|
-
subsubtitle: '
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
export const cliTpl = Util.makeTemplate(tplFn);
|
|
3
|
+
export const cliTpl = StyleUtil.getTemplate({
|
|
4
|
+
input: '#6b8e23', // Olive drab
|
|
5
|
+
output: '#ffc0cb', // Pink
|
|
6
|
+
path: '#008080', // Teal
|
|
7
|
+
success: '#00ff00', // Green
|
|
8
|
+
failure: '#ff0000', // Red
|
|
9
|
+
param: ['#ffff00', '#daa520'], // Yellow / Goldenrod
|
|
10
|
+
type: '#00ffff', // Teal
|
|
11
|
+
description: ['#e5e5e5', '#808080'], // White / Gray
|
|
12
|
+
title: ['#ffffff', '#000000'], // Bright white / black
|
|
13
|
+
identifier: '#1e90ff', // Dodger blue
|
|
14
|
+
subtitle: ['#d3d3d3', '#a9a9a9'], // Light gray / Dark Gray
|
|
15
|
+
subsubtitle: '#a9a9a9' // Dark gray
|
|
16
|
+
});
|
package/src/decorators.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { Class, ClassInstance,
|
|
2
|
-
import {
|
|
1
|
+
import { Class, ClassInstance, Env } from '@travetto/base';
|
|
2
|
+
import { RuntimeIndex, RuntimeContext } from '@travetto/manifest';
|
|
3
3
|
import { SchemaRegistry } from '@travetto/schema';
|
|
4
4
|
|
|
5
5
|
import { CliCommandShape, CliCommandShapeFields } from './types';
|
|
6
6
|
import { CliCommandRegistry, CliCommandConfigOptions } from './registry';
|
|
7
7
|
import { CliModuleUtil } from './module';
|
|
8
|
-
import { CliUtil } from './util';
|
|
9
8
|
import { CliParseUtil } from './parse';
|
|
10
9
|
|
|
11
10
|
/**
|
|
@@ -15,7 +14,7 @@ import { CliParseUtil } from './parse';
|
|
|
15
14
|
*/
|
|
16
15
|
export function CliCommand(cfg: CliCommandConfigOptions = {}) {
|
|
17
16
|
return function <T extends CliCommandShape>(target: Class<T>): void {
|
|
18
|
-
const meta =
|
|
17
|
+
const meta = RuntimeIndex.getFunctionMetadata(target);
|
|
19
18
|
if (!meta || meta.abstract) {
|
|
20
19
|
return;
|
|
21
20
|
}
|
|
@@ -25,10 +24,10 @@ export function CliCommand(cfg: CliCommandConfigOptions = {}) {
|
|
|
25
24
|
const addEnv = cfg.addEnv ?? cfg.fields?.includes('env');
|
|
26
25
|
const { commandModule } = CliCommandRegistry.registerClass(target, {
|
|
27
26
|
hidden: cfg.hidden,
|
|
28
|
-
|
|
27
|
+
runTarget: cfg.runTarget,
|
|
28
|
+
preMain: async (cmd: CliCommandShape & { env?: string }) => {
|
|
29
29
|
if (addEnv) {
|
|
30
|
-
|
|
31
|
-
defineEnv({ envName: (cmd as { env?: string }).env ?? 'dev' });
|
|
30
|
+
Env.TRV_ENV.set(cmd.env || Env.name);
|
|
32
31
|
}
|
|
33
32
|
}
|
|
34
33
|
});
|
|
@@ -37,19 +36,18 @@ export function CliCommand(cfg: CliCommandConfigOptions = {}) {
|
|
|
37
36
|
|
|
38
37
|
if (addEnv) {
|
|
39
38
|
SchemaRegistry.registerPendingFieldConfig(target, 'env', String, {
|
|
40
|
-
aliases: ['e', CliParseUtil.toEnvField(
|
|
39
|
+
aliases: ['e', CliParseUtil.toEnvField(Env.TRV_ENV.key)],
|
|
41
40
|
description: 'Application environment',
|
|
42
|
-
default: 'dev',
|
|
43
41
|
required: { active: false }
|
|
44
42
|
});
|
|
45
43
|
}
|
|
46
44
|
|
|
47
45
|
if (addModule) {
|
|
48
46
|
SchemaRegistry.registerPendingFieldConfig(target, 'module', String, {
|
|
49
|
-
aliases: ['m', CliParseUtil.toEnvField(
|
|
47
|
+
aliases: ['m', CliParseUtil.toEnvField(Env.TRV_MODULE.key)],
|
|
50
48
|
description: 'Module to run for',
|
|
51
49
|
specifiers: ['module'],
|
|
52
|
-
required: { active:
|
|
50
|
+
required: { active: RuntimeContext.monoRoot }
|
|
53
51
|
});
|
|
54
52
|
}
|
|
55
53
|
|
|
@@ -57,12 +55,12 @@ export function CliCommand(cfg: CliCommandConfigOptions = {}) {
|
|
|
57
55
|
(pendingCls.validators ??= []).push(async item => {
|
|
58
56
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
59
57
|
const { module: mod } = item as CliCommandShapeFields;
|
|
60
|
-
const runModule = (runtimeModule === 'command' ? commandModule : mod) ||
|
|
58
|
+
const runModule = (runtimeModule === 'command' ? commandModule : mod) || RuntimeContext.main.name;
|
|
61
59
|
|
|
62
60
|
// If we need to run as a specific module
|
|
63
|
-
if (runModule !==
|
|
61
|
+
if (runModule !== RuntimeContext.main.name) {
|
|
64
62
|
try {
|
|
65
|
-
|
|
63
|
+
RuntimeIndex.reinitForModule(runModule);
|
|
66
64
|
} catch (err) {
|
|
67
65
|
return { source: 'flag', message: `${runModule} is an unknown module`, kind: 'custom', path: '.' };
|
|
68
66
|
}
|
package/src/error.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { PackageUtil, RuntimeContext } from '@travetto/manifest';
|
|
3
2
|
import { cliTpl } from './color';
|
|
4
3
|
import { CliValidationError } from './types';
|
|
5
4
|
|
|
@@ -23,11 +22,7 @@ export class CliUnknownCommandError extends Error {
|
|
|
23
22
|
const matchedCfg = COMMAND_PACKAGE.find(([re]) => re.test(cmd));
|
|
24
23
|
if (matchedCfg) {
|
|
25
24
|
const [, pkg, prod] = matchedCfg;
|
|
26
|
-
|
|
27
|
-
switch (RootIndex.manifest.packageManager) {
|
|
28
|
-
case 'npm': install = `npm i ${prod ? '' : '--save-dev '}@travetto/${pkg}`; break;
|
|
29
|
-
case 'yarn': install = `yarn add ${prod ? '' : '--dev '}@travetto/${pkg}`; break;
|
|
30
|
-
}
|
|
25
|
+
const install = PackageUtil.getInstallCommand(RuntimeContext, `@travetto/${pkg}`, prod);
|
|
31
26
|
return cliTpl`
|
|
32
27
|
${{ title: 'Missing Package' }}\n${'-'.repeat(20)}\nTo use ${{ input: cmd }} please run:\n
|
|
33
28
|
${{ identifier: install }}
|
package/src/execute.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ConsoleManager, GlobalEnv } from '@travetto/base';
|
|
1
|
+
import { ConsoleManager, Env, ShutdownManager } from '@travetto/base';
|
|
3
2
|
|
|
4
3
|
import { HelpUtil } from './help';
|
|
5
|
-
import { CliCommandShape
|
|
4
|
+
import { CliCommandShape } from './types';
|
|
6
5
|
import { CliCommandRegistry } from './registry';
|
|
7
6
|
import { CliCommandSchemaUtil } from './schema';
|
|
8
7
|
import { CliUnknownCommandError, CliValidationResultError } from './error';
|
|
@@ -14,53 +13,49 @@ import { CliUtil } from './util';
|
|
|
14
13
|
*/
|
|
15
14
|
export class ExecutionManager {
|
|
16
15
|
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
*/
|
|
20
|
-
static async #runCommand(cmd: CliCommandShape, args: string[]): Promise<RunResponse> {
|
|
16
|
+
/** Prepare command for execution */
|
|
17
|
+
static async #prepareAndBind(cmd: CliCommandShape, args: string[]): Promise<unknown[]> {
|
|
21
18
|
const schema = await CliCommandSchemaUtil.getSchema(cmd);
|
|
22
19
|
args = await CliParseUtil.expandArgs(schema, args);
|
|
23
20
|
cmd._parsed = await CliParseUtil.parse(schema, args);
|
|
24
|
-
const cfg = CliCommandRegistry.getConfig(cmd);
|
|
25
21
|
|
|
26
22
|
await cmd.preBind?.();
|
|
27
|
-
|
|
23
|
+
try {
|
|
24
|
+
const known = await CliCommandSchemaUtil.bindInput(cmd, cmd._parsed);
|
|
28
25
|
|
|
29
|
-
|
|
30
|
-
|
|
26
|
+
await cmd.preValidate?.();
|
|
27
|
+
await CliCommandSchemaUtil.validate(cmd, known);
|
|
31
28
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
ConsoleManager.setDebug(GlobalEnv.debug, GlobalEnv.devMode);
|
|
35
|
-
return cmd.main(...known);
|
|
36
|
-
}
|
|
29
|
+
await cmd._cfg!.preMain?.(cmd);
|
|
30
|
+
await cmd.preMain?.();
|
|
37
31
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
32
|
+
return known;
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if (err instanceof CliValidationResultError) {
|
|
35
|
+
console.error!(await HelpUtil.renderValidationError(cmd, err));
|
|
36
|
+
console.error!(await HelpUtil.renderCommandHelp(cmd));
|
|
37
|
+
process.exit(1);
|
|
38
|
+
} else {
|
|
45
39
|
throw err;
|
|
46
40
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Fetch a single command */
|
|
45
|
+
static async #getCommand(cmd: string): Promise<CliCommandShape> {
|
|
46
|
+
try {
|
|
47
|
+
return await CliCommandRegistry.getInstance(cmd, true);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (err instanceof CliUnknownCommandError) {
|
|
53
50
|
if (err.help) {
|
|
54
51
|
console.error!(err.help);
|
|
55
52
|
} else {
|
|
56
53
|
console.error!(err.defaultMessage, '\n');
|
|
57
54
|
console.error!(await HelpUtil.renderAllHelp(''));
|
|
58
55
|
}
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
console.error!(err);
|
|
63
|
-
console.error!();
|
|
56
|
+
process.exit(1);
|
|
57
|
+
} else {
|
|
58
|
+
throw err;
|
|
64
59
|
}
|
|
65
60
|
}
|
|
66
61
|
}
|
|
@@ -70,9 +65,6 @@ export class ExecutionManager {
|
|
|
70
65
|
* @param args
|
|
71
66
|
*/
|
|
72
67
|
static async run(argv: string[]): Promise<void> {
|
|
73
|
-
await GlobalTerminal.init();
|
|
74
|
-
|
|
75
|
-
let command: CliCommandShape | undefined;
|
|
76
68
|
try {
|
|
77
69
|
const { cmd, args, help } = CliParseUtil.getArgs(argv);
|
|
78
70
|
|
|
@@ -81,16 +73,22 @@ export class ExecutionManager {
|
|
|
81
73
|
return;
|
|
82
74
|
}
|
|
83
75
|
|
|
84
|
-
|
|
85
|
-
|
|
76
|
+
const command = await this.#getCommand(cmd);
|
|
77
|
+
|
|
86
78
|
if (help) {
|
|
87
79
|
console.log!(await HelpUtil.renderCommandHelp(command));
|
|
80
|
+
return;
|
|
88
81
|
} else {
|
|
89
|
-
const
|
|
82
|
+
const known = await this.#prepareAndBind(command, args);
|
|
83
|
+
ConsoleManager.debug(Env.debug);
|
|
84
|
+
const result = await command.main(...known);
|
|
90
85
|
await CliUtil.listenForResponse(result);
|
|
91
86
|
}
|
|
92
87
|
} catch (err) {
|
|
93
|
-
|
|
88
|
+
console.error!(err);
|
|
89
|
+
console.error!();
|
|
90
|
+
} finally {
|
|
91
|
+
await ShutdownManager.gracefulShutdown(process.exitCode);
|
|
94
92
|
}
|
|
95
93
|
}
|
|
96
94
|
}
|
package/src/help.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Primitive } from '@travetto/base';
|
|
2
|
-
import {
|
|
2
|
+
import { StyleUtil } from '@travetto/terminal';
|
|
3
3
|
|
|
4
4
|
import { cliTpl } from './color';
|
|
5
5
|
import { CliCommandShape } from './types';
|
|
@@ -33,7 +33,7 @@ export class HelpUtil {
|
|
|
33
33
|
|
|
34
34
|
const usage: string[] = [cliTpl`${{ title: 'Usage:' }} ${{ param: commandName }} ${{ input: '[options]' }}`];
|
|
35
35
|
for (const field of args) {
|
|
36
|
-
const type = field.type === 'string' && field.choices && field.choices.length <=
|
|
36
|
+
const type = field.type === 'string' && field.choices && field.choices.length <= 7 ? field.choices?.join('|') : field.type;
|
|
37
37
|
const arg = `${field.name}${field.array ? '...' : ''}:${type}`;
|
|
38
38
|
usage.push(cliTpl`${{ input: field.required ? `<${arg}>` : `[${arg}]` }}`);
|
|
39
39
|
}
|
|
@@ -45,7 +45,7 @@ export class HelpUtil {
|
|
|
45
45
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
46
46
|
const key = flag.name as keyof CliCommandShape;
|
|
47
47
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
48
|
-
const flagVal = command[key] as unknown as
|
|
48
|
+
const flagVal = command[key] as unknown as Primitive;
|
|
49
49
|
|
|
50
50
|
let aliases = flag.flagNames ?? [];
|
|
51
51
|
if (isBoolFlag(flag)) {
|
|
@@ -69,8 +69,8 @@ export class HelpUtil {
|
|
|
69
69
|
descs.push(desc.join(' '));
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
const paramWidths = params.map(x =>
|
|
73
|
-
const descWidths = descs.map(x =>
|
|
72
|
+
const paramWidths = params.map(x => StyleUtil.cleanText(x).length);
|
|
73
|
+
const descWidths = descs.map(x => StyleUtil.cleanText(x).length);
|
|
74
74
|
|
|
75
75
|
const paramWidth = Math.max(...paramWidths);
|
|
76
76
|
const descWidth = Math.max(...descWidths);
|
|
@@ -98,7 +98,7 @@ export class HelpUtil {
|
|
|
98
98
|
static async renderAllHelp(title?: string): Promise<string> {
|
|
99
99
|
const rows: string[] = [];
|
|
100
100
|
const keys = [...CliCommandRegistry.getCommandMapping().keys()].sort((a, b) => a.localeCompare(b));
|
|
101
|
-
const maxWidth = keys.reduce((a, b) => Math.max(a,
|
|
101
|
+
const maxWidth = keys.reduce((a, b) => Math.max(a, StyleUtil.cleanText(b).length), 0);
|
|
102
102
|
|
|
103
103
|
for (const cmd of keys) {
|
|
104
104
|
try {
|
package/src/module.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { IndexedModule,
|
|
1
|
+
import { IndexedModule, RuntimeIndex, RuntimeContext } from '@travetto/manifest';
|
|
2
2
|
|
|
3
3
|
import { CliScmUtil } from './scm';
|
|
4
4
|
|
|
@@ -20,14 +20,14 @@ export class CliModuleUtil {
|
|
|
20
20
|
fromHash ??= await CliScmUtil.findLastRelease();
|
|
21
21
|
|
|
22
22
|
if (!fromHash) {
|
|
23
|
-
return
|
|
23
|
+
return RuntimeIndex.getWorkspaceModules();
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
const out = new Map<string, IndexedModule>();
|
|
27
27
|
for (const mod of await CliScmUtil.findChangedModules(fromHash, toHash)) {
|
|
28
28
|
out.set(mod.name, mod);
|
|
29
29
|
if (transitive) {
|
|
30
|
-
for (const sub of await
|
|
30
|
+
for (const sub of await RuntimeIndex.getDependentModules(mod, 'parents')) {
|
|
31
31
|
out.set(sub.name, sub);
|
|
32
32
|
}
|
|
33
33
|
}
|
|
@@ -46,8 +46,8 @@ export class CliModuleUtil {
|
|
|
46
46
|
static async findModules(mode: 'all' | 'changed', fromHash?: string, toHash?: string): Promise<IndexedModule[]> {
|
|
47
47
|
return (mode === 'changed' ?
|
|
48
48
|
await this.findChangedModulesRecursive(fromHash, toHash) :
|
|
49
|
-
[...
|
|
50
|
-
).filter(x => x.sourcePath !==
|
|
49
|
+
[...RuntimeIndex.getModuleList('all')].map(x => RuntimeIndex.getModule(x)!)
|
|
50
|
+
).filter(x => x.sourcePath !== RuntimeContext.workspace.path);
|
|
51
51
|
}
|
|
52
52
|
|
|
53
53
|
/**
|
package/src/parse.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import fs from 'fs/promises';
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { RuntimeIndex, RuntimeContext, path } from '@travetto/manifest';
|
|
4
4
|
import { CliCommandInput, CliCommandSchema, ParsedState } from './types';
|
|
5
5
|
|
|
6
6
|
type ParsedInput = ParsedState['all'][number];
|
|
@@ -85,10 +85,10 @@ export class CliParseUtil {
|
|
|
85
85
|
|
|
86
86
|
// We have a file
|
|
87
87
|
const rel = (key.includes('/') ? key : `@/support/pack.${key}.flags`)
|
|
88
|
-
.replace('@@/', `${
|
|
88
|
+
.replace('@@/', `${RuntimeContext.workspace.path}/`)
|
|
89
89
|
.replace('@/', `${mod}/`)
|
|
90
90
|
.replace(/^(@[^\/]+\/[^\/]+)(\/.*)$/, (_, imp, rest) => {
|
|
91
|
-
const val =
|
|
91
|
+
const val = RuntimeIndex.getModule(imp);
|
|
92
92
|
if (!val) {
|
|
93
93
|
throw new Error(`Unknown module file: ${_}, unable to proceed`);
|
|
94
94
|
}
|
|
@@ -144,9 +144,10 @@ export class CliParseUtil {
|
|
|
144
144
|
const mod = args.reduce(
|
|
145
145
|
(m, x, i, arr) =>
|
|
146
146
|
(i < SEP ? check(arr[i - 1], x) ?? check(...x.split('=')) : undefined) ?? m,
|
|
147
|
-
process.env[ENV_KEY] ||
|
|
147
|
+
process.env[ENV_KEY] || RuntimeContext.main.name
|
|
148
148
|
);
|
|
149
|
-
return (await Promise.all(args.map((x, i) =>
|
|
149
|
+
return (await Promise.all(args.map((x, i) =>
|
|
150
|
+
x.startsWith(CONFIG_PRE) && (i < SEP || SEP < 0) ? this.readFlagFile(x, mod) : x))).flat();
|
|
150
151
|
}
|
|
151
152
|
|
|
152
153
|
/**
|
package/src/registry.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Class, ConcreteClass,
|
|
2
|
-
import {
|
|
1
|
+
import { Class, ConcreteClass, Env } from '@travetto/base';
|
|
2
|
+
import { RuntimeIndex } from '@travetto/manifest';
|
|
3
3
|
|
|
4
|
-
import { CliCommandShape } from './types';
|
|
4
|
+
import { CliCommandConfig, CliCommandShape } from './types';
|
|
5
5
|
import { CliUnknownCommandError } from './error';
|
|
6
6
|
|
|
7
7
|
export type CliCommandConfigOptions = {
|
|
@@ -14,14 +14,6 @@ export type CliCommandConfigOptions = {
|
|
|
14
14
|
fields?: ('module' | 'env')[];
|
|
15
15
|
};
|
|
16
16
|
|
|
17
|
-
export type CliCommandConfig = {
|
|
18
|
-
name: string;
|
|
19
|
-
commandModule: string;
|
|
20
|
-
cls: ConcreteClass<CliCommandShape>;
|
|
21
|
-
hidden?: boolean;
|
|
22
|
-
preMain?: (cmd: CliCommandShape) => void | Promise<void>;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
17
|
const CLI_FILE_REGEX = /\/cli[.](?<name>.*)[.]tsx?$/;
|
|
26
18
|
const getName = (s: string): string => (s.match(CLI_FILE_REGEX)?.groups?.name ?? s).replaceAll('_', ':');
|
|
27
19
|
|
|
@@ -44,8 +36,8 @@ class $CliCommandRegistry {
|
|
|
44
36
|
getCommandMapping(): Map<string, string> {
|
|
45
37
|
if (!this.#fileMapping) {
|
|
46
38
|
const all = new Map<string, string>();
|
|
47
|
-
for (const e of
|
|
48
|
-
module: m =>
|
|
39
|
+
for (const e of RuntimeIndex.find({
|
|
40
|
+
module: m => !Env.production || m.prod,
|
|
49
41
|
folder: f => f === 'support',
|
|
50
42
|
file: f => f.role === 'std' && CLI_FILE_REGEX.test(f.sourceFile)
|
|
51
43
|
})) {
|
|
@@ -60,12 +52,12 @@ class $CliCommandRegistry {
|
|
|
60
52
|
* Registers a cli command
|
|
61
53
|
*/
|
|
62
54
|
registerClass(cls: Class, cfg: Partial<CliCommandConfig>): CliCommandConfig {
|
|
63
|
-
const source =
|
|
55
|
+
const source = RuntimeIndex.getFunctionMetadata(cls)!.source;
|
|
64
56
|
this.#commands.set(cls, {
|
|
65
57
|
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
66
58
|
cls: cls as ConcreteClass,
|
|
67
59
|
name: getName(source),
|
|
68
|
-
commandModule:
|
|
60
|
+
commandModule: RuntimeIndex.getModuleFromSource(source)!.name,
|
|
69
61
|
...cfg,
|
|
70
62
|
});
|
|
71
63
|
return this.#commands.get(cls)!;
|
|
@@ -101,6 +93,7 @@ class $CliCommandRegistry {
|
|
|
101
93
|
if (cfg) {
|
|
102
94
|
const inst = new cfg.cls();
|
|
103
95
|
if (!inst.isActive || inst.isActive()) {
|
|
96
|
+
inst._cfg = this.getConfig(inst);
|
|
104
97
|
return inst;
|
|
105
98
|
}
|
|
106
99
|
}
|
package/src/schema.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Class
|
|
1
|
+
import { Class } from '@travetto/base';
|
|
2
2
|
import { BindUtil, FieldConfig, SchemaRegistry, SchemaValidator, ValidationResultError } from '@travetto/schema';
|
|
3
3
|
|
|
4
4
|
import { CliCommandRegistry } from './registry';
|
|
@@ -59,16 +59,11 @@ export class CliCommandSchemaUtil {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
// Ensure finalized
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if (parent?.Ⲑid) {
|
|
66
|
-
SchemaRegistry.onInstall(parent, { type: 'added', curr: parent });
|
|
67
|
-
}
|
|
68
|
-
SchemaRegistry.onInstall(cls, { type: 'added', curr: cls });
|
|
69
|
-
} finally {
|
|
70
|
-
ConsoleManager.setDebug(GlobalEnv.debug, GlobalEnv.devMode);
|
|
62
|
+
const parent = SchemaRegistry.getParentClass(cls);
|
|
63
|
+
if (parent?.Ⲑid) {
|
|
64
|
+
SchemaRegistry.onInstall(parent, { type: 'added', curr: parent });
|
|
71
65
|
}
|
|
66
|
+
SchemaRegistry.onInstall(cls, { type: 'added', curr: cls });
|
|
72
67
|
|
|
73
68
|
const schema = await SchemaRegistry.getViewSchema(cls);
|
|
74
69
|
const flags = Object.values(schema.schema).map(fieldToInput);
|
package/src/scm.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
2
3
|
|
|
3
|
-
import {
|
|
4
|
-
import { IndexedFile, IndexedModule,
|
|
4
|
+
import { ExecUtil } from '@travetto/base';
|
|
5
|
+
import { IndexedFile, IndexedModule, RuntimeIndex, RuntimeContext, path } from '@travetto/manifest';
|
|
5
6
|
|
|
6
7
|
export class CliScmUtil {
|
|
7
8
|
/**
|
|
@@ -19,11 +20,11 @@ export class CliScmUtil {
|
|
|
19
20
|
*/
|
|
20
21
|
static async getAuthor(): Promise<{ name?: string, email: string }> {
|
|
21
22
|
const [name, email] = await Promise.all([
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
ExecUtil.getResult(spawn('git', ['config', 'user.name']), { catch: true }),
|
|
24
|
+
ExecUtil.getResult(spawn('git', ['config', 'user.email'])),
|
|
24
25
|
]);
|
|
25
26
|
return {
|
|
26
|
-
name: (name.valid ? name.stdout.trim() : '') ||
|
|
27
|
+
name: (name.valid ? name.stdout.trim() : '') || process.env.USER,
|
|
27
28
|
email: email.stdout.trim()
|
|
28
29
|
};
|
|
29
30
|
}
|
|
@@ -33,9 +34,8 @@ export class CliScmUtil {
|
|
|
33
34
|
* @returns
|
|
34
35
|
*/
|
|
35
36
|
static async findLastRelease(): Promise<string | undefined> {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
return (await result).stdout
|
|
37
|
+
const result = await ExecUtil.getResult(spawn('git', ['log', '--pretty=oneline'], { cwd: RuntimeContext.workspace.path }));
|
|
38
|
+
return result.stdout
|
|
39
39
|
.split(/\n/)
|
|
40
40
|
.find(x => /Publish /.test(x))?.split(/\s+/)?.[0];
|
|
41
41
|
}
|
|
@@ -46,11 +46,11 @@ export class CliScmUtil {
|
|
|
46
46
|
* @returns
|
|
47
47
|
*/
|
|
48
48
|
static async findChangedFiles(fromHash: string, toHash: string = 'HEAD'): Promise<string[]> {
|
|
49
|
-
const ws =
|
|
50
|
-
const res = await ExecUtil.spawn('git', ['diff', '--name-only', `${fromHash}..${toHash}`, ':!**/DOC.*', ':!**/README.*'], { cwd: ws })
|
|
49
|
+
const ws = RuntimeContext.workspace.path;
|
|
50
|
+
const res = await ExecUtil.getResult(spawn('git', ['diff', '--name-only', `${fromHash}..${toHash}`, ':!**/DOC.*', ':!**/README.*'], { cwd: ws }));
|
|
51
51
|
const out = new Set<string>();
|
|
52
52
|
for (const line of res.stdout.split(/\n/g)) {
|
|
53
|
-
const entry =
|
|
53
|
+
const entry = RuntimeIndex.getEntry(path.resolve(ws, line));
|
|
54
54
|
if (entry) {
|
|
55
55
|
out.add(entry.sourceFile);
|
|
56
56
|
}
|
|
@@ -67,9 +67,9 @@ export class CliScmUtil {
|
|
|
67
67
|
static async findChangedModules(fromHash: string, toHash?: string): Promise<IndexedModule[]> {
|
|
68
68
|
const files = await this.findChangedFiles(fromHash, toHash);
|
|
69
69
|
const mods = files
|
|
70
|
-
.map(x =>
|
|
70
|
+
.map(x => RuntimeIndex.getFromSource(x))
|
|
71
71
|
.filter((x): x is IndexedFile => !!x)
|
|
72
|
-
.map(x =>
|
|
72
|
+
.map(x => RuntimeIndex.getModule(x.module))
|
|
73
73
|
.filter((x): x is IndexedModule => !!x);
|
|
74
74
|
|
|
75
75
|
return [...new Set(mods)]
|
|
@@ -80,15 +80,15 @@ export class CliScmUtil {
|
|
|
80
80
|
* Create a commit
|
|
81
81
|
*/
|
|
82
82
|
static createCommit(message: string): Promise<string> {
|
|
83
|
-
return ExecUtil.spawn('git', ['commit', '.', '-m', message]).
|
|
83
|
+
return ExecUtil.getResult(spawn('git', ['commit', '.', '-m', message])).then(r => r.stdout);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
/**
|
|
87
87
|
* Verify if workspace is dirty
|
|
88
88
|
*/
|
|
89
89
|
static async isWorkspaceDirty(): Promise<boolean> {
|
|
90
|
-
const res1 = await ExecUtil.spawn('git', ['diff', '--quiet', '--exit-code'], {
|
|
91
|
-
const res2 = await ExecUtil.spawn('git', ['diff', '--quiet', '--exit-code', '--cached'], {
|
|
90
|
+
const res1 = await ExecUtil.getResult(spawn('git', ['diff', '--quiet', '--exit-code']), { catch: true });
|
|
91
|
+
const res2 = await ExecUtil.getResult(spawn('git', ['diff', '--quiet', '--exit-code', '--cached']), { catch: true });
|
|
92
92
|
return !res1.valid || !res2.valid;
|
|
93
93
|
}
|
|
94
94
|
}
|
package/src/trv.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import '@travetto/base';
|
|
2
|
+
|
|
3
|
+
declare global {
|
|
4
|
+
interface TravettoEnv {
|
|
5
|
+
/**
|
|
6
|
+
* Provides an IPC http url for the CLI to communicate with.
|
|
7
|
+
* This facilitates cli-based invocation for external usage.
|
|
8
|
+
*/
|
|
9
|
+
TRV_CLI_IPC: string;
|
|
10
|
+
/**
|
|
11
|
+
* Determines (assuming the operation supports it), that restart behavior can trigger
|
|
12
|
+
*/
|
|
13
|
+
TRV_CAN_RESTART: boolean;
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,14 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ConcreteClass } from '@travetto/base';
|
|
2
2
|
|
|
3
3
|
type OrProm<T> = T | Promise<T>;
|
|
4
4
|
|
|
5
|
-
export type RunResponse =
|
|
5
|
+
export type RunResponse =
|
|
6
|
+
{ wait(): Promise<unknown> } |
|
|
7
|
+
{ on(event: 'close', cb: Function): unknown } |
|
|
8
|
+
{ close: () => (void | Promise<void>) } | void | undefined;
|
|
6
9
|
|
|
7
10
|
type ParsedFlag = { type: 'flag', input: string, array?: boolean, fieldName: string, value?: unknown };
|
|
8
11
|
type ParsedArg = { type: 'arg', input: string, array?: boolean, index: number };
|
|
9
12
|
type ParsedUnknown = { type: 'unknown', input: string };
|
|
10
13
|
type ParsedInput = ParsedUnknown | ParsedFlag | ParsedArg;
|
|
11
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Command configuration
|
|
17
|
+
*/
|
|
18
|
+
export type CliCommandConfig = {
|
|
19
|
+
name: string;
|
|
20
|
+
commandModule: string;
|
|
21
|
+
runTarget?: boolean;
|
|
22
|
+
cls: ConcreteClass<CliCommandShape>;
|
|
23
|
+
hidden?: boolean;
|
|
24
|
+
preMain?: (cmd: CliCommandShape) => void | Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
|
|
12
27
|
export type ParsedState = {
|
|
13
28
|
inputs: string[];
|
|
14
29
|
all: ParsedInput[];
|
|
@@ -38,6 +53,10 @@ export interface CliCommandShape<T extends unknown[] = unknown[]> {
|
|
|
38
53
|
* Parsed state
|
|
39
54
|
*/
|
|
40
55
|
_parsed?: ParsedState;
|
|
56
|
+
/**
|
|
57
|
+
* Config
|
|
58
|
+
*/
|
|
59
|
+
_cfg?: CliCommandConfig;
|
|
41
60
|
/**
|
|
42
61
|
* Action target of the command
|
|
43
62
|
*/
|
package/src/util.ts
CHANGED
|
@@ -1,26 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
import { Env, ExecUtil, ShutdownManager } from '@travetto/base';
|
|
4
|
+
import { RuntimeContext } from '@travetto/manifest';
|
|
3
5
|
|
|
4
6
|
import { CliCommandShape, CliCommandShapeFields, RunResponse } from './types';
|
|
5
|
-
import { CliCommandRegistry } from './registry';
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*/
|
|
11
|
-
static get monoRoot(): boolean {
|
|
12
|
-
return !!RootIndex.manifest.monoRepo && RootIndex.mainModule.sourcePath === RootIndex.manifest.workspacePath;
|
|
13
|
-
}
|
|
8
|
+
const IPC_ALLOWED_ENV = new Set(['NODE_OPTIONS']);
|
|
9
|
+
const IPC_INVALID_ENV = new Set(['PS1', 'INIT_CWD', 'COLOR', 'LANGUAGE', 'PROFILEHOME', '_']);
|
|
10
|
+
const validEnv = (k: string): boolean => IPC_ALLOWED_ENV.has(k) || (!IPC_INVALID_ENV.has(k) && !/^(npm_|GTK|GDK|TRV|NODE|GIT|TERM_)/.test(k) && !/VSCODE/.test(k));
|
|
14
11
|
|
|
12
|
+
export class CliUtil {
|
|
15
13
|
/**
|
|
16
14
|
* Get a simplified version of a module name
|
|
17
15
|
* @returns
|
|
18
16
|
*/
|
|
19
17
|
static getSimpleModuleName(placeholder: string, module?: string): string {
|
|
20
|
-
const simple = (module ??
|
|
18
|
+
const simple = (module ?? RuntimeContext.main.name).replace(/[\/]/, '_').replace(/@/, '');
|
|
21
19
|
if (!simple) {
|
|
22
20
|
return placeholder;
|
|
23
|
-
} else if (!module &&
|
|
21
|
+
} else if (!module && RuntimeContext.monoRoot) {
|
|
24
22
|
return placeholder;
|
|
25
23
|
} else {
|
|
26
24
|
return placeholder.replace('<module>', simple);
|
|
@@ -31,57 +29,47 @@ export class CliUtil {
|
|
|
31
29
|
* Run a command as restartable, linking into self
|
|
32
30
|
*/
|
|
33
31
|
static runWithRestart<T extends CliCommandShapeFields & CliCommandShape>(cmd: T): Promise<unknown> | undefined {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (canRestart === false || Env.isFalse('TRV_CAN_RESTART')) {
|
|
37
|
-
delete process.env.TRV_CAN_RESTART;
|
|
32
|
+
if (Env.TRV_CAN_RESTART.isFalse || !(cmd.canRestart ?? !Env.production)) {
|
|
33
|
+
Env.TRV_CAN_RESTART.clear();
|
|
38
34
|
return;
|
|
39
35
|
}
|
|
40
|
-
return ExecUtil.
|
|
41
|
-
env: {
|
|
36
|
+
return ExecUtil.withRestart(() => spawn(process.argv0, process.argv.slice(1), {
|
|
37
|
+
env: {
|
|
38
|
+
...process.env,
|
|
39
|
+
...Env.TRV_CAN_RESTART.export(false)
|
|
40
|
+
},
|
|
42
41
|
stdio: [0, 1, 2, 'ipc']
|
|
43
|
-
});
|
|
42
|
+
}));
|
|
44
43
|
}
|
|
45
44
|
|
|
46
45
|
/**
|
|
47
46
|
* Dispatch IPC payload
|
|
48
47
|
*/
|
|
49
48
|
static async triggerIpc<T extends CliCommandShape>(action: 'run', cmd: T): Promise<boolean> {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (!ipcUrl) {
|
|
49
|
+
if (!Env.TRV_CLI_IPC.isSet) {
|
|
53
50
|
return false;
|
|
54
51
|
}
|
|
55
52
|
|
|
56
|
-
const info = await fetch(
|
|
53
|
+
const info = await fetch(Env.TRV_CLI_IPC.val!).catch(() => ({ ok: false }));
|
|
57
54
|
|
|
58
55
|
if (!info.ok) { // Server not running
|
|
59
56
|
return false;
|
|
60
57
|
}
|
|
61
58
|
|
|
62
|
-
const
|
|
59
|
+
const env: Record<string, string> = {};
|
|
63
60
|
const req = {
|
|
64
61
|
type: `@travetto/cli:${action}`,
|
|
65
62
|
data: {
|
|
66
|
-
name:
|
|
67
|
-
commandModule:
|
|
68
|
-
module:
|
|
63
|
+
name: cmd._cfg!.name, env,
|
|
64
|
+
commandModule: cmd._cfg!.commandModule,
|
|
65
|
+
module: RuntimeContext.main.name,
|
|
69
66
|
args: process.argv.slice(3),
|
|
70
67
|
}
|
|
71
68
|
};
|
|
72
|
-
|
|
73
69
|
console.log('Triggering IPC request', req);
|
|
74
70
|
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
Object.entries(process.env).filter(([k]) =>
|
|
78
|
-
!defaultEnvKeys.has(k) && !/^(npm_|GTK|GDK|TRV|NODE|GIT|TERM_)/.test(k) && !/VSCODE/.test(k)
|
|
79
|
-
)
|
|
80
|
-
);
|
|
81
|
-
|
|
82
|
-
Object.assign(req.data, { env });
|
|
83
|
-
|
|
84
|
-
const sent = await fetch(ipcUrl, { method: 'POST', body: JSON.stringify(req) });
|
|
71
|
+
Object.entries(process.env).forEach(([k, v]) => validEnv(k) && (env[k] = v!));
|
|
72
|
+
const sent = await fetch(Env.TRV_CLI_IPC.val!, { method: 'POST', body: JSON.stringify(req) });
|
|
85
73
|
return sent.ok;
|
|
86
74
|
}
|
|
87
75
|
|
|
@@ -89,8 +77,7 @@ export class CliUtil {
|
|
|
89
77
|
* Debug if IPC available
|
|
90
78
|
*/
|
|
91
79
|
static async debugIfIpc<T extends CliCommandShapeFields & CliCommandShape>(cmd: T): Promise<boolean> {
|
|
92
|
-
|
|
93
|
-
return canDebug !== false && this.triggerIpc('run', cmd);
|
|
80
|
+
return (cmd.debugIpc ?? !Env.production) && this.triggerIpc('run', cmd);
|
|
94
81
|
}
|
|
95
82
|
|
|
96
83
|
/**
|
|
@@ -107,7 +94,7 @@ export class CliUtil {
|
|
|
107
94
|
// Listen to result if non-empty
|
|
108
95
|
if (result !== undefined && result !== null) {
|
|
109
96
|
if ('close' in result) {
|
|
110
|
-
ShutdownManager.
|
|
97
|
+
ShutdownManager.onGracefulShutdown(async () => result.close()); // Tie shutdown into app close
|
|
111
98
|
}
|
|
112
99
|
if ('wait' in result) {
|
|
113
100
|
await result.wait(); // Wait for close signal
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { Env } from '@travetto/base';
|
|
2
|
+
|
|
1
3
|
import { CliCommand } from '../src/decorators';
|
|
2
|
-
import { CliCommandSchema, CliValidationError } from '../src/types';
|
|
4
|
+
import { CliCommandSchema, CliCommandShape, CliValidationError } from '../src/types';
|
|
3
5
|
import { CliCommandRegistry } from '../src/registry';
|
|
4
6
|
import { CliCommandSchemaUtil } from '../src/schema';
|
|
5
7
|
import { CliUtil } from '../src/util';
|
|
@@ -8,7 +10,7 @@ import { CliUtil } from '../src/util';
|
|
|
8
10
|
* Generates the schema for all CLI operations
|
|
9
11
|
*/
|
|
10
12
|
@CliCommand({ hidden: true })
|
|
11
|
-
export class CliSchemaCommand {
|
|
13
|
+
export class CliSchemaCommand implements CliCommandShape {
|
|
12
14
|
|
|
13
15
|
async #getSchema(name: string): Promise<CliCommandSchema> {
|
|
14
16
|
const inst = await CliCommandRegistry.getInstance(name);
|
|
@@ -24,6 +26,10 @@ export class CliSchemaCommand {
|
|
|
24
26
|
}
|
|
25
27
|
}
|
|
26
28
|
|
|
29
|
+
preMain(): void {
|
|
30
|
+
Env.DEBUG.set(false);
|
|
31
|
+
}
|
|
32
|
+
|
|
27
33
|
async main(name?: string): Promise<void> {
|
|
28
34
|
let output: unknown = undefined;
|
|
29
35
|
if (name) {
|
package/support/cli.main.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import fs from 'fs/promises';
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
2
|
|
|
3
|
-
import { ShutdownManager } from '@travetto/base';
|
|
4
3
|
import { CliCommandShape, CliCommand, CliValidationError, ParsedState } from '@travetto/cli';
|
|
5
|
-
import { path,
|
|
4
|
+
import { path, RuntimeIndex, RuntimeContext } from '@travetto/manifest';
|
|
6
5
|
import { Ignore } from '@travetto/schema';
|
|
7
6
|
|
|
8
7
|
/**
|
|
@@ -18,10 +17,10 @@ export class MainCommand implements CliCommandShape {
|
|
|
18
17
|
// If referenced file exists
|
|
19
18
|
let file = fileOrImport;
|
|
20
19
|
if (await (fs.stat(path.resolve(fileOrImport)).then(() => true, () => false))) {
|
|
21
|
-
file = path.join(
|
|
20
|
+
file = path.join(RuntimeContext.main.name, fileOrImport);
|
|
22
21
|
}
|
|
23
22
|
|
|
24
|
-
return
|
|
23
|
+
return RuntimeIndex.getFromImport(file)?.import;
|
|
25
24
|
}
|
|
26
25
|
|
|
27
26
|
async validate(fileOrImport: string): Promise<CliValidationError | undefined> {
|
|
@@ -32,13 +31,20 @@ export class MainCommand implements CliCommandShape {
|
|
|
32
31
|
}
|
|
33
32
|
|
|
34
33
|
async main(fileOrImport: string, args: string[] = []): Promise<void> {
|
|
34
|
+
let res: unknown;
|
|
35
35
|
try {
|
|
36
36
|
const imp = await this.#getImport(fileOrImport);
|
|
37
37
|
const mod = await import(imp!);
|
|
38
|
-
|
|
39
|
-
await ShutdownManager.exitWithResponse(await mod.main(...args, ...this._parsed.unknown));
|
|
38
|
+
res = await mod.main(...args, ...this._parsed.unknown);
|
|
40
39
|
} catch (err) {
|
|
41
|
-
|
|
40
|
+
res = err;
|
|
41
|
+
process.exitCode = Math.max(process.exitCode ?? 1, 1);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (res !== undefined) {
|
|
45
|
+
if (process.connected) { process.send?.(res); }
|
|
46
|
+
const payload = typeof res === 'string' ? res : (res instanceof Error ? res.stack : JSON.stringify(res));
|
|
47
|
+
process[process.exitCode ? 'stderr' : 'stdout'].write(`${payload}\n`);
|
|
42
48
|
}
|
|
43
49
|
}
|
|
44
50
|
}
|
package/support/entry.trv.ts
CHANGED
|
@@ -1,14 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
async function entry(): Promise<void> {
|
|
4
|
-
const { init, cleanup } = await import('@travetto/base/support/init.js');
|
|
5
|
-
await init();
|
|
6
|
-
try {
|
|
7
|
-
const { ExecutionManager } = await import('@travetto/cli/src/execute.js');
|
|
8
|
-
await ExecutionManager.run(process.argv);
|
|
9
|
-
} finally {
|
|
10
|
-
await cleanup();
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
entry().then(() => path);
|
|
1
|
+
import { ExecutionManager } from '@travetto/cli';
|
|
2
|
+
ExecutionManager.run(process.argv);
|