Skip to content

Commit

Permalink
refactor(server): use ES6 string interpolation wherever possible
Browse files Browse the repository at this point in the history
  • Loading branch information
lusarz committed Oct 16, 2018
1 parent 7634e71 commit c311ac0
Show file tree
Hide file tree
Showing 21 changed files with 69 additions and 86 deletions.
6 changes: 3 additions & 3 deletions lib/cli.js
Expand Up @@ -15,7 +15,7 @@ function processArgs (argv, options, fs, path) {
}

if (argv.version) {
console.log('Karma version: ' + constant.VERSION)
console.log(`Karma version: ${constant.VERSION}`)
process.exit(0)
}

Expand All @@ -24,7 +24,7 @@ function processArgs (argv, options, fs, path) {
let argumentValue = argv[name]
if (name !== '_' && name !== '$0') {
if (name.includes('_')) {
throw new Error('Bad argument: ' + name + ' did you mean ' + name.replace('_', '-'))
throw new Error(`Bad argument: ${name} did you mean ${name.replace('_', '-')}`)
}
if (Array.isArray(argumentValue)) {
// If the same argument is defined multiple times, override.
Expand Down Expand Up @@ -60,7 +60,7 @@ function processArgs (argv, options, fs, path) {
// support exports.formatError and module.exports = function
options.formatError = required.formatError || required
if (!helper.isFunction(options.formatError)) {
console.error('Format error must be a function, got: ' + typeof options.formatError)
console.error(`Format error must be a function, got: ${typeof options.formatError}`)
process.exit(1)
}
}
Expand Down
6 changes: 3 additions & 3 deletions lib/completion.js
Expand Up @@ -35,11 +35,11 @@ const options = {
}

function opositeWord (word) {
if (!word.startsWith('-')) {
if (word.startsWith('-')) {
return word.startsWith('--no-') ? `--${word.substr(5)}` : `--no-${word.substr(2)}`
} else {
return null
}

return word.substr(0, 5) === '--no-' ? '--' + word.substr(5) : '--no-' + word.substr(2)
}

function sendCompletion (possibleWords, env) {
Expand Down
2 changes: 1 addition & 1 deletion lib/config.js
Expand Up @@ -234,7 +234,7 @@ function normalizeConfig (config, configFilePath) {
const types = ['launcher', 'preprocessor', 'reporter']

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

Object.keys(definitions).forEach(function (name) {
const definition = definitions[name]
Expand Down
24 changes: 12 additions & 12 deletions lib/file-list.js
Expand Up @@ -80,13 +80,13 @@ class FileList {
const files = mg.found
if (_.isEmpty(files)) {
this.buckets.set(pattern, [])
log.warn('Pattern "%s" does not match any file.', pattern)
log.warn(`Pattern "${pattern}" does not match any file.`)
return
}

return Promise.map(files, (path) => {
if (this._findExcluded(path)) {
log.debug('Excluded file "%s"', path)
log.debug(`Excluded file "${path}"`)
return Promise.resolve()
}

Expand All @@ -98,7 +98,7 @@ class FileList {

const file = new File(path, mg.statCache[path].mtime, patternObject.nocache, type)
if (file.doNotCache) {
log.debug('Not preprocessing "%s" due to nocache', pattern)
log.debug(`Not preprocessing "${pattern}" due to nocache`)
return Promise.resolve(file)
}

Expand All @@ -109,7 +109,7 @@ class FileList {
this.buckets.set(pattern, files)

if (_.isEmpty(files)) {
log.warn('All files matched by "%s" were excluded or matched by prior matchers.', pattern)
log.warn(`All files matched by "${pattern}" were excluded or matched by prior matchers.`)
}
})
})
Expand Down Expand Up @@ -180,18 +180,18 @@ class FileList {
addFile (path) {
const excluded = this._findExcluded(path)
if (excluded) {
log.debug('Add file "%s" ignored. Excluded by "%s".', path, excluded)
log.debug(`Add file "${path}" ignored. Excluded by "${excluded}".`)
return Promise.resolve(this.files)
}

const pattern = this._findIncluded(path)
if (!pattern) {
log.debug('Add file "%s" ignored. Does not match any pattern.', path)
log.debug(`Add file "${path}" ignored. Does not match any pattern.`)
return Promise.resolve(this.files)
}

if (this._exists(path)) {
log.debug('Add file "%s" ignored. Already in the list.', path)
log.debug(`Add file "${path}" ignored. Already in the list.`)
return Promise.resolve(this.files)
}

Expand All @@ -207,7 +207,7 @@ class FileList {
return this._preprocess(file)
})
.then(() => {
log.info('Added file "%s".', path)
log.info(`Added file "${path}".`)
this._emitModified()
return this.files
})
Expand All @@ -218,7 +218,7 @@ class FileList {
const file = this._findFile(path, pattern)

if (!file) {
log.debug('Changed file "%s" ignored. Does not match any file in the list.', path)
log.debug(`Changed file "${path}" ignored. Does not match any file in the list.`)
return Promise.resolve(this.files)
}

Expand All @@ -232,7 +232,7 @@ class FileList {
return this._preprocess(file)
})
.then(() => {
log.info('Changed file "%s".', path)
log.info(`Changed file "${path}".`)
this._emitModified(force)
return this.files
})
Expand All @@ -246,11 +246,11 @@ class FileList {

if (file) {
helper.arrayRemove(this._getFilesByPattern(pattern.pattern), file)
log.info('Removed file "%s".', path)
log.info(`Removed file "${path}".`)

this._emitModified()
} else {
log.debug('Removed file "%s" ignored. Does not match any file in the list.', path)
log.debug(`Removed file "${path}" ignored. Does not match any file in the list.`)
}
return this.files
})
Expand Down
31 changes: 12 additions & 19 deletions lib/init.js
Expand Up @@ -36,26 +36,24 @@ function installPackage (pkgName) {
return
} catch (e) {}

log.debug('Missing plugin "%s". Installing...', pkgName)
log.debug(`Missing plugin "${pkgName}". Installing...`)

const options = {
cwd: path.resolve(NODE_MODULES_DIR, '..')
}

exec('npm install ' + pkgName + ' --save-dev', options, function (err, stdout, stderr) {
exec(`npm install ${pkgName} --save-dev`, options, function (err, stdout, stderr) {
// Put the logs into the queue and print them after answering current question.
// Otherwise the log would clobber the interactive terminal.
logQueue.push(function () {
if (!err) {
log.debug('%s successfully installed.', pkgName)
log.debug(`${pkgName} successfully installed.`)
} else if (/is not in the npm registry/.test(stderr)) {
log.warn('Failed to install "%s". It is not in the NPM registry!\n' +
' Please install it manually.', pkgName)
log.warn(`Failed to install "${pkgName}". It is not in the NPM registry!\n Please install it manually.`)
} else if (/Error: EACCES/.test(stderr)) {
log.warn('Failed to install "%s". No permissions to write in %s!\n' +
' Please install it manually.', pkgName, options.cwd)
log.warn(`Failed to install "${pkgName}". No permissions to write in ${options.cwd}!\n Please install it manually.`)
} else {
log.warn('Failed to install "%s"\n Please install it manually.', pkgName)
log.warn(`Failed to install "${pkgName}"\n Please install it manually.`)
}
})
})
Expand Down Expand Up @@ -91,8 +89,7 @@ var questions = [{
}, {
id: 'requirejs',
question: 'Do you want to use Require.js ?',
hint: 'This will add Require.js plugin.\n' +
'Press tab to list possible options. Enter to move to the next question.',
hint: 'This will add Require.js plugin.\nPress tab to list possible options. Enter to move to the next question.',
options: ['no', 'yes'],
validate: validateRequireJs,
boolean: true
Expand All @@ -106,15 +103,13 @@ var questions = [{
}, {
id: 'files',
question: 'What is the location of your source and test files ?',
hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\n' +
'Enter empty string to move to the next question.',
hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\nEnter empty string to move to the next question.',
multiple: true,
validate: validatePattern
}, {
id: 'exclude',
question: 'Should any of the files included by the previous patterns be excluded ?',
hint: 'You can use glob patterns, eg. "**/*.swp".\n' +
'Enter empty string to move to the next question.',
hint: 'You can use glob patterns, eg. "**/*.swp".\nEnter empty string to move to the next question.',
multiple: true,
validate: validatePattern
}, {
Expand All @@ -126,7 +121,7 @@ var questions = [{
condition: (answers) => answers.requirejs
}, {
id: 'includedFiles',
question: 'Which files do you want to include with <script> tag ?',
question: `Which files do you want to include with <script> tag ?`,
hint: 'This should be a script that bootstraps your test by configuring Require.js and ' +
'kicking __karma__.start(), probably your test-main.js file.\n' +
'Enter empty string to move to the next question.',
Expand Down Expand Up @@ -235,12 +230,10 @@ exports.init = function (config) {

if (processedAnswers.generateTestMain) {
formatter.writeRequirejsConfigFile(testMainFilePath)
console.log(colorScheme.success(
'RequireJS bootstrap file generated at "' + testMainFilePath + '".\n'
))
console.log(colorScheme.success(`RequireJS bootstrap file generated at "${testMainFilePath}".`))
}

formatter.writeConfigFile(configFilePath, processedAnswers)
console.log(colorScheme.success('Config file generated at "' + configFilePath + '".\n'))
console.log(colorScheme.success(`Config file generated at "${configFilePath}".`))
})
}
7 changes: 1 addition & 6 deletions lib/launcher.js
Expand Up @@ -91,12 +91,7 @@ function Launcher (server, emitter, injector) {
}

this.launch = (names, concurrency) => {
log.info(
'Launching browser%s %s with %s',
names.length > 1 ? 's' : '',
names.join(', '),
concurrency === Infinity ? 'unlimited concurrency' : `concurrency ${concurrency}`
)
log.info(`Launching browsers ${names.join(', ')} with concurrency ${concurrency === Infinity ? 'unlimited' : concurrency}`)
this.jobs = new Jobs({ maxConcurrency: concurrency })

lastStartTime = Date.now()
Expand Down
2 changes: 1 addition & 1 deletion lib/launchers/base.js
Expand Up @@ -79,7 +79,7 @@ function BaseLauncher (id, emitter) {
this.state = FINISHED
} else {
killingPromise = null
log.debug('Restarting %s', this.name)
log.debug(`Restarting ${this.name}`)
this.start(previousUrl)
}
})
Expand Down
2 changes: 1 addition & 1 deletion lib/launchers/capture_timeout.js
Expand Up @@ -17,7 +17,7 @@ function CaptureTimeoutLauncher (timer, captureTimeout) {
return
}

log.warn('%s have not captured in %d ms, killing.', this.name, captureTimeout)
log.warn(`${this.name} have not captured in ${captureTimeout} ms, killing.`)
this.error = 'timeout'
this.kill()
}, captureTimeout)
Expand Down
24 changes: 11 additions & 13 deletions lib/launchers/process.js
Expand Up @@ -12,7 +12,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
stderr: ''
}

this._tempDir = tempDir.getPath('/karma-' + this.id.toString())
this._tempDir = tempDir.getPath(`/karma-${this.id.toString()}`)

this.on('start', function (url) {
tempDir.create(self._tempDir)
Expand Down Expand Up @@ -45,7 +45,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
this._normalizeCommand = function (cmd) {
if (cmd.charAt(0) === cmd.charAt(cmd.length - 1) && '\'`"'.includes(cmd.charAt(0))) {
cmd = cmd.substring(1, cmd.length - 1)
log.warn('The path should not be quoted.\n Normalized the path to %s', cmd)
log.warn(`The path should not be quoted.\n Normalized the path to ${cmd}`)
}

return path.normalize(cmd)
Expand All @@ -61,8 +61,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {

this._execCommand = function (cmd, args) {
if (!cmd) {
log.error('No binary for %s browser on your platform.\n ' +
'Please, set "%s" env variable.', self.name, self.ENV_CMD)
log.error(`No binary for ${self.name} browser on your platform.\n Please, set "${self.ENV_CMD}" env variable.`)

// disable restarting
self._retryLimit = -1
Expand All @@ -87,8 +86,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
self._process.on('error', function (err) {
if (err.code === 'ENOENT') {
self._retryLimit = -1
errorOutput = 'Can not find the binary ' + cmd + '\n\t' +
'Please set env variable ' + self.ENV_CMD
errorOutput = `Can not find the binary ${cmd}\n\tPlease set env variable ${self.ENV_CMD}`
} else {
errorOutput += err.toString()
}
Expand All @@ -100,23 +98,23 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
}

this._onProcessExit = function (code, errorOutput) {
log.debug('Process %s exited with code %d', self.name, code)
log.debug(`Process ${self.name} exited with code ${code}`)

let error = null

if (self.state === self.STATE_BEING_CAPTURED) {
log.error('Cannot start %s\n\t%s', self.name, errorOutput)
log.error(`Cannot start ${self.name}\n\t${errorOutput}`)
error = 'cannot start'
}

if (self.state === self.STATE_CAPTURED) {
log.error('%s crashed.\n\t%s', self.name, errorOutput)
log.error(`${self.name} crashed.\n\t${errorOutput}`)
error = 'crashed'
}

if (error) {
log.error('%s stdout: %s', self.name, streamedOutputs.stdout)
log.error('%s stderr: %s', self.name, streamedOutputs.stderr)
log.error(`${self.name} stdout: ${streamedOutputs.stdout}`)
log.error(`${self.name} stderr: ${streamedOutputs.stderr}`)
}

self._process = null
Expand Down Expand Up @@ -144,7 +142,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
return
}

log.warn('%s was not killed in %d ms, sending SIGKILL.', self.name, killTimeout)
log.warn(`${self.name} was not killed in ${killTimeout} ms, sending SIGKILL.`)
self._process.kill('SIGKILL')

// NOTE: https://github.com/karma-runner/karma/pull/1184
Expand All @@ -154,7 +152,7 @@ function ProcessLauncher (spawn, tempDir, timer, processKillTimeout) {
// This a certainly suboptimal, but it is better than having the test harness hang waiting
// for a zombie child process to exit.
self._killTimer = timer.setTimeout(function () {
log.warn('%s was not killed by SIGKILL in %d ms, continuing.', self.name, killTimeout)
log.warn(`${self.name} was not killed by SIGKILL in ${killTimeout} ms, continuing.`)
self._onProcessExit(-1, '')
}, killTimeout)
}
Expand Down
7 changes: 3 additions & 4 deletions lib/launchers/retry.js
Expand Up @@ -9,14 +9,13 @@ function RetryLauncher (retryLimit) {
}

if (this._retryLimit > 0) {
const attempt = retryLimit - this._retryLimit + 1
log.info('Trying to start %s again (%d/%d).', this.name, attempt, retryLimit)
log.info(`Trying to start ${this.name} again (${retryLimit - this._retryLimit + 1}/${retryLimit}).`)
this.restart()
this._retryLimit--
} else if (this._retryLimit === 0) {
log.error('%s failed %d times (%s). Giving up.', this.name, retryLimit, this.error)
log.error(`${this.name} failed ${retryLimit} times (${this.error}). Giving up.`)
} else {
log.debug('%s failed (%s). Not restarting.', this.name, this.error)
log.debug(`${this.name} failed (${this.error}). Not restarting.`)
}
})
}
Expand Down
8 changes: 4 additions & 4 deletions lib/middleware/karma.js
Expand Up @@ -154,19 +154,19 @@ function createKarmaMiddleware (
let requestedFileUrl
log.debug('custom files', customContextFile, customDebugFile, customClientContextFile)
if (isRequestingContextFile && customContextFile) {
log.debug('Serving customContextFile %s', customContextFile)
log.debug(`Serving customContextFile ${customContextFile}`)
fileServer = serveFile
requestedFileUrl = customContextFile
} else if (isRequestingDebugFile && customDebugFile) {
log.debug('Serving customDebugFile %s', customDebugFile)
log.debug(`Serving customDebugFile ${customDebugFile}`)
fileServer = serveFile
requestedFileUrl = customDebugFile
} else if (isRequestingClientContextFile && customClientContextFile) {
log.debug('Serving customClientContextFile %s', customClientContextFile)
log.debug(`Serving customClientContextFile ${customClientContextFile}`)
fileServer = serveFile
requestedFileUrl = customClientContextFile
} else {
log.debug('Serving static request %s', requestUrl)
log.debug(`Serving static request ${requestUrl}`)
fileServer = serveStaticFile
requestedFileUrl = requestUrl
}
Expand Down

0 comments on commit c311ac0

Please sign in to comment.