Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace chalk with smaller and faster ansis #2845

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions actions/add.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import { Input } from '../commands';
import { getValueOrDefault } from '../lib/compiler/helpers/get-value-or-default';
import {
Expand Down Expand Up @@ -40,7 +40,7 @@ export class AddAction extends AbstractAction {
await this.addLibrary(collectionName, options, extraFlags);
} else {
console.error(
chalk.red(
red(
MESSAGES.LIBRARY_INSTALLATION_FAILED_BAD_PACKAGE(libraryName),
),
);
Expand Down Expand Up @@ -109,7 +109,7 @@ export class AddAction extends AbstractAction {
installResult = await manager.addProduction([collectionName], tagName);
} catch (error) {
if (error && error.message) {
console.error(chalk.red(error.message));
console.error(red(error.message));
}
}
return installResult;
Expand Down Expand Up @@ -140,7 +140,7 @@ export class AddAction extends AbstractAction {
);
} catch (error) {
if (error && error.message) {
console.error(chalk.red(error.message));
console.error(red(error.message));
return Promise.reject();
}
}
Expand Down
4 changes: 2 additions & 2 deletions actions/build.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import { join } from 'path';
import * as ts from 'typescript';
import { Input } from '../commands';
Expand Down Expand Up @@ -60,7 +60,7 @@ export class BuildAction extends AbstractAction {
if (err instanceof Error) {
console.log(`\n${ERROR_PREFIX} ${err.message}\n`);
} else {
console.error(`\n${chalk.red(err)}\n`);
console.error(`\n${red(err)}\n`);
}
process.exit(1);
}
Expand Down
4 changes: 2 additions & 2 deletions actions/generate.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import * as path from 'path';
import { Input } from '../commands';
import { getValueOrDefault } from '../lib/compiler/helpers/get-value-or-default';
Expand Down Expand Up @@ -143,7 +143,7 @@ const generateFiles = async (inputs: Input[]) => {
await collection.execute(schematicInput.value as string, schematicOptions);
} catch (error) {
if (error && error.message) {
console.error(chalk.red(error.message));
console.error(red(error.message));
}
}
};
Expand Down
30 changes: 15 additions & 15 deletions actions/info.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { blue, bold, green, red, yellow } from 'ansis';
import { readFileSync } from 'fs';
import { platform, release } from 'os';
import { join } from 'path';
Expand Down Expand Up @@ -50,16 +50,16 @@ export class InfoAction extends AbstractAction {
}

private displayBanner() {
console.info(chalk.red(BANNER));
console.info(red(BANNER));
}

private async displaySystemInformation(): Promise<void> {
console.info(chalk.green('[System Information]'));
console.info(green`[System Information]`);
console.info(
'OS Version :',
chalk.blue(osName(platform(), release()), release()),
blue(osName(platform(), release()) + release()),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ansis method accepts only one argument as a string, therefore we need to concatenate two stings into one

);
console.info('NodeJS Version :', chalk.blue(process.version));
console.info('NodeJS Version :', blue(process.version));
await this.displayPackageManagerVersion();
}

Expand All @@ -68,21 +68,21 @@ export class InfoAction extends AbstractAction {
const version: string = await this.manager.version();
console.info(
`${this.manager.name} Version :`,
chalk.blue(version),
blue(version),
'\n',
);
} catch {
console.error(
`${this.manager.name} Version :`,
chalk.red('Unknown'),
red`Unknown`,
'\n',
);
}
}

async displayNestInformation(): Promise<void> {
this.displayCliVersion();
console.info(chalk.green('[Nest Platform Information]'));
console.info(green`[Nest Platform Information`);
await this.displayNestInformationFromPackage();
}

Expand All @@ -93,16 +93,16 @@ export class InfoAction extends AbstractAction {
this.displayNestVersions(dependencies);
} catch (err) {
console.error(
chalk.red(MESSAGES.NEST_INFORMATION_PACKAGE_MANAGER_FAILED),
red(MESSAGES.NEST_INFORMATION_PACKAGE_MANAGER_FAILED),
);
}
}

