| 1 |
'use strict' |
| 2 |
|
| 3 |
/* global __coverage__ */ |
| 4 |
|
| 5 |
const cachingTransform = require('caching-transform') |
| 6 |
const findCacheDir = require('find-cache-dir') |
| 7 |
const fs = require('./lib/fs-promises') |
| 8 |
const os = require('os') |
| 9 |
const { debuglog, promisify } = require('util') |
| •10 |
const { glob } = require('glob') |
| 11 |
const Hash = require('./lib/hash') |
| 12 |
const libCoverage = require('istanbul-lib-coverage') |
| 13 |
const libHook = require('istanbul-lib-hook') |
| 14 |
const { ProcessInfo, ProcessDB } = require('istanbul-lib-processinfo') |
| 15 |
const mkdirp = require('make-dir') |
| 16 |
const Module = require('module') |
| •17 |
const { onExit } = require('signal-exit') |
| 18 |
const path = require('path') |
| •19 |
const { rimraf } = require('rimraf') |
| 20 |
const SourceMaps = require('./lib/source-maps') |
| 21 |
const TestExclude = require('test-exclude') |
| 22 |
const pMap = require('p-map') |
| 23 |
const getPackageType = require('get-package-type') |
| 24 |
|
| 25 |
const debugLog = debuglog('nyc') |
| 26 |
|
| 27 |
let selfCoverageHelper |
| 28 |
|
| 29 |
/* istanbul ignore next */ |
| 30 |
if (/self-coverage/.test(__dirname)) { |
| 31 |
selfCoverageHelper = require('../self-coverage-helper') |
| 32 |
} else { |
| 33 |
// Avoid additional conditional code |
| 34 |
selfCoverageHelper = { |
| 35 |
onExit () {} |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
function coverageFinder () { |
| 40 |
var coverage = global.__coverage__ |
| 41 |
if (typeof __coverage__ === 'object') coverage = __coverage__ |
| 42 |
if (!coverage) coverage = global.__coverage__ = {} |
| 43 |
return coverage |
| 44 |
} |
| 45 |
|
| 46 |
class NYC { |
| 47 |
constructor (config) { |
| 48 |
this.config = { ...config } |
| 49 |
|
| 50 |
this.subprocessBin = config.subprocessBin || path.resolve(__dirname, './bin/nyc.js') |
| 51 |
this._tempDirectory = config.tempDirectory || config.tempDir || './.nyc_output' |
| 52 |
this._instrumenterLib = require(config.instrumenter || './lib/instrumenters/istanbul') |
| 53 |
this._reportDir = config.reportDir || 'coverage' |
| 54 |
this._sourceMap = typeof config.sourceMap === 'boolean' ? config.sourceMap : true |
| 55 |
this._showProcessTree = config.showProcessTree || false |
| 56 |
this._eagerInstantiation = config.eager || false |
| 57 |
this.cwd = config.cwd || process.cwd() |
| 58 |
this.reporter = [].concat(config.reporter || 'text') |
| 59 |
|
| 60 |
this.cacheDirectory = (config.cacheDir && path.resolve(config.cacheDir)) || findCacheDir({ name: 'nyc', cwd: this.cwd }) |
| 61 |
this.cache = Boolean(this.cacheDirectory && config.cache) |
| 62 |
|
| 63 |
this.extensions = [].concat(config.extension || []) |
| 64 |
.concat('.js') |
| 65 |
.map(ext => ext.toLowerCase()) |
| 66 |
.filter((item, pos, arr) => arr.indexOf(item) === pos) |
| 67 |
|
| 68 |
this.exclude = new TestExclude({ |
| 69 |
cwd: this.cwd, |
| 70 |
include: config.include, |
| 71 |
exclude: config.exclude, |
| 72 |
excludeNodeModules: config.excludeNodeModules !== false, |
| 73 |
extension: this.extensions |
| 74 |
}) |
| 75 |
|
| 76 |
this.sourceMaps = new SourceMaps({ |
| 77 |
cache: this.cache, |
| 78 |
cacheDirectory: this.cacheDirectory |
| 79 |
}) |
| 80 |
|
| 81 |
// require extensions can be provided as config in package.json. |
| 82 |
this.require = [].concat(config.require || []) |
| 83 |
|
| 84 |
this.transforms = this.extensions.reduce((transforms, ext) => { |
| 85 |
transforms[ext] = this._createTransform(ext) |
| 86 |
return transforms |
| 87 |
}, {}) |
| 88 |
|
| 89 |
this.hookRequire = config.hookRequire |
| 90 |
this.hookRunInContext = config.hookRunInContext |
| 91 |
this.hookRunInThisContext = config.hookRunInThisContext |
| 92 |
this.fakeRequire = null |
| 93 |
|
| 94 |
this.processInfo = new ProcessInfo(Object.assign({}, config._processInfo, { |
| 95 |
directory: path.resolve(this.tempDirectory(), 'processinfo') |
| 96 |
})) |
| 97 |
|
| 98 |
this.hashCache = {} |
| 99 |
} |
| 100 |
|
| 101 |
_createTransform (ext) { |
| 102 |
const opts = { |
| 103 |
salt: Hash.salt(this.config), |
| 104 |
hashData: (input, metadata) => [metadata.filename], |
| 105 |
filenamePrefix: metadata => path.parse(metadata.filename).name + '-', |
| 106 |
onHash: (input, metadata, hash) => { |
| 107 |
this.hashCache[metadata.filename] = hash |
| 108 |
}, |
| 109 |
cacheDir: this.cacheDirectory, |
| 110 |
// when running --all we should not load source-file from |
| 111 |
// cache, we want to instead return the fake source. |
| 112 |
disableCache: this._disableCachingTransform(), |
| 113 |
ext: ext |
| 114 |
} |
| 115 |
if (this._eagerInstantiation) { |
| 116 |
opts.transform = this._transformFactory(this.cacheDirectory) |
| 117 |
} else { |
| 118 |
opts.factory = this._transformFactory.bind(this) |
| 119 |
} |
| 120 |
return cachingTransform(opts) |
| 121 |
} |
| 122 |
|
| 123 |
_disableCachingTransform () { |
| 124 |
return !(this.cache && this.config.isChildProcess) |
| 125 |
} |
| 126 |
|
| 127 |
_loadAdditionalModules () { |
| 128 |
if (!this.config.useSpawnWrap || this.require.length === 0) { |
| 129 |
return |
| 130 |
} |
| 131 |
|
| 132 |
const resolveFrom = require('resolve-from') |
| 133 |
this.require.forEach(requireModule => { |
| 134 |
// Attempt to require the module relative to the directory being instrumented. |
| 135 |
// Then try other locations, e.g. the nyc node_modules folder. |
| 136 |
require(resolveFrom.silent(this.cwd, requireModule) || requireModule) |
| 137 |
}) |
| 138 |
} |
| 139 |
|
| 140 |
instrumenter () { |
| 141 |
return this._instrumenter || (this._instrumenter = this._createInstrumenter()) |
| 142 |
} |
| 143 |
|
| 144 |
_createInstrumenter () { |
| 145 |
return this._instrumenterLib({ |
| 146 |
ignoreClassMethods: [].concat(this.config.ignoreClassMethod).filter(a => a), |
| 147 |
produceSourceMap: this.config.produceSourceMap, |
| 148 |
compact: this.config.compact, |
| 149 |
preserveComments: this.config.preserveComments, |
| 150 |
esModules: this.config.esModules, |
| 151 |
parserPlugins: this.config.parserPlugins |
| 152 |
}) |
| 153 |
} |
| 154 |
|
| 155 |
addFile (filename) { |
| 156 |
const source = this._readTranspiledSource(filename) |
| 157 |
this._maybeInstrumentSource(source, filename) |
| 158 |
} |
| 159 |
|
| 160 |
_readTranspiledSource (filePath) { |
| 161 |
var source = null |
| 162 |
var ext = path.extname(filePath) |
| 163 |
if (typeof Module._extensions[ext] === 'undefined') { |
| 164 |
ext = '.js' |
| 165 |
} |
| 166 |
Module._extensions[ext]({ |
| 167 |
_compile: function (content, filename) { |
| 168 |
source = content |
| 169 |
} |
| 170 |
}, filePath) |
| 171 |
return source |
| 172 |
} |
| 173 |
|
| 174 |
_getSourceMap (code, filename, hash) { |
| 175 |
const sourceMap = {} |
| 176 |
if (this._sourceMap) { |
| 177 |
sourceMap.sourceMap = this.sourceMaps.extract(code, filename) |
| 178 |
sourceMap.registerMap = () => this.sourceMaps.registerMap(filename, hash, sourceMap.sourceMap) |
| 179 |
} else { |
| 180 |
sourceMap.registerMap = () => {} |
| 181 |
} |
| 182 |
|
| 183 |
return sourceMap |
| 184 |
} |
| 185 |
|
| 186 |
async addAllFiles () { |
| 187 |
this._loadAdditionalModules() |
| 188 |
|
| 189 |
this.fakeRequire = true |
| 190 |
const files = await this.exclude.glob(this.cwd) |
| 191 |
for (const relFile of files) { |
| 192 |
const filename = path.resolve(this.cwd, relFile) |
| 193 |
const ext = path.extname(filename) |
| 194 |
if (ext === '.mjs' || (ext === '.js' && await getPackageType(filename) === 'module')) { |
| 195 |
const source = await fs.readFile(filename, 'utf8') |
| 196 |
this.instrumenter().instrumentSync( |
| 197 |
source, |
| 198 |
filename, |
| 199 |
this._getSourceMap(source, filename) |
| 200 |
) |
| 201 |
} else { |
| 202 |
this.addFile(filename) |
| 203 |
} |
| 204 |
const coverage = coverageFinder() |
| 205 |
const lastCoverage = this.instrumenter().lastFileCoverage() |
| 206 |
if (lastCoverage) { |
| 207 |
coverage[lastCoverage.path] = { |
| 208 |
...lastCoverage, |
| 209 |
// Only use this data if we don't have it without `all: true` |
| 210 |
all: true |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
this.fakeRequire = false |
| 215 |
|
| 216 |
this.writeCoverageFile() |
| 217 |
} |
| 218 |
|
| 219 |
async instrumentAllFiles (input, output) { |
| 220 |
let inputDir = '.' + path.sep |
| 221 |
const visitor = async relFile => { |
| 222 |
const inFile = path.resolve(inputDir, relFile) |
| 223 |
const inCode = await fs.readFile(inFile, 'utf-8') |
| 224 |
const outCode = this._transform(inCode, inFile) || inCode |
| 225 |
|
| 226 |
if (output) { |
| 227 |
const { mode } = await fs.stat(inFile) |
| 228 |
const outFile = path.resolve(output, relFile) |
| 229 |
|
| 230 |
await mkdirp(path.dirname(outFile)) |
| 231 |
await fs.writeFile(outFile, outCode) |
| 232 |
await fs.chmod(outFile, mode) |
| 233 |
} else { |
| 234 |
console.log(outCode) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
this._loadAdditionalModules() |
| 239 |
|
| 240 |
const stats = await fs.lstat(input) |
| 241 |
if (stats.isDirectory()) { |
| 242 |
inputDir = input |
| 243 |
|
| 244 |
const filesToInstrument = await this.exclude.glob(input) |
| 245 |
|
| 246 |
const concurrency = output ? os.cpus().length : 1 |
| 247 |
if (this.config.completeCopy && output) { |
| 248 |
const files = await glob(path.resolve(input, '**'), { |
| 249 |
dot: true, |
| 250 |
nodir: true, |
| 251 |
ignore: ['**/.git', '**/.git/**', path.join(output, '**')] |
| 252 |
}) |
| 253 |
const destDirs = new Set( |
| 254 |
files.map(src => path.dirname(path.join(output, path.relative(input, src)))) |
| 255 |
) |
| 256 |
|
| 257 |
await pMap( |
| 258 |
destDirs, |
| 259 |
dir => mkdirp(dir), |
| 260 |
{ concurrency } |
| 261 |
) |
| 262 |
await pMap( |
| 263 |
files, |
| 264 |
src => fs.copyFile(src, path.join(output, path.relative(input, src))), |
| 265 |
{ concurrency } |
| 266 |
) |
| 267 |
} |
| 268 |
|
| 269 |
await pMap(filesToInstrument, visitor, { concurrency }) |
| 270 |
} else { |
| 271 |
await visitor(input) |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
_transform (code, filename) { |
| 276 |
const extname = path.extname(filename).toLowerCase() |
| 277 |
const transform = this.transforms[extname] || (() => null) |
| 278 |
|
| 279 |
return transform(code, { filename }) |
| 280 |
} |
| 281 |
|
| 282 |
_maybeInstrumentSource (code, filename) { |
| 283 |
if (!this.exclude.shouldInstrument(filename)) { |
| 284 |
return null |
| 285 |
} |
| 286 |
|
| 287 |
return this._transform(code, filename) |
| 288 |
} |
| 289 |
|
| 290 |
maybePurgeSourceMapCache () { |
| 291 |
if (!this.cache) { |
| 292 |
this.sourceMaps.purgeCache() |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
_transformFactory (cacheDir) { |
| 297 |
const instrumenter = this.instrumenter() |
| 298 |
let instrumented |
| 299 |
|
| 300 |
return (code, metadata, hash) => { |
| 301 |
const filename = metadata.filename |
| 302 |
const sourceMap = this._getSourceMap(code, filename, hash) |
| 303 |
|
| 304 |
try { |
| 305 |
instrumented = instrumenter.instrumentSync(code, filename, sourceMap) |
| 306 |
} catch (e) { |
| 307 |
debugLog('failed to instrument ' + filename + ' with error: ' + e.stack) |
| 308 |
if (this.config.exitOnError) { |
| 309 |
console.error('Failed to instrument ' + filename) |
| 310 |
process.exit(1) |
| 311 |
} else { |
| 312 |
instrumented = code |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
if (this.fakeRequire) { |
| 317 |
return 'function x () {}' |
| 318 |
} else { |
| 319 |
return instrumented |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
_handleJs (code, options) { |
| 325 |
// ensure the path has correct casing (see istanbuljs/nyc#269 and nodejs/node#6624) |
| 326 |
const filename = path.resolve(this.cwd, options.filename) |
| 327 |
return this._maybeInstrumentSource(code, filename) || code |
| 328 |
} |
| 329 |
|
| 330 |
_addHook (type) { |
| 331 |
const handleJs = this._handleJs.bind(this) |
| 332 |
const dummyMatcher = () => true // we do all processing in transformer |
| 333 |
libHook['hook' + type](dummyMatcher, handleJs, { extensions: this.extensions }) |
| 334 |
} |
| 335 |
|
| 336 |
_addRequireHooks () { |
| 337 |
if (this.hookRequire) { |
| 338 |
this._addHook('Require') |
| 339 |
} |
| 340 |
if (this.hookRunInContext) { |
| 341 |
this._addHook('RunInContext') |
| 342 |
} |
| 343 |
if (this.hookRunInThisContext) { |
| 344 |
this._addHook('RunInThisContext') |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
async createTempDirectory () { |
| 349 |
await mkdirp(this.tempDirectory()) |
| 350 |
if (this.cache) { |
| 351 |
await mkdirp(this.cacheDirectory) |
| 352 |
} |
| 353 |
|
| 354 |
await mkdirp(this.processInfo.directory) |
| 355 |
} |
| 356 |
|
| 357 |
async reset () { |
| 358 |
if (!process.env.NYC_CWD) { |
| 359 |
await rimraf(this.tempDirectory()) |
| 360 |
} |
| 361 |
|
| 362 |
await this.createTempDirectory() |
| 363 |
} |
| 364 |
|
| 365 |
_wrapExit () { |
| 366 |
selfCoverageHelper.registered = true |
| 367 |
|
| 368 |
// we always want to write coverage |
| 369 |
// regardless of how the process exits. |
| 370 |
onExit( |
| 371 |
() => { |
| 372 |
this.writeCoverageFile() |
| 373 |
selfCoverageHelper.onExit() |
| 374 |
}, |
| 375 |
{ alwaysLast: true } |
| 376 |
) |
| 377 |
} |
| 378 |
|
| 379 |
wrap (bin) { |
| 380 |
process.env.NYC_PROCESS_ID = this.processInfo.uuid |
| 381 |
// This is a bug with the spawn-wrap method where |
| 382 |
// we cannot force propagation of NYC_PROCESS_ID. |
| 383 |
if (!this.config.useSpawnWrap) { |
| 384 |
const updateVariable = require('./lib/register-env.js') |
| 385 |
updateVariable('NYC_PROCESS_ID') |
| 386 |
} |
| 387 |
this._addRequireHooks() |
| 388 |
this._wrapExit() |
| 389 |
this._loadAdditionalModules() |
| 390 |
return this |
| 391 |
} |
| 392 |
|
| 393 |
writeCoverageFile () { |
| 394 |
var coverage = coverageFinder() |
| 395 |
|
| 396 |
// Remove any files that should be excluded but snuck into the coverage |
| 397 |
Object.keys(coverage).forEach(function (absFile) { |
| 398 |
if (!this.exclude.shouldInstrument(absFile)) { |
| 399 |
delete coverage[absFile] |
| 400 |
} |
| 401 |
}, this) |
| 402 |
|
| 403 |
if (this.cache) { |
| 404 |
Object.keys(coverage).forEach(function (absFile) { |
| 405 |
if (this.hashCache[absFile] && coverage[absFile]) { |
| 406 |
coverage[absFile].contentHash = this.hashCache[absFile] |
| 407 |
} |
| 408 |
}, this) |
| 409 |
} |
| 410 |
|
| 411 |
var id = this.processInfo.uuid |
| 412 |
var coverageFilename = path.resolve(this.tempDirectory(), id + '.json') |
| 413 |
|
| 414 |
fs.writeFileSync( |
| 415 |
coverageFilename, |
| 416 |
JSON.stringify(coverage), |
| 417 |
'utf-8' |
| 418 |
) |
| 419 |
|
| 420 |
this.processInfo.coverageFilename = coverageFilename |
| 421 |
this.processInfo.files = Object.keys(coverage) |
| 422 |
this.processInfo.saveSync() |
| 423 |
} |
| 424 |
|
| 425 |
async getCoverageMapFromAllCoverageFiles (baseDirectory) { |
| 426 |
const map = libCoverage.createCoverageMap({}) |
| 427 |
const files = await this.coverageFiles(baseDirectory) |
| 428 |
|
| 429 |
await pMap( |
| 430 |
files, |
| 431 |
async f => { |
| 432 |
const report = await this.coverageFileLoad(f, baseDirectory) |
| 433 |
map.merge(report) |
| 434 |
}, |
| 435 |
{ concurrency: os.cpus().length } |
| 436 |
) |
| 437 |
|
| 438 |
map.data = await this.sourceMaps.remapCoverage(map.data) |
| 439 |
|
| 440 |
// depending on whether source-code is pre-instrumented |
| 441 |
// or instrumented using a JIT plugin like @babel/require |
| 442 |
// you may opt to exclude files after applying |
| 443 |
// source-map remapping logic. |
| 444 |
if (this.config.excludeAfterRemap) { |
| 445 |
map.filter(filename => this.exclude.shouldInstrument(filename)) |
| 446 |
} |
| 447 |
|
| 448 |
return map |
| 449 |
} |
| 450 |
|
| 451 |
async report () { |
| 452 |
const libReport = require('istanbul-lib-report') |
| 453 |
const reports = require('istanbul-reports') |
| 454 |
|
| 455 |
const context = libReport.createContext({ |
| 456 |
dir: this.reportDirectory(), |
| 457 |
watermarks: this.config.watermarks, |
| 458 |
coverageMap: await this.getCoverageMapFromAllCoverageFiles() |
| 459 |
}) |
| 460 |
|
| 461 |
this.reporter.forEach((_reporter) => { |
| 462 |
reports.create(_reporter, { |
| 463 |
skipEmpty: this.config.skipEmpty, |
| 464 |
skipFull: this.config.skipFull, |
| 465 |
projectRoot: this.cwd, |
| 466 |
maxCols: process.stdout.columns || 100 |
| 467 |
}).execute(context) |
| 468 |
}) |
| 469 |
|
| 470 |
if (this._showProcessTree) { |
| 471 |
await this.showProcessTree() |
| 472 |
} |
| 473 |
} |
| 474 |
|
| 475 |
async writeProcessIndex () { |
| 476 |
const db = new ProcessDB(this.processInfo.directory) |
| 477 |
await db.writeIndex() |
| 478 |
} |
| 479 |
|
| 480 |
async showProcessTree () { |
| 481 |
const db = new ProcessDB(this.processInfo.directory) |
| 482 |
console.log(await db.renderTree(this)) |
| 483 |
} |
| 484 |
|
| 485 |
async checkCoverage (thresholds, perFile) { |
| 486 |
const map = await this.getCoverageMapFromAllCoverageFiles() |
| 487 |
|
| 488 |
if (perFile) { |
| 489 |
map.files().forEach(file => { |
| 490 |
// ERROR: Coverage for lines (90.12%) does not meet threshold (120%) for index.js |
| 491 |
this._checkCoverage(map.fileCoverageFor(file).toSummary(), thresholds, file) |
| 492 |
}) |
| 493 |
} else { |
| 494 |
// ERROR: Coverage for lines (90.12%) does not meet global threshold (120%) |
| 495 |
this._checkCoverage(map.getCoverageSummary(), thresholds) |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
_checkCoverage (summary, thresholds, file) { |
| 500 |
Object.keys(thresholds).forEach(function (key) { |
| 501 |
var coverage = summary[key].pct |
| 502 |
if (coverage < thresholds[key]) { |
| 503 |
process.exitCode = 1 |
| 504 |
if (file) { |
| 505 |
console.error('ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet threshold (' + thresholds[key] + '%) for ' + file) |
| 506 |
} else { |
| 507 |
console.error('ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet global threshold (' + thresholds[key] + '%)') |
| 508 |
} |
| 509 |
} |
| 510 |
}) |
| 511 |
} |
| 512 |
|
| 513 |
coverageFiles (baseDirectory = this.tempDirectory()) { |
| 514 |
return fs.readdir(baseDirectory) |
| 515 |
} |
| 516 |
|
| 517 |
async coverageFileLoad (filename, baseDirectory = this.tempDirectory()) { |
| 518 |
try { |
| 519 |
const report = JSON.parse(await fs.readFile(path.resolve(baseDirectory, filename)), 'utf8') |
| 520 |
await this.sourceMaps.reloadCachedSourceMaps(report) |
| 521 |
return report |
| 522 |
} catch (error) { |
| 523 |
return {} |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
// TODO: Remove from nyc v16 |
| 528 |
async coverageData (baseDirectory) { |
| 529 |
const files = await this.coverageFiles(baseDirectory) |
| 530 |
return pMap( |
| 531 |
files, |
| 532 |
f => this.coverageFileLoad(f, baseDirectory), |
| 533 |
{ concurrency: os.cpus().length } |
| 534 |
) |
| 535 |
} |
| 536 |
|
| 537 |
tempDirectory () { |
| 538 |
return path.resolve(this.cwd, this._tempDirectory) |
| 539 |
} |
| 540 |
|
| 541 |
reportDirectory () { |
| 542 |
return path.resolve(this.cwd, this._reportDir) |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
module.exports = NYC |