Skip to content

Commit

Permalink
chore(all): Migrate to ES6 (#385)
Browse files Browse the repository at this point in the history
* Convert InMemoryReport to the ES6 class

* Use default params for reporters and coverageReporter

* Remove lodash usages and dependencies

* Replace all vars on const vs let in preprocessor
  • Loading branch information
anthony-redFox authored and johnjbarton committed Oct 1, 2019
1 parent 9c8a222 commit d3f53e3
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 101 deletions.
33 changes: 17 additions & 16 deletions lib/in-memory-report.js
@@ -1,25 +1,26 @@
function InMemoryReport (opt) {
this.opt = opt
}
class InMemoryReport {
constructor (opt) {
this.opt = opt
}

InMemoryReport.prototype.onStart = function (root, context) {
this.data = {}
}
onStart () {
this.data = {}
}

InMemoryReport.prototype.onDetail = function (node) {
const fc = node.getFileCoverage()
const key = fc.path
this.data[key] = fc.toJSON()
}
onDetail (node) {
const fc = node.getFileCoverage()
const key = fc.path
this.data[key] = fc.toJSON()
}

InMemoryReport.prototype.onEnd = function () {
if (!this.opt.emitter || !this.opt.emitter.emit) {
console.error('Could not raise "coverage_complete" event, missing emitter because it was not supplied during initialization of the reporter')
} else {
onEnd () {
if (!this.opt || !this.opt.emitter || !this.opt.emitter.emit) {
console.error('Could not raise "coverage_complete" event, missing emitter because it was not supplied during initialization of the reporter')
return
}
this.opt.emitter.emit('coverage_complete', this.opt.browser, this.data)
}
}

InMemoryReport.TYPE = 'in-memory'

module.exports = InMemoryReport
103 changes: 47 additions & 56 deletions lib/preprocessor.js
Expand Up @@ -6,23 +6,21 @@
// Dependencies
// ------------

var { createInstrumenter } = require('istanbul-lib-instrument')
var minimatch = require('minimatch')
var path = require('path')
var _ = require('lodash')
var SourceMapConsumer = require('source-map').SourceMapConsumer
var SourceMapGenerator = require('source-map').SourceMapGenerator
var globalSourceMapStore = require('./source-map-store')
var globalCoverageMap = require('./coverage-map')
const { createInstrumenter } = require('istanbul-lib-instrument')
const minimatch = require('minimatch')
const path = require('path')
const { SourceMapConsumer, SourceMapGenerator } = require('source-map')
const globalSourceMapStore = require('./source-map-store')
const globalCoverageMap = require('./coverage-map')

// Regexes
// -------

var coverageObjRegex = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g
const coverageObjRegex = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g

// Preprocessor creator function
function createCoveragePreprocessor (logger, helper, basePath, reporters, coverageReporter) {
var log = logger.create('preprocessor.coverage')
function createCoveragePreprocessor (logger, basePath, reporters = [], coverageReporter = {}) {
const log = logger.create('preprocessor.coverage')

// Options
// -------
Expand All @@ -48,7 +46,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
return new Obj.Instrumenter(opts)
}
}
if (!_.isFunction(Obj)) {
if (typeof Obj !== 'function') {
// Object doesn't have old instrumenter variable and isn't a
// constructor, so we can't use it to create an instrumenter
return null
Expand All @@ -61,54 +59,49 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
return Obj
}

var instrumenterOverrides = {}
var instrumenters = { istanbul: createInstrumenter }
var includeAllSources = false
var useJSExtensionForCoffeeScript = false

if (coverageReporter) {
instrumenterOverrides = coverageReporter.instrumenter
_.forEach(coverageReporter.instrumenters, function (instrumenter, literal) {
var creatorFunction = getCreatorFunction(instrumenter)
if (creatorFunction) {
instrumenters[literal] = creatorFunction
}
})
includeAllSources = coverageReporter.includeAllSources === true
useJSExtensionForCoffeeScript = coverageReporter.useJSExtensionForCoffeeScript === true
}
const instrumenters = { istanbul: createInstrumenter }
const instrumenterOverrides = coverageReporter.instrumenter || {}
const { includeAllSources = false, useJSExtensionForCoffeeScript = false } = coverageReporter

Object.entries(coverageReporter.instrumenters || {}).forEach(([literal, instrumenter]) => {
const creatorFunction = getCreatorFunction(instrumenter)
if (creatorFunction) {
instrumenters[literal] = creatorFunction
}
})

var sourceMapStore = globalSourceMapStore.get(basePath)
const sourceMapStore = globalSourceMapStore.get(basePath)

var instrumentersOptions = _.reduce(instrumenters, function getInstrumenterOptions (memo, instrument, name) {
memo[name] = {}
const instrumentersOptions = Object.keys(instrumenters).reduce((memo, key) => {
memo[key] = {}

if (coverageReporter && coverageReporter.instrumenterOptions) {
memo[name] = coverageReporter.instrumenterOptions[name]
if (coverageReporter.instrumenterOptions) {
memo[key] = coverageReporter.instrumenterOptions[key]
}

return memo
}, {})

// if coverage reporter is not used, do not preprocess the files
if (!_.includes(reporters, 'coverage')) {
if (!reporters.includes('coverage')) {
return function (content, _, done) {
done(content)
}
}

// check instrumenter override requests
function checkInstrumenters () {
return _.reduce(instrumenterOverrides, function (acc, literal, pattern) {
if (!_.includes(_.keys(instrumenters), String(literal))) {
const keys = Object.keys(instrumenters)
return Object.values(instrumenterOverrides).some(literal => {
const notIncluded = !keys.includes(String(literal))
if (notIncluded) {
log.error('Unknown instrumenter: %s', literal)
return false
}
return acc
}, true)
return notIncluded
})
}

if (!checkInstrumenters()) {
if (checkInstrumenters()) {
return function (content, _, done) {
return done(1)
}
Expand All @@ -117,20 +110,19 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
return function (content, file, done) {
log.debug('Processing "%s".', file.originalPath)

var jsPath = path.resolve(file.originalPath)
// default instrumenters
var instrumenterLiteral = 'istanbul'

_.forEach(instrumenterOverrides, function (literal, pattern) {
const jsPath = path.resolve(file.originalPath)
// 'istanbul' is default instrumenters
const instrumenterLiteral = Object.keys(instrumenterOverrides).reduce((res, pattern) => {
if (minimatch(file.originalPath, pattern, { dot: true })) {
instrumenterLiteral = String(literal)
return instrumenterOverrides[pattern]
}
})
return res
}, 'istanbul')

var instrumenterCreator = instrumenters[instrumenterLiteral]
var constructOptions = instrumentersOptions[instrumenterLiteral] || {}
var options = Object.assign({}, constructOptions)
var codeGenerationOptions = null
const instrumenterCreator = instrumenters[instrumenterLiteral]
const constructOptions = instrumentersOptions[instrumenterLiteral] || {}
let options = Object.assign({}, constructOptions)
let codeGenerationOptions = null
options.autoWrap = options.autoWrap || !options.noAutoWrap

if (file.sourceMap) {
Expand All @@ -148,15 +140,15 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera

options = Object.assign({}, options, { codeGenerationOptions: codeGenerationOptions })

var instrumenter = instrumenterCreator(options)
const instrumenter = instrumenterCreator(options)
instrumenter.instrument(content, jsPath, function (err, instrumentedCode) {
if (err) {
log.error('%s\n at %s', err.message, file.originalPath)
done(err.message)
} else {
if (file.sourceMap && instrumenter.lastSourceMap()) {
log.debug('Adding source map to instrumented file for "%s".', file.originalPath)
var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
const generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
generator.applySourceMap(new SourceMapConsumer(file.sourceMap))
file.sourceMap = JSON.parse(generator.toString())
instrumentedCode += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,'
Expand All @@ -167,7 +159,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
sourceMapStore.registerMap(jsPath, file.sourceMap)

if (includeAllSources) {
var coverageObj
let coverageObj
// Check if the file coverage object is exposed from the instrumenter directly
if (instrumenter.lastFileCoverage) {
coverageObj = instrumenter.lastFileCoverage()
Expand All @@ -177,7 +169,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera

// reset stateful regex
coverageObjRegex.lastIndex = 0
var coverageObjMatch = coverageObjRegex.exec(instrumentedCode)
const coverageObjMatch = coverageObjRegex.exec(instrumentedCode)
if (coverageObjMatch !== null) {
coverageObj = JSON.parse(coverageObjMatch[0])
globalCoverageMap.add(coverageObj)
Expand All @@ -198,7 +190,6 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera

createCoveragePreprocessor.$inject = [
'logger',
'helper',
'config.basePath',
'config.reporters',
'config.coverageReporter'
Expand Down
6 changes: 2 additions & 4 deletions lib/reporter.js
Expand Up @@ -14,7 +14,6 @@ var path = require('path')
var istanbulLibCoverage = require('istanbul-lib-coverage')
var istanbulLibReport = require('istanbul-lib-report')
var minimatch = require('minimatch')
var _ = require('lodash')

var globalSourceMapStore = require('./source-map-store')
var globalCoverageMap = require('./coverage-map')
Expand Down Expand Up @@ -180,7 +179,7 @@ var CoverageReporter = function (rootConfig, helper, logger, emitter) {
dir = dir || 'coverage'
subdir = subdir || browserName

if (_.isFunction(subdir)) {
if (typeof subdir === 'function') {
subdir = subdir(browserName)
}

Expand Down Expand Up @@ -266,9 +265,8 @@ var CoverageReporter = function (rootConfig, helper, logger, emitter) {

// // If reporting to console or in-memory skip directory creation
var toDisk = !reporterConfig.type || !reporterConfig.type.match(/^(text|text-summary|in-memory)$/)
var hasNoFile = _.isUndefined(reporterConfig.file)

if (!toDisk && hasNoFile) {
if (!toDisk && reporterConfig.file === undefined) {
tree.visit(report, context)
return
}
Expand Down
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -24,7 +24,6 @@
"istanbul-lib-report": "^2.0.8",
"istanbul-lib-source-maps": "^3.0.6",
"istanbul-reports": "^2.2.4",
"lodash": "^4.17.11",
"minimatch": "^3.0.0",
"source-map": "^0.5.1"
},
Expand Down
21 changes: 10 additions & 11 deletions test/preprocessor.spec.coffee
Expand Up @@ -2,7 +2,6 @@ vm = require 'vm'
util = require 'util'
path = require 'path'

helper = {_: require 'lodash'}
coverageMap = require '../lib/coverage-map'

describe 'preprocessor', ->
Expand Down Expand Up @@ -39,7 +38,7 @@ describe 'preprocessor', ->


it 'should not do anything if coverage reporter is not used', (done) ->
process = createPreprocessor mockLogger, helper, null, ['dots', 'progress'], {}
process = createPreprocessor mockLogger, null, ['dots', 'progress'], {}
file = new File '/base/path/file.js'

process ORIGINAL_CODE, file, (preprocessedCode) ->
Expand All @@ -49,7 +48,7 @@ describe 'preprocessor', ->


it 'should preprocess the code', (done) ->
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'], {}
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'], {}
file = new File '/base/path/file.js'

process ORIGINAL_CODE, file, (preprocessedCode) ->
Expand All @@ -66,7 +65,7 @@ describe 'preprocessor', ->
fakeInstanbulLikeInstrumenter::instrument = (_a, _b, callback) ->
callback()
return
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
instrumenters:
fakeInstanbulLike :
Instrumenter : fakeInstanbulLikeInstrumenter
Expand All @@ -91,7 +90,7 @@ describe 'preprocessor', ->
callback()
return

process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
instrumenters:
fakeInstanbulLike:
Instrumenter: fakeInstanbulLikeInstrumenter
Expand All @@ -106,7 +105,7 @@ describe 'preprocessor', ->
process ORIGINAL_COFFEE_CODE, file, done

it 'should not preprocess the coffee code', (done) ->
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
instrumenter:
'**/*.coffee': 'istanbul'
file = new File '/base/path/file.coffee'
Expand All @@ -123,14 +122,14 @@ describe 'preprocessor', ->

it 'should fail if invalid instrumenter provided', (done) ->
work = ->
createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
instrumenter:
'**/*.coffee': 'madeup'
expect(work).to.throw()
done()

it 'should add coverageMap when including all sources', (done) ->
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], { includeAllSources: true }
process = createPreprocessor mockLogger, '/base/path', ['coverage'], { includeAllSources: true }
file = new File '/base/path/file.js'

coverageMap.reset()
Expand All @@ -140,7 +139,7 @@ describe 'preprocessor', ->
done()

it 'should not add coverageMap when not including all sources', (done) ->
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], { includeAllSources: false }
process = createPreprocessor mockLogger, '/base/path', ['coverage'], { includeAllSources: false }
file = new File '/base/path/file.js'

coverageMap.reset()
Expand All @@ -150,7 +149,7 @@ describe 'preprocessor', ->
done()

it 'should not add coverageMap in the default state', (done) ->
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], {}
process = createPreprocessor mockLogger, '/base/path', ['coverage'], {}
file = new File '/base/path/file.js'

coverageMap.reset()
Expand All @@ -166,7 +165,7 @@ describe 'preprocessor', ->
callback()
return

process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
instrumenters:
ibrik :
Instrumenter : ibrikInstrumenter
Expand Down

0 comments on commit d3f53e3

Please sign in to comment.