displayCliVersion(): void {
console.info(chalk.green('[Nest CLI]'));
console.info(green`[Nest CLI]`);
console.info(
'Nest CLI Version :',
chalk.blue(
blue(
JSON.parse(readFileSync(join(__dirname, '../package.json')).toString())
.version,
),
Expand All @@ -125,7 +125,7 @@ export class InfoAction extends AbstractAction {
displayNestVersions(dependencies: PackageJsonDependencies) {
const nestDependencies = this.buildNestVersionsMessage(dependencies);
nestDependencies.forEach((dependency) =>
console.info(dependency.name, chalk.blue(dependency.value)),
console.info(dependency.name, blue(dependency.value)),
);

this.displayWarningMessage(nestDependencies);
Expand All @@ -137,13 +137,13 @@ export class InfoAction extends AbstractAction {
const majorVersions = Object.keys(warnings);
if (majorVersions.length > 0) {
console.info('\r');
console.info(chalk.yellow('[Warnings]'));
console.info(yellow`[Warnings]`);
console.info(
'The following packages are not in the same major version',
);
console.info('This could lead to runtime errors');
majorVersions.forEach((version) => {
console.info(chalk.bold(`* Under version ${version}`));
console.info(bold`* Under version ${version}`);
warnings[version].forEach(({ packageName, value }) => {
console.info(`- ${packageName} ${value}`);
});
Expand All @@ -152,7 +152,7 @@ export class InfoAction extends AbstractAction {
} catch {
console.info('\t');
console.error(
chalk.red(
red(
MESSAGES.NEST_INFORMATION_PACKAGE_WARNING_FAILED(
this.warningMessageDependenciesWhiteList,
),
Expand Down
12 changes: 6 additions & 6 deletions actions/new.action.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { input, select } from '@inquirer/prompts';
import * as chalk from 'chalk';
import * as ansis from 'ansis';
import { execSync } from 'child_process';
import * as fs from 'fs';
import { Answers } from 'inquirer';
Expand Down Expand Up @@ -151,7 +151,7 @@ const installPackages = async (
let packageManager: AbstractPackageManager;
if (dryRunMode) {
console.info();
console.info(chalk.green(MESSAGES.DRY_RUN_MODE));
console.info(ansis.green(MESSAGES.DRY_RUN_MODE));
console.info();
return;
}
Expand All @@ -160,7 +160,7 @@ const installPackages = async (
await packageManager.install(installDirectory, inputPackageManager);
} catch (error) {
if (error && error.message) {
console.error(chalk.red(error.message));
console.error(ansis.red(error.message));
}
}
};
Expand All @@ -176,7 +176,7 @@ const askForPackageManager = async () => {
const initializeGitRepository = async (dir: string) => {
const runner = new GitRunner();
await runner.run('init', true, join(process.cwd(), dir)).catch(() => {
console.error(chalk.red(MESSAGES.GIT_INITIALIZATION_ERROR));
console.error(ansis.red(MESSAGES.GIT_INITIALIZATION_ERROR));
});
};

Expand Down Expand Up @@ -212,7 +212,7 @@ const printCollective = () => {
emptyLine();
emptyLine();
print()(
`${chalk.bold(`${EMOJIS.WINE} Donate:`)} ${chalk.underline(
`${ansis.bold`${EMOJIS.WINE} Donate:`} ${ansis.underline(
'https://opencollective.com/nest',
)}`,
);
Expand All @@ -227,7 +227,7 @@ const print =
const leftPaddingLength = Math.floor((terminalCols - strLength) / 2);
const leftPadding = ' '.repeat(Math.max(leftPaddingLength, 0));
if (color) {
str = (chalk as any)[color](str);
str = (ansis as any)[color](str);
}
console.log(leftPadding, str);
};
Expand Down
4 changes: 2 additions & 2 deletions actions/start.action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import { spawn } from 'child_process';
import * as fs from 'fs';
import { join } from 'path';
Expand Down Expand Up @@ -107,7 +107,7 @@ export class StartAction extends BuildAction {
if (err instanceof Error) {
console.log(`\n${ERROR_PREFIX} ${err.message}\n`);
} else {
console.error(`\n${chalk.red(err)}\n`);
console.error(`\n${red(err)}\n`);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions commands/command.loader.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import { CommanderStatic } from 'commander';
import {
AddAction,
Expand Down Expand Up @@ -30,11 +30,11 @@ export class CommandLoader {
private static handleInvalidCommand(program: CommanderStatic) {
program.on('command:*', () => {
console.error(
`\n${ERROR_PREFIX} Invalid command: ${chalk.red('%s')}`,
`\n${ERROR_PREFIX} Invalid command: ${red`%s`}`,
program.args.join(' '),
);
console.log(
`See ${chalk.red('--help')} for a list of available commands.\n`,
`See ${red`--help`} for a list of available commands.\n`,
);
process.exit(1);
});
Expand Down
8 changes: 4 additions & 4 deletions commands/generate.command.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { bold, cyan, green } from 'ansis';
import * as Table from 'cli-table3';
import { Command, CommanderStatic } from 'commander';
import { AbstractCollection, CollectionFactory } from '../lib/schematics';
Expand Down Expand Up @@ -107,7 +107,7 @@ export class GenerateCommand extends AbstractCommand {
const collection = await this.getCollection();
return (
'Generate a Nest element.\n' +
` Schematics available on ${chalk.bold(collection)} collection:\n` +
` Schematics available on ${bold(collection)} collection:\n` +
this.buildSchematicsListAsTable(await this.getSchematics(collection))
);
}
Expand All @@ -129,8 +129,8 @@ export class GenerateCommand extends AbstractCommand {
const table: any = new Table(tableConfig);
for (const schematic of schematics) {
table.push([
chalk.green(schematic.name),
chalk.cyan(schematic.alias),
green(schematic.name),
cyan(schematic.alias),
schematic.description,
]);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/compiler/helpers/manual-restart.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { gray } from 'ansis';

export function listenForManualRestart(callback: () => void) {
const stdinListener = (data: Buffer) => {
Expand All @@ -11,5 +11,5 @@ export function listenForManualRestart(callback: () => void) {
}

export function displayManualRestartTip(): void {
console.log(`To restart at any time, enter ${chalk.gray('rs')}.\n`);
console.log(`To restart at any time, enter ${gray`rs`}.\n`);
}
18 changes: 8 additions & 10 deletions lib/compiler/swc/constants.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import * as chalk from 'chalk';
import { bgCyan, bgGreen, bgRed, cyan, green, red } from 'ansis';

export const TSC_NO_ERRORS_MESSAGE =
'Found 0 errors. Watching for file changes.';

export const TSC_COMPILATION_STARTED_MESSAGE =
'Starting compilation in watch mode...';

export const SWC_LOG_PREFIX = chalk.cyan('> ') + chalk.bgCyan.bold(' SWC ');
export const SWC_LOG_PREFIX = cyan('> ') + bgCyan.bold(' SWC ');

export const TSC_LOG_PREFIX = chalk.cyan('> ') + chalk.bgCyan.bold(' TSC ');
export const TSC_LOG_ERROR_PREFIX = chalk.red('> ') + chalk.bgRed.bold(' TSC ');
export const TSC_LOG_SUCCESS_PREFIX =
chalk.green('> ') + chalk.bgGreen.bold(' TSC ');
export const TSC_LOG_PREFIX = cyan('> ') + bgCyan.bold(' TSC ');
export const TSC_LOG_ERROR_PREFIX = red('> ') + bgRed.bold(' TSC ');
export const TSC_LOG_SUCCESS_PREFIX = green('> ') + bgGreen.bold(' TSC ');

export const INITIALIZING_TYPE_CHECKER =
chalk.bgCyan.bold(' TSC ') + chalk.cyan(' Initializing type checker...');
bgCyan.bold(' TSC ') + cyan(' Initializing type checker...');

export const FOUND_NO_ISSUES_METADATA_GENERATION_SKIPPED =
TSC_LOG_SUCCESS_PREFIX + chalk.green(' Found 0 issues.');
TSC_LOG_SUCCESS_PREFIX + green(' Found 0 issues.');

export const FOUND_NO_ISSUES_GENERATING_METADATA =
TSC_LOG_SUCCESS_PREFIX +
chalk.green(' Found 0 issues. Generating metadata...');
TSC_LOG_SUCCESS_PREFIX + green(' Found 0 issues. Generating metadata...');
4 changes: 2 additions & 2 deletions lib/compiler/swc/swc-compiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { cyan } from 'ansis';
import { fork } from 'child_process';
import * as chokidar from 'chokidar';
import { readFileSync } from 'fs';
Expand Down Expand Up @@ -156,7 +156,7 @@ export class SwcCompiler extends BaseCompiler {
swcrcFilePath?: string,
) {
process.nextTick(() =>
console.log(SWC_LOG_PREFIX, chalk.cyan('Running...')),
console.log(SWC_LOG_PREFIX, cyan('Running...')),
);

const swcCli = this.loadSwcCliBinary();
Expand Down
4 changes: 2 additions & 2 deletions lib/compiler/swc/type-checker-host.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { red } from 'ansis';
import * as ora from 'ora';
import * as ts from 'typescript';
import { TsConfigProvider } from '../helpers/tsconfig-provider';
Expand Down Expand Up @@ -63,7 +63,7 @@ export class TypeCheckerHost {
const reportWatchStatusCallback = (diagnostic: ts.Diagnostic) => {
if (diagnostic.messageText !== TSC_NO_ERRORS_MESSAGE) {
if ((diagnostic.messageText as string)?.includes('Found')) {
console.log(TSC_LOG_ERROR_PREFIX, chalk.red(diagnostic.messageText));
console.log(TSC_LOG_ERROR_PREFIX, red(diagnostic.messageText.toString()));
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ansis method accepts the string or number argument, but diagnostic.messageText is string | ts.DiagnosticMessageChain, therefore we need it to convert into string

}
return;
}
Expand Down
10 changes: 5 additions & 5 deletions lib/package-managers/abstract.package-manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as chalk from 'chalk';
import { bold, gray, red } from 'ansis';
import { readFile } from 'fs';
import * as ora from 'ora';
import { join } from 'path';
Expand Down Expand Up @@ -34,17 +34,17 @@ export abstract class AbstractPackageManager {
console.info(MESSAGES.PACKAGE_MANAGER_INSTALLATION_SUCCEED(directory));
console.info(MESSAGES.GET_STARTED_INFORMATION);
console.info();
console.info(chalk.gray(MESSAGES.CHANGE_DIR_COMMAND(directory)));
console.info(chalk.gray(MESSAGES.START_COMMAND(packageManager)));
console.info(gray(MESSAGES.CHANGE_DIR_COMMAND(directory)));
console.info(gray(MESSAGES.START_COMMAND(packageManager)));
console.info();
} catch {
spinner.fail();
const commandArgs = this.cli.install;
const commandToRun = this.runner.rawFullCommand(commandArgs);
console.error(
chalk.red(
red(
MESSAGES.PACKAGE_MANAGER_INSTALLATION_FAILED(
chalk.bold(commandToRun),
bold(commandToRun),
),
),
);
Expand Down
Loading