Skip to content

Commit

Permalink
refactor: migrate config to ES2015
Browse files Browse the repository at this point in the history
  • Loading branch information
devoto13 committed Mar 15, 2018
1 parent a1f4716 commit 75ec567
Show file tree
Hide file tree
Showing 2 changed files with 197 additions and 188 deletions.
245 changes: 125 additions & 120 deletions lib/config.js
@@ -1,15 +1,17 @@
var path = require('path')
'use strict'

var logger = require('./logger')
var log = logger.create('config')
var helper = require('./helper')
var constant = require('./constants')
const path = require('path')

var _ = require('lodash')
const logger = require('./logger')
const log = logger.create('config')
const helper = require('./helper')
const constant = require('./constants')

var COFFEE_SCRIPT_AVAILABLE = false
var LIVE_SCRIPT_AVAILABLE = false
var TYPE_SCRIPT_AVAILABLE = false
const _ = require('lodash')

let COFFEE_SCRIPT_AVAILABLE = false
let LIVE_SCRIPT_AVAILABLE = false
let TYPE_SCRIPT_AVAILABLE = false

// Coffee is required here to enable config files written in coffee-script.
// It's not directly used in this file.
Expand All @@ -36,25 +38,29 @@ try {
TYPE_SCRIPT_AVAILABLE = true
} catch (e) {}

