initial commit taken from gitlab.lrz.de

This commit is contained in:
privatereese
2018-08-24 18:09:42 +02:00
parent ae54ed4c48
commit fc05486403
28494 changed files with 2159823 additions and 0 deletions

506
node_modules/istanbul-api/lib/config.js generated vendored Normal file
View File

@@ -0,0 +1,506 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
fs = require('fs'),
existsSync = fs.existsSync,
CAMEL_PATTERN = /([a-z])([A-Z])/g,
YML_PATTERN = /\.ya?ml$/,
yaml = require('js-yaml'),
libReport = require('istanbul-lib-report'),
inputError = require('./input-error');
function defaultConfig() {
var ret = {
verbose: false,
instrumentation: {
root: '.',
extensions: ['.js'],
'default-excludes': true,
excludes: [],
variable: '__coverage__',
compact: true,
'preserve-comments': false,
'complete-copy': false,
'save-baseline': false,
'baseline-file': './coverage/coverage-baseline.raw.json',
'include-all-sources': false,
'include-pid': false,
'es-modules': false,
'auto-wrap': false,
'ignore-class-methods': []
},
reporting: {
print: 'summary',
reports: [ 'lcov' ],
dir: './coverage',
summarizer: 'pkg',
'report-config': {}
},
hooks: {
'hook-run-in-context': false,
'hook-run-in-this-context': false,
'post-require-hook': null,
'handle-sigint': false
},
check: {
global: {
statements: 0,
lines: 0,
branches: 0,
functions: 0,
excludes: [] // Currently list of files (root + path). For future, extend to patterns.
},
each: {
statements: 0,
lines: 0,
branches: 0,
functions: 0,
excludes: []
}
}
};
ret.reporting.watermarks = libReport.getDefaultWatermarks();
ret.reporting['report-config'] = {};
return ret;
}
function dasherize(word) {
return word.replace(CAMEL_PATTERN, function (match, lch, uch) {
return lch + '-' + uch.toLowerCase();
});
}
function isScalar(v) {
if (v === null) { return true; }
return v !== undefined && !Array.isArray(v) && typeof v !== 'object';
}
function isObject(v) {
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
function mergeObjects(explicit, template, bothWays) {
var ret = {},
keys = Object.keys(template);
if (bothWays) {
keys.push.apply(keys, Object.keys(explicit));
}
keys.forEach(function (k) {
var v1 = template[k],
v2 = explicit[k];
if (Array.isArray(v1)) {
ret[k] = Array.isArray(v2) && v2.length > 0 ? v2 : v1;
} else if (isObject(v1)) {
v2 = isObject(v2) ? v2 : {};
ret[k] = mergeObjects(v2, v1, bothWays);
} else if (!v1 && v2) {
ret[k] = v2;
} else {
ret[k] = isScalar(v2) ? v2 : v1;
}
});
return ret;
}
function mergeDefaults(explicit, implicit) {
explicit = explicit || {};
var initialMerge = mergeObjects(explicit || {}, implicit),
explicitReportConfig = (explicit.reporting || {})['report-config'] || {},
implicitReportConfig = initialMerge.reporting['report-config'] || {};
initialMerge.reporting['report-config'] = mergeObjects(explicitReportConfig, implicitReportConfig, true);
return initialMerge;
}
function addMethods() {
var args = Array.prototype.slice.call(arguments),
cons = args.shift();
args.forEach(function (arg) {
var property = dasherize(arg);
cons.prototype[arg] = function () {
return this.config[property];
};
});
}
/**
* Object that returns instrumentation options
* @class InstrumentOptions
* @module config
* @constructor
* @param config the instrumentation part of the config object
*/
function InstrumentOptions(config) {
this.config = config;
}
/**
* returns if default excludes should be turned on. Used by the `cover` command.
* @method defaultExcludes
* @return {Boolean} true if default excludes should be turned on
*/
/**
* returns if non-JS files should be copied during instrumentation. Used by the
* `instrument` command.
* @method completeCopy
* @return {Boolean} true if non-JS files should be copied
*/
/**
* the coverage variable name to use. Used by the `instrument` command.
* @method variable
* @return {String} the coverage variable name to use
*/
/**
* returns if the output should be compact JS. Used by the `instrument` command.
* @method compact
* @return {Boolean} true if the output should be compact
*/
/**
* returns if comments should be preserved in the generated JS. Used by the
* `cover` and `instrument` commands.
* @method preserveComments
* @return {Boolean} true if comments should be preserved in the generated JS
*/
/**
* returns if a zero-coverage baseline file should be written as part of
* instrumentation. This allows reporting to display numbers for files that have
* no tests. Used by the `instrument` command.
* @method saveBaseline
* @return {Boolean} true if a baseline coverage file should be written.
*/
/**
* Sets the baseline coverage filename. Used by the `instrument` command.
* @method baselineFile
* @return {String} the name of the baseline coverage file.
*/
/**
* returns if comments the JS to instrument contains es6 Module syntax.
* @method esModules
* @return {Boolean} true if code contains es6 import/export statements.
*/
/**
* returns if the coverage filename should include the PID. Used by the `instrument` command.
* @method includePid
* @return {Boolean} true to include pid in coverage filename.
*/
addMethods(InstrumentOptions,
'extensions', 'defaultExcludes', 'completeCopy',
'variable', 'compact', 'preserveComments',
'saveBaseline', 'baselineFile', 'esModules',
'includeAllSources', 'includePid', 'autoWrap', 'ignoreClassMethods');
/**
* returns the root directory used by istanbul which is typically the root of the
* source tree. Used by the `cover` and `report` commands.
* @method root
* @return {String} the root directory used by istanbul.
*/
InstrumentOptions.prototype.root = function () { return path.resolve(this.config.root); };
/**
* returns an array of fileset patterns that should be excluded for instrumentation.
* Used by the `instrument` and `cover` commands.
* @method excludes
* @return {Array} an array of fileset patterns that should be excluded for
* instrumentation.
*/
InstrumentOptions.prototype.excludes = function (excludeTests) {
var defs;
if (this.defaultExcludes()) {
defs = [ '**/node_modules/**' ];
if (excludeTests) {
defs = defs.concat(['**/test/**', '**/tests/**']);
}
return defs.concat(this.config.excludes);
}
return this.config.excludes;
};
InstrumentOptions.prototype.getInstrumenterOpts = function () {
return {
coverageVariable: this.variable(),
compact: this.compact(),
preserveComments: this.preserveComments(),
esModules: this.esModules(),
autoWrap: this.autoWrap(),
ignoreClassMethods: this.ignoreClassMethods()
};
};
/**
* Object that returns reporting options
* @class ReportingOptions
* @module config
* @constructor
* @param config the reporting part of the config object
*/
function ReportingOptions(config) {
this.config = config;
}
/**
* returns the kind of information to be printed on the console. May be one
* of `summary`, `detail`, `both` or `none`. Used by the
* `cover` command.
* @method print
* @return {String} the kind of information to print to the console at the end
* of the `cover` command execution.
*/
/**
* returns a list of reports that should be generated at the end of a run. Used
* by the `cover` and `report` commands.
* @method reports
* @return {Array} an array of reports that should be produced
*/
/**
* returns the directory under which reports should be generated. Used by the
* `cover` and `report` commands.
*
* @method dir
* @return {String} the directory under which reports should be generated.
*/
/**
* returns an object that has keys that are report format names and values that are objects
* containing detailed configuration for each format. Running `istanbul help config`
* will give you all the keys per report format that can be overridden.
* Used by the `cover` and `report` commands.
* @method reportConfig
* @return {Object} detailed report configuration per report format.
*/
addMethods(ReportingOptions, 'print', 'reports', 'dir', 'reportConfig', 'summarizer');
function isInvalidMark(v, key) {
var prefix = 'Watermark for [' + key + '] :';
if (v.length !== 2) {
return prefix + 'must be an array of length 2';
}
v[0] = Number(v[0]);
v[1] = Number(v[1]);
if (isNaN(v[0]) || isNaN(v[1])) {
return prefix + 'must have valid numbers';
}
if (v[0] < 0 || v[1] < 0) {
return prefix + 'must be positive numbers';
}
if (v[1] > 100) {
return prefix + 'cannot exceed 100';
}
if (v[1] <= v[0]) {
return prefix + 'low must be less than high';
}
return null;
}
/**
* returns the low and high watermarks to be used to designate whether coverage
* is `low`, `medium` or `high`. Statements, functions, branches and lines can
* have independent watermarks. These are respected by all reports
* that color for low, medium and high coverage. See the default configuration for exact syntax
* using `istanbul help config`. Used by the `cover` and `report` commands.
*
* @method watermarks
* @return {Object} an object containing low and high watermarks for statements,
* branches, functions and lines.
*/
ReportingOptions.prototype.watermarks = function () {
var v = this.config.watermarks,
defs = libReport.getDefaultWatermarks(),
ret = {};
Object.keys(defs).forEach(function (k) {
var mark = v[k], //it will already be a non-zero length array because of the way the merge works
message = isInvalidMark(mark, k);
if (message) {
console.error(message);
ret[k] = defs[k];
} else {
ret[k] = mark;
}
});
return ret;
};
/**
* Object that returns hook options. Note that istanbul does not provide an
* option to hook `require`. This is always done by the `cover` command.
* @class HookOptions
* @module config
* @constructor
* @param config the hooks part of the config object
*/
function HookOptions(config) {
this.config = config;
}
/**
* returns if `vm.runInContext` needs to be hooked. Used by the `cover` command.
* @method hookRunInContext
* @return {Boolean} true if `vm.runInContext` needs to be hooked for coverage
*/
/**
* returns if `vm.runInThisContext` needs to be hooked, in addition to the standard
* `require` hooks added by istanbul. This should be true for code that uses
* RequireJS for example. Used by the `cover` command.
* @method hookRunInThisContext
* @return {Boolean} true if `vm.runInThisContext` needs to be hooked for coverage
*/
/**
* returns a path to JS file or a dependent module that should be used for
* post-processing files after they have been required. See the `yui-istanbul` module for
* an example of a post-require hook. This particular hook modifies the yui loader when
* that file is required to add istanbul interceptors. Use by the `cover` command
*
* @method postRequireHook
* @return {String} a path to a JS file or the name of a node module that needs
* to be used as a `require` post-processor
*/
/**
* returns if istanbul needs to add a SIGINT (control-c, usually) handler to
* save coverage information. Useful for getting code coverage out of processes
* that run forever and need a SIGINT to terminate.
* @method handleSigint
* @return {Boolean} true if SIGINT needs to be hooked to write coverage information
*/
addMethods(HookOptions, 'hookRunInContext', 'hookRunInThisContext', 'postRequireHook', 'handleSigint');
/**
* represents the istanbul configuration and provides sub-objects that can
* return instrumentation, reporting and hook options respectively.
* Usage
* -----
*
* var configObj = require('istanbul').config.loadFile();
*
* console.log(configObj.reporting.reports());
*
* @class Configuration
* @module config
* @param {Object} obj the base object to use as the configuration
* @param {Object} overrides optional - override attributes that are merged into
* the base config
* @constructor
*/
function Configuration(obj, overrides) {
var config = mergeDefaults(obj, defaultConfig(true));
if (isObject(overrides)) {
config = mergeDefaults(overrides, config);
}
if (config.verbose) {
console.error('Using configuration');
console.error('-------------------');
console.error(yaml.safeDump(config, { indent: 4, flowLevel: 3 }));
console.error('-------------------\n');
}
this.verbose = config.verbose;
this.instrumentation = new InstrumentOptions(config.instrumentation);
this.reporting = new ReportingOptions(config.reporting);
this.hooks = new HookOptions(config.hooks);
this.check = config.check; // Pass raw config sub-object.
}
/**
* true if verbose logging is required
* @property verbose
* @type Boolean
*/
/**
* instrumentation options
* @property instrumentation
* @type InstrumentOptions
*/
/**
* reporting options
* @property reporting
* @type ReportingOptions
*/
/**
* hook options
* @property hooks
* @type HookOptions
*/
function loadFile(file, overrides) {
var defaultConfigFile = path.resolve('.istanbul.yml'),
configObject;
if (file) {
if (!existsSync(file)) {
throw inputError.create('Invalid configuration file specified:' + file);
}
} else {
if (existsSync(defaultConfigFile)) {
file = defaultConfigFile;
}
}
if (file) {
if (overrides && overrides.verbose === true) {
console.error('Loading config: ' + file);
}
configObject = file.match(YML_PATTERN) ?
yaml.safeLoad(fs.readFileSync(file, 'utf8'), { filename: file }) :
require(path.resolve(file));
}
return new Configuration(configObject, overrides);
}
function loadObject(obj, overrides) {
return new Configuration(obj, overrides);
}
/**
* methods to load the configuration object.
* Usage
* -----
*
* var config = require('istanbul').config,
* configObj = config.loadFile();
*
* console.log(configObj.reporting.reports());
*
* @class Config
* @module main
* @static
*/
module.exports = {
/**
* loads the specified configuration file with optional overrides. Throws
* when a file is specified and it is not found.
* @method loadFile
* @static
* @param {String} file the file to load. If falsy, the default config file, if present, is loaded.
* If not a default config is used.
* @param {Object} overrides - an object with override keys that are merged into the
* config object loaded
* @return {Configuration} the config object with overrides applied
*/
loadFile: loadFile,
/**
* loads the specified configuration object with optional overrides.
* @method loadObject
* @static
* @param {Object} obj the object to use as the base configuration.
* @param {Object} overrides - an object with override keys that are merged into the
* config object
* @return {Configuration} the config object with overrides applied
*/
loadObject: loadObject,
/**
* returns the default configuration object. Note that this is a plain object
* and not a `Configuration` instance.
* @method defaultConfig
* @static
* @return {Object} an object that represents the default config
*/
defaultConfig: defaultConfig
};

76
node_modules/istanbul-api/lib/file-matcher.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var async = require('async'),
fileset = require('fileset'),
fs = require('fs'),
path = require('path'),
seq = 0;
function filesFor(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
var root = options.root,
includes = options.includes,
excludes = options.excludes,
realpath = options.realpath,
relative = options.relative,
opts;
root = root || process.cwd();
includes = includes && Array.isArray(includes) ? includes : [ '**/*.js' ];
excludes = excludes && Array.isArray(excludes) ? excludes : [ '**/node_modules/**' ];
opts = { cwd: root, nodir: true, ignore: excludes };
seq += 1;
opts['x' + seq + new Date().getTime()] = true; //cache buster for minimatch cache bug
fileset(includes.join(' '), excludes.join(' '), opts, function (err, files) {
/* istanbul ignore if - untestable */
if (err) { return callback(err); }
if (relative) { return callback(err, files); }
if (!realpath) {
files = files.map(function (file) { return path.resolve(root, file); });
return callback(err, files);
}
var realPathCache = module.constructor._realpathCache || /* istanbul ignore next */ {};
async.map(files, function (file, done) {
fs.realpath(path.resolve(root, file), realPathCache, done);
}, callback);
});
}
function matcherFor(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = null;
}
options = options || {};
options.relative = false; //force absolute paths
options.realpath = true; //force real paths (to match Node.js module paths)
filesFor(options, function (err, files) {
var fileMap = {},
matchFn;
/* istanbul ignore if - untestable */
if (err) { return callback(err); }
files.forEach(function (file) { fileMap[file] = true; });
matchFn = function (file) { return fileMap[file]; };
matchFn.files = Object.keys(fileMap);
return callback(null, matchFn);
});
}
module.exports = {
filesFor: filesFor,
matcherFor: matcherFor
};

