-
Notifications
You must be signed in to change notification settings - Fork 12k
/
command-runner.ts
164 lines (152 loc) · 5.52 KB
/
command-runner.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { logging } from '@angular-devkit/core';
import yargs from 'yargs';
import { Parser } from 'yargs/helpers';
import { AddCommandModule } from '../commands/add/cli';
import { AnalyticsCommandModule } from '../commands/analytics/cli';
import { BuildCommandModule } from '../commands/build/cli';
import { CacheCommandModule } from '../commands/cache/cli';
import { ConfigCommandModule } from '../commands/config/cli';
import { DeployCommandModule } from '../commands/deploy/cli';
import { DocCommandModule } from '../commands/doc/cli';
import { E2eCommandModule } from '../commands/e2e/cli';
import { ExtractI18nCommandModule } from '../commands/extract-i18n/cli';
import { GenerateCommandModule } from '../commands/generate/cli';
import { LintCommandModule } from '../commands/lint/cli';
import { AwesomeCommandModule } from '../commands/make-this-awesome/cli';
import { NewCommandModule } from '../commands/new/cli';
import { RunCommandModule } from '../commands/run/cli';
import { ServeCommandModule } from '../commands/serve/cli';
import { TestCommandModule } from '../commands/test/cli';
import { UpdateCommandModule } from '../commands/update/cli';
import { VersionCommandModule } from '../commands/version/cli';
import { colors } from '../utilities/color';
import { AngularWorkspace, getWorkspace } from '../utilities/config';
import { PackageManagerUtils } from '../utilities/package-manager';
import { CommandContext, CommandModuleError, CommandScope } from './command-module';
import { addCommandModuleToYargs, demandCommandFailureMessage } from './utilities/command';
import { jsonHelpUsage } from './utilities/json-help';
import { normalizeOptionsMiddleware } from './utilities/normalize-options-middleware';
const COMMANDS = [
VersionCommandModule,
DocCommandModule,
AwesomeCommandModule,
ConfigCommandModule,
AnalyticsCommandModule,
AddCommandModule,
GenerateCommandModule,
BuildCommandModule,
E2eCommandModule,
TestCommandModule,
ServeCommandModule,
ExtractI18nCommandModule,
DeployCommandModule,
LintCommandModule,
NewCommandModule,
UpdateCommandModule,
RunCommandModule,
CacheCommandModule,
].sort(); // Will be sorted by class name.
const yargsParser = Parser as unknown as typeof Parser.default;
export async function runCommand(args: string[], logger: logging.Logger): Promise<number> {
const {
$0,
_: positional,
help = false,
jsonHelp = false,
...rest
} = yargsParser(args, { boolean: ['help', 'json-help'], alias: { 'collection': 'c' } });
let workspace: AngularWorkspace | undefined;
let globalConfiguration: AngularWorkspace | undefined;
try {
[workspace, globalConfiguration] = await Promise.all([
getWorkspace('local'),
getWorkspace('global'),
]);
} catch (e) {
logger.fatal(e.message);
return 1;
}
const root = workspace?.basePath ?? process.cwd();
const context: CommandContext = {
globalConfiguration,
workspace,
logger,
currentDirectory: process.cwd(),
root,
packageManager: new PackageManagerUtils({ globalConfiguration, workspace, root }),
args: {
positional: positional.map((v) => v.toString()),
options: {
help,
jsonHelp,
...rest,
},
},
};
let localYargs = yargs(args);
for (const CommandModule of COMMANDS) {
if (!jsonHelp) {
// Skip scope validation when running with '--json-help' since it's easier to generate the output for all commands this way.
const scope = CommandModule.scope;
if ((scope === CommandScope.In && !workspace) || (scope === CommandScope.Out && workspace)) {
continue;
}
}
localYargs = addCommandModuleToYargs(localYargs, CommandModule, context);
}
if (jsonHelp) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(localYargs as any).getInternalMethods().getUsageInstance().help = () => jsonHelpUsage();
}
await localYargs
.scriptName('ng')
// https://github.com/yargs/yargs/blob/main/docs/advanced.md#customizing-yargs-parser
.parserConfiguration({
'populate--': true,
'unknown-options-as-args': false,
'dot-notation': false,
'boolean-negation': true,
'strip-aliased': true,
'strip-dashed': true,
'camel-case-expansion': false,
})
.option('json-help', {
describe: 'Show help in JSON format.',
implies: ['help'],
hidden: true,
type: 'boolean',
})
.help('help', 'Shows a help message for this command in the console.')
// A complete list of strings can be found: https://github.com/yargs/yargs/blob/main/locales/en.json
.updateStrings({
'Commands:': colors.cyan('Commands:'),
'Options:': colors.cyan('Options:'),
'Positionals:': colors.cyan('Arguments:'),
'deprecated': colors.yellow('deprecated'),
'deprecated: %s': colors.yellow('deprecated:') + ' %s',
'Did you mean %s?': 'Unknown command. Did you mean %s?',
})
.demandCommand(1, demandCommandFailureMessage)
.recommendCommands()
.middleware(normalizeOptionsMiddleware)
.version(false)
.showHelpOnFail(false)
.strict()
.fail((msg, err) => {
throw msg
? // Validation failed example: `Unknown argument:`
new CommandModuleError(msg)
: // Unknown exception, re-throw.
err;
})
.wrap(yargs.terminalWidth())
.parseAsync();
return process.exitCode ?? 0;
}