Commit 97ebaf16 by 刘旭阳

Merge branch '0.0.6' into 'master'

feat:增加插桩增量代码过滤 See merge request !8
parents 25a18762 6981da8d
{ {
"name": "babel-plugin-ry-istanbul-web", "name": "babel-plugin-ry-istanbul-web",
"version": "0.0.5", "version": "0.0.6",
"author": "Thai Pangsakulyanont @dtinth", "author": "Thai Pangsakulyanont @dtinth",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"description": "A babel plugin that adds istanbul instrumentation to ES6 code", "description": "A babel plugin that adds istanbul instrumentation to ES6 code",
......
...@@ -2,8 +2,8 @@ const path = require('path') ...@@ -2,8 +2,8 @@ const path = require('path')
import { realpathSync } from 'fs' import { realpathSync } from 'fs'
import { execFileSync, execSync } from 'child_process' import { execFileSync, execSync } from 'child_process'
import { declare } from '@babel/helper-plugin-utils' import { declare } from '@babel/helper-plugin-utils'
// import { programVisitor } from './istanlibment' import { programVisitor } from './dist'
import { programVisitor } from 'istanbul-lib-instrument' // import { programVisitor } from 'istanbul-lib-instrument'
import TestExclude from 'test-exclude' import TestExclude from 'test-exclude'
import schema from '@istanbuljs/schema' import schema from '@istanbuljs/schema'
import parseDiffData from './parse-diff' import parseDiffData from './parse-diff'
...@@ -94,6 +94,15 @@ function makeShouldSkip () { ...@@ -94,6 +94,15 @@ function makeShouldSkip () {
return !exclude.shouldInstrument(file) return !exclude.shouldInstrument(file)
} }
} }
function isValue(item, isNumber = false, defaultNumber) {
let data = ''
if (isNumber) {
data = item ? Number(item) : defaultNumber
} else {
data = item ? item : defaultNumber
}
return data
}
export default declare(api => { export default declare(api => {
api.assertVersion(7) api.assertVersion(7)
const shouldSkip = makeShouldSkip() const shouldSkip = makeShouldSkip()
...@@ -120,28 +129,28 @@ export default declare(api => { ...@@ -120,28 +129,28 @@ export default declare(api => {
if (item.indexOf('IS_PITCHING_PILE') !== -1) { if (item.indexOf('IS_PITCHING_PILE') !== -1) {
processData.IS_PITCHING_PILE = isItem processData.IS_PITCHING_PILE = isItem
} }
if (item.indexOf('PROSRC') !== -1) { if (item.indexOf('BRANCH') !== -1) {
processData.PROSRC = process.env[item] processData.BRANCH = process.env[item]
} }
// Object.keys(processData).length // Object.keys(processData).length
}) })
// 全局变量优先 // 全局变量优先
if (Object.keys(processData).length) { if (Object.keys(processData).length) {
BRANCH_DATA = processData.BRANCH BRANCH_DATA = isValue(processData.BRANCH, false, BRANCH_DATA)
INCREMENT_DATA = processData.INCREMENT INCREMENT_DATA = isValue(processData.INCREMENT, false, INCREMENT_DATA)
IS_PITCHING_PILE_DATA = processData.IS_PITCHING_PILE IS_PITCHING_PILE_DATA = isValue(processData.IS_PITCHING_PILE, false, IS_PITCHING_PILE_DATA)
} else if (Object.keys(instrmenttation).length) { } else if (Object.keys(instrmenttation).length) {
BRANCH_DATA = instrmenttation.BRANCH BRANCH_DATA = isValue(instrmenttation.BRANCH, false, BRANCH_DATA)
INCREMENT_DATA = instrmenttation.INCREMENT INCREMENT_DATA = isValue(instrmenttation.INCREMENT, false, INCREMENT_DATA)
IS_PITCHING_PILE_DATA = instrmenttation.IS_PITCHING_PILE IS_PITCHING_PILE_DATA = isValue(instrmenttation.IS_PITCHING_PILE, false, IS_PITCHING_PILE_DATA)
} }
// instrumenttation (branch: git diff 跟那个分支对比, increment 是否开启增量代码检测) 拿配置到底是全量代码还是增量代码 // instrumenttation (branch: git diff 跟那个分支对比, increment 是否开启增量代码检测) 拿配置到底是全量代码还是增量代码
if (!IS_PITCHING_PILE_DATA || IS_PITCHING_PILE_DATA === 'false') { if (!IS_PITCHING_PILE_DATA || IS_PITCHING_PILE_DATA === 'false') {
return false return false
} }
// const changeList = [] const changeList = []
// 下面的是零时的 // 下面的是零时的
// const gitDiffCode = execSync(`git diff ${branch}`) // // const gitDiffCode = execSync(`git diff ${branch}`)
// const diffData = parseDiffData(gitDiffCode.toString()) // const diffData = parseDiffData(gitDiffCode.toString())
// diffScreen = diffData.find(item => { // diffScreen = diffData.find(item => {
// return realPath.indexOf(item.to) > -1 // return realPath.indexOf(item.to) > -1
...@@ -172,31 +181,36 @@ export default declare(api => { ...@@ -172,31 +181,36 @@ export default declare(api => {
} }
}) })
// 后增加|| !increment这个条件判断条件后面加上 // 后增加|| !increment这个条件判断条件后面加上
// if (diffScreen !== null && increment) { if (diffScreen !== null && !diffScreen && (INCREMENT_DATA || INCREMENT_DATA === 'true')) {
// if (diffScreen) { // if (diffScreen) {
// if (Array.isArray(diffScreen && diffScreen.chunks)) { if (Array.isArray(diffScreen && diffScreen.chunks)) {
// diffScreen.chunks.forEach(item => { diffScreen.chunks.forEach(item => {
// let changes = Array.isArray(item.changes) ? item.changes : [] let changes = Array.isArray(item.changes) ? item.changes : []
// changes.forEach(items => { changes.forEach(items => {
// if (items && items.add) { if (items && items.add) {
// changeList.push(items.ln) changeList.push(items.ln)
// } }
// }) })
// }) })
// } }
if (changeList.length) {
visitorOptions.changeList = changeList
// changeList // changeList
this.__dv__ = programVisitor(t, realPath, { this.__dv__ = programVisitor(t, realPath, {
...visitorOptions, ...visitorOptions,
inputSourceMap inputSourceMap
}) })
this.__dv__.enter(path) this.__dv__.enter(path)
// } else { }
// this.__dv__ = programVisitor(t, realPath, {
// ...visitorOptions,
// inputSourceMap
// })
// this.__dv__.enter(path)
// } // }
} else if (!INCREMENT_DATA || INCREMENT_DATA === 'false') {
visitorOptions.changeList = changeList
this.__dv__ = programVisitor(t, realPath, {
...visitorOptions,
inputSourceMap,
})
this.__dv__.enter(path)
}
}, },
exit(path) { exit(path) {
if (!this.__dv__) { if (!this.__dv__) {
......
// import { major } from 'semver';
// import { name, version } from '../package.json';
const { createHash } = require('crypto')
// function to use for creating hashes
const VERSION = '4'
const SHA = 'sha1'
// name of coverage data magic key
// const MAGIC_KEY = '_coverageSchema'
// name of coverage data magic value
// export const MAGIC_VALUE = createHash(SHA).update(name + '@' + major(version)).digest('hex');
module.exports = {
SHA,
MAGIC_KEY: '_coverageSchema',
MAGIC_VALUE: createHash(SHA)
.update('name' + '@' + VERSION)
.digest('hex')
}
const { defaults } = require('@istanbuljs/schema')
const Instrumenter = require('./instrumenter')
const programVisitor = require('./visitor')
const readInitialCoverage = require('./read-coverage')
/**
* createInstrumenter creates a new instrumenter with the
* supplied options.
* @param {Object} opts - instrumenter options. See the documentation
* for the Instrumenter class.
*/
function createInstrumenter(opts) {
return new Instrumenter(opts)
}
module.exports = {
createInstrumenter,
programVisitor,
readInitialCoverage,
defaultOpts: defaults.instrumenter
}
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
const babylon = require('babylon');
const t = require('babel-types');
const traverse = require('babel-traverse');
const generate = require('babel-generator');
const programVisitor = require('./visitor');
function defaultOpts() {
return {
coverageVariable: "__coverage__",
preserveComments: false,
compact: true,
esModules: false,
autoWrap: false,
produceSourceMap: false,
sourceMapUrlCallback: null,
debug: false
};
}
/**
* Instrumenter is the public API for the instrument library.
* It is typically used for ES5 code. For ES6 code that you
* are already running under `babel` use the coverage plugin
* instead.
* @param {Object} opts optional.
* @param {string} [opts.coverageVariable=__coverage__] name of global coverage variable.
* @param {boolean} [opts.preserveComments=false] preserve comments in output
* @param {boolean} [opts.compact=true] generate compact code.
* @param {boolean} [opts.esModules=false] set to true to instrument ES6 modules.
* @param {boolean} [opts.autoWrap=false] set to true to allow `return` statements outside of functions.
* @param {boolean} [opts.produceSourceMap=false] set to true to produce a source map for the instrumented code.
* @param {Function} [opts.sourceMapUrlCallback=null] a callback function that is called when a source map URL
* is found in the original code. This function is called with the source file name and the source map URL.
* @param {boolean} [opts.debug=false] - turn debugging on
*/
class Instrumenter {
constructor(opts=defaultOpts()) {
this.opts = this.normalizeOpts(opts);
this.fileCoverage = null;
this.sourceMap = null;
}
/**
* normalize options passed in and assign defaults.
* @param opts
* @private
*/
normalizeOpts(opts) {
const normalize = (name, defaultValue) => {
if (!opts.hasOwnProperty(name)) {
opts[name] = defaultValue;
}
};
const defOpts = defaultOpts();
Object.keys(defOpts).forEach(function (k) {
normalize(k, defOpts[k]);
});
return opts;
}
/**
* instrument the supplied code and track coverage against the supplied
* filename. It throws if invalid code is passed to it. ES5 and ES6 syntax
* is supported. To instrument ES6 modules, make sure that you set the
* `esModules` property to `true` when creating the instrumenter.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {object} [inputSourceMap] - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
* @returns {string} the instrumented code.
*/
instrumentSync(code, filename, inputSourceMap) {
if (typeof code !== 'string') {
throw new Error('Code must be a string');
}
filename = filename || String(new Date().getTime()) + '.js';
const opts = this.opts;
const ast = babylon.parse(code, {
allowReturnOutsideFunction: opts.autoWrap,
sourceType: opts.esModules ? "module" : "script"
});
const ee = programVisitor(t, filename, {
coverageVariable: opts.coverageVariable,
inputSourceMap: inputSourceMap
});
let output = {};
const visitor = {
Program: {
enter: ee.enter,
exit: function (path) {
output = ee.exit(path);
}
}
};
traverse(ast, visitor);
const generateOptions = {
compact: opts.compact,
sourceMaps: opts.produceSourceMap,
sourceFileName: filename
};
const codeMap = generate(ast, generateOptions, code);
this.fileCoverage = output.fileCoverage;
this.sourceMap = codeMap.map;
const cb = this.opts.sourceMapUrlCallback;
if (cb && output.sourceMappingURL) {
cb(filename, output.sourceMappingURL);
}
return codeMap.code;
}
/**
* callback-style instrument method that calls back with an error
* as opposed to throwing one. Note that in the current implementation,
* the callback will be called in the same process tick and is not asynchronous.
*
* @param {string} code - the code to instrument
* @param {string} filename - the filename against which to track coverage.
* @param {Function} callback - the callback
* @param {Object} inputSourceMap - the source map that maps the not instrumented code back to it's original form.
* Is assigned to the coverage object and therefore, is available in the json output and can be used to remap the
* coverage to the untranspiled source.
*/
instrument(code, filename, callback, inputSourceMap) {
if (!callback && typeof filename === 'function') {
callback = filename;
filename = null;
}
try {
var out = this.instrumentSync(code, filename, inputSourceMap);
callback(null, out);
} catch (ex) {
callback(ex);
}
}
/**
* returns the file coverage object for the last file instrumented.
* @returns {Object} the file coverage object.
*/
lastFileCoverage() {
return this.fileCoverage;
}
/**
* returns the source map produced for the last file instrumented.
* @returns {null|Object} the source map object.
*/
lastSourceMap() {
return this.sourceMap;
}
}
export default Instrumenter;
// import { MAGIC_KEY, MAGIC_VALUE } from './constants';
// import { parse } from 'babylon';
const traverse = require('babel-traverse')
// import * as t from 'babel-types';
const { parseSync } = require('@babel/core')
const { defaults } = require('@istanbuljs/schema')
const { MAGIC_KEY, MAGIC_VALUE } = require('./constants')
function getAst (code) {
if (typeof code === 'object' && typeof code.type === 'string') {
return code
}
if (typeof code !== 'string') {
throw new Error('Code must be a string')
}
return parseSync(code, {
babelrc: false,
configFile: false,
parserOpts: {
allowAwaitOutsideFunction: true,
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
sourceType: 'script',
plugins: defaults.instrumenter.parserPlugins
}
})
}
module.exports = function readInitialCoverage (code) {
const ast = getAst(code)
let covScope
traverse(ast, {
ObjectProperty: function (path) {
const { node } = path;
if (!node.computed &&
path.get('key').isIdentifier() &&
node.key.name === MAGIC_KEY)
{
const magicValue = path.get('value').evaluate()
if (!magicValue.confident || magicValue.value !== MAGIC_VALUE) {
return
}
covScope = path.scope.getFunctionParent() || path.scope.getProgramParent()
path.stop()
}
}
})
if (!covScope) {
return null
}
const result = {}
for (const key of ['path', 'hash', 'gcv', 'coverageData']) {
const binding = covScope.getOwnBinding(key)
if (!binding) {
return null
}
const valuePath = binding.path.get('init')
const value = valuePath.evaluate()
if (!value.confident) {
return null
}
result[key] = value.value
}
delete result.coverageData[MAGIC_KEY]
delete result.coverageData.hash
return result
}
// export default function readInitialCoverage (code) {
// if (typeof code !== 'string') {
// throw new Error('Code must be a string');
// }
// // Parse as leniently as possible
// const ast = parse(code, {
// allowImportExportEverywhere: true,
// allowReturnOutsideFunction: true,
// allowSuperOutsideMethod: true,
// sourceType: "script", // I think ?
// plugins: ["*"]
// });
// let covScope;
// traverse(ast, {
// ObjectProperty: function (path) {
// const { node } = path;
// if (!node.computed &&
// t.isIdentifier(node.key) &&
// node.key.name === MAGIC_KEY)
// {
// const magicValue = path.get('value').evaluate();
// if (!magicValue.confident || magicValue.value !== MAGIC_VALUE) {
// return;
// }
// covScope = path.scope.getFunctionParent();
// path.stop();
// }
// }
// });
// if (!covScope) {
// return null;
// }
// const result = {};
// for (const key of ['path', 'hash', 'gcv', 'coverageData']) {
// const binding = covScope.getOwnBinding(key);
// if (!binding) {
// return null;
// }
// const valuePath = binding.path.get('init');
// const value = valuePath.evaluate();
// if (!value.confident) {
// return null;
// }
// result[key] = value.value;
// }
// delete result.coverageData[MAGIC_KEY];
// return result;
// }
const { classes } = require('istanbul-lib-coverage');
function cloneLocation(loc) {
return {
start: {
line: loc && loc.start.line,
column: loc && loc.start.column
},
end: {
line: loc && loc.end.line,
column: loc && loc.end.column
}
};
}
function isExistIncrementStartmentCode(changeList, loc) {
for (let i = 0; i < changeList.length; i++) {
if (changeList[i] > loc.start.line && changeList[i] <= loc.end.line) {
return true
}
}
return false
}
/**
* SourceCoverage provides mutation methods to manipulate the structure of
* a file coverage object. Used by the instrumenter to create a full coverage
* object for a file incrementally.
*
* @private
* @param pathOrObj {String|Object} - see the argument for {@link FileCoverage}
* @extends FileCoverage
* @constructor
*/
class SourceCoverage extends classes.FileCoverage {
constructor(pathOrObj, changeList) {
super(pathOrObj);
this.data.changeList = changeList ? changeList : [];
this.meta = {
last: {
s: 0,
f: 0,
b: 0
}
};
}
newStatement(loc) {
var s = this.meta.last.s;
this.data.statementMap[s] = cloneLocation(loc);
this.data.s[s] = 0;
this.meta.last.s += 1;
return s;
}
newFunction(name, decl, loc) {
var f = this.meta.last.f;
name = name || '(anonymous_' + f + ')';
this.data.fnMap[f] = {
name: name,
decl: cloneLocation(decl),
loc: cloneLocation(loc)
};
this.data.f[f] = 0;
this.meta.last.f += 1;
return f;
}
newBranch(type, loc) {
var b = this.meta.last.b;
this.data.b[b] = [];
this.data.branchMap[b] = {
loc: cloneLocation(loc),
type: type,
locations: []
};
this.meta.last.b += 1;
return b;
}
addBranchPath(name, location) {
var bMeta = this.data.branchMap[name],
counts = this.data.b[name];
/* istanbul ignore if: paranoid check */
if (!bMeta) {
throw new Error("Invalid branch " + name);
}
bMeta.locations.push(cloneLocation(location));
counts.push(0);
return counts.length - 1;
}
/**
* Assigns an input source map to the coverage that can be used
* to remap the coverage output to the original source
* @param sourceMap {object} the source map
*/
inputSourceMap(sourceMap) {
this.data.inputSourceMap = sourceMap;
}
freeze() {
// prune empty branches
var map = this.data.branchMap,
branches = this.data.b;
Object.keys(map).forEach(function (b) {
if (map[b].locations.length === 0) {
delete map[b];
delete branches[b];
}
});
}
}
export { SourceCoverage };
const { SourceCoverage } = require('./source-coverage');
const { SHA, MAGIC_KEY, MAGIC_VALUE } = require('./constants');
const { createHash } = require('crypto');
const template = require('babel-template');
const { Console } = require('console');
// istanbul ignore comment pattern
const COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/;
// source map URL pattern
const SOURCE_MAP_RE = /[#@]\s*sourceMappingURL=(.*)\s*$/m;
// generate a variable name from hashing the supplied file path
function genVar(filename) {
var hash = createHash(SHA);
hash.update(filename);
return 'cov_' + parseInt(hash.digest('hex').substr(0, 12), 16).toString(36);
}
// VisitState holds the state of the visitor, provides helper functions
// and is the `this` for the individual coverage visitors.
class VisitState {
constructor(types, sourceFilePath, inputSourceMap, changeList = []) {
this.varName = genVar(sourceFilePath);
this.attrs = {};
this.nextIgnore = null;
let changeLists = changeList ? changeList : []
this.cov = new SourceCoverage(sourceFilePath, changeLists);
if (typeof (inputSourceMap) !== "undefined") {
this.cov.inputSourceMap(inputSourceMap);
}
this.types = types;
this.sourceMappingURL = null;
}
// should we ignore the node? Yes, if specifically ignoring
// or if the node is generated.
shouldIgnore(path) {
return this.nextIgnore || !path.node.loc;
}
// extract the ignore comment hint (next|if|else) or null
hintFor(node) {
let hint = null;
if (node.leadingComments) {
node.leadingComments.forEach(function (c) {
const v = (c.value || /* istanbul ignore next: paranoid check */ "").trim();
const groups = v.match(COMMENT_RE);
if (groups) {
hint = groups[1];
}
});
}
return hint;
}
// extract a source map URL from comments and keep track of it
maybeAssignSourceMapURL(node) {
const that = this;
const extractURL = (comments) => {
if (!comments) {
return;
}
comments.forEach(function (c) {
const v = (c.value || /* istanbul ignore next: paranoid check */ "").trim();
const groups = v.match(SOURCE_MAP_RE);
if (groups) {
that.sourceMappingURL = groups[1];
}
});
};
extractURL(node.leadingComments);
extractURL(node.trailingComments);
}
// all the generic stuff that needs to be done on enter for every node
onEnter(path) {
const n = path.node;
this.maybeAssignSourceMapURL(n);
// if already ignoring, nothing more to do
if (this.nextIgnore !== null) {
return;
}
// check hint to see if ignore should be turned on
const hint = this.hintFor(n);
if (hint === 'next') {
this.nextIgnore = n;
return;
}
// else check custom node attribute set by a prior visitor
if (this.getAttr(path.node, 'skip-all') !== null) {
this.nextIgnore = n;
}
}
// all the generic stuff on exit of a node,
// including reseting ignores and custom node attrs
onExit(path) {
// restore ignore status, if needed
if (path.node === this.nextIgnore) {
this.nextIgnore = null;
}
// nuke all attributes for the node
delete(path.node.__cov__);
}
// set a node attribute for the supplied node
setAttr(node, name, value) {
node.__cov__ = node.__cov__ || {};
node.__cov__[name] = value;
}
// retrieve a node attribute for the supplied node or null
getAttr(node, name) {
const c = node.__cov__;
if (!c) {
return null;
}
return c[name];
}
//
increase(type, id, index) {
const T = this.types;
const wrap = (index !== null
// If `index` present, turn `x` into `x[index]`.
? (x) => T.memberExpression(x, T.numericLiteral(index), true)
: (x) => x
);
const memberExpression = T.memberExpression(
T.memberExpression(T.identifier(this.varName), T.identifier(type)),
T.numericLiteral(id),
true
)
let data = T.unaryExpression('++', wrap(memberExpression));
return data
}
insertCounter(path, increment) {
const T = this.types;
if (path.isBlockStatement()) {
path.node.body.unshift(T.expressionStatement(increment));
} else if (path.isStatement()) {
path.insertBefore(T.expressionStatement(increment));
} else if ((path.isFunctionExpression() || path.isArrowFunctionExpression()) && T.isVariableDeclarator(path.parentPath)) {
// make an attempt to hoist the statement counter, so that
// function names are maintained.
const parent = path.parentPath.parentPath;
if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
parent.insertBefore(T.expressionStatement(
increment
));
} else {
path.replaceWith(T.sequenceExpression([increment, path.node]));
}
} else {
/* istanbul ignore else: not expected */
if (path.isExpression()) {
path.replaceWith(T.sequenceExpression([increment, path.node]));
} else {
console.error('Unable to insert counter for node type:', path.node.type);
}
}
}
insertStatementCounter(path) {
/* istanbul ignore if: paranoid check */
if (!(path.node && path.node.loc)) {
return;
}
const index = this.cov.newStatement(path.node.loc);
const increment = this.increase('s', index, null);
this.insertCounter(path, increment);
}
insertFunctionCounter(path) {
const T = this.types;
/* istanbul ignore if: paranoid check */
if (!(path.node && path.node.loc)) {
return;
}
const n = path.node;
let dloc = null;
// get location for declaration
switch (n.type) {
case "FunctionDeclaration":
/* istanbul ignore else: paranoid check */
if (n.id) {
dloc = n.id.loc;
}
break;
case "FunctionExpression":
if (n.id) {
dloc = n.id.loc;
}
break;
}
if (!dloc) {
dloc = {
start: n.loc.start,
end: { line: n.loc.start.line, column: n.loc.start.column + 1 }
};
}
const name = path.node.id ? path.node.id.name : path.node.name;
const index = this.cov.newFunction(name, dloc, path.node.body.loc);
const increment = this.increase('f', index, null);
const body = path.get('body');
/* istanbul ignore else: not expected */
if (body.isBlockStatement()) {
body.node.body.unshift(T.expressionStatement(increment));
} else {
console.error('Unable to process function body node type:', path.node.type);
}
}
getBranchIncrement(branchName, loc) {
const index = this.cov.addBranchPath(branchName, loc);
console.log(3, index)
return this.increase('b', branchName, index);
}
insertBranchCounter(path, branchName, loc) {
const increment = this.getBranchIncrement(branchName, loc || path.node.loc);
this.insertCounter(path, increment);
}
findLeaves(node, accumulator, parent, property) {
if (!node) {
return;
}
if (node.type === "LogicalExpression") {
const hint = this.hintFor(node);
if (hint !== 'next') {
this.findLeaves(node.left, accumulator, node, 'left');
this.findLeaves(node.right, accumulator, node, 'right');
}
} else {
accumulator.push({
node: node,
parent: parent,
property: property
});
}
}
}
// generic function that takes a set of visitor methods and
// returns a visitor object with `enter` and `exit` properties,
// such that:
//
// * standard entry processing is done
// * the supplied visitors are called only when ignore is not in effect
// This relieves them from worrying about ignore states and generated nodes.
// * standard exit processing is done
//
function entries() {
const enter = Array.prototype.slice.call(arguments);
// the enter function
const wrappedEntry = function (path, node) {
this.onEnter(path);
if (this.shouldIgnore(path)) {
return;
}
const that = this;
enter.forEach(function (e) {
if (typeof e === 'functon' || typeof e !== null) {
e.call(that, path, node);
}
});
};
const exit = function (path, node) {
this.onExit(path, node);
};
return {
enter: wrappedEntry,
exit: exit
};
}
function coverStatement(path) {
this.insertStatementCounter(path);
}
/* istanbul ignore next: no node.js support */
function coverAssignmentPattern(path) {
const n = path.node;
const b = this.cov.newBranch('default-arg', n.loc);
this.insertBranchCounter(path.get('right'), b);
}
function coverFunction(path) {
this.insertFunctionCounter(path);
}
function coverVariableDeclarator(path) {
this.insertStatementCounter(path.get('init'));
}
function skipInit(path) {
if (path.node.init) {
this.setAttr(path.node.init, 'skip-all', true);
}
}
function makeBlock(path) {
const T = this.types;
if (!path.node) {
path.replaceWith(T.blockStatement([]));
}
if (!path.isBlockStatement()) {
path.replaceWith(T.blockStatement([path.node]));
path.node.loc = path.node.body[0].loc;
}
}
function blockProp(prop) {
return function (path) {
makeBlock.call(this, path.get(prop));
};
}
function convertArrowExpression(path) {
const n = path.node;
const T = this.types;
if (n.expression) {
const bloc = n.body.loc;
n.expression = false;
n.body = T.blockStatement([
T.returnStatement(
n.body
)
]);
// restore body location
n.body.loc = bloc;
// set up the location for the return statement so it gets
// instrumented
n.body.body[0].loc = bloc;
}
}
function coverIfBranches(path) {
const n = path.node,
hint = this.hintFor(n),
ignoreIf = hint === 'if',
ignoreElse = hint === 'else',
branch = this.cov.newBranch('if', n.loc);
if (ignoreIf) {
this.setAttr(n.consequent, 'skip-all', true);
} else {
this.insertBranchCounter(path.get('consequent'), branch, n.loc);
}
if (ignoreElse) {
this.setAttr(n.alternate, 'skip-all', true);
} else {
this.insertBranchCounter(path.get('alternate'), branch, n.loc);
}
}
function createSwitchBranch(path) {
const b = this.cov.newBranch('switch', path.node.loc);
this.setAttr(path.node, 'branchName', b);
}
function coverSwitchCase(path) {
const T = this.types;
const b = this.getAttr(path.parentPath.node, 'branchName');
/* istanbul ignore if: paranoid check */
if (b === null) {
throw new Error('Unable to get switch branch name');
}
const increment = this.getBranchIncrement(b, path.node.loc);
path.node.consequent.unshift(T.expressionStatement(increment));
}
function coverTernary(path) {
const n = path.node,
branch = this.cov.newBranch('cond-expr', path.node.loc),
cHint = this.hintFor(n.consequent),
aHint = this.hintFor(n.alternate);
if (cHint !== 'next') {
this.insertBranchCounter(path.get('consequent'), branch);
}
if (aHint !== 'next') {
this.insertBranchCounter(path.get('alternate'), branch);
}
}
function coverLogicalExpression(path) {
const T = this.types;
if (path.parentPath.node.type === "LogicalExpression") {
return; // already processed
}
let leaves = [];
this.findLeaves(path.node, leaves);
const b = this.cov.newBranch("binary-expr", path.node.loc);
for (let i = 0; i < leaves.length; i += 1) {
const leaf = leaves[i];
const hint = this.hintFor(leaf.node);
if (hint === 'next') {
continue;
}
const increment = this.getBranchIncrement(b, leaf.node.loc);
if (!increment) {
continue;
}
leaf.parent[leaf.property] = T.sequenceExpression([increment, leaf.node]);
}
}
const codeVisitor = {
ArrowFunctionExpression: entries(convertArrowExpression, coverFunction),
AssignmentPattern: entries(coverAssignmentPattern),
BlockStatement: entries(), // ignore processing only
ClassMethod: entries(coverFunction),
ExpressionStatement: entries(coverStatement),
BreakStatement: entries(coverStatement),
ContinueStatement: entries(coverStatement),
DebuggerStatement: entries(coverStatement),
ReturnStatement: entries(coverStatement),
ThrowStatement: entries(coverStatement),
TryStatement: entries(coverStatement),
VariableDeclaration: entries(), // ignore processing only
VariableDeclarator: entries(coverVariableDeclarator),
IfStatement: entries(blockProp('consequent'), blockProp('alternate'), coverStatement, coverIfBranches),
ForStatement: entries(blockProp('body'), skipInit, coverStatement),
ForInStatement: entries(blockProp('body'), skipInit, coverStatement),
ForOfStatement: entries(blockProp('body'), skipInit, coverStatement),
WhileStatement: entries(blockProp('body'), coverStatement),
DoWhileStatement: entries(blockProp('body'), coverStatement),
SwitchStatement: entries(createSwitchBranch, coverStatement),
SwitchCase: entries(coverSwitchCase),
WithStatement: entries(blockProp('body'), coverStatement),
FunctionDeclaration: entries(coverFunction),
FunctionExpression: entries(coverFunction),
LabeledStatement: entries(coverStatement),
ConditionalExpression: entries(coverTernary),
LogicalExpression: entries(coverLogicalExpression)
};
// the template to insert at the top of the program.
const coverageTemplate = template(`
var COVERAGE_VAR = (function () {
var path = PATH,
hash = HASH,
global = (new Function('return this'))(),
gcv = GLOBAL_COVERAGE_VAR,
coverageData = INITIAL,
coverage = global[gcv] || (global[gcv] = {});
if (coverage[path] && coverage[path].hash === hash) {
return coverage[path];
}
coverageData.hash = hash;
return coverage[path] = coverageData;
})();
`);
/**
* programVisitor is a `babel` adaptor for instrumentation.
* It returns an object with two methods `enter` and `exit`.
* These should be assigned to or called from `Program` entry and exit functions
* in a babel visitor.
* These functions do not make assumptions about the state set by Babel and thus
* can be used in a context other than a Babel plugin.
*
* The exit function returns an object that currently has the following keys:
*
* `fileCoverage` - the file coverage object created for the source file.
* `sourceMappingURL` - any source mapping URL found when processing the file.
*
* @param {Object} types - an instance of babel-types
* @param {string} sourceFilePath - the path to source file
* @param {Object} opts - additional options
* @param {string} [opts.coverageVariable=__coverage__] the global coverage variable name.
* @param {object} [opts.inputSourceMap=undefined] the input source map, that maps the uninstrumented code back to the
* original code.
*/
module.exports = function programVisitor (types, sourceFilePath = 'unknown.js', opts = {coverageVariable: '__coverage__', inputSourceMap: undefined, changeList: []}) {
const T = types;
const visitState = new VisitState(types, sourceFilePath, opts.inputSourceMap, opts.changeList);
return {
enter(path) {
path.traverse(codeVisitor, visitState);
},
exit(path) {
visitState.cov.freeze();
const coverageData = visitState.cov.toJSON();
coverageData[MAGIC_KEY] = MAGIC_VALUE;
const hash = createHash(SHA).update(JSON.stringify(coverageData)).digest('hex');
const coverageNode = T.valueToNode(coverageData);
delete coverageData[MAGIC_KEY];
const cv = coverageTemplate({
GLOBAL_COVERAGE_VAR: T.stringLiteral(opts.coverageVariable),
COVERAGE_VAR: T.identifier(visitState.varName),
PATH: T.stringLiteral(sourceFilePath),
INITIAL: coverageNode,
HASH: T.stringLiteral(hash)
});
cv._blockHoist = 3;
path.node.body.unshift(cv);
return {
fileCoverage: coverageData,
sourceMappingURL: visitState.sourceMappingURL
};
}
};
}
// export default {
// programVisitor
// }
// export default programVisitor;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment