Skip to content

Commit c4313f5

Browse files
clydinvikerman
authored andcommitted
refactor(@angular/cli): unify color handling and support
1 parent 1df5eeb commit c4313f5

File tree

12 files changed

+292
-271
lines changed

12 files changed

+292
-271
lines changed

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

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
import { analytics, tags, terminal } from '@angular-devkit/core';
8+
import { analytics, tags } from '@angular-devkit/core';
99
import { NodePackageDoesNotSupportSchematics } from '@angular-devkit/schematics/tools';
1010
import { dirname, join } from 'path';
1111
import { intersects, prerelease, rcompare, satisfies, valid, validRange } from 'semver';
1212
import { isPackageNameSafeForAnalytics } from '../models/analytics';
1313
import { Arguments } from '../models/interface';
1414
import { SchematicCommand } from '../models/schematic-command';
1515
import npmInstall from '../tasks/npm-install';
16+
import { colors } from '../utilities/color';
1617
import { getPackageManager } from '../utilities/package-manager';
1718
import {
1819
PackageManifest,
@@ -31,8 +32,8 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
3132
async run(options: AddCommandSchema & Arguments) {
3233
if (!options.collection) {
3334
this.logger.fatal(
34-
`The "ng add" command requires a name argument to be specified eg. `
35-
+ `${terminal.yellow('ng add [name] ')}. For more details, use "ng help".`,
35+
`The "ng add" command requires a name argument to be specified eg. ` +
36+
`${colors.yellow('ng add [name] ')}. For more details, use "ng help".`,
3637
);
3738

3839
return 1;
@@ -61,11 +62,10 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
6162
// plus special cases for packages that did not have peer deps setup
6263
let packageMetadata;
6364
try {
64-
packageMetadata = await fetchPackageMetadata(
65-
packageIdentifier.name,
66-
this.logger,
67-
{ registry: options.registry, usingYarn },
68-
);
65+
packageMetadata = await fetchPackageMetadata(packageIdentifier.name, this.logger, {
66+
registry: options.registry,
67+
usingYarn,
68+
});
6969
} catch (e) {
7070
this.logger.error('Unable to fetch package metadata: ' + e.message);
7171

@@ -79,16 +79,19 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
7979
// tslint:disable-next-line:no-any
8080
const semverOptions = { includePrerelease: true } as any;
8181

82-
if (version
83-
&& ((validRange(version) && intersects(version, '7', semverOptions))
84-
|| (valid(version) && satisfies(version, '7', semverOptions)))) {
82+
if (
83+
version &&
84+
((validRange(version) && intersects(version, '7', semverOptions)) ||
85+
(valid(version) && satisfies(version, '7', semverOptions)))
86+
) {
8587
packageIdentifier = npa.resolve('@angular/pwa', '0.12');
8688
}
8789
}
8890
} else if (!latestManifest || (await this.hasMismatchedPeer(latestManifest))) {
8991
// 'latest' is invalid so search for most recent matching package
90-
const versionManifests = Array.from(packageMetadata.versions.values())
91-
.filter(value => !prerelease(value.version));
92+
const versionManifests = Array.from(packageMetadata.versions.values()).filter(
93+
value => !prerelease(value.version),
94+
);
9295

9396
versionManifests.sort((a, b) => rcompare(a.version, b.version, true));
9497

@@ -101,7 +104,7 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
101104
}
102105

103106
if (!newIdentifier) {
104-
this.logger.warn('Unable to find compatible package. Using \'latest\'.');
107+
this.logger.warn("Unable to find compatible package. Using 'latest'.");
105108
} else {
106109
packageIdentifier = newIdentifier;
107110
}
@@ -111,11 +114,10 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
111114
let collectionName = packageIdentifier.name;
112115
if (!packageIdentifier.registry) {
113116
try {
114-
const manifest = await fetchPackageManifest(
115-
packageIdentifier,
116-
this.logger,
117-
{ registry: options.registry, usingYarn },
118-
);
117+
const manifest = await fetchPackageManifest(packageIdentifier, this.logger, {
118+
registry: options.registry,
119+
usingYarn,
120+
});
119121

120122
collectionName = manifest.name;
121123

@@ -129,12 +131,7 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
129131
}
130132
}
131133

132-
await npmInstall(
133-
packageIdentifier.raw,
134-
this.logger,
135-
this.packageManager,
136-
this.workspace.root,
137-
);
134+
await npmInstall(packageIdentifier.raw, this.logger, this.packageManager, this.workspace.root);
138135

139136
return this.executeSchematic(collectionName, options['--']);
140137
}
@@ -204,11 +201,10 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
204201
private async findProjectVersion(name: string): Promise<string | null> {
205202
let installedPackage;
206203
try {
207-
installedPackage = require.resolve(
208-
join(name, 'package.json'),
209-
{ paths: [this.workspace.root] },
210-
);
211-
} catch { }
204+
installedPackage = require.resolve(join(name, 'package.json'), {
205+
paths: [this.workspace.root],
206+
});
207+
} catch {}
212208

213209
if (installedPackage) {
214210
try {
@@ -253,8 +249,10 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
253249
// tslint:disable-next-line:no-any
254250
const options = { includePrerelease: true } as any;
255251

256-
if (!intersects(version, peerIdentifier.rawSpec, options)
257-
&& !satisfies(version, peerIdentifier.rawSpec, options)) {
252+
if (
253+
!intersects(version, peerIdentifier.rawSpec, options) &&
254+
!satisfies(version, peerIdentifier.rawSpec, options)
255+
) {
258256
return true;
259257
}
260258
} catch {
@@ -265,7 +263,6 @@ export class AddCommand extends SchematicCommand<AddCommandSchema> {
265263
// type === 'tag' | 'file' | 'directory' | 'remote' | 'git'
266264
// Cannot accurately compare these as the tag/location may have changed since install
267265
}
268-
269266
}
270267

271268
return false;

packages/angular/cli/commands/easter-egg-impl.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
9-
import { terminal } from '@angular-devkit/core';
108
import { Command } from '../models/command';
9+
import { colors } from '../utilities/color';
1110
import { Schema as AwesomeCommandSchema } from './easter-egg';
1211

1312
function pickOne(of: string[]): string {
@@ -26,6 +25,6 @@ export class AwesomeCommand extends Command<AwesomeCommandSchema> {
2625
`I spy with my little eye a great developer!`,
2726
`Noop... already awesome.`,
2827
]);
29-
this.logger.info(terminal.green(phrase));
28+
this.logger.info(colors.green(phrase));
3029
}
3130
}

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,15 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
9-
import { terminal } from '@angular-devkit/core';
108
import { Arguments, SubCommandDescription } from '../models/interface';
119
import { SchematicCommand } from '../models/schematic-command';
10+
import { colors } from '../utilities/color';
1211
import { parseJsonSchemaToSubCommandDescription } from '../utilities/json-schema';
1312
import { Schema as GenerateCommandSchema } from './generate';
1413

1514
export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
1615
// Allows us to resolve aliases before reporting analytics
17-
longSchematicName: string|undefined;
16+
longSchematicName: string | undefined;
1817

1918
async initialize(options: GenerateCommandSchema & Arguments) {
2019
// Fill up the schematics property of the command description.
@@ -114,7 +113,7 @@ export class GenerateCommand extends SchematicCommand<GenerateCommandSchema> {
114113
const subcommand = this.description.options.filter(x => x.subcommands)[0];
115114
if (Object.keys((subcommand && subcommand.subcommands) || {}).length == 1) {
116115
this.logger.info(`\nTo see help for a schematic run:`);
117-
this.logger.info(terminal.cyan(` ng generate <schematic> --help`));
116+
this.logger.info(colors.cyan(` ng generate <schematic> --help`));
118117
}
119118

120119
return 0;

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
import { terminal } from '@angular-devkit/core';
98
import { Command } from '../models/command';
9+
import { colors } from '../utilities/color';
1010
import { Schema as HelpCommandSchema } from './help';
1111

1212
export class HelpCommand extends Command<HelpCommandSchema> {
@@ -19,7 +19,7 @@ export class HelpCommand extends Command<HelpCommandSchema> {
1919
}
2020

2121
const aliasInfo = cmd.aliases.length > 0 ? ` (${cmd.aliases.join(', ')})` : '';
22-
this.logger.info(` ${terminal.cyan(cmd.name)}${aliasInfo} ${cmd.description}`);
22+
this.logger.info(` ${colors.cyan(cmd.name)}${aliasInfo} ${cmd.description}`);
2323
}
2424
this.logger.info(`\nFor more detailed help run "ng [command name] --help"`);
2525
}

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

Lines changed: 58 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
* Use of this source code is governed by an MIT-style license that can be
66
* found in the LICENSE file at https://angular.io/license
77
*/
8-
9-
import { terminal } from '@angular-devkit/core';
108
import * as child_process from 'child_process';
119
import * as fs from 'fs';
1210
import * as path from 'path';
1311
import { Command } from '../models/command';
12+
import { colors } from '../utilities/color';
1413
import { findUp } from '../utilities/find-up';
1514
import { Schema as VersionCommandSchema } from './version';
1615

@@ -45,40 +44,41 @@ export class VersionCommand extends Command<VersionCommandSchema> {
4544
: maybeNodeModules;
4645

4746
const packageNames = [
48-
...Object.keys(pkg && pkg['dependencies'] || {}),
49-
...Object.keys(pkg && pkg['devDependencies'] || {}),
50-
...Object.keys(projPkg && projPkg['dependencies'] || {}),
51-
...Object.keys(projPkg && projPkg['devDependencies'] || {}),
52-
];
47+
...Object.keys((pkg && pkg['dependencies']) || {}),
48+
...Object.keys((pkg && pkg['devDependencies']) || {}),
49+
...Object.keys((projPkg && projPkg['dependencies']) || {}),
50+
...Object.keys((projPkg && projPkg['devDependencies']) || {}),
51+
];
5352

5453
if (packageRoot != null) {
5554
// Add all node_modules and node_modules/@*/*
56-
const nodePackageNames = fs.readdirSync(packageRoot)
57-
.reduce<string[]>((acc, name) => {
58-
if (name.startsWith('@')) {
59-
return acc.concat(
60-
fs.readdirSync(path.resolve(packageRoot, name))
61-
.map(subName => name + '/' + subName),
62-
);
63-
} else {
64-
return acc.concat(name);
65-
}
66-
}, []);
55+
const nodePackageNames = fs.readdirSync(packageRoot).reduce<string[]>((acc, name) => {
56+
if (name.startsWith('@')) {
57+
return acc.concat(
58+
fs.readdirSync(path.resolve(packageRoot, name)).map(subName => name + '/' + subName),
59+
);
60+
} else {
61+
return acc.concat(name);
62+
}
63+
}, []);
6764

6865
packageNames.push(...nodePackageNames);
6966
}
7067

7168
const versions = packageNames
7269
.filter(x => patterns.some(p => p.test(x)))
73-
.reduce((acc, name) => {
74-
if (name in acc) {
75-
return acc;
76-
}
70+
.reduce(
71+
(acc, name) => {
72+
if (name in acc) {
73+
return acc;
74+
}
7775

78-
acc[name] = this.getVersion(name, packageRoot, maybeNodeModules);
76+
acc[name] = this.getVersion(name, packageRoot, maybeNodeModules);
7977

80-
return acc;
81-
}, {} as { [module: string]: string });
78+
return acc;
79+
},
80+
{} as { [module: string]: string },
81+
);
8282

8383
let ngCliVersion = pkg.version;
8484
if (!__dirname.match(/node_modules/)) {
@@ -90,8 +90,7 @@ export class VersionCommand extends Command<VersionCommandSchema> {
9090
stdio: 'pipe',
9191
});
9292
gitBranch = gitRefName.replace('\n', '');
93-
} catch {
94-
}
93+
} catch {}
9594

9695
ngCliVersion = `local (v${pkg.version}, branch: ${gitBranch})`;
9796
}
@@ -103,8 +102,10 @@ export class VersionCommand extends Command<VersionCommandSchema> {
103102
angularCoreVersion = versions['@angular/core'];
104103
if (angularCoreVersion) {
105104
for (const angularPackage of Object.keys(versions)) {
106-
if (versions[angularPackage] == angularCoreVersion
107-
&& angularPackage.startsWith('@angular/')) {
105+
if (
106+
versions[angularPackage] == angularCoreVersion &&
107+
angularPackage.startsWith('@angular/')
108+
) {
108109
angularSameAsCore.push(angularPackage.replace(/^@angular\//, ''));
109110
delete versions[angularPackage];
110111
}
@@ -125,36 +126,43 @@ export class VersionCommand extends Command<VersionCommandSchema> {
125126
/ ___ \\| | | | (_| | |_| | | (_| | | | |___| |___ | |
126127
/_/ \\_\\_| |_|\\__, |\\__,_|_|\\__,_|_| \\____|_____|___|
127128
|___/
128-
`.split('\n').map(x => terminal.red(x)).join('\n');
129+
`
130+
.split('\n')
131+
.map(x => colors.red(x))
132+
.join('\n');
129133

130134
this.logger.info(asciiArt);
131-
this.logger.info(`
135+
this.logger.info(
136+
`
132137
Angular CLI: ${ngCliVersion}
133138
Node: ${process.versions.node}
134139
OS: ${process.platform} ${process.arch}
135140
Angular: ${angularCoreVersion}
136-
... ${angularSameAsCore.reduce<string[]>((acc, name) => {
137-
// Perform a simple word wrap around 60.
138-
if (acc.length == 0) {
139-
return [name];
140-
}
141-
const line = (acc[acc.length - 1] + ', ' + name);
142-
if (line.length > 60) {
143-
acc.push(name);
144-
} else {
145-
acc[acc.length - 1] = line;
146-
}
141+
... ${angularSameAsCore
142+
.reduce<string[]>((acc, name) => {
143+
// Perform a simple word wrap around 60.
144+
if (acc.length == 0) {
145+
return [name];
146+
}
147+
const line = acc[acc.length - 1] + ', ' + name;
148+
if (line.length > 60) {
149+
acc.push(name);
150+
} else {
151+
acc[acc.length - 1] = line;
152+
}
147153
148-
return acc;
149-
}, []).join('\n... ')}
154+
return acc;
155+
}, [])
156+
.join('\n... ')}
150157
151158
Package${namePad.slice(7)}Version
152159
-------${namePad.replace(/ /g, '-')}------------------
153160
${Object.keys(versions)
154-
.map(module => `${module}${namePad.slice(module.length)}${versions[module]}`)
155-
.sort()
156-
.join('\n')}
157-
`.replace(/^ {6}/gm, ''));
161+
.map(module => `${module}${namePad.slice(module.length)}${versions[module]}`)
162+
.sort()
163+
.join('\n')}
164+
`.replace(/^ {6}/gm, ''),
165+
);
158166
}
159167

160168
private getVersion(
@@ -168,17 +176,15 @@ export class VersionCommand extends Command<VersionCommandSchema> {
168176

169177
return modulePkg.version;
170178
}
171-
} catch (_) {
172-
}
179+
} catch (_) {}
173180

174181
try {
175182
if (cliNodeModules) {
176183
const modulePkg = require(path.resolve(cliNodeModules, moduleName, 'package.json'));
177184

178185
return modulePkg.version + ' (cli-only)';
179186
}
180-
} catch {
181-
}
187+
} catch {}
182188

183189
return '<error>';
184190
}

0 commit comments

Comments
 (0)