-
-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathindex.js
executable file
·404 lines (328 loc) · 10.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* global __coverage__ */
var fs = require('fs')
var glob = require('glob')
var micromatch = require('micromatch')
var mkdirp = require('mkdirp')
var Module = require('module')
var appendTransform = require('append-transform')
var cachingTransform = require('caching-transform')
var path = require('path')
var rimraf = require('rimraf')
var onExit = require('signal-exit')
var resolveFrom = require('resolve-from')
var arrify = require('arrify')
var SourceMapCache = require('./lib/source-map-cache')
var convertSourceMap = require('convert-source-map')
var md5hex = require('md5-hex')
var findCacheDir = require('find-cache-dir')
var js = require('default-require-extensions/js')
var pkgUp = require('pkg-up')
var yargs = require('yargs/yargs')
/* istanbul ignore next */
if (/index\.covered\.js$/.test(__filename)) {
require('./lib/self-coverage-helper')
}
function NYC (opts) {
var config = this._loadConfig(opts || {})
this._istanbul = config.istanbul
this.subprocessBin = config.subprocessBin || path.resolve(__dirname, './bin/nyc.js')
this._tempDirectory = config.tempDirectory || './.nyc_output'
this._reportDir = config.reportDir
this.cwd = config.cwd
this.reporter = arrify(config.reporter || 'text')
// load exclude stanza from config.
this.include = false
if (config.include) {
this.include = this._prepGlobPatterns(arrify(config.include))
}
this.exclude = this._prepGlobPatterns(
['**/node_modules/**'].concat(arrify(config.exclude || ['test/**', 'test{,-*}.js']))
)
this.cacheDirectory = findCacheDir({name: 'nyc', cwd: this.cwd})
this.enableCache = Boolean(this.cacheDirectory && (config.enableCache === true || process.env.NYC_CACHE === 'enable'))
// require extensions can be provided as config in package.json.
this.require = arrify(config.require)
this.extensions = arrify(config.extension).concat('.js').map(function (ext) {
return ext.toLowerCase()
})
this.transforms = this.extensions.reduce(function (transforms, ext) {
transforms[ext] = this._createTransform(ext)
return transforms
}.bind(this), {})
this.sourceMapCache = new SourceMapCache()
this.hashCache = {}
this.loadedMaps = null
}
NYC.prototype._loadConfig = function (opts) {
var cwd = opts.cwd || process.env.NYC_CWD || process.cwd()
var pkgPath = pkgUp.sync(cwd)
if (pkgPath) {
cwd = path.dirname(pkgPath)
}
opts.cwd = cwd
return yargs([])
.pkgConf('nyc', cwd)
.default(opts)
.argv
}
NYC.prototype._createTransform = function (ext) {
var _this = this
return cachingTransform({
salt: JSON.stringify({
istanbul: require('istanbul/package.json').version,
nyc: require('./package.json').version
}),
hash: function (code, metadata, salt) {
var hash = md5hex([code, metadata.filename, salt])
_this.hashCache[metadata.filename] = hash
return hash
},
factory: this._transformFactory.bind(this),
cacheDir: this.cacheDirectory,
disableCache: !this.enableCache,
ext: ext
})
}
NYC.prototype._loadAdditionalModules = function () {
var _this = this
this.require.forEach(function (r) {
// first attempt to require the module relative to
// the directory being instrumented.
var p = resolveFrom(_this.cwd, r)
if (p) {
require(p)
return
}
// now try other locations, .e.g, the nyc node_modules folder.
require(r)
})
}
NYC.prototype.instrumenter = function () {
return this._instrumenter || (this._instrumenter = this._createInstrumenter())
}
NYC.prototype._createInstrumenter = function () {
var configFile = path.resolve(this.cwd, './.istanbul.yml')
if (!fs.existsSync(configFile)) configFile = undefined
var istanbul = this.istanbul()
var instrumenterConfig = istanbul.config.loadFile(configFile).instrumentation.config
return new istanbul.Instrumenter({
coverageVariable: '__coverage__',
embedSource: instrumenterConfig['embed-source'],
noCompact: !instrumenterConfig.compact,
preserveComments: instrumenterConfig['preserve-comments']
})
}
NYC.prototype._prepGlobPatterns = function (patterns) {
if (!patterns) return patterns
var result = []
function add (pattern) {
if (result.indexOf(pattern) === -1) {
result.push(pattern)
}
}
patterns.forEach(function (pattern) {
// Allow gitignore style of directory exclusion
if (!/\/\*\*$/.test(pattern)) {
add(pattern.replace(/\/$/, '') + '/**')
}
add(pattern)
})
return result
}
NYC.prototype.addFile = function (filename) {
var relFile = path.relative(this.cwd, filename)
var source = this._readTranspiledSource(path.resolve(this.cwd, filename))
var instrumentedSource = this._maybeInstrumentSource(source, filename, relFile)
return {
instrument: !!instrumentedSource,
relFile: relFile,
content: instrumentedSource || source
}
}
NYC.prototype._readTranspiledSource = function (path) {
var source = null
Module._extensions['.js']({
_compile: function (content, filename) {
source = content
}
}, path)
return source
}
NYC.prototype.shouldInstrumentFile = function (filename, relFile) {
// Don't instrument files that are outside of the current working directory.
if (/^\.\./.test(path.relative(this.cwd, filename))) return false
relFile = relFile.replace(/^\.[\\\/]/, '') // remove leading './' or '.\'.
return (!this.include || micromatch.any(relFile, this.include)) && !micromatch.any(relFile, this.exclude)
}
NYC.prototype.addAllFiles = function () {
var _this = this
this._loadAdditionalModules()
var pattern = null
if (this.extensions.length === 1) {
pattern = '**/*' + this.extensions[0]
} else {
pattern = '**/*{' + this.extensions.join() + '}'
}
glob.sync(pattern, {cwd: this.cwd, nodir: true, ignore: this.exclude}).forEach(function (filename) {
var obj = _this.addFile(path.join(_this.cwd, filename))
if (obj.instrument) {
module._compile(
_this.instrumenter().getPreamble(obj.content, obj.relFile),
filename
)
}
})
this.writeCoverageFile()
}
NYC.prototype._maybeInstrumentSource = function (code, filename, relFile) {
var instrument = this.shouldInstrumentFile(filename, relFile)
if (!instrument) {
return null
}
var ext, transform
for (ext in this.transforms) {
if (filename.toLowerCase().substr(-ext.length) === ext) {
transform = this.transforms[ext]
break
}
}
return transform ? transform(code, {filename: filename, relFile: relFile}) : null
}
NYC.prototype._transformFactory = function (cacheDir) {
var _this = this
var instrumenter = this.instrumenter()
return function (code, metadata, hash) {
var filename = metadata.filename
var sourceMap = convertSourceMap.fromSource(code) || convertSourceMap.fromMapFileSource(code, path.dirname(filename))
if (sourceMap) {
if (hash) {
var mapPath = path.join(cacheDir, hash + '.map')
fs.writeFileSync(mapPath, sourceMap.toJSON())
} else {
_this.sourceMapCache.addMap(filename, sourceMap.toJSON())
}
}
return instrumenter.instrumentSync(code, filename)
}
}
NYC.prototype._handleJs = function (code, filename) {
var relFile = path.relative(this.cwd, filename)
return this._maybeInstrumentSource(code, filename, relFile) || code
}
NYC.prototype._wrapRequire = function () {
var handleJs = this._handleJs.bind(this)
this.extensions.forEach(function (ext) {
require.extensions[ext] = js
appendTransform(handleJs, ext)
})
}
NYC.prototype.cleanup = function () {
if (!process.env.NYC_CWD) rimraf.sync(this.tempDirectory())
}
NYC.prototype.clearCache = function () {
if (this.enableCache) {
rimraf.sync(this.cacheDirectory)
}
}
NYC.prototype.createTempDirectory = function () {
mkdirp.sync(this.tempDirectory())
}
NYC.prototype.reset = function () {
this.cleanup()
this.createTempDirectory()
}
NYC.prototype._wrapExit = function () {
var _this = this
// we always want to write coverage
// regardless of how the process exits.
onExit(function () {
_this.writeCoverageFile()
}, {alwaysLast: true})
}
NYC.prototype.wrap = function (bin) {
this._wrapRequire()
this._wrapExit()
this._loadAdditionalModules()
return this
}
NYC.prototype.writeCoverageFile = function () {
var coverage = global.__coverage__
if (typeof __coverage__ === 'object') coverage = __coverage__
if (!coverage) return
if (this.enableCache) {
Object.keys(coverage).forEach(function (absFile) {
if (this.hashCache[absFile] && coverage[absFile]) {
coverage[absFile].contentHash = this.hashCache[absFile]
}
}, this)
} else {
this.sourceMapCache.applySourceMaps(coverage)
}
fs.writeFileSync(
path.resolve(this.tempDirectory(), './', process.pid + '.json'),
JSON.stringify(coverage),
'utf-8'
)
}
NYC.prototype.istanbul = function () {
return this._istanbul || (this._istanbul = require('istanbul'))
}
NYC.prototype.report = function (cb, _collector, _reporter) {
cb = cb || function () {}
var istanbul = this.istanbul()
var collector = _collector || new istanbul.Collector()
var reporter = _reporter || new istanbul.Reporter(null, this._reportDir)
this._loadReports().forEach(function (report) {
collector.add(report)
})
this.reporter.forEach(function (_reporter) {
reporter.add(_reporter)
})
reporter.write(collector, true, cb)
}
NYC.prototype._loadReports = function () {
var _this = this
var files = fs.readdirSync(this.tempDirectory())
var cacheDir = _this.cacheDirectory
var loadedMaps = this.loadedMaps || (this.loadedMaps = {})
return files.map(function (f) {
var report
try {
report = JSON.parse(fs.readFileSync(
path.resolve(_this.tempDirectory(), './', f),
'utf-8'
))
} catch (e) { // handle corrupt JSON output.
return {}
}
Object.keys(report).forEach(function (absFile) {
var fileReport = report[absFile]
if (fileReport && fileReport.contentHash) {
var hash = fileReport.contentHash
if (!(hash in loadedMaps)) {
try {
var mapPath = path.join(cacheDir, hash + '.map')
loadedMaps[hash] = JSON.parse(fs.readFileSync(mapPath, 'utf8'))
} catch (e) {
// set to false to avoid repeatedly trying to load the map
loadedMaps[hash] = false
}
}
if (loadedMaps[hash]) {
_this.sourceMapCache.addMap(absFile, loadedMaps[hash])
}
}
})
_this.sourceMapCache.applySourceMaps(report)
return report
})
}
NYC.prototype.tempDirectory = function () {
return path.resolve(this.cwd, './', this._tempDirectory)
}
NYC.prototype.mungeArgs = function (yargv) {
var argv = process.argv.slice(1)
argv = argv.slice(argv.indexOf(yargv._[0]))
return argv
}
module.exports = NYC