|
| 1 | +'use strict'; |
| 2 | +const path = require('path'); |
| 3 | +const { mkdirSync, writeFileSync } = require('fs'); |
| 4 | +// TODO(addaleax): add support for coverage to worker threads. |
| 5 | +const hasInspector = process.config.variables.v8_enable_inspector === 1 && |
| 6 | + require('internal/worker').isMainThread; |
| 7 | +let inspector = null; |
| 8 | +if (hasInspector) inspector = require('inspector'); |
| 9 | + |
| 10 | +let session; |
| 11 | + |
| 12 | +function writeCoverage() { |
| 13 | + if (!session) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + const filename = `coverage-${process.pid}-${Date.now()}.json`; |
| 18 | + try { |
| 19 | + // TODO(bcoe): switch to mkdirp once #22302 is addressed. |
| 20 | + mkdirSync(process.env.NODE_V8_COVERAGE); |
| 21 | + } catch (err) { |
| 22 | + if (err.code !== 'EEXIST') { |
| 23 | + console.error(err); |
| 24 | + return; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + const target = path.join(process.env.NODE_V8_COVERAGE, filename); |
| 29 | + |
| 30 | + try { |
| 31 | + session.post('Profiler.takePreciseCoverage', (err, coverageInfo) => { |
| 32 | + if (err) return console.error(err); |
| 33 | + try { |
| 34 | + writeFileSync(target, JSON.stringify(coverageInfo)); |
| 35 | + } catch (err) { |
| 36 | + console.error(err); |
| 37 | + } |
| 38 | + }); |
| 39 | + } catch (err) { |
| 40 | + console.error(err); |
| 41 | + } finally { |
| 42 | + session.disconnect(); |
| 43 | + session = null; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +exports.writeCoverage = writeCoverage; |
| 48 | + |
| 49 | +function setup() { |
| 50 | + if (!hasInspector) { |
| 51 | + console.warn('coverage currently only supported in main thread'); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + session = new inspector.Session(); |
| 56 | + session.connect(); |
| 57 | + session.post('Profiler.enable'); |
| 58 | + session.post('Profiler.startPreciseCoverage', { callCount: true, |
| 59 | + detailed: true }); |
| 60 | + |
| 61 | + const reallyReallyExit = process.reallyExit; |
| 62 | + |
| 63 | + process.reallyExit = function(code) { |
| 64 | + writeCoverage(); |
| 65 | + reallyReallyExit(code); |
| 66 | + }; |
| 67 | + |
| 68 | + process.on('exit', writeCoverage); |
| 69 | +} |
| 70 | + |
| 71 | +exports.setup = setup; |
0 commit comments