Added logging, changed some directory structure

This commit is contained in:
2018-01-13 21:33:40 -05:00
parent f079a5f067
commit 8e72ffb917
73656 changed files with 35284 additions and 53718 deletions

View File

@@ -0,0 +1,137 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
<a name="1.2.1"></a>
## [1.2.1](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.2.0...istanbul-api@1.2.1) (2017-10-22)
**Note:** Version bump only for package istanbul-api
<a name="1.2.0"></a>
# [1.2.0](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.2.0) (2017-10-21)
### Features
* hook vm.runInContext ([#90](https://github.com/istanbuljs/istanbuljs/issues/90)) ([9659936](https://github.com/istanbuljs/istanbuljs/commit/9659936))
### Performance Improvements
* set excludes to options.ignore on fileset ([#67](https://github.com/istanbuljs/istanbuljs/issues/67)) ([8b514a3](https://github.com/istanbuljs/istanbuljs/commit/8b514a3))
<a name="1.1.14"></a>
## [1.1.14](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.1.14) (2017-09-05)
### Performance Improvements
* set excludes to options.ignore on fileset ([#67](https://github.com/istanbuljs/istanbuljs/issues/67)) ([8b514a3](https://github.com/istanbuljs/istanbuljs/commit/8b514a3))
<a name="1.1.13"></a>
## [1.1.13](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.1.13) (2017-08-26)
### Performance Improvements
* set excludes to options.ignore on fileset ([#67](https://github.com/istanbuljs/istanbuljs/issues/67)) ([8b514a3](https://github.com/istanbuljs/istanbuljs/commit/8b514a3))
<a name="1.1.12"></a>
## [1.1.12](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.1.12) (2017-08-23)
### Performance Improvements
* set excludes to options.ignore on fileset ([#67](https://github.com/istanbuljs/istanbuljs/issues/67)) ([8b514a3](https://github.com/istanbuljs/istanbuljs/commit/8b514a3))
<a name="1.1.11"></a>
## [1.1.11](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.1.11) (2017-07-16)
### Performance Improvements
* set excludes to options.ignore on fileset ([#67](https://github.com/istanbuljs/istanbuljs/issues/67)) ([8b514a3](https://github.com/istanbuljs/istanbuljs/commit/8b514a3))
<a name="1.1.10"></a>
## [1.1.10](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.9...istanbul-api@1.1.10) (2017-06-25)
<a name="1.1.9"></a>
## [1.1.9](https://github.com/istanbuljs/istanbuljs/compare/istanbul-api@1.1.8...istanbul-api@1.1.9) (2017-05-27)
<a name="1.1.8"></a>
## [1.1.8](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.7...istanbul-api@1.1.8) (2017-04-29)
<a name="1.1.7"></a>
## [1.1.7](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.6...istanbul-api@1.1.7) (2017-03-27)
<a name="1.1.6"></a>
## [1.1.6](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.5...istanbul-api@1.1.6) (2017-03-22)
<a name="1.1.5"></a>
## [1.1.5](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.4...istanbul-api@1.1.5) (2017-03-21)
<a name="1.1.4"></a>
## [1.1.4](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.3...istanbul-api@1.1.4) (2017-03-21)
<a name="1.1.3"></a>
## [1.1.3](https://github.com/istanbuljs/istanbul-api/compare/istanbul-api@1.1.1...istanbul-api@1.1.3) (2017-03-21)
<a name="1.1.1"></a>
## [1.1.1](https://github.com/istanbuljs/istanbul-api/compare/v1.1.0...v1.1.1) (2017-01-17)
### Bug Fixes
* explicit upgrade to version of istanbul-lib-hook with fix for ts-node ([a4af720](https://github.com/istanbuljs/istanbul-api/commit/a4af720))
<a name="1.1.0"></a>
# [1.1.0](https://github.com/istanbuljs/istanbul-api/compare/v1.1.0-alpha.1...v1.1.0) (2016-12-27)
### Bug Fixes
* bump fileset version ([#7](https://github.com/istanbuljs/istanbul-api/issues/7)) ([8750735](https://github.com/istanbuljs/istanbul-api/commit/8750735))
* specify absolute mocha path in npm test script ([#9](https://github.com/istanbuljs/istanbul-api/issues/9)) ([06196e5](https://github.com/istanbuljs/istanbul-api/commit/06196e5))
* use blank ignore, so that the behavior of fileset is non-breaking ([7659ef9](https://github.com/istanbuljs/istanbul-api/commit/7659ef9))
<a name="1.1.0-candidate.0"></a>
# [1.1.0-candidate.0](https://github.com/istanbuljs/istanbul-api/compare/v1.1.0-alpha.1...v1.1.0-candidate.0) (2016-12-19)
### Bug Fixes
* bump fileset version ([#7](https://github.com/istanbuljs/istanbul-api/issues/7)) ([8750735](https://github.com/istanbuljs/istanbul-api/commit/8750735))
* specify absolute mocha path in npm test script ([#9](https://github.com/istanbuljs/istanbul-api/issues/9)) ([06196e5](https://github.com/istanbuljs/istanbul-api/commit/06196e5))
* use blank ignore, so that the behavior of fileset is non-breaking ([7659ef9](https://github.com/istanbuljs/istanbul-api/commit/7659ef9))

View File

@@ -0,0 +1,24 @@
Copyright 2015 Yahoo! Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yahoo! Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,7 @@
istanbul-api
============
[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-api.svg)](https://greenkeeper.io/)
[![Build Status](https://travis-ci.org/istanbuljs/istanbul-api.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-api)
High-level API for istanbul.

View File

@@ -0,0 +1,67 @@
/*
Copyright 2012-2015, Yahoo Inc.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Reporter = require('./lib/reporter');
/**
* @module Exports
*/
module.exports = {
config: require('./lib/config'),
cover: require('./lib/run-cover'),
reports: require('./lib/run-reports'),
instrument: require('./lib/run-instrument'),
checkCoverage: require('./lib/run-check-coverage'),
createReporter: function (cfg, opts) {
return new Reporter(cfg, opts);
},
/**
* asynchronously returns a function that can match filesystem paths.
* The function returned in the callback may be passed directly as a `matcher`
* to the functions in the `hook` module.
*
* When no options are passed, the match function is one that matches all JS
* files under the current working directory except ones under `node_modules`
*
* Match patterns are `ant`-style patterns processed using the `fileset` library.
* Examples not provided due to limitations in putting asterisks inside
* jsdoc comments. Please refer to tests under `test/other/test-matcher.js`
* for examples.
*
* @method matcherFor
* @static
* @param {Object} options Optional. Lookup options.
* @param {String} [options.root] the root of the filesystem tree under
* which to match files. Defaults to `process.cwd()`
* @param {Array} [options.includes] an array of include patterns to match.
* Defaults to all JS files under the root.
* @param {Array} [options.excludes] and array of exclude patterns. File paths
* matching these patterns will be excluded by the returned matcher.
* Defaults to files under `node_modules` found anywhere under root.
* @param {Function(err, matchFunction)} callback The callback that is
* called with two arguments. The first is an `Error` object in case
* of errors or a falsy value if there were no errors. The second
* is a function that may be use as a matcher.
*/
matcherFor: require('./lib/file-matcher').matcherFor,
filesFor: require('./lib/file-matcher').filesFor
};
// export all the istanbul libraries as is so users don't have to take 5 deps
// that are potentially inconsistent
var DASH_PATTERN = /-([a-z])/g;
function camelize(word) {
return word.replace(DASH_PATTERN, function (match, lch) {
return lch.toUpperCase();
});
}
[ 'coverage', 'hook', 'instrument', 'report', 'source-maps'].forEach(function (k) {
var mod = 'lib-' + k,
prop = camelize(mod);
module.exports[prop] = require('istanbul-' + mod);
});
module.exports.reportsImpl = require('istanbul-reports');

View File

@@ -0,0 +1,504 @@
/*
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
},
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');
/**
* 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()
};
};
/**
* 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
};

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
};

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;
};

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;

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
};

View File

@@ -0,0 +1,209 @@
/*
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'),
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,
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, file) {
return instrumenter.instrumentSync(code, file);
};
requireTransformer = function (code, file) {
var cov,
ret = transformer(code, file);
if (fakeRequire) {
cov = coverageFinderFn();
cov[file] = 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, transformer, hookOpts);
}
if (config.hooks.hookRunInThisContext()) {
hook.hookRunInThisContext(matchFn, transformer, hookOpts);
}
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
};

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
};

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
};

View File

@@ -0,0 +1,81 @@
{
"_args": [
[
"istanbul-api@1.2.1",
"C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project"
]
],
"_from": "istanbul-api@1.2.1",
"_id": "istanbul-api@1.2.1",
"_inBundle": false,
"_integrity": "sha512-oFCwXvd65amgaPCzqrR+a2XjanS1MvpXN6l/MlMUTv6uiA1NOgGX+I0uyq8Lg3GDxsxPsaP1049krz3hIJ5+KA==",
"_location": "/react-scripts/istanbul-api",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "istanbul-api@1.2.1",
"name": "istanbul-api",
"escapedName": "istanbul-api",
"rawSpec": "1.2.1",
"saveSpec": null,
"fetchSpec": "1.2.1"
},
"_requiredBy": [
"/react-scripts/jest/jest-cli"
],
"_resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-1.2.1.tgz",
"_spec": "1.2.1",
"_where": "C:\\Users\\deranjer\\go\\src\\github.com\\deranjer\\goTorrent\\torrent-project",
"author": {
"name": "Krishnan Anantheswaran",
"email": "kananthmail-github@yahoo.com"
},
"bugs": {
"url": "https://github.com/istanbuljs/istanbuljs/issues"
},
"dependencies": {
"async": "^2.1.4",
"fileset": "^2.0.2",
"istanbul-lib-coverage": "^1.1.1",
"istanbul-lib-hook": "^1.1.0",
"istanbul-lib-instrument": "^1.9.1",
"istanbul-lib-report": "^1.1.2",
"istanbul-lib-source-maps": "^1.2.2",
"istanbul-reports": "^1.1.3",
"js-yaml": "^3.7.0",
"mkdirp": "^0.5.1",
"once": "^1.4.0"
},
"description": "High level API for istanbul features",
"devDependencies": {
"chai": "^3.0.0",
"is-windows": "^1.0.0",
"jshint": "^2.8.0",
"memory-streams": "^0.1.0",
"mocha": "^3.1.2",
"rimraf": "^2.6.1"
},
"files": [
"lib",
"index.js"
],
"homepage": "https://github.com/istanbuljs/istanbuljs#readme",
"keywords": [
"istanbul",
"api"
],
"license": "BSD-3-Clause",
"main": "index.js",
"name": "istanbul-api",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git"
},
"scripts": {
"fast": "mocha --slow 1000",
"pretest": "jshint index.js lib/ test/",
"test": "mocha"
},
"version": "1.2.1"
}