forked from cypress-io/code-coverage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task-utils.js
404 lines (354 loc) · 11.3 KB
/
task-utils.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
// helper functions to use from "task.js" plugins code
// that need access to the file system
// @ts-check
/// <reference types="cypress" />
const { readFileSync, writeFileSync, existsSync } = require('fs')
const { isAbsolute, resolve, join } = require('path')
const debug = require('debug')('code-coverage')
const chalk = require('chalk')
const globby = require('globby')
const yaml = require('js-yaml')
const {
combineNycOptions,
defaultNycOptions,
fileCoveragePlaceholder
} = require('./common-utils')
function readNycOptions(workingDirectory) {
const pkgFilename = join(workingDirectory, 'package.json')
const pkg = existsSync(pkgFilename)
? JSON.parse(readFileSync(pkgFilename, 'utf8'))
: {}
const pkgNycOptions = pkg.nyc || {}
const nycrcFilename = join(workingDirectory, '.nycrc')
const nycrc = existsSync(nycrcFilename)
? JSON.parse(readFileSync(nycrcFilename, 'utf8'))
: {}
const nycrcJsonFilename = join(workingDirectory, '.nycrc.json')
const nycrcJson = existsSync(nycrcJsonFilename)
? JSON.parse(readFileSync(nycrcJsonFilename, 'utf8'))
: {}
const nycrcYamlFilename = join(workingDirectory, '.nycrc.yaml')
let nycrcYaml = {}
if (existsSync(nycrcYamlFilename)) {
try {
nycrcYaml = yaml.safeLoad(readFileSync(nycrcYamlFilename, 'utf8'))
} catch (error) {
throw new Error(`Failed to load .nycrc.yaml: ${error.message}`)
}
}
const nycrcYmlFilename = join(workingDirectory, '.nycrc.yml')
let nycrcYml = {}
if (existsSync(nycrcYmlFilename)) {
try {
nycrcYml = yaml.safeLoad(readFileSync(nycrcYmlFilename, 'utf8'))
} catch (error) {
throw new Error(`Failed to load .nycrc.yml: ${error.message}`)
}
}
const nycConfigFilename = join(workingDirectory, 'nyc.config.js')
let nycConfig = {}
if (existsSync(nycConfigFilename)) {
try {
nycConfig = require(nycConfigFilename)
} catch (error) {
throw new Error(`Failed to load nyc.config.js: ${error.message}`)
}
}
const nycConfigCommonJsFilename = join(workingDirectory, 'nyc.config.cjs')
let nycConfigCommonJs = {}
if (existsSync(nycConfigCommonJsFilename)) {
try {
nycConfigCommonJs = require(nycConfigCommonJsFilename)
} catch (error) {
throw new Error(`Failed to load nyc.config.cjs: ${error.message}`)
}
}
const nycOptions = combineNycOptions(
defaultNycOptions,
nycrc,
nycrcJson,
nycrcYaml,
nycrcYml,
nycConfig,
nycConfigCommonJs,
pkgNycOptions
)
debug('combined NYC options %o', nycOptions)
return nycOptions
}
function checkAllPathsNotFound(nycFilename) {
const nycCoverage = JSON.parse(readFileSync(nycFilename, 'utf8'))
const coverageKeys = Object.keys(nycCoverage)
if (!coverageKeys.length) {
debug('⚠️ file %s has no coverage information', nycFilename)
return
}
const allFilesAreMissing = coverageKeys.every((key, k) => {
const coverage = nycCoverage[key]
return !existsSync(coverage.path)
})
debug(
'in file %s all files are not found? %o',
nycFilename,
allFilesAreMissing
)
return allFilesAreMissing
}
/**
* A small debug utility to inspect paths saved in NYC output JSON file
*/
function showNycInfo(nycFilename) {
const nycCoverage = JSON.parse(readFileSync(nycFilename, 'utf8'))
const coverageKeys = Object.keys(nycCoverage)
if (!coverageKeys.length) {
console.error(
'⚠️ file %s has no coverage information',
chalk.yellow(nycFilename)
)
console.error(
'Did you forget to instrument your web application? Read %s',
chalk.blue(
'https://github.com/cypress-io/code-coverage#instrument-your-application'
)
)
return
}
debug('NYC file %s has %d key(s)', nycFilename, coverageKeys.length)
const maxPrintKeys = 3
const showKeys = coverageKeys.slice(0, maxPrintKeys)
showKeys.forEach((key, k) => {
const coverage = nycCoverage[key]
// printing a few found keys and file paths from the coverage file
// will make debugging any problems much much easier
if (k < maxPrintKeys) {
debug('%d key %s file path %s', k + 1, key, coverage.path)
}
})
}
/**
* Looks at all coverage objects in the given JSON coverage file
* and if the file is relative, and exists, changes its path to
* be absolute.
*/
function resolveRelativePaths(nycFilename) {
const nycCoverage = JSON.parse(readFileSync(nycFilename, 'utf8'))
const coverageKeys = Object.keys(nycCoverage)
if (!coverageKeys.length) {
debug('⚠️ file %s has no coverage information', nycFilename)
return
}
debug('NYC file %s has %d key(s)', nycFilename, coverageKeys.length)
let changed
coverageKeys.forEach((key, k) => {
const coverage = nycCoverage[key]
if (!coverage.path) {
debug('key %s does not have path', key)
return
}
if (!isAbsolute(coverage.path)) {
if (existsSync(coverage.path)) {
debug('resolving path %s', coverage.path)
coverage.path = resolve(coverage.path)
changed = true
}
return
}
// path is absolute, let's check if it exists
if (!existsSync(coverage.path)) {
debug('⚠️ cannot find file %s with hash %s', coverage.path, coverage.hash)
}
})
if (changed) {
debug('resolveRelativePaths saving updated file %s', nycFilename)
debug('there are %d keys in the file', coverageKeys.length)
writeFileSync(
nycFilename,
JSON.stringify(nycCoverage, null, 2) + '\n',
'utf8'
)
}
}
/**
* @param {string[]} filepaths
* @returns {string | undefined} common prefix that corresponds to current folder
*/
function findCommonRoot(filepaths) {
if (!filepaths.length) {
debug('cannot find common root without any files')
return
}
// assuming / as file separator
const splitParts = filepaths.map((name) => name.split('/'))
const lengths = splitParts.map((arr) => arr.length)
const shortestLength = Math.min.apply(null, lengths)
debug('shorted file path has %d parts', shortestLength)
const cwd = process.cwd()
let commonPrefix = []
let foundCurrentFolder
for (let k = 0; k < shortestLength; k += 1) {
const part = splitParts[0][k]
const prefix = commonPrefix.concat(part).join('/')
debug('testing prefix %o', prefix)
const allFilesStart = filepaths.every((name) => name.startsWith(prefix))
if (!allFilesStart) {
debug('stopped at non-common prefix %s', prefix)
break
}
commonPrefix.push(part)
const removedPrefixNames = filepaths.map((filepath) =>
filepath.slice(prefix.length)
)
debug('removedPrefix %o', removedPrefixNames)
const foundAllPaths = removedPrefixNames.every((filepath) =>
existsSync(join(cwd, filepath))
)
debug('all files found at %s? %o', prefix, foundAllPaths)
if (foundAllPaths) {
debug('found prefix that matches current folder: %s', prefix)
foundCurrentFolder = prefix
break
}
}
return foundCurrentFolder
}
function tryFindingLocalFiles(nycFilename) {
const nycCoverage = JSON.parse(readFileSync(nycFilename, 'utf8'))
const coverageKeys = Object.keys(nycCoverage)
const filenames = coverageKeys.map((key) => nycCoverage[key].path)
const commonFolder = findCommonRoot(filenames)
if (!commonFolder) {
debug('could not find common folder %s', commonFolder)
return
}
const cwd = process.cwd()
debug(
'found common folder %s that matches current working directory %s',
commonFolder,
cwd
)
const length = commonFolder.length
let changed
coverageKeys.forEach((key) => {
const from = nycCoverage[key].path
if (from.startsWith(commonFolder)) {
const to = join(cwd, from.slice(length))
// ? Do we need to replace the "key" in the coverage object or can we just replace the "path"?
nycCoverage[key].path = to
debug('replaced %s -> %s', from, to)
changed = true
}
})
if (changed) {
debug('tryFindingLocalFiles saving updated file %s', nycFilename)
debug('there are %d keys in the file', coverageKeys.length)
writeFileSync(
nycFilename,
JSON.stringify(nycCoverage, null, 2) + '\n',
'utf8'
)
}
}
/**
* Tries to find source files to be included in the final coverage report
* using NYC options: extension list, include and exclude.
*/
function findSourceFiles(nycOptions) {
debug('include all files options: %o', {
all: nycOptions.all,
include: nycOptions.include,
exclude: nycOptions.exclude,
extension: nycOptions.extension
})
if (!Array.isArray(nycOptions.extension)) {
console.error(
'Expected NYC "extension" option to be a list of file extensions'
)
console.error(nycOptions)
return []
}
let patterns = []
if (Array.isArray(nycOptions.include)) {
patterns = patterns.concat(nycOptions.include)
} else if (typeof nycOptions.include === 'string') {
patterns.push(nycOptions.include)
} else {
debug('using default list of extensions')
nycOptions.extension.forEach((extension) => {
patterns.push('**/*' + extension)
})
}
if (Array.isArray(nycOptions.exclude)) {
const negated = nycOptions.exclude.map((s) => '!' + s)
patterns = patterns.concat(negated)
} else if (typeof nycOptions.exclude === 'string') {
patterns.push('!' + nycOptions.exclude)
}
// always exclude node_modules
// https://github.com/istanbuljs/nyc#including-files-within-node_modules
patterns.push('!**/node_modules/**')
debug('searching files to include using patterns %o', patterns)
const allFiles = globby.sync(patterns, { absolute: true })
return allFiles
}
/**
* If the website or unit tests did not load ALL files we need to
* include, then we should include the missing files ourselves
* before generating the report.
*
* @see https://github.com/cypress-io/code-coverage/issues/207
*/
function includeAllFiles(nycFilename, nycOptions) {
if (!nycOptions.all) {
debug('NYC "all" option is not set, skipping including all files')
return
}
const allFiles = findSourceFiles(nycOptions)
if (debug.enabled) {
debug('found %d file(s)', allFiles.length)
console.error(allFiles.join('\n'))
}
if (!allFiles.length) {
debug('no files found, hoping for the best')
return
}
const nycCoverage = JSON.parse(readFileSync(nycFilename, 'utf8'))
const coverageKeys = Object.keys(nycCoverage)
const coveredPaths = coverageKeys.map((key) =>
nycCoverage[key].path.replace(/\\/g, '/')
)
debug('coverage has %d record(s)', coveredPaths.length)
// report on first couple of entries
if (debug.enabled) {
console.error('coverage has the following first paths')
console.error(coveredPaths.slice(0, 4).join('\n'))
}
let changed
allFiles.forEach((fullPath) => {
if (coveredPaths.includes(fullPath)) {
// all good, this file exists in coverage object
return
}
debug('adding empty coverage for file %s', fullPath)
changed = true
// insert placeholder object for now
const placeholder = fileCoveragePlaceholder(fullPath)
nycCoverage[fullPath] = placeholder
})
if (changed) {
debug('includeAllFiles saving updated file %s', nycFilename)
debug('there are %d keys in the file', Object.keys(nycCoverage).length)
writeFileSync(
nycFilename,
JSON.stringify(nycCoverage, null, 2) + '\n',
'utf8'
)
}
}
module.exports = {
showNycInfo,
resolveRelativePaths,
checkAllPathsNotFound,
tryFindingLocalFiles,
readNycOptions,
includeAllFiles
}