Skip to content

Commit

Permalink
Deprecate colors.js module in favour of chalk.js (#3852)
Browse files Browse the repository at this point in the history
  • Loading branch information
garg3133 authored Aug 17, 2023
1 parent 1c54cab commit 0c796df
Show file tree
Hide file tree
Showing 14 changed files with 166 additions and 232 deletions.
2 changes: 1 addition & 1 deletion lib/http/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ class HttpRequest extends EventEmitter {
});
}

const content = ` Request ${Logger.colors.light_cyan([this.reqOptions.method, this.hostname + this.reqOptions.path, retryStr + ' '].join(' '))}`;
const content = ` Request ${[this.reqOptions.method, this.hostname + this.reqOptions.path, retryStr + ' '].join(' ')}`;
const paramsStr = this.redact ? '<REDACTED>' : params;

Logger.request(content, paramsStr);
Expand Down
12 changes: 6 additions & 6 deletions lib/reporter/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class Reporter extends SimplifiedReporter {
get currentTest() {
return this.testResults.currentTest;
}

get currentSection() {
return this.testResults.currentSection;
}
Expand Down Expand Up @@ -209,8 +209,8 @@ class Reporter extends SimplifiedReporter {
stack,
beautifiedStack
};
}
}

if (this.shouldLogCommand(node)) {
this.testResults.logCommand({
name: node.fullName,
Expand Down Expand Up @@ -240,7 +240,7 @@ class Reporter extends SimplifiedReporter {
if (!node.parent) { //root node
return false;
}

if (node.parent.isRootNode) {
return true;
}
Expand Down Expand Up @@ -330,7 +330,7 @@ class Reporter extends SimplifiedReporter {
const result = [colors[ok ? 'green': 'red'](Utils.symbols[ok ? 'ok' : 'fail'])];
if (!this.unitTestsMode) {
if (isWorker) {
result.push(colors.white(this.settings.testEnv, colors.background.black));
result.push(colors.bgBlack.white.bold(this.settings.testEnv));
}

result.push(colors.cyan('[' + this.suiteName + ']'));
Expand All @@ -340,7 +340,7 @@ class Reporter extends SimplifiedReporter {
result.push(ok ? testName : colors.red(testName));

if (elapsedTime > 20) {
result.push(colors.yellow('(' + Utils.formatElapsedTime(elapsedTime, true) + ')'));
result.push(colors.yellow.bold('(' + Utils.formatElapsedTime(elapsedTime, true) + ')'));
}

// eslint-disable-next-line no-console
Expand Down
6 changes: 3 additions & 3 deletions lib/runner/concurrency/child-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class ChildProcess extends EventEmitter {

setLabel(label) {
this.env_itemKey = label;
this.env_label = this.settings.disable_colors ? ` ${label} ` : Logger.colors.yellow(` ${label} `, Logger.colors.background.black);
this.env_label = this.settings.disable_colors ? ` ${label} ` : Logger.colors.bgBlack.yellow.bold(` ${label} `);

return this;
}
Expand Down Expand Up @@ -97,7 +97,7 @@ class ChildProcess extends EventEmitter {
childProcessLabel = ' ' + this.environment + ' ';
} else {
childProcessLabel = '';
this.env_label = Logger.colors[color_pair[1]](` ${this.environment} `, Logger.colors.background[color_pair[0]]);
this.env_label = Logger.colors[color_pair[0]][color_pair[1]](` ${this.environment} `);
}

const lines = data.split('\n').map(line => {
Expand Down Expand Up @@ -150,7 +150,7 @@ class ChildProcess extends EventEmitter {

const color_pair = this.availColors[this.index%4];

this.printLog(' Running: ' + Logger.colors[color_pair[1]](` ${this.env_itemKey} `, Logger.colors.background[color_pair[0]]));
this.printLog(' Running: ' + Logger.colors[color_pair[0]][color_pair[1]](` ${this.env_itemKey} `));

this.child.stdout.on('data', data => {
this.writeToStdout(data);
Expand Down
34 changes: 17 additions & 17 deletions lib/runner/concurrency/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ class Concurrency extends EventEmitter {
createChildProcess(label, args = [], extraArgs = [], index = 0) {
this.childProcessOutput[label] = [];
const childArgs = args.slice().concat(extraArgs);

const childProcess = new ChildProcess(label, index, this.childProcessOutput[label], this.settings, childArgs);
childProcess.on('message', data => {
this.emit('message', data);
});

return childProcess;
}

Expand Down Expand Up @@ -84,7 +84,7 @@ class Concurrency extends EventEmitter {
runChildProcesses(envs, modules) {
const availColors = Concurrency.getAvailableColors();
const args = Concurrency.getChildProcessArgs(envs);

if (this.testWorkersEnabled) {
const jobs = [];
if (envs.length > 0) {
Expand All @@ -106,10 +106,10 @@ class Concurrency extends EventEmitter {
});
jobs.push(...jobList);
}

return this.runMultipleTestProcess(jobs, args, availColors);
}

return this.runProcessTestEnvironment(envs, args, availColors);
}

Expand Down Expand Up @@ -220,7 +220,7 @@ class Concurrency extends EventEmitter {
Promise.allSettled(workerPool.tasks)
.then(values => {
values.some(({status}) => status === 'rejected') ? reject() : resolve();
});
});
});
}

Expand Down Expand Up @@ -287,7 +287,7 @@ class Concurrency extends EventEmitter {
modules.forEach(({module, env}) => {
let outputLabel = Utils.getModuleKey(module, this.settings.src_folders, modules);
outputLabel = env ? `${env}: ${outputLabel}` : outputLabel;

const workerArgv = {...this.argv};
workerArgv._source = [module];
workerArgv.env = env;
Expand All @@ -301,21 +301,21 @@ class Concurrency extends EventEmitter {
});
});


return new Promise((resolve, reject) => {
Promise.allSettled(workerPool.tasks)
.then(values => {
values.some(({status}) => status === 'rejected') ? reject() : resolve();
});
});
});
}


/**
*
* @param {Array} args
* @param {Object} settings
* @param {Number} maxWorkerCount
*
* @param {Array} args
* @param {Object} settings
* @param {Number} maxWorkerCount
*/
setupWorkerPool(args, settings, maxWorkerCount) {
const workerPool = new WorkerPool(args, settings, maxWorkerCount);
Expand Down Expand Up @@ -407,10 +407,10 @@ class Concurrency extends EventEmitter {

static getAvailableColors() {
const availColorPairs = [
['red', 'light_gray'],
['green', 'black'],
['blue', 'light_gray'],
['magenta', 'light_gray']
['bgRed', 'white'],
['bgGreen', 'black'],
['bgBlue', 'white'],
['bgMagenta', 'white']
];
let currentIndex = availColorPairs.length;
let temporaryValue;
Expand Down
12 changes: 6 additions & 6 deletions lib/runner/concurrency/worker-task.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ class WorkerTask extends EventEmitter {
}

setlabel(colorPair) {
this.task_label = this.settings.disable_colors ? ` ${this.label} ` : Logger.colors[colorPair[1]](` ${this.label} `, Logger.colors.background[colorPair[0]]);
this.task_label = this.settings.disable_colors ? ` ${this.label} ` : Logger.colors[colorPair[0]][colorPair[1]](` ${this.label} `);
}

writeToStdOut(data) {
let output = '';

if (WorkerTask.prevIndex !== this.index) {
WorkerTask.prevIndex = this.index;
WorkerTask.prevIndex = this.index;
if (this.settings.live_output) {
output += '\n';
}
Expand All @@ -68,9 +68,9 @@ class WorkerTask extends EventEmitter {
this.availColors = colors;
const colorPair = this.availColors[this.index%4];
this.setlabel(colorPair);
this.printLog('Running '+ Logger.colors[colorPair[1]](` ${this.task_label} `, Logger.colors.background[colorPair[0]]));

this.printLog('Running '+ Logger.colors[colorPair[0]][colorPair[1]](` ${this.task_label} `));

const {port1, port2} = new MessageChannel();
port2.onmessage = ({data: result}) => {
if (isString(result)) {
Expand All @@ -86,7 +86,7 @@ class WorkerTask extends EventEmitter {
this.emit('message', result);
break;

case 'stdout':
case 'stdout':
this.writeToStdOut(result.data);
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class BaseService {
let binaryMissing = `${this.serviceName} cannot be found in the current project.`;

if (this.npmPackageName) {
binaryMissing += '\n\n ' + Logger.colors.yellow(`You can either install ${this.npmPackageName} from NPM with: \n\n npm install ${this.npmPackageName} --save-dev\n\n`) + ' or ';
binaryMissing += '\n\n ' + Logger.colors.yellow.bold(`You can either install ${this.npmPackageName} from NPM with: \n\n npm install ${this.npmPackageName} --save-dev\n\n`) + ' or ';
} else {
binaryMissing += '\n\n Please ';
}
Expand All @@ -51,7 +51,7 @@ class BaseService {
}

get errorOutput() {
let errorOut = this.error_out.split('\n');
const errorOut = this.error_out.split('\n');

return errorOut.reduce(function(prev, message) {
if (prev.indexOf(message) < 0) {
Expand Down Expand Up @@ -148,7 +148,7 @@ class BaseService {
this.processExited = true;

if (code > 0) {
let err = this.createError(null, code);
const err = this.createError(null, code);
err.detailedErr = this.error_out || this.output;
}
}
Expand Down Expand Up @@ -182,7 +182,7 @@ class BaseService {
message = this.createErrorMessage(code);
}

let err = new Error(message);
const err = new Error(message);
err.code = code;
err.errorOut = this.errorOutput;

Expand Down Expand Up @@ -308,7 +308,7 @@ class BaseService {
this.process.kill();
} catch (err) {
Logger.error(err);

return Promise.reject(err);
}
}
Expand All @@ -324,7 +324,7 @@ class BaseService {
}

getLogPath() {
let {log_path = 'logs'} = this.settings.webdriver;
const {log_path = 'logs'} = this.settings.webdriver;
if (log_path === false) {
return null;
}
Expand Down
14 changes: 7 additions & 7 deletions lib/utils/beautifyStackTrace.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ const stackTraceParser = require('stacktrace-parser');
const AssertionError = require('assertion-error');
const {filterStackTrace} = require('./stackTrace.js');
const alwaysDisplayError = require('./alwaysDisplayError.js');
const {colors} = require('./colors.js');
const {colors} = require('./chalkColors.js');

/**
* Read the User file from the stackTrace and create a string with highlighting the line with error
* @param {Error} err
*/
*/
function beautifyStackTrace(err, errStackPassed = false, modulepath, cli = true) {
if ((err instanceof AssertionError) || alwaysDisplayError(err) || errStackPassed) {
try {
Expand All @@ -20,7 +20,7 @@ function beautifyStackTrace(err, errStackPassed = false, modulepath, cli = true)
if (!parsedStack) {
parsedStack = parsedStacks[0];
}

const file = fs.readFileSync(parsedStack.file, 'utf-8');
const errorLinesofFile = file.split(/\r?\n/);

Expand All @@ -32,11 +32,11 @@ function beautifyStackTrace(err, errStackPassed = false, modulepath, cli = true)
const desiredLines = formattedStack.codeSnippet.reduce(function(lines, newLine) {
const currentLine = newLine.line_number;
if (currentLine === formattedStack.error_line_number) {
lines += '\n ' + colors.light_gray(` ${currentLine} | ${newLine.code} `, colors.background.red);
lines += '\n ' + colors.bgRed.white(` ${currentLine} | ${newLine.code} `);
} else if (currentLine <= (formattedStack.error_line_number + 2) && currentLine >= (formattedStack.error_line_number - 2)) {
lines += `\n ${currentLine} | ${newLine.code}`;
}

return lines;
}, '');

Expand All @@ -54,7 +54,7 @@ function beautifyStackTrace(err, errStackPassed = false, modulepath, cli = true)
/**
* Read the User file from the stackTrace and create a string with highlighting the line with error
* @param {Error} err
*/
*/
function formatStackTrace(errorLinesofFile, parsedStack) {

const result = {
Expand All @@ -74,7 +74,7 @@ function formatStackTrace(errorLinesofFile, parsedStack) {


return result;

}

module.exports = beautifyStackTrace;
Expand Down
54 changes: 54 additions & 0 deletions lib/utils/chalkColors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const chalk = require('chalk');

class ChalkColors {
constructor() {
this.instance = new chalk.Instance();
this.origLevel = this.instance.level;

this.loadCustomColors(); // for backward compatibility

if (process.env.COLORS === '0') {
this.disable();
}
}

loadCustomColors() {
const colorsInstance = this.instance;

// foreground colors
colorsInstance.dark_gray = colorsInstance.black.bold;
colorsInstance.light_blue = colorsInstance.blue.bold;
colorsInstance.light_green = colorsInstance.green.bold;
colorsInstance.light_cyan = colorsInstance.cyan.bold;
colorsInstance.light_red = colorsInstance.red.bold;
colorsInstance.light_purple = colorsInstance.magenta.bold;
colorsInstance.light_gray = colorsInstance.white;

colorsInstance.purple = colorsInstance.magenta;
colorsInstance.brown = colorsInstance.yellow;
colorsInstance.stack_trace = colorsInstance.gray;
}

get colors() {
return this.instance;
}

get colorsEnabled() {
return this.instance.level !== 0;
}

disable() {
this.prevLevel = this.instance.level;
this.instance.level = 0;
}

enable() {
this.instance.level = this.prevLevel;
}

reset() {
this.instance.level = this.origLevel;
}
}

module.exports = new ChalkColors();
Loading

0 comments on commit 0c796df

Please sign in to comment.