Skip to content

Commit

Permalink
refactor: refactor lib/reporter in to ES6 (#3021)
Browse files Browse the repository at this point in the history
  • Loading branch information
lusarz authored and johnjbarton committed May 30, 2018
1 parent 36b550f commit 0ca3a26
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 83 deletions.
140 changes: 57 additions & 83 deletions lib/reporter.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
var util = require('util')
var resolve = require('url').resolve
var SourceMapConsumer = require('source-map').SourceMapConsumer
var _ = require('lodash')
'use strict'

var log = require('./logger').create('reporter')
var MultiReporter = require('./reporters/multi')
var baseReporterDecoratorFactory = require('./reporters/base').decoratorFactory
const resolve = require('url').resolve
const SourceMapConsumer = require('source-map').SourceMapConsumer
const _ = require('lodash')

var createErrorFormatter = function (config, emitter, SourceMapConsumer) {
var basePath = config.basePath
var urlRoot = config.urlRoot === '/' ? '' : (config.urlRoot || '')
var lastServedFiles = []
const PathUtils = require('./utils/path-utils')
const log = require('./logger').create('reporter')
const MultiReporter = require('./reporters/multi')
const baseReporterDecoratorFactory = require('./reporters/base').decoratorFactory

emitter.on('file_list_modified', function (files) {
function createErrorFormatter (config, emitter, SourceMapConsumer) {
const basePath = config.basePath
const urlRoot = config.urlRoot === '/' ? '' : (config.urlRoot || '')
let lastServedFiles = []

emitter.on('file_list_modified', (files) => {
lastServedFiles = files.served
})

var findFile = function (path) {
for (var i = 0; i < lastServedFiles.length; i++) {
if (lastServedFiles[i].path === path) {
return lastServedFiles[i]
}
}
return null
}

var URL_REGEXP = new RegExp('(?:https?:\\/\\/' +
const URL_REGEXP = new RegExp('(?:https?:\\/\\/' +
config.hostname + '(?:\\:' + config.port + ')?' + ')?\\/?' +
urlRoot + '\\/?' +
'(base/|absolute)' + // prefix, including slash for base/ to create relative paths.
Expand All @@ -35,15 +28,14 @@ var createErrorFormatter = function (config, emitter, SourceMapConsumer) {
'(\\:(\\d+))?' + // column
'', 'g')

var getSourceMapConsumer = (function () {
var cache = new WeakMap()
return function (sourceMap) {
if (!cache.has(sourceMap)) {
cache.set(sourceMap, new SourceMapConsumer(sourceMap))
}
return cache.get(sourceMap)
const cache = new WeakMap()

function getSourceMapConsumer (sourceMap) {
if (!cache.has(sourceMap)) {
cache.set(sourceMap, new SourceMapConsumer(sourceMap))
}
}())
return cache.get(sourceMap)
}

return function (input, indentation) {
indentation = _.isString(indentation) ? indentation : ''
Expand All @@ -55,69 +47,56 @@ var createErrorFormatter = function (config, emitter, SourceMapConsumer) {
input = JSON.stringify(input, null, indentation)
}

// remove domain and timestamp from source files
// and resolve base path / absolute path urls into absolute path
var msg = input.replace(URL_REGEXP, function (_, prefix, path, __, ___, line, ____, column) {
// Find the file using basePath + path, but use the more readable path down below.
var file = findFile(prefix === 'base/' ? basePath + '/' + path : path)
const normalizedPath = prefix === 'base/' ? `${basePath}/${path}` : path
const file = lastServedFiles.find((file) => file.path === normalizedPath)

if (file && file.sourceMap && line) {
line = parseInt(line || '0', 10)

column = parseInt(column, 10)
line = +line
column = +column

// When no column is given and we default to 0, it doesn't make sense to only search for smaller
// or equal columns in the sourcemap, let's search for equal or greater columns.
var bias = column ? SourceMapConsumer.GREATEST_LOWER_BOUND : SourceMapConsumer.LEAST_UPPER_BOUND
const bias = column ? SourceMapConsumer.GREATEST_LOWER_BOUND : SourceMapConsumer.LEAST_UPPER_BOUND

try {
var original = getSourceMapConsumer(file.sourceMap)
.originalPositionFor({line: line, column: (column || 0), bias: bias})
const original = getSourceMapConsumer(file.sourceMap).originalPositionFor({ line, column: (column || 0), bias })

// Source maps often only have a local file name, resolve to turn into a full path if
// the path is not absolute yet.
var sourcePath = resolve(path, original.source)
var formattedColumn = column ? util.format(':%s', column) : ''
return util.format('%s:%d:%d <- %s:%d%s', sourcePath, original.line, original.column,
path, line, formattedColumn)
return `${PathUtils.formatPathMapping(resolve(path, original.source), original.line, original.column)} <- ${PathUtils.formatPathMapping(path, line, column)}`
} catch (e) {
log.warn('SourceMap position not found for trace: %s', msg)
// Fall back to non-source-mapped formatting.
log.warn(`SourceMap position not found for trace: ${input}`)
}
}

var result = path + (line ? ':' + line : '') + (column ? ':' + column : '')
return result || prefix
return PathUtils.formatPathMapping(path, line, column) || prefix
})

// indent every line
if (indentation) {
msg = indentation + msg.replace(/\n/g, '\n' + indentation)
}

// allow the user to format the error
if (config.formatError) {
return config.formatError(msg)
}

return msg + '\n'
return config.formatError ? config.formatError(msg) : msg + '\n'
}
}

var createReporters = function (names, config, emitter, injector) {
var errorFormatter = createErrorFormatter(config, emitter, SourceMapConsumer)
var reporters = []
function createReporters (names, config, emitter, injector) {
const errorFormatter = createErrorFormatter(config, emitter, SourceMapConsumer)
const reporters = []

// TODO(vojta): instantiate all reporters through DI
names.forEach(function (name) {
names.forEach((name) => {
if (['dots', 'progress'].indexOf(name) !== -1) {
var Cls = require('./reporters/' + name)
var ClsColor = require('./reporters/' + name + '_color')
reporters.push(new Cls(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions))
return reporters.push(new ClsColor(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions))
[
require('./reporters/' + name),
require('./reporters/' + name + '_color')
].forEach((Reporter) => {
reporters.push(new Reporter(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions))
})
return
}

var locals = {
const locals = {
baseReporterDecorator: ['factory', baseReporterDecoratorFactory],
formatError: ['value', errorFormatter]
}
Expand All @@ -126,31 +105,27 @@ var createReporters = function (names, config, emitter, injector) {
log.debug('Trying to load reporter: %s', name)
reporters.push(injector.createChild([locals], ['reporter:' + name]).get('reporter:' + name))
} catch (e) {
if (e.message.indexOf('No provider for "reporter:' + name + '"') !== -1) {
log.error('Can not load reporter "%s", it is not registered!\n ' +
'Perhaps you are missing some plugin?', name)
if (e.message.indexOf(`No provider for "reporter:${name}"`) !== -1) {
log.error(`Can not load reporter "${name}", it is not registered!\n Perhaps you are missing some plugin?`)
} else {
log.error('Can not load "%s"!\n ' + e.stack, name)
log.error(`Can not load "${name}"!\n ${e.stack}`)
}
emitter.emit('load_error', 'reporter', name)
return
}
var colorName = name + '_color'
if (names.indexOf(colorName) !== -1) {
return
}
try {
log.debug('Trying to load color-version of reporter: %s (%s)', name, colorName)
reporters.push(injector.createChild([locals], ['reporter:' + name + '_color']).get('reporter:' + name))
} catch (e) {
log.debug('Couldn\'t load color-version.')

const colorName = name + '_color'
if (names.indexOf(colorName) === -1) {
try {
log.debug(`Trying to load color-version of reporter: ${name} (${colorName})`)
reporters.push(injector.createChild([locals], ['reporter:' + colorName]).get('reporter:' + name))
} catch (e) {
log.debug('Couldn\'t load color-version.')
}
}
})

// bind all reporters
reporters.forEach(function (reporter) {
emitter.bind(reporter)
})
reporters.forEach((reporter) => emitter.bind(reporter))

return new MultiReporter(reporters)
}
Expand All @@ -162,5 +137,4 @@ createReporters.$inject = [
'injector'
]

// PUBLISH
exports.createReporters = createReporters
9 changes: 9 additions & 0 deletions lib/utils/path-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict'

const PathUtils = {
formatPathMapping (path, line, column) {
return path + (line ? `:${line}` : '') + (column ? `:${column}` : '')
}
}

module.exports = PathUtils

0 comments on commit 0ca3a26

Please sign in to comment.