9
node_modules/istanbul-api/lib/input-error.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
module.exports.create = function (message) {
var err = new Error(message);
err.inputError = true;
return err;
};

89
node_modules/istanbul-api/lib/reporter.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
configuration = require('./config'),
inputError = require('./input-error'),
libReport = require('istanbul-lib-report'),
libReports = require('istanbul-reports');
function Reporter(cfg, opts) {
opts = opts || {};
this.config = cfg || configuration.loadFile();
this.dir = path.resolve(this.config.reporting.dir());
this.reports = {};
var summarizer = opts.summarizer,
s = this.config.reporting.summarizer();
if (summarizer && typeof summarizer === 'function') {
this.summarizer = summarizer;
} else {
summarizer = libReport.summarizers[s];
if (!summarizer) {
throw inputError.create('Invalid summarizer in report config: ' + s);
}
this.summarizer = summarizer;
}
}
Reporter.prototype = {
/**
* adds a report to be generated. Must be one of the entries returned
* by `Report.getReportList()`
* @method add
* @param {String} fmt the format of the report to generate
*/
add: function (fmt) {
if (this.reports[fmt]) { // already added
return;
}
var config = this.config,
rptConfig = config.reporting.reportConfig()[fmt] || {};
rptConfig.verbose = config.verbose;
try {
if (this.config.verbose) {
console.error('Create report', fmt,' with', rptConfig);
}
this.reports[fmt] = libReports.create(fmt, rptConfig);
} catch (ex) {
throw inputError.create('Invalid report format [' + fmt + ']');
}
},
/**
* adds an array of report formats to be generated
* @method addAll
* @param {Array} fmts an array of report formats
*/
addAll: function (fmts) {
var that = this;
fmts.forEach(function (f) {
that.add(f);
});
},
/**
* writes all reports added
* @method write
*/
write: function (coverageMap, opts) {
opts = opts || {};
var that = this,
sourceFinder = opts.sourceFinder || null,
context,
tree;
context = libReport.createContext({
dir: this.dir,
watermarks: this.config.reporting.watermarks(),
sourceFinder: sourceFinder
});
tree = this.summarizer(coverageMap);
Object.keys(this.reports).forEach(function (name) {
var report = that.reports[name];
tree.visit(report, context);
});
}
};
module.exports = Reporter;

