Skip to content

Commit

Permalink
refactor: use ansi-colors instead of removed terminal utils
Browse files Browse the repository at this point in the history
  • Loading branch information
alan-agius4 committed Sep 10, 2020
1 parent 6d43e32 commit 622d084
Show file tree
Hide file tree
Showing 21 changed files with 149 additions and 76 deletions.
12 changes: 6 additions & 6 deletions bin/devkit-admin
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ process.chdir(path.join(__dirname, '..'));
let logger = null;
try {
logger = new (require('@angular-devkit/core').logging.IndentLogger)('root');
const { bold, gray, red, yellow, white } = require('@angular-devkit/core').terminal;
const colors = require('ansi-colors').create();
const filter = require('rxjs/operators').filter;

logger
.pipe(filter(entry => (entry.level !== 'debug' || args.verbose)))
.subscribe(entry => {
let color = gray;
let color = colors.gray;
let output = process.stdout;
switch (entry.level) {
case 'info': color = white; break;
case 'warn': color = yellow; break;
case 'error': color = red; output = process.stderr; break;
case 'fatal': color = x => bold(red(x)); output = process.stderr; break;
case 'info': color = colors.white; break;
case 'warn': color = colors.yellow; break;
case 'error': color = colors.red; output = process.stderr; break;
case 'fatal': color = x => colors.bold.red(x); output = process.stderr; break;
}

output.write(color(entry.message) + '\n');
Expand Down
12 changes: 6 additions & 6 deletions packages/angular/cli/lib/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { createConsoleLogger } from '@angular-devkit/core/node';
import { format } from 'util';
import { runCommand } from '../../models/command-runner';
import { colors, removeColor, supportsColor } from '../../utilities/color';
import { colors, removeColor } from '../../utilities/color';
import { getWorkspaceRaw } from '../../utilities/config';
import { writeErrorToLogFile } from '../../utilities/log-file';
import { getWorkspaceDetails } from '../../utilities/project';
Expand Down Expand Up @@ -49,11 +49,11 @@ export default async function(options: { testing?: boolean; cliArgs: string[] })
}

const logger = createConsoleLogger(isDebug, process.stdout, process.stderr, {
info: s => (supportsColor ? s : removeColor(s)),
debug: s => (supportsColor ? s : removeColor(s)),
warn: s => (supportsColor ? colors.bold.yellow(s) : removeColor(s)),
error: s => (supportsColor ? colors.bold.red(s) : removeColor(s)),
fatal: s => (supportsColor ? colors.bold.red(s) : removeColor(s)),
info: s => (colors.enabled ? s : removeColor(s)),
debug: s => (colors.enabled ? s : removeColor(s)),
warn: s => (colors.enabled ? colors.bold.yellow(s) : removeColor(s)),
error: s => (colors.enabled ? colors.bold.red(s) : removeColor(s)),
fatal: s => (colors.enabled ? colors.bold.red(s) : removeColor(s)),
});

// Redirect console to logger
Expand Down
14 changes: 9 additions & 5 deletions packages/angular/cli/utilities/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@
import * as ansiColors from 'ansi-colors';
import { WriteStream } from 'tty';

type AnsiColors = typeof ansiColors;

// Typings do not contain the function call (added in Node.js v9.9.0)
export const supportsColor =
const supportsColor =
process.stdout instanceof WriteStream &&
((process.stdout as unknown) as { getColorDepth(): number }).getColorDepth() > 1;

export function removeColor(text: string): string {
return text.replace(new RegExp(ansiColors.ansiRegex), '');
// This has been created because when colors.enabled is false unstyle doesn't work
// see: https://github.com/doowb/ansi-colors/blob/a4794363369d7b4d1872d248fc43a12761640d8e/index.js#L38
return text.replace(ansiColors.ansiRegex, '');
}

// create a separate instance to prevent unintended global changes to the color configuration
// create function is not defined in the typings
const colors = (ansiColors as typeof ansiColors & { create: () => typeof ansiColors }).create();
// Create a separate instance to prevent unintended global changes to the color configuration
// Create function is not defined in the typings. See: https://github.com/doowb/ansi-colors/pull/44
const colors = (ansiColors as AnsiColors & { create: () => AnsiColors }).create();
colors.enabled = supportsColor;

export { colors };
1 change: 1 addition & 0 deletions packages/angular_devkit/architect_cli/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ ts_library(
"@npm//@types/minimist",
"@npm//@types/node",
"@npm//@types/progress",
"@npm//ansi-colors",
"@npm//rxjs",
],
)
21 changes: 16 additions & 5 deletions packages/angular_devkit/architect_cli/bin/architect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
*/
import { Architect, BuilderInfo, BuilderProgressState, Target } from '@angular-devkit/architect';
import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node';
import { logging, schema, tags, terminal, workspaces } from '@angular-devkit/core';
import { logging, schema, tags, workspaces } from '@angular-devkit/core';
import { NodeJsSyncHost, createConsoleLogger } from '@angular-devkit/core/node';
import * as ansiColors from 'ansi-colors';
import { existsSync } from 'fs';
import * as minimist from 'minimist';
import * as path from 'path';
Expand Down Expand Up @@ -68,6 +69,10 @@ interface BarInfo {
target?: Target;
}
// Create a separate instance to prevent unintended global changes to the color configuration
// Create function is not defined in the typings. See: https://github.com/doowb/ansi-colors/pull/44
const colors = (ansiColors as typeof ansiColors & { create: () => typeof ansiColors }).create();
async function _executeTarget(
parentLogger: logging.Logger,
workspace: workspaces.WorkspaceDefinition,
Expand Down Expand Up @@ -139,9 +144,9 @@ async function _executeTarget(
.pipe(
tap(result => {
if (result.success) {
parentLogger.info(terminal.green('SUCCESS'));
parentLogger.info(colors.green('SUCCESS'));
} else {
parentLogger.info(terminal.yellow('FAILURE'));
parentLogger.info(colors.red('FAILURE'));
}
parentLogger.info('Result: ' + JSON.stringify({ ...result, info: undefined }, null, 4));
Expand All @@ -157,7 +162,7 @@ async function _executeTarget(
return success ? 0 : 1;
} catch (err) {
parentLogger.info(terminal.red('ERROR'));
parentLogger.info(colors.red('ERROR'));
parentLogger.info('\nLogs:');
logs.forEach(l => parentLogger.next(l));
Expand All @@ -173,7 +178,13 @@ async function main(args: string[]): Promise<number> {
const argv = minimist(args, { boolean: ['help'] });
/** Create the DevKit Logger used through the CLI. */
const logger = createConsoleLogger(argv['verbose']);
const logger = createConsoleLogger(argv['verbose'], process.stdout, process.stderr, {
info: s => s,
debug: s => s,
warn: s => colors.bold.yellow(s),
error: s => colors.bold.red(s),
fatal: s => colors.bold.red(s),
});
// Check the target.
const targetStr = argv._[0] || '';
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/architect_cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dependencies": {
"@angular-devkit/architect": "0.0.0",
"@angular-devkit/core": "0.0.0",
"ansi-colors": "4.1.1",
"minimist": "1.2.5",
"progress": "2.0.3",
"rxjs": "6.6.3",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/benchmark/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ ts_library(
"@npm//@types/minimist",
"@npm//@types/node",
"@npm//@types/pidusage",
"@npm//ansi-colors",
"@npm//rxjs",
],
)
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/benchmark/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
},
"dependencies": {
"@angular-devkit/core": "0.0.0",
"ansi-colors": "4.1.1",
"minimist": "1.2.5",
"pidusage": "2.0.21",
"pidtree": "0.5.0",
Expand Down
15 changes: 10 additions & 5 deletions packages/angular_devkit/benchmark/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
* found in the LICENSE file at https://angular.io/license
*/

import { logging, tags, terminal } from '@angular-devkit/core';
import { logging, tags } from '@angular-devkit/core';
import { ProcessOutput } from '@angular-devkit/core/node';
import * as ansiColors from 'ansi-colors';
import { appendFileSync, writeFileSync } from 'fs';
import * as minimist from 'minimist';
import { filter, map, toArray } from 'rxjs/operators';
Expand Down Expand Up @@ -102,26 +103,30 @@ export async function main({
})),
);

// Create a separate instance to prevent unintended global changes to the color configuration
// Create function is not defined in the typings. See: https://github.com/doowb/ansi-colors/pull/44
const colors = (ansiColors as typeof ansiColors & { create: () => typeof ansiColors }).create();

// Log to console.
logger
.pipe(filter(entry => (entry.level != 'debug' || argv['verbose'])))
.subscribe(entry => {
let color: (s: string) => string = x => terminal.dim(terminal.white(x));
let color: (s: string) => string = x => colors.dim.white(x);
let output = stdout;
switch (entry.level) {
case 'info':
color = s => s;
break;
case 'warn':
color = terminal.yellow;
color = colors.yellow;
output = stderr;
break;
case 'error':
color = terminal.red;
color = colors.red;
output = stderr;
break;
case 'fatal':
color = (x: string) => terminal.bold(terminal.red(x));
color = (x: string) => colors.bold.red(x);
output = stderr;
break;
}
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ ts_library(
"@npm//@types/webpack-dev-server",
"@npm//@types/webpack-sources",
"@npm//ajv",
"@npm//ansi-colors",
"@npm//autoprefixer",
"@npm//babel-loader",
"@npm//browserslist",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@babel/template": "7.10.4",
"@jsdevtools/coverage-istanbul-loader": "3.0.5",
"@ngtools/webpack": "0.0.0",
"ansi-colors": "4.1.1",
"autoprefixer": "9.8.6",
"babel-loader": "8.1.0",
"browserslist": "^4.9.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
*/
// tslint:disable
// TODO: cleanup this file, it's copied as is from Angular CLI.
import { logging, tags, terminal } from '@angular-devkit/core';
import { logging, tags } from '@angular-devkit/core';
import { WebpackLoggingCallback } from '@angular-devkit/build-webpack';
import * as path from 'path';


const { bold, green, red, reset, white, yellow } = terminal;
import { colors as ansiColors } from '../../utils/color';

export function formatSize(size: number): string {
if (size <= 0) {
Expand All @@ -37,8 +35,8 @@ export function generateBundleStats(
},
colors: boolean,
): string {
const g = (x: string) => (colors ? bold(green(x)) : x);
const y = (x: string) => (colors ? bold(yellow(x)) : x);
const g = (x: string) => (colors ? ansiColors.bold.green(x) : x);
const y = (x: string) => (colors ? ansiColors.bold.yellow(x) : x);

const id = info.id ? y(info.id.toString()) : '';
const size = typeof info.size === 'number' ? ` ${formatSize(info.size)}` : '';
Expand All @@ -53,14 +51,14 @@ export function generateBundleStats(
}

export function generateBuildStats(hash: string, time: number, colors: boolean): string {
const w = (x: string) => colors ? bold(white(x)) : x;
const w = (x: string) => colors ? ansiColors.bold.white(x) : x;
return `Date: ${w(new Date().toISOString())} - Hash: ${w(hash)} - Time: ${w('' + time)}ms`
}

export function statsToString(json: any, statsConfig: any) {
const colors = statsConfig.colors;
const rs = (x: string) => colors ? reset(x) : x;
const w = (x: string) => colors ? bold(white(x)) : x;
const rs = (x: string) => colors ? ansiColors.reset(x) : x;
const w = (x: string) => colors ? ansiColors.bold.white(x) : x;

const changedChunksStats = json.chunks
.filter((chunk: any) => chunk.rendered)
Expand Down Expand Up @@ -97,8 +95,8 @@ const ERRONEOUS_WARNINGS_FILTER = (warning: string) => ![

export function statsWarningsToString(json: any, statsConfig: any): string {
const colors = statsConfig.colors;
const rs = (x: string) => colors ? reset(x) : x;
const y = (x: string) => colors ? bold(yellow(x)) : x;
const rs = (x: string) => colors ? ansiColors.reset(x) : x;
const y = (x: string) => colors ? ansiColors.bold.yellow(x) : x;
const warnings = [...json.warnings];
if (json.children) {
warnings.push(...json.children
Expand All @@ -116,8 +114,8 @@ export function statsWarningsToString(json: any, statsConfig: any): string {

export function statsErrorsToString(json: any, statsConfig: any): string {
const colors = statsConfig.colors;
const rs = (x: string) => colors ? reset(x) : x;
const r = (x: string) => colors ? bold(red(x)) : x;
const rs = (x: string) => colors ? ansiColors.reset(x) : x;
const r = (x: string) => colors ? ansiColors.bold.red(x) : x;
const errors = [...json.errors];
if (json.children) {
errors.push(...json.children
Expand Down
29 changes: 29 additions & 0 deletions packages/angular_devkit/build_angular/src/utils/color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @license
* Copyright Google Inc. 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 * as ansiColors from 'ansi-colors';
import { WriteStream } from 'tty';

type AnsiColors = typeof ansiColors;

// Typings do not contain the function call (added in Node.js v9.9.0)
const supportsColor =
process.stdout instanceof WriteStream &&
((process.stdout as unknown) as { getColorDepth(): number }).getColorDepth() > 1;

export function removeColor(text: string): string {
// This has been created because when colors.enabled is false unstyle doesn't work
// see: https://github.com/doowb/ansi-colors/blob/a4794363369d7b4d1872d248fc43a12761640d8e/index.js#L38
return text.replace(ansiColors.ansiRegex, '');
}

// Create a separate instance to prevent unintended global changes to the color configuration
// Create function is not defined in the typings. See: https://github.com/doowb/ansi-colors/pull/44
const colors = (ansiColors as AnsiColors & { create: () => AnsiColors }).create();
colors.enabled = supportsColor;

export { colors };
13 changes: 4 additions & 9 deletions packages/angular_devkit/core/node/cli-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import { filter } from 'rxjs/operators';
import { logging, terminal } from '../src';
import { logging } from '../src';

export interface ProcessOutput {
write(buffer: string | Buffer): boolean;
Expand All @@ -24,20 +24,15 @@ export function createConsoleLogger(
const logger = new logging.IndentLogger('cling');

logger
.pipe(filter(entry => (entry.level != 'debug' || verbose)))
.pipe(filter(entry => entry.level !== 'debug' || verbose))
.subscribe(entry => {
let color = colors && colors[entry.level];
const color = colors && colors[entry.level];
let output = stdout;

switch (entry.level) {
case 'info':
break;
case 'warn':
color = color || (s => terminal.bold(terminal.yellow(s)));
output = stderr;
break;
case 'fatal':
case 'error':
color = color || (s => terminal.bold(terminal.red(s)));
output = stderr;
break;
}
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/core/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 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 * as experimental from './experimental/jobs/job-registry';
import * as fs from './fs';
export * from './cli-logger';
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/schematics_cli/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ ts_library(
"@npm//@types/inquirer",
"@npm//@types/minimist",
"@npm//@types/node",
"@npm//ansi-colors",
"@npm//inquirer", # @external
"@npm//minimist", # @external
"@npm//rxjs",
Expand Down
Loading

0 comments on commit 622d084

Please sign in to comment.