Skip to content

Commit

Permalink
refactor: replace chalk with nanocolors (#1685)
Browse files Browse the repository at this point in the history
  • Loading branch information
web-padawan authored Sep 24, 2021
1 parent d4f92e2 commit a09282b
Show file tree
Hide file tree
Showing 24 changed files with 104 additions and 109 deletions.
9 changes: 9 additions & 0 deletions .changeset/rare-lions-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@web/dev-server': patch
'@web/dev-server-core': patch
'@web/dev-server-rollup': patch
'@web/test-runner': patch
'@web/test-runner-core': patch
---

Replace chalk with nanocolors
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"husky": "^7.0.1",
"lint-staged": "^11.1.1",
"mocha": "^8.2.1",
"nanocolors": "^0.1.6",
"prettier": "^2.3.2",
"prettier-plugin-package": "^1.3.0",
"rimraf": "^3.0.2",
Expand Down
6 changes: 2 additions & 4 deletions packages/dev-server-core/src/test-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import portfinder from 'portfinder';
import { expect } from 'chai';
import chalk from 'chalk';
import { green, red, yellow } from 'nanocolors';
import fetch, { RequestInit } from 'node-fetch';

import { DevServer } from './server/DevServer';
Expand Down Expand Up @@ -66,9 +66,7 @@ export async function fetchText(url: string, init?: RequestInit) {

export function expectIncludes(text: string, expected: string) {
if (!text.includes(expected)) {
throw new Error(
chalk.red(`Expected "${chalk.yellow(expected)}" in string: \n\n${chalk.green(text)}`),
);
throw new Error(red(`Expected "${yellow(expected)}" in string: \n\n${green(text)}`));
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/dev-server-rollup/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
],
"dependencies": {
"@web/dev-server-core": "^0.3.3",
"chalk": "^4.1.0",
"nanocolors": "^0.1.6",
"parse5": "^6.0.1",
"rollup": "^2.56.2",
"whatwg-url": "^9.0.0"
Expand Down
6 changes: 3 additions & 3 deletions packages/dev-server-rollup/src/rollupAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import { parse as parseHtml, serialize as serializeHtml } from 'parse5';
import { CustomPluginOptions, Plugin as RollupPlugin, TransformPluginContext } from 'rollup';
import { InputOptions } from 'rollup';
import { red, cyanBright } from 'chalk';
import { red, cyan } from 'nanocolors';

import { toBrowserPath, isAbsoluteFilePath, isOutsideRootDir } from './utils';
import { createRollupPluginContextAdapter } from './createRollupPluginContextAdapter';
Expand Down Expand Up @@ -172,7 +172,7 @@ export function rollupAdapter(
!['/', './', '../'].some(prefix => resolvableImport.startsWith(prefix)) &&
adapterOptions.throwOnUnresolvedImport
) {
const errorMessage = red(`Could not resolve import ${cyanBright(`"${source}"`)}.`);
const errorMessage = red(`Could not resolve import ${cyan(`"${source}"`)}.`);
if (
typeof code === 'string' &&
typeof column === 'number' &&
Expand Down Expand Up @@ -222,7 +222,7 @@ export function rollupAdapter(
if (dirUpStrings.length === 0 || dirUpStrings.some(str => !['..', ''].includes(str))) {
// we expect the relative part to consist of only ../ or ..\\
const errorMessage =
red(`\n\nResolved ${cyanBright(source)} to ${cyanBright(resolvedImportPath)}.\n\n`) +
red(`\n\nResolved ${cyan(source)} to ${cyan(resolvedImportPath)}.\n\n`) +
red(
'This path could not be converted to a browser path. Please file an issue with a reproduction.',
);
Expand Down
2 changes: 1 addition & 1 deletion packages/dev-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@
"@web/dev-server-core": "^0.3.15",
"@web/dev-server-rollup": "^0.3.9",
"camelcase": "^6.2.0",
"chalk": "^4.1.0",
"command-line-args": "^5.1.1",
"command-line-usage": "^6.1.1",
"debounce": "^1.2.0",
"deepmerge": "^4.2.2",
"ip": "^1.1.5",
"nanocolors": "^0.1.6",
"open": "^8.0.2",
"portfinder": "^1.0.28"
},
Expand Down
6 changes: 2 additions & 4 deletions packages/dev-server/src/logger/DevServerLogger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Logger, PluginSyntaxError } from '@web/dev-server-core';
import { codeFrameColumns } from '@babel/code-frame';
import path from 'path';
import chalk from 'chalk';
import { red, cyan } from 'nanocolors';

export class DevServerLogger implements Logger {
private debugLogging: boolean;
Expand Down Expand Up @@ -48,9 +48,7 @@ export class DevServerLogger implements Logger {
const result = codeFrameColumns(code, { start: { line, column } }, { highlightCode: false });

const relativePath = path.relative(process.cwd(), filePath);
console.error(
chalk.red(`Error while transforming ${chalk.cyanBright(relativePath)}: ${message}\n`),
);
console.error(red(`Error while transforming ${cyan(relativePath)}: ${message}\n`));
console.error(highlightedResult);
console.error('');

Expand Down
14 changes: 5 additions & 9 deletions packages/dev-server/src/logger/logStartMessage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DevServerConfig } from '../config/DevServerConfig';
import { Logger } from '@web/dev-server-core';
import ip from 'ip';
import chalk from 'chalk';
import { bold, cyan, white } from 'nanocolors';

const createAddress = (config: DevServerConfig, host: string, path: string) =>
`http${config.http2 ? 's' : ''}://${host}:${config.port}${path}`;
Expand All @@ -10,9 +10,7 @@ function logNetworkAddress(config: DevServerConfig, logger: Logger, openPath: st
try {
const address = ip.address();
if (typeof address === 'string') {
logger.log(
`${chalk.white('Network:')} ${chalk.cyanBright(createAddress(config, address, openPath))}`,
);
logger.log(`${white('Network:')} ${cyan(createAddress(config, address, openPath))}`);
}
} catch {
//
Expand All @@ -26,14 +24,12 @@ export function logStartMessage(config: DevServerConfig, logger: Logger) {
openPath = `/${openPath}`;
}

logger.log(chalk.bold('Web Dev Server started...'));
logger.log(bold('Web Dev Server started...'));
logger.log('');

logger.group();
logger.log(`${chalk.white('Root dir:')} ${chalk.cyanBright(config.rootDir)}`);
logger.log(
`${chalk.white('Local:')} ${chalk.cyanBright(createAddress(config, prettyHost, openPath))}`,
);
logger.log(`${white('Root dir:')} ${cyan(config.rootDir)}`);
logger.log(`${white('Local:')} ${cyan(createAddress(config, prettyHost, openPath))}`);
logNetworkAddress(config, logger, openPath);
logger.groupEnd();
logger.log('');
Expand Down
2 changes: 1 addition & 1 deletion packages/test-runner-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
"@types/istanbul-reports": "^3.0.0",
"@web/browser-logs": "^0.2.1",
"@web/dev-server-core": "^0.3.12",
"chalk": "^4.1.0",
"chokidar": "^3.4.3",
"cli-cursor": "^3.1.0",
"co-body": "^6.1.0",
Expand All @@ -72,6 +71,7 @@
"istanbul-lib-report": "^3.0.0",
"istanbul-reports": "^3.0.2",
"log-update": "^4.0.0",
"nanocolors": "^0.1.6",
"nanoid": "^3.1.25",
"open": "^8.0.2",
"picomatch": "^2.2.2",
Expand Down
10 changes: 4 additions & 6 deletions packages/test-runner-core/src/cli/TestRunnerCli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { codeFrameColumns } from '@babel/code-frame';
import path from 'path';
import chalk from 'chalk';
import { bold, cyan, red } from 'nanocolors';
import openBrowser from 'open';

import { writeCoverageReport } from './writeCoverageReport';
Expand Down Expand Up @@ -85,7 +85,7 @@ export class TestRunnerCli {
}

if (this.config.staticLogging || !this.terminal.isInteractive) {
this.logger.log(chalk.bold(`Running ${this.runner.testFiles.length} test files...\n`));
this.logger.log(bold(`Running ${this.runner.testFiles.length} test files...\n`));
}

if (this.config.open) {
Expand Down Expand Up @@ -316,7 +316,7 @@ export class TestRunnerCli {
if (this.config.watch) {
if (this.runner.focusedTestFile) {
reports.push(
`Focused on test file: ${chalk.cyanBright(
`Focused on test file: ${cyan(
path.relative(process.cwd(), this.runner.focusedTestFile),
)}\n`,
);
Expand Down Expand Up @@ -359,9 +359,7 @@ export class TestRunnerCli {
const { message, code, line, column } = error;
const result = codeFrameColumns(code, { start: { line, column } }, { highlightCode: true });
const relativePath = path.relative(process.cwd(), filePath);
report.push(
chalk.red(`Error while transforming ${chalk.cyanBright(relativePath)}: ${message}`),
);
report.push(red(`Error while transforming ${cyan(relativePath)}: ${message}`));
report.push(result);
report.push('');
}
Expand Down
10 changes: 5 additions & 5 deletions packages/test-runner-core/src/cli/getManualDebugMenu.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import chalk from 'chalk';
import { cyan, gray } from 'nanocolors';
import ip from 'ip';

import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig';
Expand All @@ -13,10 +13,10 @@ export function getManualDebugMenu(config: TestRunnerCoreConfig): string[] {
"Advanced functionalities such commands for changing viewport and screenshots don't work there.",
'Use the regular debug option to debug in a controlled browser.',
' ',
`Local address: ${chalk.cyanBright(localAddress)}`,
`Network address: ${chalk.cyanBright(networkAddress)}`,
`Local address: ${cyan(localAddress)}`,
`Network address: ${cyan(networkAddress)}`,
' ',
`${chalk.gray('Press')} D ${chalk.gray('to open the browser.')}`,
`${chalk.gray('Press')} ${config.manual ? 'Q' : 'ESC'} ${chalk.gray('to exit manual debug.')}`,
`${gray('Press')} D ${gray('to open the browser.')}`,
`${gray('Press')} ${config.manual ? 'Q' : 'ESC'} ${gray('to exit manual debug.')}`,
].filter(_ => !!_);
}
9 changes: 5 additions & 4 deletions packages/test-runner-core/src/cli/getSelectFilesMenu.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import chalk from 'chalk';
import { cyan, red } from 'nanocolors';
import { relative } from 'path';

export function getSelectFilesMenu(succeededFiles: string[], failedFiles: string[]) {
const maxI = succeededFiles.length + failedFiles.length;
const minWidth = maxI.toString().length + 1;

function formatTestFile(file: string, i: number, offset: number, failed: boolean) {
return `[${i + offset}]${' '.repeat(
Math.max(0, minWidth - (i + offset).toString().length),
)}${chalk[failed ? 'red' : 'cyan'](relative(process.cwd(), file))}`;
const relativePath = relative(process.cwd(), file);
return `[${i + offset}]${' '.repeat(Math.max(0, minWidth - (i + offset).toString().length))}${
failed ? red(relativePath) : cyan(relativePath)
}`;
}

const entries: string[] = [
Expand Down
28 changes: 13 additions & 15 deletions packages/test-runner-core/src/cli/getWatchCommands.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import chalk from 'chalk';
import { gray } from 'nanocolors';

export function getWatchCommands(
coverage: boolean,
Expand All @@ -7,23 +7,21 @@ export function getWatchCommands(
): string[] {
if (focusedTest) {
return [
`${chalk.gray('Press')} F ${chalk.gray('to focus another test file.')}`,
`${chalk.gray('Press')} D ${chalk.gray('to debug in the browser.')}`,
coverage ? `${chalk.gray('Press')} C ${chalk.gray('to view coverage details.')}` : '',
`${chalk.gray('Press')} Q ${chalk.gray('to exit watch mode.')}`,
`${chalk.gray('Press')} Enter ${chalk.gray('to re-run this test file.')}`,
`${chalk.gray('Press')} ESC ${chalk.gray('to exit focus mode')}`,
`${gray('Press')} F ${gray('to focus another test file.')}`,
`${gray('Press')} D ${gray('to debug in the browser.')}`,
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
`${gray('Press')} Q ${gray('to exit watch mode.')}`,
`${gray('Press')} Enter ${gray('to re-run this test file.')}`,
`${gray('Press')} ESC ${gray('to exit focus mode')}`,
].filter(_ => !!_);
}

return [
testFiles.length > 1
? `${chalk.gray('Press')} F ${chalk.gray('to focus on a test file.')}`
: '',
`${chalk.gray('Press')} D ${chalk.gray('to debug in the browser.')}`,
`${chalk.gray('Press')} M ${chalk.gray('to debug manually in a custom browser.')}`,
coverage ? `${chalk.gray('Press')} C ${chalk.gray('to view coverage details.')}` : '',
`${chalk.gray('Press')} Q ${chalk.gray('to quit watch mode.')}`,
`${chalk.gray('Press')} Enter ${chalk.gray('to re-run all tests.')}`,
testFiles.length > 1 ? `${gray('Press')} F ${gray('to focus on a test file.')}` : '',
`${gray('Press')} D ${gray('to debug in the browser.')}`,
`${gray('Press')} M ${gray('to debug manually in a custom browser.')}`,
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
`${gray('Press')} Q ${gray('to quit watch mode.')}`,
`${gray('Press')} Enter ${gray('to re-run all tests.')}`,
].filter(_ => !!_);
}
2 changes: 1 addition & 1 deletion packages/test-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@
"@web/test-runner-core": "^0.10.20",
"@web/test-runner-mocha": "^0.7.4",
"camelcase": "^6.2.0",
"chalk": "^4.1.0",
"command-line-args": "^5.1.1",
"command-line-usage": "^6.1.1",
"convert-source-map": "^1.7.0",
"diff": "^5.0.0",
"globby": "^11.0.1",
"nanocolors": "^0.1.6",
"portfinder": "^1.0.28",
"source-map": "^0.7.3"
},
Expand Down
17 changes: 7 additions & 10 deletions packages/test-runner/src/reporter/getCodeCoverage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CoverageThresholdConfig, TestCoverage, CoverageConfig } from '@web/test-runner-core';
import path from 'path';
import chalk from 'chalk';
import { bold, green, red, underline } from 'nanocolors';

const coverageTypes: (keyof CoverageThresholdConfig)[] = [
'lines',
Expand All @@ -20,28 +20,25 @@ export function getCodeCoverage(
const avgCoverage = Math.round((coverageSum * 100) / 4) / 100;

if (!Number.isNaN(avgCoverage)) {
entries.push(
`Code coverage: ${chalk.bold(
chalk[testCoverage.passed ? 'green' : 'red'](`${avgCoverage} %`),
)}`,
);
const percent = `${avgCoverage} %`;
entries.push(`Code coverage: ${bold(testCoverage.passed ? green(percent) : red(percent))}`);
}

if (!testCoverage.passed && coverageConfig.threshold) {
coverageTypes.forEach(type => {
if (testCoverage.summary[type].pct < coverageConfig.threshold![type]) {
entries.push(
`Coverage for ${chalk.bold(type)} failed with ${chalk.bold(
chalk.red(`${testCoverage.summary[type].pct} %`),
)} compared to configured ${chalk.bold(`${coverageConfig.threshold![type]} %`)}`,
`Coverage for ${bold(type)} failed with ${bold(
red(`${testCoverage.summary[type].pct} %`),
)} compared to configured ${bold(`${coverageConfig.threshold![type]} %`)}`,
);
}
});
}

if (!watch && coverageConfig.report && coverageConfig.reporters?.includes('lcov')) {
entries.push(
`View full coverage report at ${chalk.underline(
`View full coverage report at ${underline(
path.join(coverageConfig.reportDir ?? '', 'lcov-report', 'index.html'),
)}`,
);
Expand Down
Loading

0 comments on commit a09282b

Please sign in to comment.