Skip to content

Commit b630317

Browse files
clydinKeen Yee Liau
authored andcommitted
refactor(@angular/cli): convert workspace access to async
This is in preparation for conversion from the experimental workspace API to the stable workspace API.
1 parent 2e4cae1 commit b630317

File tree

13 files changed

+151
-152
lines changed

13 files changed

+151
-152
lines changed

packages/angular/cli/bin/postinstall/analytics-prompt.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ if ('NG_CLI_ANALYTICS' in process.env) {
55
return;
66
}
77

8-
(async () => {
9-
try {
10-
const analytics = require('../../models/analytics');
8+
try {
9+
var analytics = require('../../models/analytics');
1110

12-
if (!analytics.hasGlobalAnalyticsConfiguration()) {
13-
await analytics.promptGlobalAnalytics();
11+
analytics.hasGlobalAnalyticsConfiguration().then(hasGlobalConfig => {
12+
if (!hasGlobalConfig) {
13+
return analytics.promptGlobalAnalytics();
1414
}
15-
} catch (_) {}
16-
})();
15+
});
16+
} catch (_) {}

packages/angular/cli/commands/add-impl.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ const npa = require('npm-package-arg');
2727
export class AddCommand extends SchematicCommand<AddCommandSchema> {
2828
readonly allowPrivateSchematics = true;
2929
readonly allowAdditionalArgs = true;
30-
readonly packageManager = getPackageManager(this.workspace.root);
3130

3231
async run(options: AddCommandSchema & Arguments) {
3332
if (!options.collection) {
@@ -55,7 +54,8 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
5554
return this.executeSchematic(packageIdentifier.name, options['--']);
5655
}
5756

58-
const usingYarn = this.packageManager === 'yarn';
57+
const packageManager = await getPackageManager(this.workspace.root);
58+
const usingYarn = packageManager === 'yarn';
5959

6060
if (packageIdentifier.type === 'tag' && !packageIdentifier.rawSpec) {
6161
// only package name provided; search for viable version
@@ -135,7 +135,7 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
135135
}
136136
}
137137

138-
await npmInstall(packageIdentifier.raw, this.logger, this.packageManager, this.workspace.root);
138+
await npmInstall(packageIdentifier.raw, this.logger, packageManager, this.workspace.root);
139139

140140
return this.executeSchematic(collectionName, options['--']);
141141
}

packages/angular/cli/commands/config-impl.ts

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import {
2828
} from '../utilities/config';
2929
import { Schema as ConfigCommandSchema, Value as ConfigCommandSchemaValue } from './config';
3030

31-
3231
function _validateBoolean(value: string) {
3332
if (('' + value).trim() === 'true') {
3433
return true;
@@ -71,8 +70,7 @@ function _validateAnalyticsSharingTracking(value: string) {
7170
return value;
7271
}
7372

74-
75-
const validCliPaths = new Map<string, ((arg: string) => JsonValue)>([
73+
const validCliPaths = new Map<string, (arg: string) => JsonValue>([
7674
['cli.warnings.versionMismatch', _validateBoolean],
7775
['cli.defaultCollection', _validateString],
7876
['cli.packageManager', _validateString],
@@ -89,9 +87,9 @@ const validCliPaths = new Map<string, ((arg: string) => JsonValue)>([
8987
* @returns {(string|number)[]} The fragments for the string.
9088
* @private
9189
*/
92-
function parseJsonPath(path: string): (string|number)[] {
90+
function parseJsonPath(path: string): (string | number)[] {
9391
const fragments = (path || '').split(/\./g);
94-
const result: (string|number)[] = [];
92+
const result: (string | number)[] = [];
9593

9694
while (fragments.length > 0) {
9795
const fragment = fragments.shift();
@@ -109,7 +107,7 @@ function parseJsonPath(path: string): (string|number)[] {
109107
const indices = match[2]
110108
.slice(1, -1)
111109
.split('][')
112-
.map(x => /^\d$/.test(x) ? +x : x.replace(/\"|\'/g, ''));
110+
.map(x => (/^\d$/.test(x) ? +x : x.replace(/\"|\'/g, '')));
113111
result.push(...indices);
114112
}
115113
}
@@ -213,14 +211,12 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
213211
await this.validateScope(CommandScope.InProject);
214212
}
215213

216-
let config =
217-
(getWorkspace(level) as {} as { _workspace: experimental.workspace.WorkspaceSchema });
214+
let config = await getWorkspace(level);
218215

219216
if (options.global && !config) {
220217
try {
221218
if (migrateLegacyGlobalConfig()) {
222-
config =
223-
(getWorkspace(level) as {} as { _workspace: experimental.workspace.WorkspaceSchema });
219+
config = await getWorkspace(level);
224220
this.logger.info(tags.oneLine`
225221
We found a global configuration that was used in Angular CLI 1.
226222
It has been automatically migrated.`);
@@ -235,7 +231,10 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
235231
return 1;
236232
}
237233

238-
return this.get(config._workspace, options);
234+
const workspace = ((config as {}) as { _workspace: experimental.workspace.WorkspaceSchema })
235+
._workspace;
236+
237+
return this.get(workspace, options);
239238
} else {
240239
return this.set(options);
241240
}
@@ -253,7 +252,7 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
253252
return 0;
254253
}
255254

256-
value = getValueFromPath(config as {} as JsonObject, options.jsonPath);
255+
value = getValueFromPath((config as {}) as JsonObject, options.jsonPath);
257256
} else {
258257
value = config;
259258
}
@@ -271,7 +270,7 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
271270
return 0;
272271
}
273272

274-
private set(options: ConfigCommandSchema) {
273+
private async set(options: ConfigCommandSchema) {
275274
if (!options.jsonPath || !options.jsonPath.trim()) {
276275
throw new Error('Invalid Path.');
277276
}
@@ -283,9 +282,11 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
283282
return 0;
284283
}
285284

286-
if (options.global
287-
&& !options.jsonPath.startsWith('schematics.')
288-
&& !validCliPaths.has(options.jsonPath)) {
285+
if (
286+
options.global &&
287+
!options.jsonPath.startsWith('schematics.') &&
288+
!validCliPaths.has(options.jsonPath)
289+
) {
289290
throw new Error('Invalid Path.');
290291
}
291292

@@ -309,7 +310,7 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
309310
}
310311

311312
try {
312-
validateWorkspace(configValue);
313+
await validateWorkspace(configValue);
313314
} catch (error) {
314315
this.logger.fatal(error.message);
315316

@@ -321,5 +322,4 @@ export class ConfigCommand extends Command<ConfigCommandSchema> {
321322

322323
return 0;
323324
}
324-
325325
}

packages/angular/cli/commands/generate-impl.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
1717

1818
async initialize(options: GenerateCommandSchema & Arguments) {
1919
// Fill up the schematics property of the command description.
20-
const [collectionName, schematicName] = this.parseSchematicInfo(options);
20+
const [collectionName, schematicName] = await this.parseSchematicInfo(options);
2121
this.collectionName = collectionName;
2222
this.schematicName = schematicName;
2323

@@ -45,7 +45,7 @@ export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
4545
continue;
4646
}
4747

48-
if (this.getDefaultSchematicCollection() == collectionName) {
48+
if ((await this.getDefaultSchematicCollection()) == collectionName) {
4949
subcommands[name] = subcommand;
5050
} else {
5151
subcommands[`${collectionName}:${name}`] = subcommand;
@@ -78,7 +78,7 @@ export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
7878
paths: string[],
7979
options: GenerateCommandSchema & Arguments,
8080
): Promise<void> {
81-
const [collectionName, schematicName] = this.parseSchematicInfo(options);
81+
const [collectionName, schematicName] = await this.parseSchematicInfo(options);
8282

8383
if (!schematicName || !collectionName) {
8484
return;
@@ -91,8 +91,10 @@ export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
9191
);
9292
}
9393

94-
private parseSchematicInfo(options: { schematic?: string }): [string, string | undefined] {
95-
let collectionName = this.getDefaultSchematicCollection();
94+
private async parseSchematicInfo(options: {
95+
schematic?: string;
96+
}): Promise<[string, string | undefined]> {
97+
let collectionName = await this.getDefaultSchematicCollection();
9698

9799
let schematicName = options.schematic;
98100

packages/angular/cli/commands/new-impl.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export class NewCommand extends SchematicCommand<NewCommandSchema> {
2020
if (options.collection) {
2121
this.collectionName = options.collection;
2222
} else {
23-
this.collectionName = this.parseCollectionName(options);
23+
this.collectionName = await this.parseCollectionName(options);
2424
}
2525

2626
return super.initialize(options);
@@ -43,7 +43,7 @@ export class NewCommand extends SchematicCommand<NewCommandSchema> {
4343
});
4444
}
4545

46-
private parseCollectionName(options: any): string {
46+
private async parseCollectionName(options: any): Promise<string> {
4747
return options.collection || this.getDefaultSchematicCollection();
4848
}
4949
}

packages/angular/cli/commands/update-impl.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ export class UpdateCommand extends SchematicCommand<UpdateCommandSchema> {
9999
}
100100
}
101101

102-
const packageManager = getPackageManager(this.workspace.root);
102+
const packageManager = await getPackageManager(this.workspace.root);
103103
this.logger.info(`Using package manager: '${packageManager}'`);
104104

105105
// Special handling for Angular CLI 1.x migrations

packages/angular/cli/lib/init.ts

Lines changed: 66 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -77,76 +77,79 @@ if (process.env['NG_CLI_PROFILING']) {
7777
process.on('uncaughtException', () => exitHandler({ exit: true }));
7878
}
7979

80-
let cli;
81-
try {
82-
const projectLocalCli = require.resolve('@angular/cli', { paths: [process.cwd()] });
83-
84-
// This was run from a global, check local version.
85-
const globalVersion = new SemVer(packageJson['version']);
86-
let localVersion;
87-
let shouldWarn = false;
88-
80+
(async () => {
81+
let cli;
8982
try {
90-
localVersion = _fromPackageJson();
91-
shouldWarn = localVersion != null && globalVersion.compare(localVersion) > 0;
92-
} catch (e) {
93-
// eslint-disable-next-line no-console
94-
console.error(e);
95-
shouldWarn = true;
96-
}
83+
const projectLocalCli = require.resolve('@angular/cli', { paths: [process.cwd()] });
9784

98-
if (shouldWarn && isWarningEnabled('versionMismatch')) {
99-
const warning = colors.yellow(tags.stripIndents`
100-
Your global Angular CLI version (${globalVersion}) is greater than your local
101-
version (${localVersion}). The local Angular CLI version is used.
85+
// This was run from a global, check local version.
86+
const globalVersion = new SemVer(packageJson['version']);
87+
let localVersion;
88+
let shouldWarn = false;
10289

103-
To disable this warning use "ng config -g cli.warnings.versionMismatch false".
104-
`);
105-
// Don't show warning colorised on `ng completion`
106-
if (process.argv[2] !== 'completion') {
107-
// eslint-disable-next-line no-console
108-
console.error(warning);
109-
} else {
90+
try {
91+
localVersion = _fromPackageJson();
92+
shouldWarn = localVersion != null && globalVersion.compare(localVersion) > 0;
93+
} catch (e) {
11094
// eslint-disable-next-line no-console
111-
console.error(warning);
112-
process.exit(1);
95+
console.error(e);
96+
shouldWarn = true;
11397
}
114-
}
11598

116-
// No error implies a projectLocalCli, which will load whatever
117-
// version of ng-cli you have installed in a local package.json
118-
cli = require(projectLocalCli);
119-
} catch {
120-
// If there is an error, resolve could not find the ng-cli
121-
// library from a package.json. Instead, include it from a relative
122-
// path to this script file (which is likely a globally installed
123-
// npm package). Most common cause for hitting this is `ng new`
124-
cli = require('./cli');
125-
}
99+
if (shouldWarn && await isWarningEnabled('versionMismatch')) {
100+
const warning = colors.yellow(tags.stripIndents`
101+
Your global Angular CLI version (${globalVersion}) is greater than your local
102+
version (${localVersion}). The local Angular CLI version is used.
103+
104+
To disable this warning use "ng config -g cli.warnings.versionMismatch false".
105+
`);
106+
// Don't show warning colorised on `ng completion`
107+
if (process.argv[2] !== 'completion') {
108+
// eslint-disable-next-line no-console
109+
console.error(warning);
110+
} else {
111+
// eslint-disable-next-line no-console
112+
console.error(warning);
113+
process.exit(1);
114+
}
115+
}
126116

127-
if ('default' in cli) {
128-
cli = cli['default'];
129-
}
117+
// No error implies a projectLocalCli, which will load whatever
118+
// version of ng-cli you have installed in a local package.json
119+
cli = require(projectLocalCli);
120+
} catch {
121+
// If there is an error, resolve could not find the ng-cli
122+
// library from a package.json. Instead, include it from a relative
123+
// path to this script file (which is likely a globally installed
124+
// npm package). Most common cause for hitting this is `ng new`
125+
cli = require('./cli');
126+
}
130127

131-
// This is required to support 1.x local versions with a 6+ global
132-
let standardInput;
133-
try {
134-
standardInput = process.stdin;
135-
} catch (e) {
136-
delete process.stdin;
137-
process.stdin = new Duplex();
138-
standardInput = process.stdin;
139-
}
128+
if ('default' in cli) {
129+
cli = cli['default'];
130+
}
140131

141-
cli({
142-
cliArgs: process.argv.slice(2),
143-
inputStream: standardInput,
144-
outputStream: process.stdout,
145-
})
146-
.then((exitCode: number) => {
147-
process.exit(exitCode);
148-
})
149-
.catch((err: Error) => {
150-
console.error('Unknown error: ' + err.toString());
151-
process.exit(127);
132+
return cli;
133+
})().then(cli => {
134+
// This is required to support 1.x local versions with a 6+ global
135+
let standardInput;
136+
try {
137+
standardInput = process.stdin;
138+
} catch (e) {
139+
delete process.stdin;
140+
process.stdin = new Duplex();
141+
standardInput = process.stdin;
142+
}
143+
144+
return cli({
145+
cliArgs: process.argv.slice(2),
146+
inputStream: standardInput,
147+
outputStream: process.stdout,
152148
});
149+
}).then((exitCode: number) => {
150+
process.exit(exitCode);
151+
})
152+
.catch((err: Error) => {
153+
console.error('Unknown error: ' + err.toString());
154+
process.exit(127);
155+
});

0 commit comments

Comments
 (0)