forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-runner.ts
More file actions
243 lines (220 loc) · 7.64 KB
/
command-runner.ts
File metadata and controls
243 lines (220 loc) · 7.64 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**
* @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.dev/license
*/
import { JsonValue, isJsonObject, logging } from '@angular-devkit/core';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import yargs from 'yargs';
import { Parser as yargsParser } from 'yargs/helpers';
import { getCacheConfig } from '../commands/cache/utilities';
import {
CommandConfig,
CommandNames,
RootCommands,
RootCommandsAliases,
} from '../commands/command-config';
import { PackageManager, createPackageManager } from '../package-managers';
import { ConfiguredPackageManagerInfo } from '../package-managers/factory';
import { colors } from '../utilities/color';
import { AngularWorkspace, getProjectByCwd, getWorkspace } from '../utilities/config';
import { assertIsError } from '../utilities/error';
import { VERSION } from '../utilities/version';
import { CommandContext, CommandModuleError } from './command-module';
import {
CommandModuleConstructor,
addCommandModuleToYargs,
demandCommandFailureMessage,
} from './utilities/command';
import { jsonHelpUsage } from './utilities/json-help';
import { createNormalizeOptionsMiddleware } from './utilities/normalize-options-middleware';
export async function runCommand(args: string[], logger: logging.Logger): Promise<number> {
const {
$0,
_,
help = false,
dryRun = false,
jsonHelp = false,
getYargsCompletions = false,
...rest
} = yargsParser(args, {
boolean: ['help', 'json-help', 'get-yargs-completions', 'dry-run'],
alias: { 'collection': 'c' },
});
// When `getYargsCompletions` is true the scriptName 'ng' at index 0 is not removed.
const positional = getYargsCompletions ? _.slice(1) : _;
let workspace: AngularWorkspace | undefined;
let globalConfiguration: AngularWorkspace;
try {
[workspace, globalConfiguration] = await Promise.all([
getWorkspace('local'),
getWorkspace('global'),
]);
} catch (e) {
assertIsError(e);
logger.fatal(e.message);
return 1;
}
const root = workspace?.basePath ?? process.cwd();
const localYargs = yargs(args);
let packageManager: Promise<PackageManager> | undefined;
const context: CommandContext = {
globalConfiguration,
workspace,
logger,
currentDirectory: process.cwd(),
yargsInstance: localYargs,
root,
get packageManager() {
return (packageManager ??= (async () => {
const cacheConfig = workspace && getCacheConfig(workspace);
return createPackageManager({
cwd: root,
logger,
dryRun: dryRun || help || jsonHelp || getYargsCompletions,
tempDirectory: cacheConfig?.enabled ? cacheConfig.path : undefined,
configuredPackageManager: await getConfiguredPackageManager(
root,
workspace,
globalConfiguration,
),
});
})());
},
args: {
positional: positional.map((v) => v.toString()),
options: {
help,
jsonHelp,
getYargsCompletions,
...rest,
},
},
};
for (const CommandModule of await getCommandsToRegister(positional[0])) {
addCommandModuleToYargs(CommandModule, context);
}
if (jsonHelp) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const usageInstance = (localYargs as any).getInternalMethods().getUsageInstance();
usageInstance.help = () => jsonHelpUsage(localYargs);
}
// Add default command to support version option when no subcommand is specified
localYargs.command('*', false, (builder) =>
builder.version('version', 'Show Angular CLI version.', VERSION.full),
);
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?',
})
.epilogue('For more information, see https://angular.dev/cli/.\n')
.demandCommand(1, demandCommandFailureMessage)
.recommendCommands()
.middleware(createNormalizeOptionsMiddleware(localYargs))
.version(false)
.showHelpOnFail(false)
.strict()
.fail((msg, err) => {
throw msg
? // Validation failed example: `Unknown argument:`
new CommandModuleError(msg)
: // Unknown exception, re-throw.
err;
})
.wrap(localYargs.terminalWidth())
.parseAsync();
return +(process.exitCode ?? 0);
}
/**
* Get the commands that need to be registered.
* @returns One or more command factories that needs to be registered.
*/
async function getCommandsToRegister(
commandName: string | number,
): Promise<CommandModuleConstructor[]> {
const commands: CommandConfig[] = [];
if (commandName in RootCommands) {
commands.push(RootCommands[commandName as CommandNames]);
} else if (commandName in RootCommandsAliases) {
commands.push(RootCommandsAliases[commandName]);
} else {
// Unknown command, register every possible command.
Object.values(RootCommands).forEach((c) => commands.push(c));
}
return Promise.all(commands.map((command) => command.factory().then((m) => m.default)));
}
/**
* Gets the configured package manager by checking package.json, or the local and global angular.json files.
*
* @param root The root directory of the workspace.
* @param localWorkspace The local workspace.
* @param globalWorkspace The global workspace.
* @returns The package manager name and version.
*/
async function getConfiguredPackageManager(
root: string,
localWorkspace: AngularWorkspace | undefined,
globalWorkspace: AngularWorkspace,
): Promise<ConfiguredPackageManagerInfo | undefined> {
let result: ConfiguredPackageManagerInfo | undefined;
try {
const packageJsonPath = join(root, 'package.json');
const pkgJson = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as JsonValue;
result = getPackageManager(pkgJson);
} catch {}
if (result) {
return result;
}
if (localWorkspace) {
const project = getProjectByCwd(localWorkspace);
if (project) {
result = getPackageManager(localWorkspace.projects.get(project)?.extensions['cli']);
}
result ??= getPackageManager(localWorkspace.extensions['cli']);
}
result ??= getPackageManager(globalWorkspace.extensions['cli']);
return result;
}
/**
* Get the package manager name from a JSON value.
* @param source The JSON value to get the package manager name from.
* @returns The package manager name and version.
*/
function getPackageManager(
source: JsonValue | undefined,
): ConfiguredPackageManagerInfo | undefined {
if (source && isJsonObject(source)) {
const value = source['packageManager'];
if (typeof value === 'string') {
return value.split('@', 2) as unknown as ConfiguredPackageManagerInfo;
}
}
return undefined;
}