Skip to content
This repository has been archived by the owner on Jul 9, 2021. It is now read-only.

Commit

Permalink
[added] the logger module, the isomorphic wrapper for console.log
Browse files Browse the repository at this point in the history
… with ANSI 16 styles
  • Loading branch information
thealjey committed Jan 19, 2017
1 parent 8d12a47 commit bff7641
Show file tree
Hide file tree
Showing 15 changed files with 550 additions and 95 deletions.
3 changes: 2 additions & 1 deletion bin/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import {join} from 'path';
import {JS} from '../src/JS';
import {NativeProcess} from '../src/NativeProcess';
import {logError} from '../src/logger';
import noop from 'lodash/noop';

const rootDir = join(__dirname, '..'),
Expand All @@ -17,7 +18,7 @@ const rootDir = join(__dirname, '..'),
js.be(srcDir, libDir, [testDir, binDir, interfacesDir], () => {
npm.run(stderr => {
if (stderr) {
return console.error(stderr);
return logError(stderr);
}
npm.run(noop, ['test'], {stdio: 'inherit'});
}, ['run', 'docs-build'], {stdio: 'inherit'});
Expand Down
6 changes: 4 additions & 2 deletions bin/docs.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
/* @flow */

import {Documentation} from '../src/Documentation';
import {log, consoleStyles} from '../src/logger';
import {createReadStream, createWriteStream} from 'fs';
import {join} from 'path';

const rootDir = join(__dirname, '..'),
docsDir = join(rootDir, 'docs'),
docs = new Documentation();
docs = new Documentation(),
{green} = consoleStyles;

docs.run(() => {
createReadStream(join(rootDir, 'LICENSE')).pipe(createWriteStream(join(docsDir, 'LICENSE')));
createReadStream(join(rootDir, 'README.md')).pipe(createWriteStream(join(docsDir, 'README.md')));
console.log('\x1b[32mGenerated API documentation!\x1b[0m');
log(green('Generated API documentation!'));
});
15 changes: 8 additions & 7 deletions src/Compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import mkdirp from 'mkdirp';
import {dirname} from 'path';
import {writeFile, readFile} from 'fs';
import {gzip, gunzip} from 'zlib';
import {logError, log, consoleStyles} from './logger';

/* eslint-disable no-process-env */

const {green} = consoleStyles;

let i = 0;

/**
Expand Down Expand Up @@ -58,7 +61,7 @@ export class Compiler {
* Compiler.done('/path/to/an/input/file', callback);
*/
static done(inPath: string, callback: () => void) {
console.log('\x1b[32m%s. Compiled %s\x1b[0m', ++i, inPath);
log(green(++i, '. Compiled ', inPath));
callback();
}

Expand Down Expand Up @@ -102,14 +105,14 @@ export class Compiler {
Compiler.mkdir(path, () => {
writeFile(path, data.code, scriptErr => {
if (scriptErr) {
return console.error(scriptErr);
return logError(scriptErr);
}
if (!data.map) {
return callback();
}
writeFile(`${path}.map`, data.map, mapErr => {
if (mapErr) {
return console.error(mapErr);
return logError(mapErr);
}
callback();
});
Expand All @@ -131,7 +134,7 @@ export class Compiler {
static mkdir(path: string, callback: () => void) {
mkdirp(dirname(path), mkdirpErr => {
if (mkdirpErr) {
return console.error(mkdirpErr);
return logError(mkdirpErr);
}
callback();
});
Expand All @@ -154,10 +157,9 @@ export class Compiler {
return callback(data);
}

/* @flowignore */
gzip(data.code, (err, code) => {
if (err) {
return console.error(err);
return logError(err);
}
callback({code, map: data.map});
});
Expand Down Expand Up @@ -186,7 +188,6 @@ export class Compiler {
return callback({code: scriptData.toString('utf8'), map});
}

/* @flowignore */
gunzip(scriptData, (zipErr, zipData) => {
callback({code: zipErr ? '' : zipData.toString('utf8'), map});
});
Expand Down
6 changes: 4 additions & 2 deletions src/DevServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import type {DevServerConfig} from './typedef';
import {SASSCompiler} from './SASSCompiler';
import {logError, log, consoleStyles} from './logger';
import {watch} from './watch';
import tinylr from 'tiny-lr';
import WebpackDevServer from 'webpack-dev-server';
Expand All @@ -13,6 +14,7 @@ import serveStatic from 'serve-static';
const LIVERELOAD_PORT = 35729,
WEB_PORT = 3000,
cwd = process.cwd(),
{green} = consoleStyles,
defaultOptions = {
port: WEB_PORT,
react: true,
Expand Down Expand Up @@ -205,9 +207,9 @@ export class DevServer {

server.listen(port, '0.0.0.0', error => {
if (error) {
return console.error(error);
return logError(error);
}
console.log('\x1b[32mStarted the development server at localhost:%d\x1b[0m', port);
log(green('Started the development server at localhost:', port));
});
}

Expand Down
3 changes: 2 additions & 1 deletion src/Documentation.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {NativeProcess} from './NativeProcess';
import {stat} from 'fs';
import {join} from 'path';
import noop from 'lodash/noop';
import {logError} from './logger';

const npm = new NativeProcess('npm'),
cwd = process.cwd(),
Expand Down Expand Up @@ -172,7 +173,7 @@ export class Documentation {

jsdoc.run(stderr => {
if (stderr) {
return console.error(stderr);
return logError(stderr);
}
callback();
}, [inputDir, '-d', outputDir, '-R', readMe, '-c', jsdocConfig, '-t', template]);
Expand Down
20 changes: 8 additions & 12 deletions src/JS.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import {JSCompiler} from './JSCompiler';
import {NativeProcess} from './NativeProcess';
import {JSLint} from './JSLint';
import forEach from 'lodash/forEach';
import noop from 'lodash/noop';
import {logError, logLintingErrors} from './logger';

/**
* JavaScript compilation tools
Expand All @@ -22,6 +22,7 @@ import noop from 'lodash/noop';
* const js = new JS();
*/
export class JS {

/**
* JavaScript compiler
*
Expand Down Expand Up @@ -73,7 +74,7 @@ export class JS {
typecheck(callback: () => void) {
this.flow.run((flowErr, stdout) => {
if (flowErr) {
return console.error(flowErr);
return logError(flowErr);
}
if (!JSON.parse(stdout).passed) {
return this.flow.run(noop, [], {stdio: 'inherit'});
Expand All @@ -97,15 +98,10 @@ export class JS {
*/
lint(paths: Array<string>, callback: () => void) {
this.linter.run(paths, linterErr => {
if (!linterErr) {
return callback();
if (linterErr) {
return logLintingErrors(linterErr, 'JavaScript');
}
forEach(linterErr, e => {
console.log(
'\x1b[41mESLint error\x1b[0m "\x1b[33m%s%s\x1b[0m" in \x1b[36m%s\x1b[0m on \x1b[35m%s:%s\x1b[0m',
e.message, e.ruleId ? ` (${e.ruleId})` : '', e.filePath, e.line, e.column);
});
console.log('JavaScript linting errors: %s', linterErr.length);
callback();
});
}

Expand Down Expand Up @@ -142,7 +138,7 @@ export class JS {
* @param {Function} [callback=function () {}] - a callback function
* @return {void}
* @example
* compiler.be('/path/to/an/input/file.js', '/path/to/the/output/file.js', ['/lint/this/directory/too'], () => {
* compiler.be('/path/to/the/input/file.js', '/path/to/the/output/file.js', ['/lint/this/directory/too'], () => {
* // the code has passed all the checks and has been compiled successfully
* });
*/
Expand All @@ -164,7 +160,7 @@ export class JS {
* @param {Function} [callback=function () {}] - a callback function
* @return {void}
* @example
* compiler.fe('/path/to/an/input/file.js', '/path/to/the/output/file.js', ['/lint/this/directory/too'], () => {
* compiler.fe('/path/to/the/input/file.js', '/path/to/the/output/file.js', ['/lint/this/directory/too'], () => {
* // the code has passed all the checks and has been compiled successfully
* });
*/
Expand Down
20 changes: 12 additions & 8 deletions src/JSCompiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import get from 'lodash/get';
import isArray from 'lodash/isArray';
import uniq from 'lodash/uniq';
import map from 'lodash/map';
import {logError, log, consoleStyles} from './logger';

/* eslint-disable no-sync */
/* eslint-disable no-process-env */
Expand All @@ -28,6 +29,7 @@ const config = JSON.parse(readFileSync(join(__dirname, '..', '.babelrc'), 'utf8'
new DedupePlugin(),
new UglifyJsPlugin({compress: {warnings: false}})
];
const {yellow, red} = consoleStyles;

/**
* A JavaScript compiler
Expand Down Expand Up @@ -114,7 +116,7 @@ export class JSCompiler extends Compiler {
beDir(inPath: string, outPath: string, callback: () => void) {
readdir(inPath, (readdirErr, files) => {
if (readdirErr) {
return console.error(readdirErr);
return logError(readdirErr);
}
forEach(files, file => {
this.beTraverse(join(inPath, file), join(outPath, file), callback);
Expand All @@ -139,7 +141,7 @@ export class JSCompiler extends Compiler {
++this.processing;
transformFile(inPath, this.options, (transformFileErr, result) => {
if (transformFileErr) {
return console.error(transformFileErr);
return logError(transformFileErr);
}
Compiler.fsWrite(outPath, result, callback);
});
Expand Down Expand Up @@ -183,7 +185,7 @@ export class JSCompiler extends Compiler {
beTraverse(inPath: string, outPath: string, callback: () => void) {
stat(inPath, (statErr, stats) => {
if (statErr) {
return console.error(statErr);
return logError(statErr);
}
if (stats.isDirectory()) {
this.beDir(inPath, outPath, callback);
Expand All @@ -210,7 +212,7 @@ export class JSCompiler extends Compiler {
*/
be(inPath: string, outPath: string, callback: () => void = noop) {
if (this.processing) {
return console.error('Still working...');
return logError(new Error('Still working'));
}
this.beTraverse(inPath, outPath, () => {
--this.processing;
Expand Down Expand Up @@ -277,17 +279,19 @@ export class JSCompiler extends Compiler {

compiler.run((err, stats) => {
if (err) {
return console.error(err);
return logError(err);
}
const {warnings, errors} = stats.toJson();

forEach(warnings, warning => {
console.log('\x1b[33m%s\x1b[0m', warning);
log(yellow(warning));
});
if (errors.length) {
return forEach(errors, error => {
console.error(error);
forEach(errors, error => {
log(red(error));
});

return;
}
this.save(inPath, outPath, {
code: fakeFS.readFileSync(outPath, 'utf8'),
Expand Down
28 changes: 14 additions & 14 deletions src/JSLint.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* @flow */

import type {JSLintCallback} from './typedef';
import type {LintCallback} from './typedef';
import {CLIEngine} from 'eslint';
import {join} from 'path';
import forEach from 'lodash/forEach';
Expand All @@ -12,6 +12,7 @@ const configFile = join(__dirname, '..', '.eslintrc.yml');
*
* @class JSLint
* @param {Object} [rules={}] - an object that lets you override default linting rules
* @see {@link http://eslint.org/ ESLint}
* @example
* import {JSLint} from 'webcompiler';
* // or - import {JSLint} from 'webcompiler/lib/JSLint';
Expand All @@ -22,6 +23,7 @@ const configFile = join(__dirname, '..', '.eslintrc.yml');
* const linter = new JSLint();
*/
export class JSLint {

/**
* an internal linter instance
*
Expand All @@ -44,28 +46,26 @@ export class JSLint {
* @memberof JSLint
* @instance
* @method run
* @param {Array<string>} paths - an array of paths to files/directories to lint
* @param {JSLintCallback} callback - a callback function, accepts 1 argument: an array of error objects or null
* @param {Array<string>} paths - an array of paths to files/directories to lint
* @param {LintCallback} callback - a callback function
* @example
* import {logLintingErrors} from 'webcompiler';
*
* // lint "index.js" as well as the entire contents of the "src" directory
* linter.run([join(__dirname, 'index.js'), join(__dirname, 'src')], function (err) {
* if (err) {
* return e.forEach(e => {
* console.log('\x1b[41mESLint error\x1b[0m "\x1b[33m%s%s\x1b[0m" in \x1b[36m%s\x1b[0m on \x1b[35m%s:%s\x1b[0m',
* e.message, e.ruleId ? ` (${e.ruleId})` : '', e.filePath, e.line, e.column);
* });
* linter.run([join(__dirname, 'index.js'), join(__dirname, 'src')], errors => {
* if (errors) {
* return logLintingErrors(errors);
* }
* // there were no linting errors
* });
*/
run(paths: Array<string>, callback: JSLintCallback) {
run(paths: Array<string>, callback: LintCallback) {
const report = this.linter.executeOnFiles(paths),
errors = [];

forEach(report.results, f => {
forEach(f.messages, e => {
e.filePath = f.filePath;
errors.push(e);
forEach(report.results, ({messages, filePath: file}) => {
forEach(messages, ({line, column, message, ruleId: rule}) => {
errors.push({file, line, column, message, rule});
});
});
callback(errors.length ? errors : null);
Expand Down
9 changes: 6 additions & 3 deletions src/NativeProcess.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import noop from 'lodash/noop';
* const mkdir = new NativeProcess('mkdir');
*/
export class NativeProcess {

/**
* a process name
*
Expand Down Expand Up @@ -56,16 +57,18 @@ export class NativeProcess {
* @param {Object} [opts={}] - a configuration object for the process
* @return {void}
* @example
* import {logError} from 'webcompiler';
*
* mkdir.run(error => {
* if (error) {
* return console.error(error);
* return logError(error);
* }
* // created a directory named "example" in cwd
* }, ['example']);
*/
run(callback: NativeProcessCallback = noop, args: Array<string> = [], opts: Object = {}) {
if (this.proc) {
return callback('Still working...', '');
return callback(new Error('Still working'), '');
}
this.proc = spawn(this.task, args, opts);

Expand All @@ -86,7 +89,7 @@ export class NativeProcess {
});
this.proc.on('close', code => {
this.proc = null;
callback(code ? stderr : null, stdout);
callback(code ? new Error(stderr) : null, stdout);
});
}

Expand Down
Loading

0 comments on commit bff7641

Please sign in to comment.