Commit 6981da8d by lxyang

feat:增加插桩增量代码过滤

parent 909acbf6
{
"name": "babel-plugin-ry-istanbul-web",
"version": "0.0.5",
"version": "0.0.6",
"author": "Thai Pangsakulyanont @dtinth",
"license": "BSD-3-Clause",
"description": "A babel plugin that adds istanbul instrumentation to ES6 code",
......
......@@ -2,8 +2,8 @@ const path = require('path')
import { realpathSync } from 'fs'
import { execFileSync, execSync } from 'child_process'
import { declare } from '@babel/helper-plugin-utils'
// import { programVisitor } from './istanlibment'
import { programVisitor } from 'istanbul-lib-instrument'
import { programVisitor } from './dist'
// import { programVisitor } from 'istanbul-lib-instrument'
import TestExclude from 'test-exclude'
import schema from '@istanbuljs/schema'
import parseDiffData from './parse-diff'
......@@ -94,6 +94,15 @@ function makeShouldSkip () {
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 => {
api.assertVersion(7)
const shouldSkip = makeShouldSkip()
......@@ -120,28 +129,28 @@ export default declare(api => {
if (item.indexOf('IS_PITCHING_PILE') !== -1) {
processData.IS_PITCHING_PILE = isItem
}
if (item.indexOf('PROSRC') !== -1) {
processData.PROSRC = process.env[item]
if (item.indexOf('BRANCH') !== -1) {
processData.BRANCH = process.env[item]
}
// Object.keys(processData).length
})
// 全局变量优先
if (Object.keys(processData).length) {
BRANCH_DATA = processData.BRANCH
INCREMENT_DATA = processData.INCREMENT
IS_PITCHING_PILE_DATA = processData.IS_PITCHING_PILE
BRANCH_DATA = isValue(processData.BRANCH, false, BRANCH_DATA)
INCREMENT_DATA = isValue(processData.INCREMENT, false, INCREMENT_DATA)
IS_PITCHING_PILE_DATA = isValue(processData.IS_PITCHING_PILE, false, IS_PITCHING_PILE_DATA)
} else if (Object.keys(instrmenttation).length) {
BRANCH_DATA = instrmenttation.BRANCH
INCREMENT_DATA = instrmenttation.INCREMENT
IS_PITCHING_PILE_DATA = instrmenttation.IS_PITCHING_PILE
BRANCH_DATA = isValue(instrmenttation.BRANCH, false, BRANCH_DATA)
INCREMENT_DATA = isValue(instrmenttation.INCREMENT, false, INCREMENT_DATA)
IS_PITCHING_PILE_DATA = isValue(instrmenttation.IS_PITCHING_PILE, false, IS_PITCHING_PILE_DATA)
}
// instrumenttation (branch: git diff 跟那个分支对比, increment 是否开启增量代码检测) 拿配置到底是全量代码还是增量代码
if (!IS_PITCHING_PILE_DATA || IS_PITCHING_PILE_DATA === 'false') {
return false
}
// const changeList = []
const changeList = []
// 下面的是零时的
// const gitDiffCode = execSync(`git diff ${branch}`)
// // const gitDiffCode = execSync(`git diff ${branch}`)
// const diffData = parseDiffData(gitDiffCode.toString())
// diffScreen = diffData.find(item => {
// return realPath.indexOf(item.to) > -1
......@@ -172,31 +181,36 @@ export default declare(api => {
}
})
// 后增加|| !increment这个条件判断条件后面加上
// if (diffScreen !== null && increment) {
if (diffScreen !== null && !diffScreen && (INCREMENT_DATA || INCREMENT_DATA === 'true')) {
// if (diffScreen) {
// if (Array.isArray(diffScreen && diffScreen.chunks)) {
// diffScreen.chunks.forEach(item => {
// let changes = Array.isArray(item.changes) ? item.changes : []
// changes.forEach(items => {
// if (items && items.add) {
// changeList.push(items.ln)
// }
// })
// })
if (Array.isArray(diffScreen && diffScreen.chunks)) {
diffScreen.chunks.forEach(item => {
let changes = Array.isArray(item.changes) ? item.changes : []
changes.forEach(items => {
if (items && items.add) {
changeList.push(items.ln)
}
})
})
}
if (changeList.length) {
visitorOptions.changeList = changeList
// changeList
this.__dv__ = programVisitor(t, realPath, {
...visitorOptions,
inputSourceMap
})
this.__dv__.enter(path)
}
// }
// changeList
} else if (!INCREMENT_DATA || INCREMENT_DATA === 'false') {
visitorOptions.changeList = changeList
this.__dv__ = programVisitor(t, realPath, {
...visitorOptions,
inputSourceMap
inputSourceMap,
})
this.__dv__.enter(path)
// } else {
// this.__dv__ = programVisitor(t, realPath, {
// ...visitorOptions,
// inputSourceMap
// })
// this.__dv__.enter(path)
// }
}
},
exit(path) {
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 };
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