Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(chore) Minor ES6 tweaks. #1253

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions bin/nyc.js
Expand Up @@ -5,7 +5,7 @@ const configUtil = require('../lib/config-util')
const { cliWrapper, suppressEPIPE } = require('../lib/commands/helpers')
const foreground = require('foreground-child')
const resolveFrom = require('resolve-from')
const NYC = require('../index.js')
const NYC = require('..')

// parse configuration and command-line arguments;
// we keep these values in a few different forms,
Expand All @@ -32,7 +32,7 @@ async function main () {
if (!argv.instrument) argv.instrumenter = './lib/instrumenters/noop'
else argv.instrumenter = './lib/instrumenters/istanbul'

var nyc = (new NYC(argv))
const nyc = (new NYC(argv))
if (argv.clean) {
await nyc.reset()
} else {
Expand Down
50 changes: 25 additions & 25 deletions index.js
Expand Up @@ -36,7 +36,7 @@ if (/self-coverage/.test(__dirname)) {
}

function coverageFinder () {
var coverage = global.__coverage__
let coverage = global.__coverage__
if (typeof __coverage__ === 'object') coverage = __coverage__
if (!coverage) coverage = global.__coverage__ = {}
return coverage
Expand Down Expand Up @@ -90,9 +90,10 @@ class NYC {
this.hookRunInThisContext = config.hookRunInThisContext
this.fakeRequire = null

this.processInfo = new ProcessInfo(Object.assign({}, config._processInfo, {
this.processInfo = new ProcessInfo({
...config._processInfo,
directory: path.resolve(this.tempDirectory(), 'processinfo')
}))
})

this.hashCache = {}
}
Expand All @@ -101,15 +102,15 @@ class NYC {
const opts = {
salt: Hash.salt(this.config),
hashData: (input, metadata) => [metadata.filename],
filenamePrefix: metadata => path.parse(metadata.filename).name + '-',
filenamePrefix: metadata => `${path.parse(metadata.filename).name}-`,
onHash: (input, metadata, hash) => {
this.hashCache[metadata.filename] = hash
},
cacheDir: this.cacheDirectory,
// when running --all we should not load source-file from
// cache, we want to instead return the fake source.
disableCache: this._disableCachingTransform(),
ext: ext
ext
}
if (this._eagerInstantiation) {
opts.transform = this._transformFactory(this.cacheDirectory)
Expand Down Expand Up @@ -157,13 +158,13 @@ class NYC {
}

_readTranspiledSource (filePath) {
var source = null
var ext = path.extname(filePath)
let source = null
let ext = path.extname(filePath)
if (typeof Module._extensions[ext] === 'undefined') {
ext = '.js'
}
Module._extensions[ext]({
_compile: function (content, filename) {
_compile (content) {
source = content
}
}, filePath)
Expand Down Expand Up @@ -194,7 +195,7 @@ class NYC {
}

async instrumentAllFiles (input, output) {
let inputDir = '.' + path.sep
let inputDir = `.${path.sep}`
const visitor = async relFile => {
const inFile = path.resolve(inputDir, relFile)
const inCode = await fs.readFile(inFile, 'utf-8')
Expand Down Expand Up @@ -270,12 +271,12 @@ class NYC {
}
}

_transformFactory (cacheDir) {
_transformFactory () {
const instrumenter = this.instrumenter()
let instrumented

return (code, metadata, hash) => {
const filename = metadata.filename
const { filename } = metadata
const sourceMap = {}

if (this._sourceMap) {
Expand All @@ -287,10 +288,10 @@ class NYC {

try {
instrumented = instrumenter.instrumentSync(code, filename, sourceMap)
} catch (e) {
debugLog('failed to instrument ' + filename + ' with error: ' + e.stack)
} catch (error) {
debugLog(`failed to instrument ${filename} with error: ${error.stack}`)
if (this.config.exitOnError) {
console.error('Failed to instrument ' + filename)
console.error(`Failed to instrument ${filename}`)
process.exit(1)
} else {
instrumented = code
Expand All @@ -299,9 +300,8 @@ class NYC {

if (this.fakeRequire) {
return 'function x () {}'
} else {
return instrumented
}
return instrumented
}
}

Expand All @@ -314,7 +314,7 @@ class NYC {
_addHook (type) {
const handleJs = this._handleJs.bind(this)
const dummyMatcher = () => true // we do all processing in transformer
libHook['hook' + type](dummyMatcher, handleJs, { extensions: this.extensions })
libHook[`hook${type}`](dummyMatcher, handleJs, { extensions: this.extensions })
}

_addRequireHooks () {
Expand Down Expand Up @@ -360,7 +360,7 @@ class NYC {
)
}

wrap (bin) {
wrap () {
process.env.NYC_PROCESS_ID = this.processInfo.uuid
// This is a bug with the spawn-wrap method where
// we cannot force propagation of NYC_PROCESS_ID.
Expand All @@ -375,7 +375,7 @@ class NYC {
}

writeCoverageFile () {
var coverage = coverageFinder()
const coverage = coverageFinder()

// Remove any files that should be excluded but snuck into the coverage
Object.keys(coverage).forEach(function (absFile) {
Expand All @@ -392,8 +392,8 @@ class NYC {
}, this)
}

var id = this.processInfo.uuid
var coverageFilename = path.resolve(this.tempDirectory(), id + '.json')
const id = this.processInfo.uuid
const coverageFilename = path.resolve(this.tempDirectory(), `${id}.json`)

fs.writeFileSync(
coverageFilename,
Expand Down Expand Up @@ -476,14 +476,14 @@ class NYC {
}

_checkCoverage (summary, thresholds, file) {
Object.keys(thresholds).forEach(function (key) {
var coverage = summary[key].pct
Object.keys(thresholds).forEach(key => {
const coverage = summary[key].pct
if (coverage < thresholds[key]) {
process.exitCode = 1
if (file) {
console.error('ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet threshold (' + thresholds[key] + '%) for ' + file)
console.error(`ERROR: Coverage for ${key} (${coverage}%) does not meet threshold (${thresholds[key]}%) for ${file}`)
} else {
console.error('ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet global threshold (' + thresholds[key] + '%)')
console.error(`ERROR: Coverage for ${key} (${coverage}%) does not meet global threshold (${thresholds[key]}%)`)
}
}
})
Expand Down
4 changes: 2 additions & 2 deletions lib/commands/check-coverage.js
@@ -1,13 +1,13 @@
'use strict'

const NYC = require('../../index.js')
const NYC = require('../..')
const { cliWrapper, suppressEPIPE, setupOptions } = require('./helpers.js')

exports.command = 'check-coverage'

exports.describe = 'check whether coverage is within thresholds provided'

exports.builder = function (yargs) {
exports.builder = (yargs) => {
yargs
.demandCommand(0, 0)
.example('$0 check-coverage --lines 95', "check whether the JSON in nyc's output folder meets the thresholds provided")
Expand Down
4 changes: 2 additions & 2 deletions lib/commands/instrument.js
@@ -1,6 +1,6 @@
'use strict'

const NYC = require('../../index.js')
const NYC = require('../..')
const path = require('path')
const { promisify } = require('util')
const resolveFrom = require('resolve-from')
Expand All @@ -11,7 +11,7 @@ exports.command = 'instrument <input> [output]'

exports.describe = 'instruments a file or a directory tree and writes the instrumented code to the desired output location'

exports.builder = function (yargs) {
exports.builder = (yargs) => {
yargs
.demandCommand(0, 0)
.example('$0 instrument ./lib ./output', 'instrument all .js files in ./lib with coverage and output in ./output')
Expand Down
4 changes: 2 additions & 2 deletions lib/commands/merge.js
Expand Up @@ -4,13 +4,13 @@ const makeDir = require('make-dir')
const fs = require('../fs-promises')
const { cliWrapper, setupOptions } = require('./helpers.js')

const NYC = require('../../index.js')
const NYC = require('../..')

exports.command = 'merge <input-directory> [output-file]'

exports.describe = 'merge istanbul format coverage output in a given folder'

exports.builder = function (yargs) {
exports.builder = (yargs) => {
yargs
.demandCommand(0, 0)
.example('$0 merge ./out coverage.json', 'merge together reports in ./out and output as coverage.json')
Expand Down
6 changes: 3 additions & 3 deletions lib/commands/report.js
@@ -1,13 +1,13 @@
'use strict'

const NYC = require('../../index.js')
const NYC = require('../..')
const { cliWrapper, suppressEPIPE, setupOptions } = require('./helpers.js')

exports.command = 'report'

exports.describe = 'run coverage report for .nyc_output'

exports.builder = function (yargs) {
exports.builder = (yargs) => {
yargs
.demandCommand(0, 0)
.example('$0 report --reporter=lcov', 'output an HTML lcov report to ./coverage')
Expand All @@ -17,7 +17,7 @@ exports.builder = function (yargs) {

exports.handler = cliWrapper(async argv => {
process.env.NYC_CWD = process.cwd()
var nyc = new NYC(argv)
const nyc = new NYC(argv)
await nyc.report().catch(suppressEPIPE)
if (argv.checkCoverage) {
await nyc.checkCoverage({
Expand Down
6 changes: 3 additions & 3 deletions lib/instrumenters/istanbul.js
Expand Up @@ -18,18 +18,18 @@ function InstrumenterIstanbul (options) {

return {
instrumentSync (code, filename, { sourceMap, registerMap }) {
var instrumented = instrumenter.instrumentSync(code, filename, sourceMap)
let instrumented = instrumenter.instrumentSync(code, filename, sourceMap)
if (instrumented !== code) {
registerMap()
}

// the instrumenter can optionally produce source maps,
// this is useful for features like remapping stack-traces.
if (options.produceSourceMap) {
var lastSourceMap = instrumenter.lastSourceMap()
const lastSourceMap = instrumenter.lastSourceMap()
/* istanbul ignore else */
if (lastSourceMap) {
instrumented += '\n' + convertSourceMap.fromObject(lastSourceMap).toComment()
instrumented += `\n${convertSourceMap.fromObject(lastSourceMap).toComment()}`
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/instrumenters/noop.js
Expand Up @@ -4,7 +4,7 @@ function NOOP () {
const { readInitialCoverage } = require('istanbul-lib-instrument')

return {
instrumentSync (code, filename) {
instrumentSync (code) {
const extracted = readInitialCoverage(code)
if (extracted) {
this.fileCoverage = extracted.coverageData
Expand Down
14 changes: 7 additions & 7 deletions lib/process-args.js
Expand Up @@ -11,8 +11,8 @@ const commands = [
module.exports = {
// don't pass arguments that are meant
// for nyc to the bin being instrumented.
hideInstrumenterArgs: function (yargv) {
var argv = process.argv.slice(1)
hideInstrumenterArgs (yargv) {
let argv = process.argv.slice(1)
argv = argv.slice(argv.indexOf(yargv._[0]))
if (argv[0][0] === '-') {
argv.unshift(process.execPath)
Expand All @@ -21,12 +21,12 @@ module.exports = {
},
// don't pass arguments for the bin being
// instrumented to nyc.
hideInstrumenteeArgs: function () {
var argv = process.argv.slice(2)
var yargv = Parser(argv)
hideInstrumenteeArgs () {
let argv = process.argv.slice(2)
const yargv = Parser(argv)
if (!yargv._.length) return argv
for (var i = 0, command; (command = yargv._[i]) !== undefined; i++) {
if (~commands.indexOf(command)) return argv
for (let i = 0, command; (command = yargv._[i]) !== undefined; i++) {
if (commands.includes(command)) return argv
}

// drop all the arguments after the bin being
Expand Down
2 changes: 1 addition & 1 deletion lib/register-env.js
Expand Up @@ -22,6 +22,6 @@ for (const env of copyAtLoad) {
}
}

module.exports = function updateVariable (envName) {
module.exports = (envName) => {
envToCopy[envName] = process.env[envName]
}
2 changes: 1 addition & 1 deletion lib/source-maps.js
Expand Up @@ -66,7 +66,7 @@ class SourceMaps {
try {
const mapPath = this.cachedPath(absFile, hash)
this.loadedMaps[hash] = JSON.parse(await fs.readFile(mapPath, 'utf8'))
} catch (e) {
} catch (error) {
// set to false to avoid repeatedly trying to load the map
this.loadedMaps[hash] = false
}
Expand Down
4 changes: 2 additions & 2 deletions lib/wrap.js
@@ -1,6 +1,6 @@
'use strict'

const NYC = require('../index.js')
const NYC = require('..')

const config = JSON.parse(
process.env.NYC_CONFIG ||
Expand All @@ -25,4 +25,4 @@ if (process.env.NYC_CONFIG_OVERRIDE) {
process.env.NYC_CONFIG = JSON.stringify(config)
}

;(new NYC(config)).wrap()
(new NYC(config)).wrap()
2 changes: 1 addition & 1 deletion self-coverage-helper.js
Expand Up @@ -15,7 +15,7 @@ module.exports = {
const selfCoverageDir = path.join(__dirname, '.self_coverage')
mkdirp.sync(selfCoverageDir)
fs.writeFileSync(
path.join(selfCoverageDir, process.pid + '.json'),
path.join(selfCoverageDir, `${process.pid}.json`),
JSON.stringify(coverage),
'utf-8'
)
Expand Down
2 changes: 1 addition & 1 deletion test/add-all-files.js
Expand Up @@ -78,7 +78,7 @@ t.test('transpiles .js files added via addAllFiles', async t => {
await fs.unlink(needsTranspilePath)
})

t.test('does not attempt to transpile files when they are excluded', async t => {
t.test('does not attempt to transpile files when they are excluded', async () => {
const notNeedTranspilePath = path.join(fixtures, './do-not-need-transpile.do-not-transpile')
await fs.writeFile(
notNeedTranspilePath,
Expand Down
3 changes: 2 additions & 1 deletion test/config-override.js
Expand Up @@ -10,6 +10,7 @@ t.test('spawn that does config overriding', t => testSuccess(t, {
args: [
'--exclude-after-remap=false',
'--include=conf-override-root.js',
process.execPath, 'conf-override-root.js'
process.execPath,
'conf-override-root.js'
]
}))
4 changes: 2 additions & 2 deletions test/helpers/reset-state.js
Expand Up @@ -8,14 +8,14 @@ const extensions = Object.assign({}, require.extensions) // eslint-disable-line
const glob = promisify(require('glob'))
const rimraf = promisify(require('rimraf'))

module.exports = async function () {
module.exports = async () => {
// nuke any temporary files created during test runs.
const files = await glob('test/**/*/{.nyc_output,.cache}')
await Promise.all(files.map(f => rimraf(f)))

// reset Node's require cache.
Object.keys(require.cache).forEach((key) => {
if (key.indexOf('node_modules') === -1) delete require.cache[key]
if (!key.includes('node_modules')) delete require.cache[key]
})

// reset any custom loaders for extensions, disabling the stack maintained
Expand Down
2 changes: 1 addition & 1 deletion test/helpers/run-nyc.js
Expand Up @@ -34,7 +34,7 @@ function sanitizeString (str, cwd, leavePathSep) {
async function runNYC ({ args, tempDir, leavePathSep, cwd = fixturesCLI, env = {} }) {
const runArgs = [nycBin].concat(tempDir ? ['--temp-dir', tempDir] : [], args)
const { status, stderr, stdout } = await spawn(process.execPath, runArgs, {
cwd: cwd,
cwd,
env: {
...envPath,
...env
Expand Down