Add helper to instrument electron.asar

This commit is contained in:
Kevin Sawicki 2016-08-02 11:03:47 -07:00
parent afdff69482
commit 5b5d51ecf4

View file

@ -1,12 +1,16 @@
const asar = require('asar')
const fs = require('fs')
const glob = require('glob')
const mkdirp = require('mkdirp')
const path = require('path')
const {ipcRenderer} = require('electron')
const {Collector, Instrumenter, Reporter} = require('istanbul')
const outputPath = path.join(__dirname, '..', '..', 'out', 'coverage')
const libPath = path.join(__dirname, '..', '..', 'lib')
// Add unrequired files to the coverage report so all files are present there
const addUnrequiredFiles = (coverage) => {
const instrumenter = new Instrumenter()
const transformer = instrumenter.instrumentSync.bind(instrumenter)
const libPath = path.join(__dirname, '..', '..', 'lib')
glob.sync('**/*.js', {cwd: libPath}).map(function (relativePath) {
@ -14,7 +18,7 @@ const addUnrequiredFiles = (coverage) => {
}).filter(function (filePath) {
return coverage[filePath] == null
}).forEach(function (filePath) {
transformer(fs.readFileSync(filePath, 'utf8'), filePath)
instrumenter.instrumentSync(fs.readFileSync(filePath, 'utf8'), filePath)
// When instrumenting the code, istanbul will give each FunctionDeclaration
// a value of 1 in coverState.s,presumably to compensate for function
@ -28,6 +32,7 @@ const addUnrequiredFiles = (coverage) => {
})
}
// Generate a code coverage report in out/coverage/lcov-report
exports.generate = () => {
const coverage = window.__coverage__
if (coverage == null) return
@ -36,10 +41,35 @@ exports.generate = () => {
const collector = new Collector()
collector.add(coverage)
const {ipcRenderer} = require('electron')
collector.add(ipcRenderer.sendSync('get-coverage'))
const outPath = path.join(__dirname, '..', '..', 'out', 'coverage')
const reporter = new Reporter(null, outPath)
const reporter = new Reporter(null, outputPath)
reporter.addAll(['text', 'lcov'])
reporter.write(collector, true, function () {})
}
// Generate an instrumented .asar file for all the files in lib/ and save it
// to out/coverage/electron-instrumented.asar
exports.instrument = () => {
const instrumenter = new Instrumenter()
glob.sync('**/*.js', {cwd: libPath}).forEach(function (relativePath) {
const rawPath = path.join(libPath, relativePath)
const raw = fs.readFileSync(rawPath, 'utf8')
const generatedPath = path.join(outputPath, 'lib', relativePath)
const generated = instrumenter.instrumentSync(raw, rawPath)
mkdirp.sync(path.dirname(generatedPath))
fs.writeFileSync(generatedPath, generated)
})
const asarPath = path.join(outputPath, 'electron-instrumented.asar')
asar.createPackageWithOptions(path.join(outputPath, 'lib'), asarPath, {}, function (error) {
if (error) {
console.error(error.stack || error)
process.exit(1)
}
})
}