var Pattern = function (pattern, served, included, watched, nocache, type) {
this.pattern = pattern
this.served = helper.isDefined(served) ? served : true
this.included = helper.isDefined(included) ? included : true
this.watched = helper.isDefined(watched) ? watched : true
this.nocache = helper.isDefined(nocache) ? nocache : false
this.weight = helper.mmPatternWeight(pattern)
this.type = type
}
class Pattern {
constructor (pattern, served, included, watched, nocache, type) {
this.pattern = pattern
this.served = helper.isDefined(served) ? served : true
this.included = helper.isDefined(included) ? included : true
this.watched = helper.isDefined(watched) ? watched : true
this.nocache = helper.isDefined(nocache) ? nocache : false
this.weight = helper.mmPatternWeight(pattern)
this.type = type
}

Pattern.prototype.compare = function (other) {
return helper.mmComparePatternWeights(this.weight, other.weight)
compare (other) {
return helper.mmComparePatternWeights(this.weight, other.weight)
}
}

var UrlPattern = function (url, type) {
Pattern.call(this, url, false, true, false, false, type)
class UrlPattern extends Pattern {
constructor (url, type) {
super(url, false, true, false, false, type)
}
}

var createPatternObject = function (pattern) {
function createPatternObject (pattern) {
if (pattern && helper.isString(pattern)) {
return helper.isUrlAbsolute(pattern) ? new UrlPattern(pattern) : new Pattern(pattern)
}
Expand All @@ -80,7 +86,7 @@ var createPatternObject = function (pattern) {
return new Pattern(null, false, false, false, false)
}

var normalizeUrl = function (url) {
function normalizeUrl (url) {
if (url.charAt(0) !== '/') {
url = '/' + url
}
Expand All @@ -92,8 +98,8 @@ var normalizeUrl = function (url) {
return url
}

var normalizeUrlRoot = function (urlRoot) {
var normalizedUrlRoot = normalizeUrl(urlRoot)
function normalizeUrlRoot (urlRoot) {
const normalizedUrlRoot = normalizeUrl(urlRoot)

if (normalizedUrlRoot !== urlRoot) {
log.warn('urlRoot normalized to "%s"', normalizedUrlRoot)
Expand All @@ -102,8 +108,8 @@ var normalizeUrlRoot = function (urlRoot) {
return normalizedUrlRoot
}

var normalizeProxyPath = function (proxyPath) {
var normalizedProxyPath = normalizeUrl(proxyPath)
function normalizeProxyPath (proxyPath) {
const normalizedProxyPath = normalizeUrl(proxyPath)

if (normalizedProxyPath !== proxyPath) {
log.warn('proxyPath normalized to "%s"', normalizedProxyPath)
Expand All @@ -112,8 +118,8 @@ var normalizeProxyPath = function (proxyPath) {
return normalizedProxyPath
}

var normalizeConfig = function (config, configFilePath) {
var basePathResolve = function (relativePath) {
function normalizeConfig (config, configFilePath) {
function basePathResolve (relativePath) {
if (helper.isUrlAbsolute(relativePath)) {
return relativePath
}
Expand All @@ -124,8 +130,8 @@ var normalizeConfig = function (config, configFilePath) {
return path.resolve(config.basePath, relativePath)
}

var createPatternMapper = function (resolve) {
return function (objectPattern) {
function createPatternMapper (resolve) {
return (objectPattern) => {
objectPattern.pattern = resolve(objectPattern.pattern)

return objectPattern
Expand Down Expand Up @@ -161,7 +167,7 @@ var normalizeConfig = function (config, configFilePath) {

// normalize and default upstream proxy settings if given
if (config.upstreamProxy) {
var proxy = config.upstreamProxy
const proxy = config.upstreamProxy
proxy.path = _.isUndefined(proxy.path) ? '/' : normalizeProxyPath(proxy.path)
proxy.hostname = _.isUndefined(proxy.hostname) ? 'localhost' : proxy.hostname
proxy.port = _.isUndefined(proxy.port) ? 9875 : proxy.port
Expand Down Expand Up @@ -223,33 +229,33 @@ var normalizeConfig = function (config, configFilePath) {
throw new TypeError('Invalid configuration: processKillTimeout option must be a number.')
}

var defaultClient = config.defaultClient || {}
const defaultClient = config.defaultClient || {}
Object.keys(defaultClient).forEach(function (key) {
var option = config.client[key]
const option = config.client[key]
config.client[key] = helper.isDefined(option) ? option : defaultClient[key]
})

// normalize preprocessors
var preprocessors = config.preprocessors || {}
var normalizedPreprocessors = config.preprocessors = Object.create(null)
const preprocessors = config.preprocessors || {}
const normalizedPreprocessors = config.preprocessors = Object.create(null)

Object.keys(preprocessors).forEach(function (pattern) {
var normalizedPattern = helper.normalizeWinPath(basePathResolve(pattern))
const normalizedPattern = helper.normalizeWinPath(basePathResolve(pattern))

normalizedPreprocessors[normalizedPattern] = helper.isString(preprocessors[pattern])
? [preprocessors[pattern]] : preprocessors[pattern]
})

// define custom launchers/preprocessors/reporters - create an inlined plugin
var module = Object.create(null)
var hasSomeInlinedPlugin = false
var types = ['launcher', 'preprocessor', 'reporter']
const module = Object.create(null)
let hasSomeInlinedPlugin = false
const types = ['launcher', 'preprocessor', 'reporter']

types.forEach(function (type) {
var definitions = config['custom' + helper.ucFirst(type) + 's'] || {}
const definitions = config['custom' + helper.ucFirst(type) + 's'] || {}

Object.keys(definitions).forEach(function (name) {
var definition = definitions[name]
const definition = definitions[name]

if (!helper.isObject(definition)) {
return log.warn('Can not define %s %s. Definition has to be an object.', type, name)
Expand All @@ -259,13 +265,13 @@ var normalizeConfig = function (config, configFilePath) {
return log.warn('Can not define %s %s. Missing base %s.', type, name, type)
}

var token = type + ':' + definition.base
var locals = {
const token = type + ':' + definition.base
const locals = {
args: ['value', definition]
}

module[type + ':' + name] = ['factory', function (injector) {
var plugin = injector.createChild([locals], [token]).get(token)
const plugin = injector.createChild([locals], [token]).get(token)
if (type === 'launcher' && helper.isDefined(definition.displayName)) {
plugin.displayName = definition.displayName
}
Expand All @@ -282,90 +288,89 @@ var normalizeConfig = function (config, configFilePath) {
return config
}

var Config = function () {
var config = this

this.LOG_DISABLE = constant.LOG_DISABLE
this.LOG_ERROR = constant.LOG_ERROR
this.LOG_WARN = constant.LOG_WARN
this.LOG_INFO = constant.LOG_INFO
this.LOG_DEBUG = constant.LOG_DEBUG
class Config {
constructor () {
this.LOG_DISABLE = constant.LOG_DISABLE
this.LOG_ERROR = constant.LOG_ERROR
this.LOG_WARN = constant.LOG_WARN
this.LOG_INFO = constant.LOG_INFO
this.LOG_DEBUG = constant.LOG_DEBUG

// DEFAULT CONFIG
this.frameworks = []
this.protocol = 'http:'
this.port = constant.DEFAULT_PORT
this.listenAddress = constant.DEFAULT_LISTEN_ADDR
this.hostname = constant.DEFAULT_HOSTNAME
this.httpsServerConfig = {}
this.basePath = ''
this.files = []
this.browserConsoleLogOptions = {
level: 'debug',
format: '%b %T: %m',
terminal: true
}
this.customContextFile = null
this.customDebugFile = null
this.customClientContextFile = null
this.exclude = []
this.logLevel = constant.LOG_INFO
this.colors = true
this.autoWatch = true
this.autoWatchBatchDelay = 250
this.restartOnFileChange = false
this.usePolling = process.platform === 'linux'
this.reporters = ['progress']
this.singleRun = false
this.browsers = []
this.captureTimeout = 60000
this.proxies = {}
this.proxyValidateSSL = true
this.preprocessors = {}
this.urlRoot = '/'
this.upstreamProxy = undefined
this.reportSlowerThan = 0
this.loggers = [constant.CONSOLE_APPENDER]
this.transports = ['polling', 'websocket']
this.forceJSONP = false
this.plugins = ['karma-*']
this.defaultClient = this.client = {
args: [],
useIframe: true,
runInParent: false,
captureConsole: true,
clearContext: true
}
this.browserDisconnectTimeout = 2000
this.browserDisconnectTolerance = 0
this.browserNoActivityTimeout = 10000
this.processKillTimeout = 2000
this.concurrency = Infinity
this.failOnEmptyTestSuite = true
this.retryLimit = 2
this.detached = false
this.crossOriginAttribute = true
}

this.set = function (newConfig) {
_.mergeWith(config, newConfig, function (obj, src) {
set (newConfig) {
_.mergeWith(this, newConfig, (obj, src) => {
// Overwrite arrays to keep consistent with #283
if (_.isArray(src)) {
return src
}
})
}

// DEFAULT CONFIG
this.frameworks = []
this.protocol = 'http:'
this.port = constant.DEFAULT_PORT
this.listenAddress = constant.DEFAULT_LISTEN_ADDR
this.hostname = constant.DEFAULT_HOSTNAME
this.httpsServerConfig = {}
this.basePath = ''
this.files = []
this.browserConsoleLogOptions = {
level: 'debug',
format: '%b %T: %m',
terminal: true
}
this.customContextFile = null
this.customDebugFile = null
this.customClientContextFile = null
this.exclude = []
this.logLevel = constant.LOG_INFO
this.colors = true
this.autoWatch = true
this.autoWatchBatchDelay = 250
this.restartOnFileChange = false
this.usePolling = process.platform === 'linux'
this.reporters = ['progress']
this.singleRun = false
this.browsers = []
this.captureTimeout = 60000
this.proxies = {}
this.proxyValidateSSL = true
this.preprocessors = {}
this.urlRoot = '/'
this.upstreamProxy = undefined
this.reportSlowerThan = 0
this.loggers = [constant.CONSOLE_APPENDER]
this.transports = ['polling', 'websocket']
this.forceJSONP = false
this.plugins = ['karma-*']
this.defaultClient = this.client = {
args: [],
useIframe: true,
runInParent: false,
captureConsole: true,
clearContext: true
}
this.browserDisconnectTimeout = 2000
this.browserDisconnectTolerance = 0
this.browserNoActivityTimeout = 10000
this.processKillTimeout = 2000
this.concurrency = Infinity
this.failOnEmptyTestSuite = true
this.retryLimit = 2
this.detached = false
this.crossOriginAttribute = true
}

var CONFIG_SYNTAX_HELP = ' module.exports = function(config) {\n' +
const CONFIG_SYNTAX_HELP = ' module.exports = function(config) {\n' +
' config.set({\n' +
' // your config\n' +
' });\n' +
' };\n'

var parseConfig = function (configFilePath, cliOptions) {
var configModule
function parseConfig (configFilePath, cliOptions) {
let configModule
if (configFilePath) {

try {
configModule = require(configFilePath)
if (typeof configModule === 'object' && typeof configModule.default !== 'undefined') {
Expand All @@ -377,7 +382,7 @@ var parseConfig = function (configFilePath, cliOptions) {
} else {
log.error('Invalid config file!\n ' + e.stack)

var extension = path.extname(configFilePath)
const extension = path.extname(configFilePath)
if (extension === '.coffee' && !COFFEE_SCRIPT_AVAILABLE) {
log.error('You need to install CoffeeScript.\n' +
' npm install coffee-script --save-dev')
Expand All @@ -397,16 +402,16 @@ var parseConfig = function (configFilePath, cliOptions) {
}
} else {
// if no config file path is passed, we define a dummy config module.
configModule = function () {}
configModule = () => {}
}

var config = new Config()
const config = new Config()

// save and reset hostname and listenAddress so we can detect if the user
// changed them
var defaultHostname = config.hostname
const defaultHostname = config.hostname
config.hostname = null
var defaultListenAddress = config.listenAddress
const defaultListenAddress = config.listenAddress
config.listenAddress = null

// add the user's configuration in
Expand Down

0 comments on commit 75ec567

Please sign in to comment.