148
node_modules/istanbul-api/lib/run-check-coverage.js generated vendored Normal file
View File

@@ -0,0 +1,148 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
fs = require('fs'),
filesFor = require('./file-matcher').filesFor,
libCoverage = require('istanbul-lib-coverage'),
inputError = require('./input-error'),
isAbsolute = path.isAbsolute || function (file) {
return path.resolve(file) === path.normalize(file);
};
function removeFiles(origMap, root, files) {
var filesObj = {},
ret = libCoverage.createCoverageMap();
// Create lookup table.
files.forEach(function (file) {
filesObj[file] = true;
});
origMap.files().forEach(function (key) {
// Exclude keys will always be relative, but covObj keys can be absolute or relative
var excludeKey = isAbsolute(key) ? path.relative(root, key) : key;
// Also normalize for files that start with `./`, etc.
excludeKey = path.normalize(excludeKey);
if (filesObj[excludeKey] !== true) {
ret.addFileCoverage(origMap.fileCoverageFor(key));
}
});
return ret;
}
function run(config, opts, callback) {
if (!callback && typeof(opts) === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var root = opts.root || config.instrumentation.root() || process.cwd(),
includePattern = opts.include || '**/coverage*.json',
errors = [],
check,
makeMap,
processFiles;
check = function (name, thresholds, actuals) {
[
"statements",
"branches",
"lines",
"functions"
].forEach(function (key) {
var actual = actuals[key].pct,
actualUncovered = actuals[key].total - actuals[key].covered,
threshold = thresholds[key];
if (threshold < 0) {
if (threshold * -1 < actualUncovered) {
errors.push('ERROR: Uncovered count for ' + key + ' (' + actualUncovered +
') exceeds ' + name + ' threshold (' + -1 * threshold + ')');
}
} else {
if (actual < threshold) {
errors.push('ERROR: Coverage for ' + key + ' (' + actual +
'%) does not meet ' + name + ' threshold (' + threshold + '%)');
}
}
});
};
makeMap = function (files, callback) {
var coverageMap = libCoverage.createCoverageMap();
if (files.length === 0) {
return callback(inputError.create('ERROR: No coverage files found.'));
}
files.forEach(function (file) {
var coverageObject = JSON.parse(fs.readFileSync(file, 'utf8'));
coverageMap.merge(coverageObject);
});
return callback(null, coverageMap);
};
processFiles = function (coverageMap, callback) {
var thresholds = {
global: {
statements: config.check.global.statements || 0,
branches: config.check.global.branches || 0,
lines: config.check.global.lines || 0,
functions: config.check.global.functions || 0,
excludes: config.check.global.excludes || []
},
each: {
statements: config.check.each.statements || 0,
branches: config.check.each.branches || 0,
lines: config.check.each.lines || 0,
functions: config.check.each.functions || 0,
excludes: config.check.each.excludes || []
}
},
globalResults = removeFiles(coverageMap, root, thresholds.global.excludes),
eachResults = removeFiles(coverageMap, root, thresholds.each.excludes),
finalError;
if (config.verbose) {
console.error('Compare actuals against thresholds');
console.error(JSON.stringify({
global: globalResults,
each: eachResults,
thresholds: thresholds
}, undefined, 4));
}
check("global", thresholds.global, globalResults.getCoverageSummary());
eachResults.files().forEach(function (key) {
var summary = eachResults.fileCoverageFor(key).toSummary();
check("per-file" + " (" + key + ") ", thresholds.each, summary);
});
finalError = errors.length === 0 ? null : errors.join("\n");
return callback(finalError);
};
filesFor({
root: root,
includes: [includePattern]
}, function (err, files) {
if (err) {
return callback(err);
}
makeMap(files, function (err, map) {
if (err) {
return callback(err);
}
return processFiles(map, callback);
});
});
}
module.exports = {
run: run
};

224
node_modules/istanbul-api/lib/run-cover.js generated vendored Normal file
View File

@@ -0,0 +1,224 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
fs = require('fs'),
mkdirp = require('mkdirp'),
compareVersions = require('compare-versions'),
matcherFor = require('./file-matcher').matcherFor,
libInstrument = require('istanbul-lib-instrument'),
libCoverage = require('istanbul-lib-coverage'),
libSourceMaps = require('istanbul-lib-source-maps'),
hook = require('istanbul-lib-hook'),
Reporter = require('./reporter');
function getCoverFunctions(config, includes, callback) {
if (!callback && typeof includes === 'function') {
callback = includes;
includes = null;
}
var includePid = config.instrumentation.includePid(),
reportingDir = path.resolve(config.reporting.dir()),
reporter = new Reporter(config),
excludes = config.instrumentation.excludes(true),
// The coverage variable below should have different value than
// that of the coverage variable actually used by the instrumenter (in this case: __coverage__).
// Otherwise if you run nyc to provide coverage on these files,
// both the actual instrumenter and this file will write to the global coverage variable,
// and provide unexpected coverage result.
coverageVar = '$$coverage$$',
instOpts = config.instrumentation.getInstrumenterOpts(),
sourceMapStore = libSourceMaps.createSourceMapStore({}),
instrumenter,
transformer,
runInContextTransformer,
runInThisContextTransformer,
fakeRequire,
requireTransformer,
reportInitFn,
hookFn,
unhookFn,
coverageFinderFn,
coverageSetterFn,
beforeReportFn,
exitFn;
instOpts.coverageVariable = coverageVar;
instOpts.sourceMapUrlCallback = function (file, url) {
sourceMapStore.registerURL(file, url);
};
coverageFinderFn = function () {
return global[coverageVar];
};
instrumenter = libInstrument.createInstrumenter(instOpts);
transformer = function (code, options) {
var filename = typeof options === 'string' ? options : options.filename;
return instrumenter.instrumentSync(code, filename);
};
runInContextTransformer = function (code, options) {
return transformer(code, options);
};
runInThisContextTransformer = function (code, options) {
return transformer(code, options);
};
requireTransformer = function (code, options) {
var cov,
ret = transformer(code, options),
filename = typeof options === 'string' ? options : options.filename;
if (fakeRequire) {
cov = coverageFinderFn();
cov[filename] = instrumenter.lastFileCoverage();
return 'function x() {}';
}
return ret;
};
coverageSetterFn = function (cov) {
global[coverageVar] = cov;
};
reportInitFn = function () {
// set up reporter
mkdirp.sync(reportingDir); //ensure we fail early if we cannot do this
reporter.addAll(config.reporting.reports());
if (config.reporting.print() !== 'none') {
switch (config.reporting.print()) {
case 'detail':
reporter.add('text');
break;
case 'both':
reporter.add('text');
reporter.add('text-summary');
break;
default:
reporter.add('text-summary');
break;
}
}
};
var disabler;
hookFn = function (matchFn) {
var hookOpts = {
verbose: config.verbose,
extensions: config.instrumentation.extensions(),
coverageVariable: coverageVar
};
//initialize the global variable
coverageSetterFn({});
reportInitFn();
if (config.hooks.hookRunInContext()) {
hook.hookRunInContext(matchFn, runInContextTransformer, hookOpts);
}
if (config.hooks.hookRunInThisContext()) {
hook.hookRunInThisContext(matchFn, runInThisContextTransformer, hookOpts);
if(compareVersions(process.versions.node, "6.0.0") === -1) {
disabler = hook.hookRequire(matchFn, requireTransformer, hookOpts);
}
} else {
disabler = hook.hookRequire(matchFn, requireTransformer, hookOpts);
}
};
unhookFn = function (matchFn) {
if (disabler) {
disabler();
}
hook.unhookRunInThisContext();
hook.unhookRunInContext();
hook.unloadRequireCache(matchFn);
};
beforeReportFn = function (matchFn, cov) {
var pidExt = includePid ? ('-' + process.pid) : '',
file = path.resolve(reportingDir, 'coverage' + pidExt + '.raw.json'),
missingFiles,
finalCoverage = cov;
if (config.instrumentation.includeAllSources()) {
if (config.verbose) {
console.error("Including all sources not require'd by tests");
}
missingFiles = [];
// Files that are not touched by code ran by the test runner is manually instrumented, to
// illustrate the missing coverage.
matchFn.files.forEach(function (file) {
if (!cov[file]) {
missingFiles.push(file);
}
});
fakeRequire = true;
missingFiles.forEach(function (file) {
try {
require(file);
} catch (ex) {
console.error('Unable to post-instrument: ' + file);
}
});
}
if (Object.keys(finalCoverage).length >0) {
if (config.verbose) {
console.error('=============================================================================');
console.error('Writing coverage object [' + file + ']');
console.error('Writing coverage reports at [' + reportingDir + ']');
console.error('=============================================================================');
}
fs.writeFileSync(file, JSON.stringify(finalCoverage), 'utf8');
}
return finalCoverage;
};
exitFn = function (matchFn, reporterOpts) {
var cov,
coverageMap,
transformed;
cov = coverageFinderFn() || {};
cov = beforeReportFn(matchFn, cov);
coverageSetterFn(cov);
if (!(cov && typeof cov === 'object') || Object.keys(cov).length === 0) {
console.error('No coverage information was collected, exit without writing coverage information');
return;
}
coverageMap = libCoverage.createCoverageMap(cov);
transformed = sourceMapStore.transformCoverage(coverageMap);
reporterOpts.sourceFinder = transformed.sourceFinder;
reporter.write(transformed.map, reporterOpts);
sourceMapStore.dispose();
};
excludes.push(path.relative(process.cwd(), path.join(reportingDir, '**', '*')));
includes = includes || config.instrumentation.extensions().map(function (ext) {
return '**/*' + ext;
});
var matchConfig = {
root: config.instrumentation.root() || /* istanbul ignore next: untestable */ process.cwd(),
includes: includes,
excludes: excludes
};
matcherFor(matchConfig, function (err, matchFn) {
/* istanbul ignore if: untestable */
if (err) {
return callback(err);
}
return callback(null, {
coverageFn: coverageFinderFn,
hookFn: hookFn.bind(null, matchFn),
exitFn: exitFn.bind(null, matchFn, {}), // XXX: reporter opts
unhookFn: unhookFn.bind(null, matchFn)
});
});
}
module.exports = {
getCoverFunctions: getCoverFunctions
};

208
node_modules/istanbul-api/lib/run-instrument.js generated vendored Normal file
View File

@@ -0,0 +1,208 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
mkdirp = require('mkdirp'),
once = require('once'),
async = require('async'),
fs = require('fs'),
filesFor = require('./file-matcher').filesFor,
libInstrument = require('istanbul-lib-instrument'),
libCoverage = require('istanbul-lib-coverage'),
inputError = require('./input-error');
/*
* Chunk file size to use when reading non JavaScript files in memory
* and copying them over when using complete-copy flag.
*/
var READ_FILE_CHUNK_SIZE = 64 * 1024;
function BaselineCollector(instrumenter) {
this.instrumenter = instrumenter;
this.map = libCoverage.createCoverageMap();
this.instrument = instrumenter.instrument.bind(this.instrumenter);
var origInstrumentSync = instrumenter.instrumentSync;
this.instrumentSync = function () {
var args = Array.prototype.slice.call(arguments),
ret = origInstrumentSync.apply(this.instrumenter, args),
baseline = this.instrumenter.lastFileCoverage();
this.map.addFileCoverage(baseline);
return ret;
};
//monkey patch the instrumenter to call our version instead
instrumenter.instrumentSync = this.instrumentSync.bind(this);
}
BaselineCollector.prototype.getCoverage = function () {
return this.map.toJSON();
};
function processFiles(instrumenter, opts, callback) {
var inputDir = opts.inputDir,
outputDir = opts.outputDir,
relativeNames = opts.names,
extensions = opts.extensions,
verbose = opts.verbose;
var processor = function (name, callback) {
var inputFile = path.resolve(inputDir, name),
outputFile = path.resolve(outputDir, name),
inputFileExtension = path.extname(inputFile),
isJavaScriptFile = extensions.indexOf(inputFileExtension) > -1,
oDir = path.dirname(outputFile),
readStream, writeStream;
callback = once(callback);
mkdirp.sync(oDir);
/* istanbul ignore if */
if (fs.statSync(inputFile).isDirectory()) {
return callback(null, name);
}
if (isJavaScriptFile) {
fs.readFile(inputFile, 'utf8', function (err, data) {
/* istanbul ignore if */ if (err) { return callback(err, name); }
instrumenter.instrument(data, inputFile, function (iErr, instrumented) {
if (iErr) { return callback(iErr, name); }
fs.writeFile(outputFile, instrumented, 'utf8', function (err) {
return callback(err, name);
});
});
});
}
else {
// non JavaScript file, copy it as is
readStream = fs.createReadStream(inputFile, {'bufferSize': READ_FILE_CHUNK_SIZE});
writeStream = fs.createWriteStream(outputFile);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.pipe(writeStream);
readStream.on('end', function() {
callback(null, name);
});
}
},
q = async.queue(processor, 10),
errors = [],
count = 0,
startTime = new Date().getTime();
q.push(relativeNames, function (err, name) {
var inputFile, outputFile;
if (err) {
errors.push({ file: name, error: err.message || /* istanbul ignore next */ err.toString() });
inputFile = path.resolve(inputDir, name);
outputFile = path.resolve(outputDir, name);
fs.writeFileSync(outputFile, fs.readFileSync(inputFile));
}
if (verbose) {
console.error('Processed: ' + name);
} else {
if (count % 100 === 0) { process.stdout.write('.'); }
}
count += 1;
});
q.drain = function () {
var endTime = new Date().getTime();
console.error('\nProcessed [' + count + '] files in ' + Math.floor((endTime - startTime) / 1000) + ' secs');
if (errors.length > 0) {
console.error('The following ' + errors.length + ' file(s) had errors and were copied as-is');
console.error(errors);
}
return callback();
};
}
function run(config, opts, callback) {
opts = opts || {};
var iOpts = config.instrumentation,
input = opts.input,
output = opts.output,
excludes = opts.excludes,
file,
stats,
stream,
includes,
instrumenter,
origCallback = callback,
needBaseline = iOpts.saveBaseline(),
baselineFile = path.resolve(iOpts.baselineFile());
if (iOpts.completeCopy()) {
includes = ['**/*'];
}
else {
includes = iOpts.extensions().map(function(ext) {
return '**/*' + ext;
});
}
if (!input) {
return callback(new Error('No input specified'));
}
instrumenter = libInstrument.createInstrumenter(iOpts.getInstrumenterOpts());
if (needBaseline) {
mkdirp.sync(path.dirname(baselineFile));
instrumenter = new BaselineCollector(instrumenter);
callback = function (err) {
/* istanbul ignore else */
if (!err) {
console.error('Saving baseline coverage at ' + baselineFile);
fs.writeFileSync(baselineFile, JSON.stringify(instrumenter.getCoverage()), 'utf8');
}
return origCallback(err);
};
}
file = path.resolve(input);
stats = fs.statSync(file);
if (stats.isDirectory()) {
if (!output) { return callback(inputError.create('Need an output directory when input is a directory!')); }
if (output === file) { return callback(inputError.create('Cannot instrument into the same directory/ file as input!')); }
mkdirp.sync(output);
filesFor({
root: file,
includes: includes,
excludes: excludes || iOpts.excludes(false),
relative: true
}, function (err, files) {
/* istanbul ignore if */
if (err) { return callback(err); }
processFiles(instrumenter, {
inputDir: file,
outputDir: output,
names: files,
extensions: iOpts.extensions(),
verbose: config.verbose
}, callback);
});
} else {
if (output) {
stream = fs.createWriteStream(output);
} else {
stream = process.stdout;
}
stream.write(instrumenter.instrumentSync(fs.readFileSync(file, 'utf8'), file));
if (stream !== process.stdout) {
stream.end();
}
return callback();
}
}
module.exports = {
run: run
};

53
node_modules/istanbul-api/lib/run-reports.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Reporter = require('./reporter'),
fs = require('fs'),
filesFor = require('./file-matcher').filesFor,
libCoverage = require('istanbul-lib-coverage');
function run(formats, config, opts, callback) {
if (!callback && typeof(opts) === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var root,
coverageMap = libCoverage.createCoverageMap(),
includePattern = opts.include || '**/coverage*.raw.json',
reporter = new Reporter(config);
if (!formats || formats.length === 0) {
formats = config.reporting.reports();
}
try {
reporter.addAll(formats);
} catch (ex) {
ex.inputError = true;
return callback(ex);
}
root = opts.root || process.cwd();
filesFor({
root: root,
includes: [ includePattern ]
}, function (err, files) {
/* istanbul ignore if */
if (err) {
return callback(err);
}
files.forEach(function (file) {
var coverageObject = JSON.parse(fs.readFileSync(file, 'utf8'));
coverageMap.merge(coverageObject);
});
reporter.write(coverageMap, {});
return callback();
});
}
module.exports = {
run: run
};