Permalink
Browse files

Even more ES2015ification

  • Loading branch information...
1 parent 61cdd09 commit 1a9ddbe203af76e078380aa560d886ff4dcb33f7 @sindresorhus sindresorhus committed Jan 7, 2017
Showing with 632 additions and 680 deletions.
  1. +5 −5 cli.js
  2. +0 −1 lib/ava-error.js
  3. +1 −1 lib/beautify-stack.js
  4. +59 −71 lib/caching-precompiler.js
  5. +65 −65 lib/cli.js
  6. +59 −73 lib/logger.js
  7. +83 −84 lib/reporters/tap.js
  8. +246 −263 lib/watcher.js
  9. +0 −1 test/cli.js
  10. +63 −65 test/logger.js
  11. +51 −51 test/reporters/tap.js
View
@@ -1,12 +1,12 @@
#!/usr/bin/env node
'use strict';
-var path = require('path');
-var debug = require('debug')('ava');
+const path = require('path');
+const debug = require('debug')('ava');
// Prefer the local installation of AVA.
-var resolveCwd = require('resolve-cwd');
-var localCLI = resolveCwd('ava/cli');
+const resolveCwd = require('resolve-cwd');
+const localCLI = resolveCwd('ava/cli');
// Use path.relative() to detect local AVA installation,
// because __filename's case is inconsistent on Windows
@@ -22,7 +22,7 @@ if (localCLI && path.relative(localCLI, __filename) !== '') {
try {
require('./lib/cli').run();
} catch (err) {
- console.error('\n ' + err.message);
+ console.error(`\n ${err.message}`);
process.exit(1);
}
}
View
@@ -4,7 +4,6 @@ class AvaError extends Error {
constructor(message) {
super(message);
this.name = 'AvaError';
- this.message = message;
}
}
@@ -17,7 +17,7 @@ if (!debug.enabled) {
const stackUtils = new StackUtils({internals: ignoreStackLines});
-module.exports = function (stack) {
+module.exports = stack => {
if (!stack) {
return '';
}
@@ -9,83 +9,71 @@ const autoBind = require('auto-bind');
const md5Hex = require('md5-hex');
const babelConfigHelper = require('./babel-config');
-function CachingPrecompiler(options) {
- if (!(this instanceof CachingPrecompiler)) {
- throw new TypeError('Class constructor CachingPrecompiler cannot be invoked without \'new\'');
- }
-
- autoBind(this);
-
- options = options || {};
+class CachingPrecompiler {
+ constructor(options) {
+ autoBind(this);
- this.babelConfig = babelConfigHelper.validate(options.babel);
- this.cacheDirPath = options.path;
- this.powerAssert = Boolean(options.powerAssert);
- this.fileHashes = {};
- this.transform = this._createTransform();
-}
-
-module.exports = CachingPrecompiler;
+ options = options || {};
-CachingPrecompiler.prototype.precompileFile = function (filePath) {
- if (!this.fileHashes[filePath]) {
- const source = stripBomBuf(fs.readFileSync(filePath));
-
- this.transform(source, filePath);
+ this.babelConfig = babelConfigHelper.validate(options.babel);
+ this.cacheDirPath = options.path;
+ this.powerAssert = Boolean(options.powerAssert);
+ this.fileHashes = {};
+ this.transform = this._createTransform();
}
+ precompileFile(filePath) {
+ if (!this.fileHashes[filePath]) {
+ const source = stripBomBuf(fs.readFileSync(filePath));
+ this.transform(source, filePath);
+ }
- return this.fileHashes[filePath];
-};
-
-// Conditionally called by caching-transform when precompiling is required
-CachingPrecompiler.prototype._init = function () {
- this.babel = require('babel-core');
-
- return this._transform;
-};
-
-CachingPrecompiler.prototype._transform = function (code, filePath, hash) {
- code = code.toString();
-
- var options = babelConfigHelper.build(this.babelConfig, this.powerAssert, filePath, code);
- var result = this.babel.transform(code, options);
-
- // Save source map
- var mapPath = path.join(this.cacheDirPath, hash + '.js.map');
- fs.writeFileSync(mapPath, JSON.stringify(result.map));
-
- // Append source map comment to transformed code
- // So that other libraries (like nyc) can find the source map
- var dirPath = path.dirname(filePath);
- var relativeMapPath = path.relative(dirPath, mapPath);
- var comment = convertSourceMap.generateMapFileComment(relativeMapPath);
-
- return `${result.code}\n${comment}`;
-};
-
-CachingPrecompiler.prototype._createTransform = function () {
- const pluginPackages = babelConfigHelper.pluginPackages;
- const avaPackage = require.resolve('../package.json');
- const packages = [avaPackage].concat(pluginPackages);
+ return this.fileHashes[filePath];
+ }
+ // Conditionally called by caching-transform when precompiling is required
+ _init() {
+ this.babel = require('babel-core');
+ return this._transform;
+ }
+ _transform(code, filePath, hash) {
+ code = code.toString();
- const majorNodeVersion = process.version.split('.')[0];
- const babelConfig = JSON.stringify(this.babelConfig);
- const packageSalt = babelConfig + majorNodeVersion + this.powerAssert;
+ const options = babelConfigHelper.build(this.babelConfig, this.powerAssert, filePath, code);
+ const result = this.babel.transform(code, options);
- const salt = packageHash.sync(packages, packageSalt);
+ // Save source map
+ const mapPath = path.join(this.cacheDirPath, `${hash}.js.map`);
+ fs.writeFileSync(mapPath, JSON.stringify(result.map));
- return cachingTransform({
- factory: this._init,
- cacheDir: this.cacheDirPath,
- hash: this._generateHash,
- salt,
- ext: '.js'
- });
-};
+ // Append source map comment to transformed code
+ // So that other libraries (like nyc) can find the source map
+ const dirPath = path.dirname(filePath);
+ const relativeMapPath = path.relative(dirPath, mapPath);
+ const comment = convertSourceMap.generateMapFileComment(relativeMapPath);
-CachingPrecompiler.prototype._generateHash = function (code, filePath, salt) {
- const hash = md5Hex([code, filePath, salt]);
- this.fileHashes[filePath] = hash;
+ return `${result.code}\n${comment}`;
+ }
+ _createTransform() {
+ const pluginPackages = babelConfigHelper.pluginPackages;
+ const avaPackage = require.resolve('../package.json');
+ const packages = [avaPackage].concat(pluginPackages);
+ const majorNodeVersion = process.version.split('.')[0];
+ const babelConfig = JSON.stringify(this.babelConfig);
+ const packageSalt = babelConfig + majorNodeVersion + this.powerAssert;
+ const salt = packageHash.sync(packages, packageSalt);
+
+ return cachingTransform({
+ factory: this._init,
+ cacheDir: this.cacheDirPath,
+ hash: this._generateHash,
+ salt,
+ ext: '.js'
+ });
+ }
+ _generateHash(code, filePath, salt) {
+ const hash = md5Hex([code, filePath, salt]);
+ this.fileHashes[filePath] = hash;
+ return hash;
+ }
+}
- return hash;
-};
+module.exports = CachingPrecompiler;
View
@@ -1,61 +1,61 @@
'use strict';
-var path = require('path');
-var updateNotifier = require('update-notifier');
-var figures = require('figures');
-var arrify = require('arrify');
-var meow = require('meow');
-var Promise = require('bluebird');
-var pkgConf = require('pkg-conf');
-var isCi = require('is-ci');
-var hasFlag = require('has-flag');
-var Api = require('../api');
-var colors = require('./colors');
-var verboseReporter = require('./reporters/verbose');
-var miniReporter = require('./reporters/mini');
-var tapReporter = require('./reporters/tap');
-var Logger = require('./logger');
-var Watcher = require('./watcher');
-var babelConfig = require('./babel-config');
+const path = require('path');
+const updateNotifier = require('update-notifier');
+const figures = require('figures');
+const arrify = require('arrify');
+const meow = require('meow');
+const Promise = require('bluebird');
+const pkgConf = require('pkg-conf');
+const isCi = require('is-ci');
+const hasFlag = require('has-flag');
+const Api = require('../api');
+const colors = require('./colors');
+const verboseReporter = require('./reporters/verbose');
+const miniReporter = require('./reporters/mini');
+const tapReporter = require('./reporters/tap');
+const Logger = require('./logger');
+const Watcher = require('./watcher');
+const babelConfig = require('./babel-config');
// Bluebird specific
Promise.longStackTraces();
-exports.run = function () {
- var conf = pkgConf.sync('ava');
-
- var filepath = pkgConf.filepath(conf);
- var pkgDir = filepath === null ? process.cwd() : path.dirname(filepath);
-
- var cli = meow([
- 'Usage',
- ' ava [<file|directory|glob> ...]',
- '',
- 'Options',
- ' --init Add AVA to your project',
- ' --fail-fast Stop after first test failure',
- ' --serial, -s Run tests serially',
- ' --tap, -t Generate TAP output',
- ' --verbose, -v Enable verbose output',
- ' --no-cache Disable the transpiler cache',
- ' --no-power-assert Disable Power Assert',
- ' --match, -m Only run tests with matching title (Can be repeated)',
- ' --watch, -w Re-run tests when tests and source files change',
- ' --source, -S Pattern to match source files so tests can be re-run (Can be repeated)',
- ' --timeout, -T Set global timeout',
- ' --concurrency, -c Maximum number of test files running at the same time (EXPERIMENTAL)',
- ' --update-snapshots, -u Update snapshots',
- '',
- 'Examples',
- ' ava',
- ' ava test.js test2.js',
- ' ava test-*.js',
- ' ava test',
- ' ava --init',
- ' ava --init foo.js',
- '',
- 'Default patterns when no arguments:',
- 'test.js test-*.js test/**/*.js **/__tests__/**/*.js **/*.test.js'
- ], {
+exports.run = () => {
+ const conf = pkgConf.sync('ava');
+
+ const filepath = pkgConf.filepath(conf);
+ const pkgDir = filepath === null ? process.cwd() : path.dirname(filepath);
+
+ const cli = meow(`
+ Usage
+ ava [<file|directory|glob> ...]
+
+ Options
+ --init Add AVA to your project
+ --fail-fast Stop after first test failure
+ --serial, -s Run tests serially
+ --tap, -t Generate TAP output
+ --verbose, -v Enable verbose output
+ --no-cache Disable the transpiler cache
+ --no-power-assert Disable Power Assert
+ --match, -m Only run tests with matching title (Can be repeated)
+ --watch, -w Re-run tests when tests and source files change
+ --source, -S Pattern to match source files so tests can be re-run (Can be repeated)
+ --timeout, -T Set global timeout
+ --concurrency, -c Maximum number of test files running at the same time (EXPERIMENTAL)
+ --update-snapshots, -u Update snapshots
+
+ Examples
+ ava
+ ava test.js test2.js
+ ava test-*.js
+ ava test
+ ava --init
+ ava --init foo.js
+
+ Default patterns when no arguments:
+ test.js test-*.js test/**/*.js **/__tests__/**/*.js **/*.test.js'
+ `, {
string: [
'_',
'timeout',
@@ -103,7 +103,7 @@ exports.run = function () {
throw new Error(colors.error(figures.cross) + ' The --require and -r flags are deprecated. Requirements should be configured in package.json - see documentation.');
}
- var api = new Api({
+ const api = new Api({
failFast: cli.flags.failFast,
serial: cli.flags.serial,
require: arrify(conf.require),
@@ -113,13 +113,13 @@ exports.run = function () {
match: arrify(cli.flags.match),
babelConfig: babelConfig.validate(conf.babel),
resolveTestsFrom: cli.input.length === 0 ? pkgDir : process.cwd(),
- pkgDir: pkgDir,
+ pkgDir,
timeout: cli.flags.timeout,
concurrency: cli.flags.concurrency ? parseInt(cli.flags.concurrency, 10) : 0,
updateSnapshots: cli.flags.updateSnapshots
});
- var reporter;
+ let reporter;
if (cli.flags.tap && !cli.flags.watch) {
reporter = tapReporter();
@@ -130,11 +130,11 @@ exports.run = function () {
}
reporter.api = api;
- var logger = new Logger(reporter);
+ const logger = new Logger(reporter);
logger.start();
- api.on('test-run', function (runStatus) {
+ api.on('test-run', runStatus => {
reporter.api = runStatus;
runStatus.on('test', logger.test);
runStatus.on('error', logger.unhandledError);
@@ -143,32 +143,32 @@ exports.run = function () {
runStatus.on('stderr', logger.stderr);
});
- var files = cli.input.length ? cli.input : arrify(conf.files);
+ const files = cli.input.length ? cli.input : arrify(conf.files);
if (cli.flags.watch) {
try {
- var watcher = new Watcher(logger, api, files, arrify(cli.flags.source));
+ const watcher = new Watcher(logger, api, files, arrify(cli.flags.source));
watcher.observeStdin(process.stdin);
} catch (err) {
if (err.name === 'AvaError') {
// An AvaError may be thrown if chokidar is not installed. Log it nicely.
- console.error(' ' + colors.error(figures.cross) + ' ' + err.message);
+ console.error(` ${colors.error(figures.cross)} ${err.message}`);
logger.exit(1);
} else {
- // Rethrow so it becomes an uncaught exception.
+ // Rethrow so it becomes an uncaught exception
throw err;
}
}
} else {
api.run(files)
- .then(function (runStatus) {
+ .then(runStatus => {
logger.finish(runStatus);
logger.exit(runStatus.failCount > 0 || runStatus.rejectionCount > 0 || runStatus.exceptionCount > 0 ? 1 : 0);
})
- .catch(function (err) {
+ .catch(err => {
// Don't swallow exceptions. Note that any expected error should already
// have been logged.
- setImmediate(function () {
+ setImmediate(() => {
throw err;
});
});
Oops, something went wrong.

0 comments on commit 1a9ddbe

Please sign in to comment.