Current Dev State

This commit is contained in:
Tim Lorsbach
2025-06-23 20:13:54 +02:00
parent b4f9bb277d
commit ded50edaa2
22617 changed files with 4345095 additions and 174 deletions

362
static/js/ketcher2/node_modules/istanbul/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,362 @@
Changelog
---------
<table>
<tr>
<td>0.4.5</td>
<td>
<ul>
<li>log filename when file fails to parse using esprima, thanks to @djorg83</li>
<li>swap fileset for glob (security fix), thanks to @popomore and @graingert</li>
</ul>
</td>
</tr>
<tr>
<td>0.4.4</td>
<td>
<ul>
<li>Handle ExportNamedDeclaration, thanks to @VictoryStick</li>
<li>Use tmpdir setting in temp store, thanks to @inversion</li>
<li>Set "medium" coverage CSS color scheme to yellow, thanks to @JamesMGreene</li>
<li>use os.tmpdir() instead of os.tmpDir(), thanks to @ChALkeR</li>
</ul>
</td>
</tr>
<tr>
<td>0.4.3</td>
<td>
<ul>
<li>Create new handlebars instance for the HTML report, thanks to @doowb</li>
<li>MetaProperty support thanks to @steve-gray</li>
<li>Use ansi colors from 16-color palette for better console support, thanks to @jtangelder</li>
<li>Misc doc/ css fixes thanks to @pra85, @abejfehr</li>
</ul>
</td>
</tr>
<tr>
<td>0.4.2</td>
<td>Fix confusing error message on check-coverage failures, thanks to @isaacs/td>
</tr>
<tr>
<td>v0.4.1</td>
<td>
<ul>
<li>Update esprima to 2.7.x, thanks to @ariya</li>
<li>Make table header clickable in HTML report, thanks to @iphands</li>
<li>Fix strict mode issues thanks to @kpdecker</li>
<li>update ignore code example for UMD, thanks to @pgurnee</li>
<li>misc build fixes, no user visible changes, thanks to @ariya</li>
</ul>
</td>
</tr>
<tr>
<td>v0.4.0</td>
<td>
<ul>
<li>HTML report design, thanks a bunch to @tmcw</li>
<li>"loading config file" message on the console is now tied to the verbose state, thanks @asa-git</li>
<li>Add the `l` property to documentation, thanks @kitsonk</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.21</td>
<td>
<ul>
<li>Updated dependencies to the latest</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.20</td>
<td>
<ul>
<li>Fix broken es6 `super` support, thanks @sterlinghw</li>
<li>Improve readability via better lineHeight, thanks @dhoko</li>
<li>Adding ability to set custom block name in teamcity report, thanks @aryelu</li>
<li>Replaced deprecated util.puts with console.log, thanks @arty-name
</ul>
</td>
</tr>
<tr>
<td>v0.3.19</td>
<td>Fix instrumenter for multiple blank array positions, thanks @alexdunphy</td>
</tr>
<tr>
<tr>
<td>v0.3.18</td>
<td>Upgrade esprima, get support for more ES6 features</td>
</tr>
<tr>
<td>v0.3.17</td>
<td>Upgrade esprima, get correct for-of support</td>
</tr>
<tr>
<td>v0.3.16</td>
<td>
<ul>
<li>upgrades to filset and async modules, thanks to @roderickhsiao, @popomore</li>
<li>updated text reporter so that it displays a list of the lines missing coverage, thanks @bcoe</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.15</td>
<td>
<ul>
<li>Fix #375: add nodir option to exclude directory for *.js matcher thanks to @yurenju</li>
<li>Fix #362: When setting up the `reportDir` add it to `reporter.dir`</li>
<li>Fixes #238 (added a poorman's clone)</li>
<li>Incrementing hits on ignored statements implemented</li>
<li>`a:visited color: #777` (a nice gray color)</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.14</td>
<td>
Add text-lcov report format to emit lcov to console, thanks to @bcoe
</td>
</tr>
<tr>
<td>v0.3.13</td>
<td>
Fix #339
</td>
</tr>
<tr>
<td>v0.3.12</td>
<td>
Allow other-than-dot-js files to be hooked, thanks to @sethpollack
</td>
</tr>
<tr>
<td>v0.3.11</td>
<td>
Avoid modification of global objects, thanks to @dominykas
</td>
</tr>
<tr>
<td>v0.3.10</td>
<td>
Update escodegen to 1.6.x and add browser download script
</td>
</tr>
<tr>
<td>v0.3.9</td>
<td>
<ul>
<li>Merge harmony branch and start adding ES6 features to istanbul</li>
<li>Arrow functions are the only feature of interest now</li>
<li>`for-of` and `yield` support exist but not present in mainline esprima yet</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.8</td>
<td>
<ul>
<li>Fail check coverage command when no coverage files found, thanks to @nexus-uw</li>
<li>handle relative paths in check-coverage, thanks to @dragn</li>
<li>support explicit includes for cover, thanks to @tonylukasavage</li>
</ul>
</td>
</tr>
<tr>
<td>v0.3.7</td>
<td>
Fix asset paths on windows, thanks to @juangabreil
</td>
</tr>
<tr>
<td>v0.3.6</td>
<td>
<ul>
<li>Update to Esprima 2.0</li>
<li>Remove YUI dependency and provide custom sort code. No network access needed for HTML report view</li>
<li>use supports-color module to colorize output, thanks to @gustavnikolaj</li>
<li>Fix tests to work on Windows, thanks to @dougwilson</li>
<li>Docs: "Instrument code" API example correction thanks to @robatron</li>
<li>Extracted embedded CSS and JavaScript and made them external files, thanks to @booleangate</td>
</ul>
</td>
</tr>
<tr>
<td>v0.3.5</td>
<td>
<p>Merge #275 - `--include-all-sources` option. Thanks @gustavnikolaj</p>
<p>
The `--preload-sources` option is now deprecated and superseded by the
`--include-all-sources` option instead. This provides a better coverage representation
of the code that has not been included for testing.
</p>
</td>
</tr>
<tr>
<td>v0.3.4</td>
<td>Merge #219 - Support reporting within symlink/junction. Thanks to @dougwilson</td>
</tr>
<tr>
<td>v0.3.3</td>
<td>Merge #268 - per file coverage enforcement. Thanks to @ryan-roemer</td>
</tr>
<tr>
<td>v0.3.2</td>
<td>Republish 0.3.1 because of bad shasum</td>
</tr>
<tr>
<td>v0.3.1</td>
<td>Fixes #249</td>
</tr>
<tr>
<td>v0.3.0</td>
<td>
The *reports* release. **Potentially backwards-incompatible** if you are using
undocumented features or custom report implementations.
<ul>
<li>Change report command line to support multiple reports, add back-compat processing with warnings</li>
<li>Enable `report` command to read report list from config, thanks to @piuccio</li>
<li>Support multiple reports for `cover` and `report` commands</li>
<li>Support per-report config options in configuration file</li>
<li>Turn reports into event emitters so they can signal `done`</li>
<li>Add `Reporter` class to be able to generate multiple reports</li>
<li>Add a bunch of API docs, refactor README</li>
</ul>
</td>
</tr>
<tr>
<td>v0.2.16</td><td>Make YUI links https-always since relative links break local
filesystem use-case
</td>
</tr>
<tr>
<td>v0.2.15</td><td>make link protocols relative so they don't break on https connections
(thanks to @yasyf)
</td>
</tr>
<tr>
<td>v0.2.14</td><td>Fix hook to deal with non-string/ missing filenames
(thanks to @jason0x43), update dependencies
</td>
</tr>
<tr>
<td>v0.2.13</td><td>Add `--preload-sources` option to `cover` command to make
code not required by tests to appear in the coverage report.
</td>
</tr>
<tr>
<td>v0.2.12</td><td>Text summary as valid markdown, thanks to @smikes</td>
</tr>
<tr>
<td>v0.2.11</td><td>Allow source map generation, thanks to @jason0x43</td>
</tr>
<tr>
<td>v0.2.10</td><td>Add flag to handle sigints and dump coverage, thanks to @samccone</td>
</tr>
<tr>
<td>v0.2.9</td><td>Fix #202</td>
</tr>
<tr>
<tr>
<td>v0.2.8</td><td>Upgrade esprima</td>
</tr>
<tr>
<td>v0.2.7</td><td><ul>
<li>Upgrade esprima</li>
<li>Misc jshint fixes</li>
</ul></td>
</tr>
<tr>
<td>v0.2.6</td><td><ul>
<li>Revert bad commit for tree summarizer</li>
</ul></td>
</tr>
<tr>
<td>v0.2.5</td><td><ul>
<li>Add clover report, thanks to @bixdeng, @mpderbec</li>
<li>Fix cobertura report bug for relative paths, thanks to @jxiaodev</li>
<li>Run self-coverage on tests always</li>
<li>Fix tree summarizer when relative paths are involved, thanks to @Swatinem</li>
</ul></td>
</tr>
<tr>
<td>v0.2.4</td><td><ul>
<li>Fix line-split algo to handle Mac lin separators, thanks to @asifrc</li>
<li>Update README for quick intro to ignoring code for coverage, thanks to @gergelyke</li>
</ul></td>
</tr>
<tr>
<td>v0.2.3</td><td><ul>
<li>Add YAML config file. `istanbul help config` has more details</li>
<li>Support custom reporting thresholds using the `watermarks` section of the config file</li>
</ul></td>
</tr>
<tr><td>v0.2.2</td><td>update escodegen, handlebars and resolve dependency versions</td></tr>
<tr>
<td>v0.2.1</td><td><ul>
<li>Add ability to skip branches and other hard-to-test code using comments.
See <a href="https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md">the doc</a> for more details</li>
<li>Turn `util.error` into `console.error` for node 0.11 compatibility, thanks to @pornel</li>
</ul></td>
</tr>
<tr><td>v0.2.0</td><td><ul>
<li>Add --preserve-comments to instrumenter options, thanks to @arikon</li>
<li>Support 'use strict;' in file scope, thanks to @pornel</li>
</ul>
Up minor version due to the new way in which the global object is accessed.
This _should_ be backwards-compatible but has not been tested in the wild.
</td></tr>
<tr><td>v0.1.46</td><td>Fix #114</td></tr>
<tr><td>v0.1.45</td><td>Add teamcity reporter, thanks to @chrisgladd</td></tr>
<tr><td>v0.1.44</td><td>Fix inconsistency in processing empty switch with latest esprima, up deps</td></tr>
<tr><td>v0.1.43</td><td>Add colors to text report thanks to @runk</td></tr>
<tr><td>v0.1.42</td><td>fix #78: embed source regression introduced in v0.1.38. Fix broken test for this</td></tr>
<tr><td>v0.1.41</td><td>add json report to dump coverage object for certain use cases</td></tr>
<tr><td>v0.1.40</td><td>forward sourceStore from lcov to html report, pull request by @vojtajina</td></tr>
<tr><td>v0.1.39</td><td>add <source> tag to cobertura report, pull request by @jhansche</td></tr>
<tr><td>v0.1.38</td><td><ul>
<li>factor out AST instrumentation into own instrumentASTSync method</li>
<li>always set function declaration coverage stats to 1 since every such declaration is "executed" exactly one time by the compiler</li>
</ul></td></tr>
<tr><td>v0.1.37</td><td>--complete-copy flag contrib from @kami, correct strict mode semantics for instrumented functions</td></tr>
<tr><td>v0.1.36</td><td>real quiet when --print=none specified, add repo URL to package.json, add contributors</td></tr>
<tr><td>v0.1.35</td><td>accept cobertura contrib from @nbrownus, fix #52</td></tr>
<tr><td>v0.1.34</td><td>fix async reporting, update dependencies, accept html cleanup contrib from @mathiasbynens</td></tr>
<tr><td>v0.1.33</td><td>initialize global coverage object before running tests to workaround mocha leak detection</td></tr>
<tr><td>v0.1.32</td><td>Fix for null nodes in array expressions, add @unindented as contributor</td></tr>
<tr><td>v0.1.31</td><td>Misc internal fixes and test changes</td></tr>
<tr><td>v0.1.30</td><td>Write standard blurbs ("writing coverage object..." etc.) to stderr rather than stdout</td></tr>
<tr><td>v0.1.29</td><td>Allow --post-require-hook to be a module that can be `require`-d</td></tr>
<tr><td>v0.1.28</td><td>Add --post-require-hook switch to support use-cases similar to the YUI loader</td></tr>
<tr><td>v0.1.27</td><td>Add --hook-run-in-context switch to support RequireJS modules. Thanks to @millermedeiros for the pull request</td></tr>
<tr><td>v0.1.26</td><td>Add support for minimum uncovered unit for check-coverage. Fixes #25</td></tr>
<tr><td>v0.1.25</td><td>Allow for relative paths in the YUI loader hook</td></tr>
<tr><td>v0.1.24</td><td>Add lcov summaries. Fixes issue #20</td></tr>
<tr><td>v0.1.23</td><td>Add ability to save a baseline coverage file for the instrument command. Fixes issue #19</td></tr>
<tr><td>v0.1.22</td><td>Add signature attribute to cobertura method tags to fix NPE by the Hudson publisher</td></tr>
<tr><td>v0.1.21</td><td>Add cobertura XML report format; exprimental for now</td></tr>
<tr><td>v0.1.20</td><td>Fix HTML/ lcov report interface to be more customizable for middleware needs</td></tr>
<tr><td>v0.1.19</td><td>make all hooking non-destructive in that already loaded modules are never reloaded. Add self-test mode so that already loaded istanbul modules can be unloaded prior to hooking.</td></tr>
<tr><td>v0.1.18</td><td>Add option to hook in non-destructive mode; i.e. the require cache is not unloaded when hooking</td></tr>
<tr><td>v0.1.17</td><td>Export some more objects; undocumented for now</td></tr>
<tr><td>v0.1.16</td><td>Fix npm keywords for istanbul which expects an array of strings but was being fed a single string with keywords instead</td></tr>
<tr><td>v0.1.15</td><td>Add the 'check-coverage' command so that Istanbul can be used as a posttest script to enforce minimum coverage</td></tr>
<tr><td>v0.1.14</td><td>Expose the experimental YUI load hook in the interface</td></tr>
<tr><td>v0.1.13</td><td>Internal jshint cleanup, no features or fixes</td></tr>
<tr><td>v0.1.12</td><td>Give npm the README that was getting inadvertently excluded</td></tr>
<tr><td>v0.1.11</td><td>Merge pull request #14 for HTML tweaks. Thanks @davglass. Add @davglass and @nowamasa as contributors in `package.json`</td></tr>
<tr><td>v0.1.10</td><td>Fix to issue #12. Do not install `uncaughtException` handler and pass input error back to CLI using a callback as opposed to throwing.</td></tr>
<tr><td>v0.1.9</td><td>Attempt to create reporting directory again just before writing coverage in addition to initial creation</td></tr>
<tr><td>v0.1.8</td><td>Fix issue #11.</td></tr>
<tr><td>v0.1.7</td><td>Add text summary and detailed reporting available as --print [summary|detail|both|none]. summary is the default if nothing specified.</td></tr>
<tr><td>v0.1.6</td><td>Handle backslashes in the file path correctly in emitted code. Fixes #9. Thanks to @nowamasa for bug report and fix</td></tr>
<tr><td>v0.1.5</td><td>make object-utils.js work on a browser as-is</td></tr>
<tr><td>v0.1.4</td><td>partial fix for issue #4; add titles to missing coverage spans, remove negative margin for missing if/else indicators</td></tr>
<tr><td>v0.1.3</td><td>Set the environment variable running_under_istanbul to 1 when that is the case. This allows test runners that use istanbul as a library to back off on using it when set.</td></tr>
<tr><td>v0.1.2</td><td>HTML reporting cosmetics. Reports now show syntax-colored JS using `prettify`. Summary tables no longer wrap in awkward places.</td></tr>
<tr><td>v0.1.1</td><td>Fixes issue #1. HTML reports use sources embedded inside the file coverage objects if found rather than reading from the filesystem</td></tr>
<tr><td>v0.1.0</td><td>Initial version</td></tr>
</td></tr>
</table>

24
static/js/ketcher2/node_modules/istanbul/LICENSE generated vendored Normal file
View File

@ -0,0 +1,24 @@
Copyright 2012 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.

288
static/js/ketcher2/node_modules/istanbul/README.md generated vendored Normal file
View File

@ -0,0 +1,288 @@
## Istanbul - a JS code coverage tool written in JS
[![Build Status](https://secure.travis-ci.org/gotwarlost/istanbul.svg?branch=master)](http://travis-ci.org/gotwarlost/istanbul)
[![Dependency Status](https://gemnasium.com/gotwarlost/istanbul.svg)](https://gemnasium.com/gotwarlost/istanbul)
[![Coverage Status](https://img.shields.io/coveralls/gotwarlost/istanbul.svg)](https://coveralls.io/r/gotwarlost/istanbul?branch=master)
[![bitHound Score](https://www.bithound.io/github/gotwarlost/istanbul/badges/score.svg)](https://www.bithound.io/github/gotwarlost/istanbul)
[![NPM](https://nodei.co/npm/istanbul.png?downloads=true)](https://nodei.co/npm/istanbul/)
**New** `v0.4.0` now has beautiful HTML reports. Props to Tom MacWright @tmcw for a fantastic job!
* [Features and use cases](#features)
* [Getting started and configuration](#getting-started)
* [Usage on Windows](#usage-on-windows)
* [The command line](#the-command-line)
* [Ignoring code for coverage](#ignoring-code-for-coverage)
* [API](#api)
* [Changelog](https://github.com/gotwarlost/istanbul/blob/master/CHANGELOG.md)
* [License and credits](#license)
### Features
* All-javascript instrumentation library that tracks **statement, branch,
and function coverage**.
* **Module loader hooks** to instrument code on the fly
* **Command line tools** to run node unit tests "with coverage turned on" and no cooperation
whatsoever from the test runner
* Multiple report formats: **HTML**, **LCOV**, **Cobertura** and more.
* Ability to use as [middleware](https://github.com/gotwarlost/istanbul-middleware) when serving JS files that need to be tested on the browser.
* Can be used on the **command line** as well as a **library**
* Based on the awesome `esprima` parser and the equally awesome `escodegen` code generator
* Well-tested on node (prev, current and next versions) and the browser (instrumentation library only)
### Use cases
Supports the following use cases and more
* transparent coverage of nodejs unit tests
* instrumentation/ reporting of files in batch mode for browser tests
* Server side code coverage for nodejs by embedding it as [custom middleware](https://github.com/gotwarlost/istanbul-middleware)
### Getting started
$ npm install -g istanbul
The best way to see it in action is to run node unit tests. Say you have a test
script `test.js` that runs all tests for your node project without coverage.
Simply:
$ cd /path/to/your/source/root
$ istanbul cover test.js
and this should produce a `coverage.json`, `lcov.info` and `lcov-report/*html` under `./coverage`
Sample of code coverage reports produced by this tool (for this tool!):
[HTML reports](http://gotwarlost.github.com/istanbul/public/coverage/lcov-report/index.html)
### Usage on Windows
Istanbul assumes that the `command` passed to it is a JS file (e.g. Jasmine, vows etc.),
this is however not true on Windows where npm wrap bin files in a `.cmd` file.
Since Istanbul can not parse `.cmd` files you need to reference the bin file manually.
Here is an example using Jasmine 2:
istanbul cover node_modules\jasmine\bin\jasmine.js
In order to use this cross platform (e.i. Linux, Mac and Windows), you can insert
the above line into the script object in your package.json file but with normal
slash.
"scripts": {
"test": "istanbul cover node_modules/jasmine/bin/jasmine.js"
}
### Configuring
Drop a `.istanbul.yml` file at the top of the source tree to configure istanbul.
`istanbul help config` tells you more about the config file format.
### The command line
$ istanbul help
gives you detailed help on all commands.
```
Usage: istanbul help config | <command>
`config` provides help with istanbul configuration
Available commands are:
check-coverage
checks overall/per-file coverage against thresholds from coverage
JSON files. Exits 1 if thresholds are not met, 0 otherwise
cover transparently adds coverage information to a node command. Saves
coverage.json and reports at the end of execution
help shows help
instrument
instruments a file or a directory tree and writes the
instrumented code to the desired output location
report writes reports for coverage JSON objects produced in a previous
run
test cover a node command only when npm_config_coverage is set. Use in
an `npm test` script for conditional coverage
Command names can be abbreviated as long as the abbreviation is unambiguous
```
To get detailed help for a command and what command-line options it supports, run:
istanbul help <command>
(Most of the command line options are not covered in this document.)
#### The `cover` command
$ istanbul cover my-test-script.js -- my test args
# note the -- between the command name and the arguments to be passed
The `cover` command can be used to get a coverage object and reports for any arbitrary
node script. By default, coverage information is written under `./coverage` - this
can be changed using command-line options.
The `cover` command can also be passed an optional `--handle-sigint` flag to
enable writing reports when a user triggers a manual SIGINT of the process that is
being covered. This can be useful when you are generating coverage for a long lived process.
#### The `test` command
The `test` command has almost the same behavior as the `cover` command, except that
it skips coverage unless the `npm_config_coverage` environment variable is set.
**This command is deprecated** since the latest versions of npm do not seem to
set the `npm_config_coverage` variable.
#### The `instrument` command
Instruments a single JS file or an entire directory tree and produces an output
directory tree with instrumented code. This should not be required for running node
unit tests but is useful for tests to be run on the browser.
#### The `report` command
Writes reports using `coverage*.json` files as the source of coverage information.
Reports are available in multiple formats and can be individually configured
using the istanbul config file. See `istanbul help report` for more details.
#### The `check-coverage` command
Checks the coverage of statements, functions, branches, and lines against the
provided thresholds. Positive thresholds are taken to be the minimum percentage
required and negative numbers are taken to be the number of uncovered entities
allowed.
### Ignoring code for coverage
* Skip an `if` or `else` path with `/* istanbul ignore if */` or `/* istanbul ignore else */` respectively.
* For all other cases, skip the next 'thing' in the source with: `/* istanbul ignore next */`
See [ignoring-code-for-coverage.md](ignoring-code-for-coverage.md) for the spec.
### API
All the features of istanbul can be accessed as a library.
#### Instrument code
```javascript
var istanbul = require('istanbul');
var instrumenter = new istanbul.Instrumenter();
var generatedCode = instrumenter.instrumentSync('function meaningOfLife() { return 42; }',
'filename.js');
```
#### Generate reports given a bunch of coverage JSON objects
```javascript
var istanbul = require('istanbul'),
collector = new istanbul.Collector(),
reporter = new istanbul.Reporter(),
sync = false;
collector.add(obj1);
collector.add(obj2); //etc.
reporter.add('text');
reporter.addAll([ 'lcov', 'clover' ]);
reporter.write(collector, sync, function () {
console.log('All reports generated');
});
```
For the gory details consult the [public API](http://gotwarlost.github.com/istanbul/public/apidocs/index.html)
### Multiple Process Usage
Istanbul can be used in a multiple process environment by running each process
with Istanbul, writing a unique coverage file for each process, and combining
the results when generating reports. The method used to perform this will
depend on the process forking API used. For example when using the
[cluster module](http://nodejs.org/api/cluster.html) you must setup the master
to start child processes with Istanbul coverage, disable reporting, and output
coverage files that include the PID in the filename. Before each run you may
need to clear out the coverage data directory.
```javascript
if(cluster.isMaster) {
// setup cluster if running with istanbul coverage
if(process.env.running_under_istanbul) {
// use coverage for forked process
// disabled reporting and output for child process
// enable pid in child process coverage filename
cluster.setupMaster({
exec: './node_modules/.bin/istanbul',
args: [
'cover', '--report', 'none', '--print', 'none', '--include-pid',
process.argv[1], '--'].concat(process.argv.slice(2))
});
}
// ...
// ... cluster.fork();
// ...
} else {
// ... worker code
}
```
### Coverage.json
For details on the format of the coverage.json object, [see here](./coverage.json.md).
### License
istanbul is licensed under the [BSD License](http://github.com/gotwarlost/istanbul/raw/master/LICENSE).
### Third-party libraries
The following third-party libraries are used by this module:
* abbrev: https://github.com/isaacs/abbrev-js - to handle command abbreviations
* async: https://github.com/caolan/async - for parallel instrumentation of files
* escodegen: https://github.com/Constellation/escodegen - for JS code generation
* esprima: https://github.com/ariya/esprima - for JS parsing
* glob: https://github.com/isaacs/node-glob - for loading and matching path expressions
* handlebars: https://github.com/wycats/handlebars.js/ - for report template expansion
* js-yaml: https://github.com/nodeca/js-yaml - for YAML config file load
* mkdirp: https://github.com/substack/node-mkdirp - to create output directories
* nodeunit: https://github.com/caolan/nodeunit - dev dependency for unit tests
* nopt: https://github.com/isaacs/nopt - for option parsing
* once: https://github.com/isaacs/once - to ensure callbacks are called once
* resolve: https://github.com/substack/node-resolve - for resolving a post-require hook module name into its main file.
* rimraf - https://github.com/isaacs/rimraf - dev dependency for unit tests
* which: https://github.com/isaacs/node-which - to resolve a node command to a file for the `cover` command
* wordwrap: https://github.com/substack/node-wordwrap - for prettier help
* prettify: http://code.google.com/p/google-code-prettify/ - for syntax colored HTML reports. Files checked in under `lib/vendor/`
### Inspired by
* YUI test coverage - https://github.com/yui/yuitest - the grand-daddy of JS coverage tools. Istanbul has been specifically designed to offer an alternative to this library with an easy migration path.
* cover: https://github.com/itay/node-cover - the inspiration for the `cover` command, modeled after the `run` command in that tool. The coverage methodology used by istanbul is quite different, however
### Shout out to
* [mfncooper](https://github.com/mfncooper) - for great brainstorming discussions
* [reid](https://github.com/reid), [davglass](https://github.com/davglass), the YUI dudes, for interesting conversations, encouragement, support and gentle pressure to get it done :)
### Why the funky name?
Since all the good ones are taken. Comes from the loose association of ideas across
coverage, carpet-area coverage, the country that makes good carpets and so on...

153
static/js/ketcher2/node_modules/istanbul/index.js generated vendored Normal file
View File

@ -0,0 +1,153 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
/*jslint nomen: true */
var path = require('path'),
Store = require('./lib/store'),
Report = require('./lib/report'),
meta = require('./lib/util/meta');
//register our standard plugins
require('./lib/register-plugins');
/**
* the top-level API for `istanbul`. provides access to the key libraries in
* istanbul so you can write your own tools using `istanbul` as a library.
*
* Usage
* -----
*
* var istanbul = require('istanbul');
*
*
* @class Istanbul
* @static
* @module main
* @main main
*/
module.exports = {
/**
* the Instrumenter class.
* @property Instrumenter
* @type Instrumenter
* @static
*/
Instrumenter: require('./lib/instrumenter'),
/**
* the Store class.
* @property Store
* @type Store
* @static
*/
Store: Store,
/**
* the Collector class
* @property Collector
* @type Collector
* @static
*/
Collector: require('./lib/collector'),
/**
* the hook module
* @property hook
* @type Hook
* @static
*/
hook: require('./lib/hook'),
/**
* the Report class
* @property Report
* @type Report
* @static
*/
Report: Report,
/**
* the config module
* @property config
* @type Config
* @static
*/
config: require('./lib/config'),
/**
* the Reporter class
* @property Reporter
* @type Reporter
* @static
*/
Reporter: require('./lib/reporter'),
/**
* utility for processing coverage objects
* @property utils
* @type ObjectUtils
* @static
*/
utils: require('./lib/object-utils'),
/**
* 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 `glob` 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/util/file-matcher').matcherFor,
/**
* the version of the library
* @property VERSION
* @type String
* @static
*/
VERSION: meta.VERSION,
/**
* the abstract Writer class
* @property Writer
* @type Writer
* @static
*/
Writer: require('./lib/util/writer').Writer,
/**
* the abstract ContentWriter class
* @property ContentWriter
* @type ContentWriter
* @static
*/
ContentWriter: require('./lib/util/writer').ContentWriter,
/**
* the concrete FileWriter class
* @property FileWriter
* @type FileWriter
* @static
*/
FileWriter: require('./lib/util/file-writer'),
//undocumented
_yuiLoadHook: require('./lib/util/yui-load-hook'),
//undocumented
TreeSummarizer: require('./lib/util/tree-summarizer'),
//undocumented
assetsDir: path.resolve(__dirname, 'lib', 'assets')
};

View File

@ -0,0 +1,213 @@
body, html {
margin:0; padding: 0;
height: 100%;
}
body {
font-family: Helvetica Neue, Helvetica, Arial;
font-size: 14px;
color:#333;
}
.small { font-size: 12px; }
*, *:after, *:before {
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
}
h1 { font-size: 20px; margin: 0;}
h2 { font-size: 14px; }
pre {
font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace;
margin: 0;
padding: 0;
-moz-tab-size: 2;
-o-tab-size: 2;
tab-size: 2;
}
a { color:#0074D9; text-decoration:none; }
a:hover { text-decoration:underline; }
.strong { font-weight: bold; }
.space-top1 { padding: 10px 0 0 0; }
.pad2y { padding: 20px 0; }
.pad1y { padding: 10px 0; }
.pad2x { padding: 0 20px; }
.pad2 { padding: 20px; }
.pad1 { padding: 10px; }
.space-left2 { padding-left:55px; }
.space-right2 { padding-right:20px; }
.center { text-align:center; }
.clearfix { display:block; }
.clearfix:after {
content:'';
display:block;
height:0;
clear:both;
visibility:hidden;
}
.fl { float: left; }
@media only screen and (max-width:640px) {
.col3 { width:100%; max-width:100%; }
.hide-mobile { display:none!important; }
}
.quiet {
color: #7f7f7f;
color: rgba(0,0,0,0.5);
}
.quiet a { opacity: 0.7; }
.fraction {
font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace;
font-size: 10px;
color: #555;
background: #E8E8E8;
padding: 4px 5px;
border-radius: 3px;
vertical-align: middle;
}
div.path a:link, div.path a:visited { color: #333; }
table.coverage {
border-collapse: collapse;
margin: 10px 0 0 0;
padding: 0;
}
table.coverage td {
margin: 0;
padding: 0;
vertical-align: top;
}
table.coverage td.line-count {
text-align: right;
padding: 0 5px 0 20px;
}
table.coverage td.line-coverage {
text-align: right;
padding-right: 10px;
min-width:20px;
}
table.coverage td span.cline-any {
display: inline-block;
padding: 0 5px;
width: 100%;
}
.missing-if-branch {
display: inline-block;
margin-right: 5px;
border-radius: 3px;
position: relative;
padding: 0 4px;
background: #333;
color: yellow;
}
.skip-if-branch {
display: none;
margin-right: 10px;
position: relative;
padding: 0 4px;
background: #ccc;
color: white;
}
.missing-if-branch .typ, .skip-if-branch .typ {
color: inherit !important;
}
.coverage-summary {
border-collapse: collapse;
width: 100%;
}
.coverage-summary tr { border-bottom: 1px solid #bbb; }
.keyline-all { border: 1px solid #ddd; }
.coverage-summary td, .coverage-summary th { padding: 10px; }
.coverage-summary tbody { border: 1px solid #bbb; }
.coverage-summary td { border-right: 1px solid #bbb; }
.coverage-summary td:last-child { border-right: none; }
.coverage-summary th {
text-align: left;
font-weight: normal;
white-space: nowrap;
}
.coverage-summary th.file { border-right: none !important; }
.coverage-summary th.pct { }
.coverage-summary th.pic,
.coverage-summary th.abs,
.coverage-summary td.pct,
.coverage-summary td.abs { text-align: right; }
.coverage-summary td.file { white-space: nowrap; }
.coverage-summary td.pic { min-width: 120px !important; }
.coverage-summary tfoot td { }
.coverage-summary .sorter {
height: 10px;
width: 7px;
display: inline-block;
margin-left: 0.5em;
background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent;
}
.coverage-summary .sorted .sorter {
background-position: 0 -20px;
}
.coverage-summary .sorted-desc .sorter {
background-position: 0 -10px;
}
.status-line { height: 10px; }
/* dark red */
.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 }
.low .chart { border:1px solid #C21F39 }
/* medium red */
.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE }
/* light red */
.low, .cline-no { background:#FCE1E5 }
/* light green */
.high, .cline-yes { background:rgb(230,245,208) }
/* medium green */
.cstat-yes { background:rgb(161,215,106) }
/* dark green */
.status-line.high, .high .cover-fill { background:rgb(77,146,33) }
.high .chart { border:1px solid rgb(77,146,33) }
/* dark yellow (gold) */
.medium .chart { border:1px solid #f9cd0b; }
.status-line.medium, .medium .cover-fill { background: #f9cd0b; }
/* light yellow */
.medium { background: #fff4c2; }
/* light gray */
span.cline-neutral { background: #eaeaea; }
.cbranch-no { background: yellow !important; color: #111; }
.cstat-skip { background: #ddd; color: #111; }
.fstat-skip { background: #ddd; color: #111 !important; }
.cbranch-skip { background: #ddd !important; color: #111; }
.cover-fill, .cover-empty {
display:inline-block;
height: 12px;
}
.chart {
line-height: 0;
}
.cover-empty {
background: white;
}
.cover-full {
border-right: none !important;
}
pre.prettyprint {
border: none !important;
padding: 0 !important;
margin: 0 !important;
}
.com { color: #999 !important; }
.ignore-none { color: #999; font-weight: normal; }
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -48px;
}
.footer, .push {
height: 48px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 B

View File

@ -0,0 +1,158 @@
var addSorting = (function () {
"use strict";
var cols,
currentSort = {
index: 0,
desc: false
};
// returns the summary table element
function getTable() { return document.querySelector('.coverage-summary'); }
// returns the thead element of the summary table
function getTableHeader() { return getTable().querySelector('thead tr'); }
// returns the tbody element of the summary table
function getTableBody() { return getTable().querySelector('tbody'); }
// returns the th element for nth column
function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; }
// loads all columns
function loadColumns() {
var colNodes = getTableHeader().querySelectorAll('th'),
colNode,
cols = [],
col,
i;
for (i = 0; i < colNodes.length; i += 1) {
colNode = colNodes[i];
col = {
key: colNode.getAttribute('data-col'),
sortable: !colNode.getAttribute('data-nosort'),
type: colNode.getAttribute('data-type') || 'string'
};
cols.push(col);
if (col.sortable) {
col.defaultDescSort = col.type === 'number';
colNode.innerHTML = colNode.innerHTML + '<span class="sorter"></span>';
}
}
return cols;
}
// attaches a data attribute to every tr element with an object
// of data values keyed by column name
function loadRowData(tableRow) {
var tableCols = tableRow.querySelectorAll('td'),
colNode,
col,
data = {},
i,
val;
for (i = 0; i < tableCols.length; i += 1) {
colNode = tableCols[i];
col = cols[i];
val = colNode.getAttribute('data-value');
if (col.type === 'number') {
val = Number(val);
}
data[col.key] = val;
}
return data;
}
// loads all row data
function loadData() {
var rows = getTableBody().querySelectorAll('tr'),
i;
for (i = 0; i < rows.length; i += 1) {
rows[i].data = loadRowData(rows[i]);
}
}
// sorts the table using the data for the ith column
function sortByIndex(index, desc) {
var key = cols[index].key,
sorter = function (a, b) {
a = a.data[key];
b = b.data[key];
return a < b ? -1 : a > b ? 1 : 0;
},
finalSorter = sorter,
tableBody = document.querySelector('.coverage-summary tbody'),
rowNodes = tableBody.querySelectorAll('tr'),
rows = [],
i;
if (desc) {
finalSorter = function (a, b) {
return -1 * sorter(a, b);
};
}
for (i = 0; i < rowNodes.length; i += 1) {
rows.push(rowNodes[i]);
tableBody.removeChild(rowNodes[i]);
}
rows.sort(finalSorter);
for (i = 0; i < rows.length; i += 1) {
tableBody.appendChild(rows[i]);
}
}
// removes sort indicators for current column being sorted
function removeSortIndicators() {
var col = getNthColumn(currentSort.index),
cls = col.className;
cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
col.className = cls;
}
// adds sort indicators for current column being sorted
function addSortIndicators() {
getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted';
}
// adds event listeners for all sorter widgets
function enableUI() {
var i,
el,
ithSorter = function ithSorter(i) {
var col = cols[i];
return function () {
var desc = col.defaultDescSort;
if (currentSort.index === i) {
desc = !currentSort.desc;
}
sortByIndex(i, desc);
removeSortIndicators();
currentSort.index = i;
currentSort.desc = desc;
addSortIndicators();
};
};
for (i =0 ; i < cols.length; i += 1) {
if (cols[i].sortable) {
// add the click event handler on the th so users
// dont have to click on those tiny arrows
el = getNthColumn(i).querySelector('.sorter').parentElement;
if (el.addEventListener) {
el.addEventListener('click', ithSorter(i));
} else {
el.attachEvent('onclick', ithSorter(i));
}
}
}
}
// adds sorting functionality to the UI
return function () {
if (!getTable()) {
return;
}
cols = loadColumns();
loadData(cols);
addSortIndicators();
enableUI();
};
})();
window.addEventListener('load', addSorting);

View File

@ -0,0 +1 @@
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee}

File diff suppressed because one or more lines are too long

99
static/js/ketcher2/node_modules/istanbul/lib/cli.js generated vendored Executable file
View File

@ -0,0 +1,99 @@
#!/usr/bin/env node
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var async = require('async'),
Command = require('./command'),
inputError = require('./util/input-error'),
exitProcess = process.exit; //hold a reference to original process.exit so that we are not affected even when a test changes it
require('./register-plugins');
function findCommandPosition(args) {
var i;
for (i = 0; i < args.length; i += 1) {
if (args[i].charAt(0) !== '-') {
return i;
}
}
return -1;
}
function exit(ex, code) {
// flush output for Node.js Windows pipe bug
// https://github.com/joyent/node/issues/6247 is just one bug example
// https://github.com/visionmedia/mocha/issues/333 has a good discussion
var streams = [process.stdout, process.stderr];
async.forEach(streams, function (stream, done) {
// submit a write request and wait until it's written
stream.write('', done);
}, function () {
if (ex) {
if (typeof ex === 'string') {
console.error(ex);
exitProcess(1);
} else {
throw ex; // turn it into an uncaught exception
}
} else {
exitProcess(code);
}
});
}
function errHandler (ex) {
if (!ex) { return; }
if (!ex.inputError) {
// exit with exception stack trace
exit(ex);
} else {
//don't print nasty traces but still exit(1)
console.error(ex.message);
console.error('Try "istanbul help" for usage');
exit(null, 1);
}
}
function runCommand(args, callback) {
var pos = findCommandPosition(args),
command,
commandArgs,
commandObject;
if (pos < 0) {
return callback(inputError.create('Need a command to run'));
}
commandArgs = args.slice(0, pos);
command = args[pos];
commandArgs.push.apply(commandArgs, args.slice(pos + 1));
try {
commandObject = Command.create(command);
} catch (ex) {
errHandler(inputError.create(ex.message));
return;
}
commandObject.run(commandArgs, errHandler);
}
function runToCompletion(args) {
runCommand(args, errHandler);
}
/* istanbul ignore if: untestable */
if (require.main === module) {
var args = Array.prototype.slice.call(process.argv, 2);
runToCompletion(args);
}
module.exports = {
runToCompletion: runToCompletion
};

View File

@ -0,0 +1,122 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
"use strict";
var MemoryStore = require('./store/memory'),
utils = require('./object-utils');
/**
* a mechanism to merge multiple coverage objects into one. Handles the use case
* of overlapping coverage information for the same files in multiple coverage
* objects and does not double-count in this situation. For example, if
* you pass the same coverage object multiple times, the final merged object will be
* no different that any of the objects passed in (except for execution counts).
*
* The `Collector` is built for scale to handle thousands of coverage objects.
* By default, all processing is done in memory since the common use-case is of
* one or a few coverage objects. You can work around memory
* issues by passing in a `Store` implementation that stores temporary computations
* on disk (the `tmp` store, for example).
*
* The `getFinalCoverage` method returns an object with merged coverage information
* and is provided as a convenience for implementors working with coverage information
* that can fit into memory. Reporters, in the interest of generality, should *not* use this method for
* creating reports.
*
* Usage
* -----
*
* var collector = new require('istanbul').Collector();
*
* files.forEach(function (f) {
* //each coverage object can have overlapping information about multiple files
* collector.add(JSON.parse(fs.readFileSync(f, 'utf8')));
* });
*
* collector.files().forEach(function(file) {
* var fileCoverage = collector.fileCoverageFor(file);
* console.log('Coverage for ' + file + ' is:' + JSON.stringify(fileCoverage));
* });
*
* // convenience method: do not use this when dealing with a large number of files
* var finalCoverage = collector.getFinalCoverage();
*
* @class Collector
* @module main
* @constructor
* @param {Object} options Optional. Configuration options.
* @param {Store} options.store - an implementation of `Store` to use for temporary
* calculations.
*/
function Collector(options) {
options = options || {};
this.store = options.store || new MemoryStore();
}
Collector.prototype = {
/**
* adds a coverage object to the collector.
*
* @method add
* @param {Object} coverage the coverage object.
* @param {String} testName Optional. The name of the test used to produce the object.
* This is currently not used.
*/
add: function (coverage /*, testName */) {
var store = this.store;
Object.keys(coverage).forEach(function (key) {
var fileCoverage = coverage[key];
if (store.hasKey(key)) {
store.setObject(key, utils.mergeFileCoverage(fileCoverage, store.getObject(key)));
} else {
store.setObject(key, fileCoverage);
}
});
},
/**
* returns a list of unique file paths for which coverage information has been added.
* @method files
* @return {Array} an array of file paths for which coverage information is present.
*/
files: function () {
return this.store.keys();
},
/**
* return file coverage information for a single file
* @method fileCoverageFor
* @param {String} fileName the path for the file for which coverage information is
* required. Must be one of the values returned in the `files()` method.
* @return {Object} the coverage information for the specified file.
*/
fileCoverageFor: function (fileName) {
var ret = this.store.getObject(fileName);
utils.addDerivedInfoForFile(ret);
return ret;
},
/**
* returns file coverage information for all files. This has the same format as
* any of the objects passed in to the `add` method. The number of keys in this
* object will be a superset of all keys found in the objects passed to `add()`
* @method getFinalCoverage
* @return {Object} the merged coverage information
*/
getFinalCoverage: function () {
var ret = {},
that = this;
this.files().forEach(function (file) {
ret[file] = that.fileCoverageFor(file);
});
return ret;
},
/**
* disposes this collector and reclaims temporary resources used in the
* computation. Calls `dispose()` on the underlying store.
* @method dispose
*/
dispose: function () {
this.store.dispose();
}
};
module.exports = Collector;

View File

@ -0,0 +1,195 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var nopt = require('nopt'),
path = require('path'),
fs = require('fs'),
Collector = require('../collector'),
formatOption = require('../util/help-formatter').formatOption,
util = require('util'),
utils = require('../object-utils'),
filesFor = require('../util/file-matcher').filesFor,
Command = require('./index'),
configuration = require('../config');
function isAbsolute(file) {
if (path.isAbsolute) {
return path.isAbsolute(file);
}
return path.resolve(file) === path.normalize(file);
}
function CheckCoverageCommand() {
Command.call(this);
}
function removeFiles(covObj, root, files) {
var filesObj = {},
obj = {};
// Create lookup table.
files.forEach(function (file) {
filesObj[file] = true;
});
Object.keys(covObj).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) {
obj[key] = covObj[key];
}
});
return obj;
}
CheckCoverageCommand.TYPE = 'check-coverage';
util.inherits(CheckCoverageCommand, Command);
Command.mix(CheckCoverageCommand, {
synopsis: function () {
return "checks overall/per-file coverage against thresholds from coverage JSON files. Exits 1 if thresholds are not met, 0 otherwise";
},
usage: function () {
console.error('\nUsage: ' + this.toolName() + ' ' + this.type() + ' <options> [<include-pattern>]\n\nOptions are:\n\n' +
[
formatOption('--statements <threshold>', 'global statement coverage threshold'),
formatOption('--functions <threshold>', 'global function coverage threshold'),
formatOption('--branches <threshold>', 'global branch coverage threshold'),
formatOption('--lines <threshold>', 'global line coverage threshold')
].join('\n\n') + '\n');
console.error('\n\n');
console.error('Thresholds, when specified as a positive number are taken to be the minimum percentage required.');
console.error('When a threshold is specified as a negative number it represents the maximum number of uncovered entities allowed.\n');
console.error('For example, --statements 90 implies minimum statement coverage is 90%.');
console.error(' --statements -10 implies that no more than 10 uncovered statements are allowed\n');
console.error('Per-file thresholds can be specified via a configuration file.\n');
console.error('<include-pattern> is a glob pattern that can be used to select one or more coverage files ' +
'for merge. This defaults to "**/coverage*.json"');
console.error('\n');
},
run: function (args, callback) {
var template = {
config: path,
root: path,
statements: Number,
lines: Number,
branches: Number,
functions: Number,
verbose: Boolean
},
opts = nopt(template, { v : '--verbose' }, args, 0),
// Translate to config opts.
config = configuration.loadFile(opts.config, {
verbose: opts.verbose,
check: {
global: {
statements: opts.statements,
lines: opts.lines,
branches: opts.branches,
functions: opts.functions
}
}
}),
includePattern = '**/coverage*.json',
root,
collector = new Collector(),
errors = [];
if (opts.argv.remain.length > 0) {
includePattern = opts.argv.remain[0];
}
root = opts.root || process.cwd();
filesFor({
root: root,
includes: [ includePattern ]
}, function (err, files) {
if (err) { throw err; }
if (files.length === 0) {
return callback('ERROR: No coverage files found.');
}
files.forEach(function (file) {
var coverageObject = JSON.parse(fs.readFileSync(file, 'utf8'));
collector.add(coverageObject);
});
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 || []
}
},
rawCoverage = collector.getFinalCoverage(),
globalResults = utils.summarizeCoverage(removeFiles(rawCoverage, root, thresholds.global.excludes)),
eachResults = removeFiles(rawCoverage, root, thresholds.each.excludes);
// Summarize per-file results and mutate original results.
Object.keys(eachResults).forEach(function (key) {
eachResults[key] = utils.summarizeFileCoverage(eachResults[key]);
});
if (config.verbose) {
console.log('Compare actuals against thresholds');
console.log(JSON.stringify({ global: globalResults, each: eachResults, thresholds: thresholds }, undefined, 4));
}
function check(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 + '%)');
}
}
});
}
check("global", thresholds.global, globalResults);
Object.keys(eachResults).forEach(function (key) {
check("per-file" + " (" + key + ") ", thresholds.each, eachResults[key]);
});
return callback(errors.length === 0 ? null : errors.join("\n"));
});
}
});
module.exports = CheckCoverageCommand;

View File

@ -0,0 +1,261 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Module = require('module'),
path = require('path'),
fs = require('fs'),
nopt = require('nopt'),
which = require('which'),
mkdirp = require('mkdirp'),
existsSync = fs.existsSync || path.existsSync,
inputError = require('../../util/input-error'),
matcherFor = require('../../util/file-matcher').matcherFor,
Instrumenter = require('../../instrumenter'),
Collector = require('../../collector'),
formatOption = require('../../util/help-formatter').formatOption,
hook = require('../../hook'),
Reporter = require('../../reporter'),
resolve = require('resolve'),
configuration = require('../../config');
function usage(arg0, command) {
console.error('\nUsage: ' + arg0 + ' ' + command + ' [<options>] <executable-js-file-or-command> [-- <arguments-to-jsfile>]\n\nOptions are:\n\n'
+ [
formatOption('--config <path-to-config>', 'the configuration file to use, defaults to .istanbul.yml'),
formatOption('--root <path> ', 'the root path to look for files to instrument, defaults to .'),
formatOption('-x <exclude-pattern> [-x <exclude-pattern>]', 'one or more glob patterns e.g. "**/vendor/**"'),
formatOption('-i <include-pattern> [-i <include-pattern>]', 'one or more glob patterns e.g. "**/*.js"'),
formatOption('--[no-]default-excludes', 'apply default excludes [ **/node_modules/**, **/test/**, **/tests/** ], defaults to true'),
formatOption('--hook-run-in-context', 'hook vm.runInThisContext in addition to require (supports RequireJS), defaults to false'),
formatOption('--post-require-hook <file> | <module>', 'JS module that exports a function for post-require processing'),
formatOption('--report <format> [--report <format>] ', 'report format, defaults to lcov (= lcov.info + HTML)'),
formatOption('--dir <report-dir>', 'report directory, defaults to ./coverage'),
formatOption('--print <type>', 'type of report to print to console, one of summary (default), detail, both or none'),
formatOption('--verbose, -v', 'verbose mode'),
formatOption('--[no-]preserve-comments', 'remove / preserve comments in the output, defaults to false'),
formatOption('--include-all-sources', 'instrument all unused sources after running tests, defaults to false'),
formatOption('--[no-]include-pid', 'include PID in output coverage filename')
].join('\n\n') + '\n');
console.error('\n');
}
function run(args, commandName, enableHooks, callback) {
var template = {
config: path,
root: path,
x: [ Array, String ],
report: [Array, String ],
dir: path,
verbose: Boolean,
yui: Boolean,
'default-excludes': Boolean,
print: String,
'self-test': Boolean,
'hook-run-in-context': Boolean,
'post-require-hook': String,
'preserve-comments': Boolean,
'include-all-sources': Boolean,
'preload-sources': Boolean,
i: [ Array, String ],
'include-pid': Boolean
},
opts = nopt(template, { v : '--verbose' }, args, 0),
overrides = {
verbose: opts.verbose,
instrumentation: {
root: opts.root,
'default-excludes': opts['default-excludes'],
excludes: opts.x,
'include-all-sources': opts['include-all-sources'],
'preload-sources': opts['preload-sources'],
'include-pid': opts['include-pid']
},
reporting: {
reports: opts.report,
print: opts.print,
dir: opts.dir
},
hooks: {
'hook-run-in-context': opts['hook-run-in-context'],
'post-require-hook': opts['post-require-hook'],
'handle-sigint': opts['handle-sigint']
}
},
config = configuration.loadFile(opts.config, overrides),
verbose = config.verbose,
cmdAndArgs = opts.argv.remain,
preserveComments = opts['preserve-comments'],
includePid = opts['include-pid'],
cmd,
cmdArgs,
reportingDir,
reporter = new Reporter(config),
runFn,
excludes;
if (cmdAndArgs.length === 0) {
return callback(inputError.create('Need a filename argument for the ' + commandName + ' command!'));
}
cmd = cmdAndArgs.shift();
cmdArgs = cmdAndArgs;
if (!existsSync(cmd)) {
try {
cmd = which.sync(cmd);
} catch (ex) {
return callback(inputError.create('Unable to resolve file [' + cmd + ']'));
}
} else {
cmd = path.resolve(cmd);
}
runFn = function () {
process.argv = ["node", cmd].concat(cmdArgs);
if (verbose) {
console.log('Running: ' + process.argv.join(' '));
}
process.env.running_under_istanbul=1;
Module.runMain(cmd, null, true);
};
excludes = config.instrumentation.excludes(true);
if (enableHooks) {
reportingDir = path.resolve(config.reporting.dir());
mkdirp.sync(reportingDir); //ensure we fail early if we cannot do this
reporter.dir = reportingDir;
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;
}
}
excludes.push(path.relative(process.cwd(), path.join(reportingDir, '**', '*')));
matcherFor({
root: config.instrumentation.root() || process.cwd(),
includes: opts.i || config.instrumentation.extensions().map(function (ext) {
return '**/*' + ext;
}),
excludes: excludes
},
function (err, matchFn) {
if (err) { return callback(err); }
var coverageVar = '$$cov_' + new Date().getTime() + '$$',
instrumenter = new Instrumenter({ coverageVariable: coverageVar , preserveComments: preserveComments}),
transformer = instrumenter.instrumentSync.bind(instrumenter),
hookOpts = { verbose: verbose, extensions: config.instrumentation.extensions() },
postRequireHook = config.hooks.postRequireHook(),
postLoadHookFile;
if (postRequireHook) {
postLoadHookFile = path.resolve(postRequireHook);
} else if (opts.yui) { //EXPERIMENTAL code: do not rely on this in anyway until the docs say it is allowed
postLoadHookFile = path.resolve(__dirname, '../../util/yui-load-hook');
}
if (postRequireHook) {
if (!existsSync(postLoadHookFile)) { //assume it is a module name and resolve it
try {
postLoadHookFile = resolve.sync(postRequireHook, { basedir: process.cwd() });
} catch (ex) {
if (verbose) { console.error('Unable to resolve [' + postRequireHook + '] as a node module'); }
callback(ex);
return;
}
}
}
if (postLoadHookFile) {
if (verbose) { console.error('Use post-load-hook: ' + postLoadHookFile); }
hookOpts.postLoadHook = require(postLoadHookFile)(matchFn, transformer, verbose);
}
if (opts['self-test']) {
hook.unloadRequireCache(matchFn);
}
// runInThisContext is used by RequireJS [issue #23]
if (config.hooks.hookRunInContext()) {
hook.hookRunInThisContext(matchFn, transformer, hookOpts);
}
hook.hookRequire(matchFn, transformer, hookOpts);
//initialize the global variable to stop mocha from complaining about leaks
global[coverageVar] = {};
// enable passing --handle-sigint to write reports on SIGINT.
// This allows a user to manually kill a process while
// still getting the istanbul report.
if (config.hooks.handleSigint()) {
process.once('SIGINT', process.exit);
}
process.once('exit', function () {
var pidExt = includePid ? ('-' + process.pid) : '',
file = path.resolve(reportingDir, 'coverage' + pidExt + '.json'),
collector,
cov;
if (typeof global[coverageVar] === 'undefined' || Object.keys(global[coverageVar]).length === 0) {
console.error('No coverage information was collected, exit without writing coverage information');
return;
} else {
cov = global[coverageVar];
}
//important: there is no event loop at this point
//everything that happens in this exit handler MUST be synchronous
if (config.instrumentation.includeAllSources()) {
// 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]) {
transformer(fs.readFileSync(file, 'utf-8'), file);
// When instrumenting the code, istanbul will give each FunctionDeclaration a value of 1 in coverState.s,
// presumably to compensate for function hoisting. We need to reset this, as the function was not hoisted,
// as it was never loaded.
Object.keys(instrumenter.coverState.s).forEach(function (key) {
instrumenter.coverState.s[key] = 0;
});
cov[file] = instrumenter.coverState;
}
});
}
mkdirp.sync(reportingDir); //yes, do this again since some test runners could clean the dir initially created
if (config.reporting.print() !== 'none') {
console.error('=============================================================================');
console.error('Writing coverage object [' + file + ']');
}
fs.writeFileSync(file, JSON.stringify(cov), 'utf8');
collector = new Collector();
collector.add(cov);
if (config.reporting.print() !== 'none') {
console.error('Writing coverage reports at [' + reportingDir + ']');
console.error('=============================================================================');
}
reporter.write(collector, true, callback);
});
runFn();
});
} else {
runFn();
}
}
module.exports = {
run: run,
usage: usage
};

View File

@ -0,0 +1,33 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var runWithCover = require('./common/run-with-cover'),
util = require('util'),
Command = require('./index');
function CoverCommand() {
Command.call(this);
}
CoverCommand.TYPE = 'cover';
util.inherits(CoverCommand, Command);
Command.mix(CoverCommand, {
synopsis: function () {
return "transparently adds coverage information to a node command. Saves coverage.json and reports at the end of execution";
},
usage: function () {
runWithCover.usage(this.toolName(), this.type());
},
run: function (args, callback) {
runWithCover.run(args, this.type(), true, callback);
}
});
module.exports = CoverCommand;

View File

@ -0,0 +1,102 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Command = require('./index.js'),
util = require('util'),
formatOption = require('../util/help-formatter').formatOption,
VERSION = require('../../index').VERSION,
configuration = require('../config'),
yaml = require('js-yaml'),
formatPara = require('../util/help-formatter').formatPara;
function showConfigHelp(toolName) {
console.error('\nConfiguring ' + toolName);
console.error('====================');
console.error('\n' +
formatPara(toolName + ' can be configured globally using a .istanbul.yml YAML file ' +
'at the root of your source tree. Every command also accepts a --config=<config-file> argument to ' +
'customize its location per command. The alternate config file can be in YAML, JSON or node.js ' +
'(exporting the config object).'));
console.error('\n' +
formatPara('The config file currently has four sections for instrumentation, reporting, hooks, ' +
'and checking. Note that certain commands (like `cover`) use information from multiple sections.'));
console.error('\n' +
formatPara('Keys in the config file usually correspond to command line parameters with the same name. ' +
'The verbose option for every command shows you the exact configuration used. See the api ' +
'docs for an explanation of each key.'));
console.error('\n' +
formatPara('You only need to specify the keys that you want to override. Your overrides will be merged ' +
'with the default config.'));
console.error('\nThe default configuration is as follows:\n');
console.error(yaml.safeDump(configuration.defaultConfig(), { indent: 4, flowLevel: 3 }));
console.error('\n' +
formatPara('The `watermarks` section does not have a command line equivalent. It allows you to set up ' +
'low and high watermark percentages for reporting. These are honored by all reporters that colorize ' +
'their output based on low/ medium/ high coverage.'));
console.error('\n' +
formatPara('The `reportConfig` section allows you to configure each report format independently ' +
'and has no command-line equivalent either.'));
console.error('\n' +
formatPara('The `check` section configures minimum threshold enforcement for coverage results. ' +
'`global` applies to all files together and `each` on a per-file basis. A list of files can ' +
'be excluded from enforcement relative to root via the `exclude` property.'));
console.error('');
}
function HelpCommand() {
Command.call(this);
}
HelpCommand.TYPE = 'help';
util.inherits(HelpCommand, Command);
Command.mix(HelpCommand, {
synopsis: function () {
return "shows help";
},
usage: function () {
console.error('\nUsage: ' + this.toolName() + ' ' + this.type() + ' config | <command>\n');
console.error('`config` provides help with istanbul configuration\n');
console.error('Available commands are:\n');
var commandObj;
Command.getCommandList().forEach(function (cmd) {
commandObj = Command.create(cmd);
console.error(formatOption(cmd, commandObj.synopsis()));
console.error("\n");
});
console.error("Command names can be abbreviated as long as the abbreviation is unambiguous");
console.error(this.toolName() + ' version:' + VERSION);
console.error("\n");
},
run: function (args, callback) {
var command;
if (args.length === 0) {
this.usage();
} else {
if (args[0] === 'config') {
showConfigHelp(this.toolName());
} else {
try {
command = Command.create(args[0]);
command.usage('istanbul', Command.resolveCommandName(args[0]));
} catch (ex) {
console.error('Invalid command: ' + args[0]);
this.usage();
}
}
}
return callback();
}
});
module.exports = HelpCommand;

View File

@ -0,0 +1,33 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Factory = require('../util/factory'),
factory = new Factory('command', __dirname, true);
function Command() {}
// add register, create, mix, loadAll, getCommandList, resolveCommandName to the Command object
factory.bindClassMethods(Command);
Command.prototype = {
toolName: function () {
return require('../util/meta').NAME;
},
type: function () {
return this.constructor.TYPE;
},
synopsis: /* istanbul ignore next: base method */ function () {
return "the developer has not written a one-line summary of the " + this.type() + " command";
},
usage: /* istanbul ignore next: base method */ function () {
console.error("the developer has not provided a usage for the " + this.type() + " command");
},
run: /* istanbul ignore next: abstract method */ function (args, callback) {
return callback(new Error("run: must be overridden for the " + this.type() + " command"));
}
};
module.exports = Command;

View File

@ -0,0 +1,265 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
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('../util/file-matcher').filesFor,
nopt = require('nopt'),
Instrumenter = require('../instrumenter'),
inputError = require('../util/input-error'),
formatOption = require('../util/help-formatter').formatOption,
util = require('util'),
Command = require('./index'),
Collector = require('../collector'),
configuration = require('../config'),
verbose;
/*
* 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.collector = new Collector();
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(),
coverage = {};
coverage[baseline.path] = baseline;
this.collector.add(coverage);
return ret;
};
//monkey patch the instrumenter to call our version instead
instrumenter.instrumentSync = this.instrumentSync.bind(this);
}
BaselineCollector.prototype = {
getCoverage: function () {
return this.collector.getFinalCoverage();
}
};
function processFiles(instrumenter, inputDir, outputDir, relativeNames, extensions) {
var processor = function (name, callback) {
var inputFile = path.resolve(inputDir, name),
outputFile = path.resolve(outputDir, name),
inputFileExtenstion = path.extname(inputFile),
isJavaScriptFile = extensions.indexOf(inputFileExtenstion) > -1,
oDir = path.dirname(outputFile),
readStream, writeStream;
callback = once(callback);
mkdirp.sync(oDir);
if (fs.statSync(inputFile).isDirectory()) {
return callback(null, name);
}
if (isJavaScriptFile) {
fs.readFile(inputFile, 'utf8', function (err, data) {
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 || err.toString() });
inputFile = path.resolve(inputDir, name);
outputFile = path.resolve(outputDir, name);
fs.writeFileSync(outputFile, fs.readFileSync(inputFile));
}
if (verbose) {
console.log('Processed: ' + name);
} else {
if (count % 100 === 0) { process.stdout.write('.'); }
}
count += 1;
});
q.drain = function () {
var endTime = new Date().getTime();
console.log('\nProcessed [' + count + '] files in ' + Math.floor((endTime - startTime) / 1000) + ' secs');
if (errors.length > 0) {
console.log('The following ' + errors.length + ' file(s) had errors and were copied as-is');
console.log(errors);
}
};
}
function InstrumentCommand() {
Command.call(this);
}
InstrumentCommand.TYPE = 'instrument';
util.inherits(InstrumentCommand, Command);
Command.mix(InstrumentCommand, {
synopsis: function synopsis() {
return "instruments a file or a directory tree and writes the instrumented code to the desired output location";
},
usage: function () {
console.error('\nUsage: ' + this.toolName() + ' ' + this.type() + ' <options> <file-or-directory>\n\nOptions are:\n\n' +
[
formatOption('--config <path-to-config>', 'the configuration file to use, defaults to .istanbul.yml'),
formatOption('--output <file-or-dir>', 'The output file or directory. This is required when the input is a directory, ' +
'defaults to standard output when input is a file'),
formatOption('-x <exclude-pattern> [-x <exclude-pattern>]', 'one or more glob patterns (e.g. "**/vendor/**" to ignore all files ' +
'under a vendor directory). Also see the --default-excludes option'),
formatOption('--variable <global-coverage-variable-name>', 'change the variable name of the global coverage variable from the ' +
'default value of `__coverage__` to something else'),
formatOption('--embed-source', 'embed source code into the coverage object, defaults to false'),
formatOption('--[no-]compact', 'produce [non]compact output, defaults to compact'),
formatOption('--[no-]preserve-comments', 'remove / preserve comments in the output, defaults to false'),
formatOption('--[no-]complete-copy', 'also copy non-javascript files to the ouput directory as is, defaults to false'),
formatOption('--save-baseline', 'produce a baseline coverage.json file out of all files instrumented'),
formatOption('--baseline-file <file>', 'filename of baseline file, defaults to coverage/coverage-baseline.json'),
formatOption('--es-modules', 'source code uses es import/export module syntax')
].join('\n\n') + '\n');
console.error('\n');
},
run: function (args, callback) {
var template = {
config: path,
output: path,
x: [Array, String],
variable: String,
compact: Boolean,
'complete-copy': Boolean,
verbose: Boolean,
'save-baseline': Boolean,
'baseline-file': path,
'embed-source': Boolean,
'preserve-comments': Boolean,
'es-modules': Boolean
},
opts = nopt(template, { v : '--verbose' }, args, 0),
overrides = {
verbose: opts.verbose,
instrumentation: {
variable: opts.variable,
compact: opts.compact,
'embed-source': opts['embed-source'],
'preserve-comments': opts['preserve-comments'],
excludes: opts.x,
'complete-copy': opts['complete-copy'],
'save-baseline': opts['save-baseline'],
'baseline-file': opts['baseline-file'],
'es-modules': opts['es-modules']
}
},
config = configuration.loadFile(opts.config, overrides),
iOpts = config.instrumentation,
cmdArgs = opts.argv.remain,
file,
stats,
stream,
includes,
instrumenter,
needBaseline = iOpts.saveBaseline(),
baselineFile = path.resolve(iOpts.baselineFile()),
output = opts.output;
verbose = config.verbose;
if (cmdArgs.length !== 1) {
return callback(inputError.create('Need exactly one filename/ dirname argument for the instrument command!'));
}
if (iOpts.completeCopy()) {
includes = ['**/*'];
}
else {
includes = iOpts.extensions().map(function(ext) {
return '**/*' + ext;
});
}
instrumenter = new Instrumenter({
coverageVariable: iOpts.variable(),
embedSource: iOpts.embedSource(),
noCompact: !iOpts.compact(),
preserveComments: iOpts.preserveComments(),
esModules: iOpts.esModules()
});
if (needBaseline) {
mkdirp.sync(path.dirname(baselineFile));
instrumenter = new BaselineCollector(instrumenter);
process.on('exit', function () {
console.log('Saving baseline coverage at: ' + baselineFile);
fs.writeFileSync(baselineFile, JSON.stringify(instrumenter.getCoverage()), 'utf8');
});
}
file = path.resolve(cmdArgs[0]);
stats = fs.statSync(file);
if (stats.isDirectory()) {
if (!output) { return callback(inputError.create('Need an output directory [-o <dir>] 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: opts.x || iOpts.excludes(false), // backwards-compat, *sigh*
relative: true
}, function (err, files) {
if (err) { return callback(err); }
processFiles(instrumenter, file, output, files, iOpts.extensions());
});
} 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();
}
}
}
});
module.exports = InstrumentCommand;

View File

@ -0,0 +1,123 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var nopt = require('nopt'),
Report = require('../report'),
Reporter = require('../reporter'),
path = require('path'),
fs = require('fs'),
Collector = require('../collector'),
helpFormatter = require('../util/help-formatter'),
formatOption = helpFormatter.formatOption,
formatPara = helpFormatter.formatPara,
filesFor = require('../util/file-matcher').filesFor,
util = require('util'),
Command = require('./index'),
configuration = require('../config');
function ReportCommand() {
Command.call(this);
}
ReportCommand.TYPE = 'report';
util.inherits(ReportCommand, Command);
function printDeprecationMessage(pat, fmt) {
console.error('**********************************************************************');
console.error('DEPRECATION WARNING! You are probably using the old format of the report command');
console.error('This will stop working soon, see `istanbul help report` for the new command format');
console.error('Assuming you meant: istanbul report --include=' + pat + ' ' + fmt);
console.error('**********************************************************************');
}
Command.mix(ReportCommand, {
synopsis: function () {
return "writes reports for coverage JSON objects produced in a previous run";
},
usage: function () {
console.error('\nUsage: ' + this.toolName() + ' ' + this.type() + ' <options> [ <format> ... ]\n\nOptions are:\n\n' +
[
formatOption('--config <path-to-config>', 'the configuration file to use, defaults to .istanbul.yml'),
formatOption('--root <input-directory>', 'The input root directory for finding coverage files'),
formatOption('--dir <report-directory>', 'The output directory where files will be written. This defaults to ./coverage/'),
formatOption('--include <glob>', 'The glob pattern to select one or more coverage files, defaults to **/coverage*.json'),
formatOption('--verbose, -v', 'verbose mode')
].join('\n\n'));
console.error('\n');
console.error('<format> is one of ');
Report.getReportList().forEach(function (name) {
console.error(formatOption(name, Report.create(name).synopsis()));
});
console.error("");
console.error(formatPara([
'Default format is lcov unless otherwise specified in the config file.',
'In addition you can tweak the file names for various reports using the config file.',
'Type `istanbul help config` to see what can be tweaked.'
].join(' ')));
console.error('\n');
},
run: function (args, callback) {
var template = {
config: path,
root: path,
dir: path,
include: String,
verbose: Boolean
},
opts = nopt(template, { v : '--verbose' }, args, 0),
includePattern = opts.include || '**/coverage*.json',
root,
collector = new Collector(),
config = configuration.loadFile(opts.config, {
verbose: opts.verbose,
reporting: {
dir: opts.dir
}
}),
formats = opts.argv.remain,
reporter = new Reporter(config);
// Start: backward compatible processing
if (formats.length === 2 &&
Report.getReportList().indexOf(formats[1]) < 0) {
includePattern = formats[1];
formats = [ formats[0] ];
printDeprecationMessage(includePattern, formats[0]);
}
// End: backward compatible processing
if (formats.length === 0) {
formats = config.reporting.reports();
}
if (formats.length === 0) {
formats = [ 'lcov' ];
}
reporter.addAll(formats);
root = opts.root || process.cwd();
filesFor({
root: root,
includes: [ includePattern ]
}, function (err, files) {
if (err) { throw err; }
files.forEach(function (file) {
var coverageObject = JSON.parse(fs.readFileSync(file, 'utf8'));
collector.add(coverageObject);
});
reporter.write(collector, false, function (err) {
console.log('Done');
return callback(err);
});
});
}
});
module.exports = ReportCommand;

View File

@ -0,0 +1,31 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var runWithCover = require('./common/run-with-cover'),
util = require('util'),
Command = require('./index');
function TestCommand() {
Command.call(this);
}
TestCommand.TYPE = 'test';
util.inherits(TestCommand, Command);
Command.mix(TestCommand, {
synopsis: function () {
return "cover a node command only when npm_config_coverage is set. Use in an `npm test` script for conditional coverage";
},
usage: function () {
runWithCover.usage(this.toolName(), this.type());
},
run: function (args, callback) {
runWithCover.run(args, this.type(), !!process.env.npm_config_coverage, callback);
}
});
module.exports = TestCommand;

491
static/js/ketcher2/node_modules/istanbul/lib/config.js generated vendored Normal file
View File

@ -0,0 +1,491 @@
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
fs = require('fs'),
existsSync = fs.existsSync || path.existsSync,
CAMEL_PATTERN = /([a-z])([A-Z])/g,
YML_PATTERN = /\.ya?ml$/,
yaml = require('js-yaml'),
defaults = require('./report/common/defaults');
function defaultConfig(includeBackCompatAttrs) {
var ret = {
verbose: false,
instrumentation: {
root: '.',
extensions: ['.js'],
'default-excludes': true,
excludes: [],
'embed-source': false,
variable: '__coverage__',
compact: true,
'preserve-comments': false,
'complete-copy': false,
'save-baseline': false,
'baseline-file': './coverage/coverage-baseline.json',
'include-all-sources': false,
'include-pid': false,
'es-modules': false
},
reporting: {
print: 'summary',
reports: [ 'lcov' ],
dir: './coverage'
},
hooks: {
'hook-run-in-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 = defaults.watermarks();
ret.reporting['report-config'] = defaults.defaultReportConfig();
if (includeBackCompatAttrs) {
ret.instrumentation['preload-sources'] = false;
}
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) {
var ret = {};
Object.keys(template).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);
} else {
ret[k] = isScalar(v2) ? v2 : v1;
}
});
return ret;
}
function mergeDefaults(explicit, implicit) {
return mergeObjects(explicit || {}, implicit);
}
function addMethods() {
var args = Array.prototype.slice.call(arguments),
cons = args.shift();
args.forEach(function (arg) {
var method = arg,
property = dasherize(arg);
cons.prototype[method] = 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) {
if (config['preload-sources']) {
console.error('The preload-sources option is deprecated, please use include-all-sources instead.');
config['include-all-sources'] = config['preload-sources'];
}
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
*/
/**
* returns if the source should be embedded in the instrumented code. Used by the
* `instrument` command.
* @method embedSource
* @return {Boolean} true if the source should be embedded in the instrumented code
*/
/**
* 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',
'embedSource', 'variable', 'compact', 'preserveComments',
'saveBaseline', 'baselineFile', 'esModules',
'includeAllSources', 'includePid');
/**
* 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 glob patterns that should be excluded for instrumentation.
* Used by the `instrument` and `cover` commands.
* @method excludes
* @return {Array} an array of glob 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;
};
/**
* 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');
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 = defaults.watermarks(),
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.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 hookRunInContext
* @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', '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 new Error('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
};

198
static/js/ketcher2/node_modules/istanbul/lib/hook.js generated vendored Normal file
View File

@ -0,0 +1,198 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
/**
* provides a mechanism to transform code in the scope of `require` or `vm.createScript`.
* This mechanism is general and relies on a user-supplied `matcher` function that determines when transformations should be
* performed and a user-supplied `transformer` function that performs the actual transform.
* Instrumenting code for coverage is one specific example of useful hooking.
*
* Note that both the `matcher` and `transformer` must execute synchronously.
*
* For the common case of matching filesystem paths based on inclusion/ exclusion patterns, use the `matcherFor`
* function in the istanbul API to get a matcher.
*
* It is up to the transformer to perform processing with side-effects, such as caching, storing the original
* source code to disk in case of dynamically generated scripts etc. The `Store` class can help you with this.
*
* Usage
* -----
*
* var hook = require('istanbul').hook,
* myMatcher = function (file) { return file.match(/foo/); },
* myTransformer = function (code, file) { return 'console.log("' + file + '");' + code; };
*
* hook.hookRequire(myMatcher, myTransformer);
*
* var foo = require('foo'); //will now print foo's module path to console
*
* @class Hook
* @module main
*/
var path = require('path'),
fs = require('fs'),
Module = require('module'),
vm = require('vm'),
originalLoaders = {},
originalCreateScript = vm.createScript,
originalRunInThisContext = vm.runInThisContext;
function transformFn(matcher, transformer, verbose) {
return function (code, filename) {
var shouldHook = typeof filename === 'string' && matcher(path.resolve(filename)),
transformed,
changed = false;
if (shouldHook) {
if (verbose) {
console.error('Module load hook: transform [' + filename + ']');
}
try {
transformed = transformer(code, filename);
changed = true;
} catch (ex) {
console.error('Transformation error; return original code');
console.error(ex);
transformed = code;
}
} else {
transformed = code;
}
return { code: transformed, changed: changed };
};
}
function unloadRequireCache(matcher) {
if (matcher && typeof require !== 'undefined' && require && require.cache) {
Object.keys(require.cache).forEach(function (filename) {
if (matcher(filename)) {
delete require.cache[filename];
}
});
}
}
/**
* hooks `require` to return transformed code to the node module loader.
* Exceptions in the transform result in the original code being used instead.
* @method hookRequire
* @static
* @param matcher {Function(filePath)} a function that is called with the absolute path to the file being
* `require`-d. Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
* @param transformer {Function(code, filePath)} a function called with the original code and the associated path of the file
* from where the code was loaded. Should return the transformed code.
* @param options {Object} options Optional.
* @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
* @param {Function} [options.postLoadHook] a function that is called with the name of the file being
* required. This is called after the require is processed irrespective of whether it was transformed.
*/
function hookRequire(matcher, transformer, options) {
options = options || {};
var extensions,
fn = transformFn(matcher, transformer, options.verbose),
postLoadHook = options.postLoadHook &&
typeof options.postLoadHook === 'function' ? options.postLoadHook : null;
extensions = options.extensions || ['.js'];
extensions.forEach(function(ext){
if (!(ext in originalLoaders)) {
originalLoaders[ext] = Module._extensions[ext] || Module._extensions['.js'];
}
Module._extensions[ext] = function (module, filename) {
var ret = fn(fs.readFileSync(filename, 'utf8'), filename);
if (ret.changed) {
module._compile(ret.code, filename);
} else {
originalLoaders[ext](module, filename);
}
if (postLoadHook) {
postLoadHook(filename);
}
};
});
}
/**
* unhook `require` to restore it to its original state.
* @method unhookRequire
* @static
*/
function unhookRequire() {
Object.keys(originalLoaders).forEach(function(ext) {
Module._extensions[ext] = originalLoaders[ext];
});
}
/**
* hooks `vm.createScript` to return transformed code out of which a `Script` object will be created.
* Exceptions in the transform result in the original code being used instead.
* @method hookCreateScript
* @static
* @param matcher {Function(filePath)} a function that is called with the filename passed to `vm.createScript`
* Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
* @param transformer {Function(code, filePath)} a function called with the original code and the filename passed to
* `vm.createScript`. Should return the transformed code.
* @param options {Object} options Optional.
* @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
*/
function hookCreateScript(matcher, transformer, opts) {
opts = opts || {};
var fn = transformFn(matcher, transformer, opts.verbose);
vm.createScript = function (code, file) {
var ret = fn(code, file);
return originalCreateScript(ret.code, file);
};
}
/**
* unhooks vm.createScript, restoring it to its original state.
* @method unhookCreateScript
* @static
*/
function unhookCreateScript() {
vm.createScript = originalCreateScript;
}
/**
* hooks `vm.runInThisContext` to return transformed code.
* @method hookRunInThisContext
* @static
* @param matcher {Function(filePath)} a function that is called with the filename passed to `vm.createScript`
* Should return a truthy value when transformations need to be applied to the code, a falsy value otherwise
* @param transformer {Function(code, filePath)} a function called with the original code and the filename passed to
* `vm.createScript`. Should return the transformed code.
* @param options {Object} options Optional.
* @param {Boolean} [options.verbose] write a line to standard error every time the transformer is called
*/
function hookRunInThisContext(matcher, transformer, opts) {
opts = opts || {};
var fn = transformFn(matcher, transformer, opts.verbose);
vm.runInThisContext = function (code, file) {
var ret = fn(code, file);
return originalRunInThisContext(ret.code, file);
};
}
/**
* unhooks vm.runInThisContext, restoring it to its original state.
* @method unhookRunInThisContext
* @static
*/
function unhookRunInThisContext() {
vm.runInThisContext = originalRunInThisContext;
}
module.exports = {
hookRequire: hookRequire,
unhookRequire: unhookRequire,
hookCreateScript: hookCreateScript,
unhookCreateScript: unhookCreateScript,
hookRunInThisContext : hookRunInThisContext,
unhookRunInThisContext : unhookRunInThisContext,
unloadRequireCache: unloadRequireCache
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,425 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
/**
* utility methods to process coverage objects. A coverage object has the following
* format.
*
* {
* "/path/to/file1.js": { file1 coverage },
* "/path/to/file2.js": { file2 coverage }
* }
*
* The internals of the file coverage object are intentionally not documented since
* it is not a public interface.
*
* *Note:* When a method of this module has the word `File` in it, it will accept
* one of the sub-objects of the main coverage object as an argument. Other
* methods accept the higher level coverage object with multiple keys.
*
* Works on `node` as well as the browser.
*
* Usage on nodejs
* ---------------
*
* var objectUtils = require('istanbul').utils;
*
* Usage in a browser
* ------------------
*
* Load this file using a `script` tag or other means. This will set `window.coverageUtils`
* to this module's exports.
*
* @class ObjectUtils
* @module main
* @static
*/
(function (isNode) {
/**
* adds line coverage information to a file coverage object, reverse-engineering
* it from statement coverage. The object passed in is updated in place.
*
* Note that if line coverage information is already present in the object,
* it is not recomputed.
*
* @method addDerivedInfoForFile
* @static
* @param {Object} fileCoverage the coverage object for a single file
*/
function addDerivedInfoForFile(fileCoverage) {
var statementMap = fileCoverage.statementMap,
statements = fileCoverage.s,
lineMap;
if (!fileCoverage.l) {
fileCoverage.l = lineMap = {};
Object.keys(statements).forEach(function (st) {
var line = statementMap[st].start.line,
count = statements[st],
prevVal = lineMap[line];
if (count === 0 && statementMap[st].skip) { count = 1; }
if (typeof prevVal === 'undefined' || prevVal < count) {
lineMap[line] = count;
}
});
}
}
/**
* adds line coverage information to all file coverage objects.
*
* @method addDerivedInfo
* @static
* @param {Object} coverage the coverage object
*/
function addDerivedInfo(coverage) {
Object.keys(coverage).forEach(function (k) {
addDerivedInfoForFile(coverage[k]);
});
}
/**
* removes line coverage information from all file coverage objects
* @method removeDerivedInfo
* @static
* @param {Object} coverage the coverage object
*/
function removeDerivedInfo(coverage) {
Object.keys(coverage).forEach(function (k) {
delete coverage[k].l;
});
}
function percent(covered, total) {
var tmp;
if (total > 0) {
tmp = 1000 * 100 * covered / total + 5;
return Math.floor(tmp / 10) / 100;
} else {
return 100.00;
}
}
function computeSimpleTotals(fileCoverage, property, mapProperty) {
var stats = fileCoverage[property],
map = mapProperty ? fileCoverage[mapProperty] : null,
ret = { total: 0, covered: 0, skipped: 0 };
Object.keys(stats).forEach(function (key) {
var covered = !!stats[key],
skipped = map && map[key].skip;
ret.total += 1;
if (covered || skipped) {
ret.covered += 1;
}
if (!covered && skipped) {
ret.skipped += 1;
}
});
ret.pct = percent(ret.covered, ret.total);
return ret;
}
function computeBranchTotals(fileCoverage) {
var stats = fileCoverage.b,
branchMap = fileCoverage.branchMap,
ret = { total: 0, covered: 0, skipped: 0 };
Object.keys(stats).forEach(function (key) {
var branches = stats[key],
map = branchMap[key],
covered,
skipped,
i;
for (i = 0; i < branches.length; i += 1) {
covered = branches[i] > 0;
skipped = map.locations && map.locations[i] && map.locations[i].skip;
if (covered || skipped) {
ret.covered += 1;
}
if (!covered && skipped) {
ret.skipped += 1;
}
}
ret.total += branches.length;
});
ret.pct = percent(ret.covered, ret.total);
return ret;
}
/**
* returns a blank summary metrics object. A metrics object has the following
* format.
*
* {
* lines: lineMetrics,
* statements: statementMetrics,
* functions: functionMetrics,
* branches: branchMetrics
* linesCovered: lineCoveredCount
* }
*
* Each individual metric object looks as follows:
*
* {
* total: n,
* covered: m,
* pct: percent
* }
*
* @method blankSummary
* @static
* @return {Object} a blank metrics object
*/
function blankSummary() {
return {
lines: {
total: 0,
covered: 0,
skipped: 0,
pct: 'Unknown'
},
statements: {
total: 0,
covered: 0,
skipped: 0,
pct: 'Unknown'
},
functions: {
total: 0,
covered: 0,
skipped: 0,
pct: 'Unknown'
},
branches: {
total: 0,
covered: 0,
skipped: 0,
pct: 'Unknown'
},
linesCovered: {}
};
}
/**
* returns the summary metrics given the coverage object for a single file. See `blankSummary()`
* to understand the format of the returned object.
*
* @method summarizeFileCoverage
* @static
* @param {Object} fileCoverage the coverage object for a single file.
* @return {Object} the summary metrics for the file
*/
function summarizeFileCoverage(fileCoverage) {
var ret = blankSummary();
addDerivedInfoForFile(fileCoverage);
ret.lines = computeSimpleTotals(fileCoverage, 'l');
ret.functions = computeSimpleTotals(fileCoverage, 'f', 'fnMap');
ret.statements = computeSimpleTotals(fileCoverage, 's', 'statementMap');
ret.branches = computeBranchTotals(fileCoverage);
ret.linesCovered = fileCoverage.l;
return ret;
}
/**
* merges two instances of file coverage objects *for the same file*
* such that the execution counts are correct.
*
* @method mergeFileCoverage
* @static
* @param {Object} first the first file coverage object for a given file
* @param {Object} second the second file coverage object for the same file
* @return {Object} an object that is a result of merging the two. Note that
* the input objects are not changed in any way.
*/
function mergeFileCoverage(first, second) {
var ret = JSON.parse(JSON.stringify(first)),
i;
delete ret.l; //remove derived info
Object.keys(second.s).forEach(function (k) {
ret.s[k] += second.s[k];
});
Object.keys(second.f).forEach(function (k) {
ret.f[k] += second.f[k];
});
Object.keys(second.b).forEach(function (k) {
var retArray = ret.b[k],
secondArray = second.b[k];
for (i = 0; i < retArray.length; i += 1) {
retArray[i] += secondArray[i];
}
});
return ret;
}
/**
* merges multiple summary metrics objects by summing up the `totals` and
* `covered` fields and recomputing the percentages. This function is generic
* and can accept any number of arguments.
*
* @method mergeSummaryObjects
* @static
* @param {Object} summary... multiple summary metrics objects
* @return {Object} the merged summary metrics
*/
function mergeSummaryObjects() {
var ret = blankSummary(),
args = Array.prototype.slice.call(arguments),
keys = ['lines', 'statements', 'branches', 'functions'],
increment = function (obj) {
if (obj) {
keys.forEach(function (key) {
ret[key].total += obj[key].total;
ret[key].covered += obj[key].covered;
ret[key].skipped += obj[key].skipped;
});
// keep track of all lines we have coverage for.
Object.keys(obj.linesCovered).forEach(function (key) {
if (!ret.linesCovered[key]) {
ret.linesCovered[key] = obj.linesCovered[key];
} else {
ret.linesCovered[key] += obj.linesCovered[key];
}
});
}
};
args.forEach(function (arg) {
increment(arg);
});
keys.forEach(function (key) {
ret[key].pct = percent(ret[key].covered, ret[key].total);
});
return ret;
}
/**
* returns the coverage summary for a single coverage object. This is
* wrapper over `summarizeFileCoverage` and `mergeSummaryObjects` for
* the common case of a single coverage object
* @method summarizeCoverage
* @static
* @param {Object} coverage the coverage object
* @return {Object} summary coverage metrics across all files in the coverage object
*/
function summarizeCoverage(coverage) {
var fileSummary = [];
Object.keys(coverage).forEach(function (key) {
fileSummary.push(summarizeFileCoverage(coverage[key]));
});
return mergeSummaryObjects.apply(null, fileSummary);
}
/**
* makes the coverage object generated by this library yuitest_coverage compatible.
* Note that this transformation is lossy since the returned object will not have
* statement and branch coverage.
*
* @method toYUICoverage
* @static
* @param {Object} coverage The `istanbul` coverage object
* @return {Object} a coverage object in `yuitest_coverage` format.
*/
function toYUICoverage(coverage) {
var ret = {};
addDerivedInfo(coverage);
Object.keys(coverage).forEach(function (k) {
var fileCoverage = coverage[k],
lines = fileCoverage.l,
functions = fileCoverage.f,
fnMap = fileCoverage.fnMap,
o;
o = ret[k] = {
lines: {},
calledLines: 0,
coveredLines: 0,
functions: {},
calledFunctions: 0,
coveredFunctions: 0
};
Object.keys(lines).forEach(function (k) {
o.lines[k] = lines[k];
o.coveredLines += 1;
if (lines[k] > 0) {
o.calledLines += 1;
}
});
Object.keys(functions).forEach(function (k) {
var name = fnMap[k].name + ':' + fnMap[k].line;
o.functions[name] = functions[k];
o.coveredFunctions += 1;
if (functions[k] > 0) {
o.calledFunctions += 1;
}
});
});
return ret;
}
/**
* Creates new file coverage object with incremented hits count
* on skipped statements, branches and functions
*
* @method incrementIgnoredTotals
* @static
* @param {Object} cov File coverage object
* @return {Object} New file coverage object
*/
function incrementIgnoredTotals(cov) {
//TODO: This may be slow in the browser and may break in older browsers
// Look into using a library that works in Node and the browser
var fileCoverage = JSON.parse(JSON.stringify(cov));
[
{mapKey: 'statementMap', hitsKey: 's'},
{mapKey: 'branchMap', hitsKey: 'b'},
{mapKey: 'fnMap', hitsKey: 'f'}
].forEach(function (keys) {
Object.keys(fileCoverage[keys.mapKey])
.forEach(function (key) {
var map = fileCoverage[keys.mapKey][key];
var hits = fileCoverage[keys.hitsKey];
if (keys.mapKey === 'branchMap') {
var locations = map.locations;
locations.forEach(function (location, index) {
if (hits[key][index] === 0 && location.skip) {
hits[key][index] = 1;
}
});
return;
}
if (hits[key] === 0 && map.skip) {
hits[key] = 1;
}
});
});
return fileCoverage;
}
var exportables = {
addDerivedInfo: addDerivedInfo,
addDerivedInfoForFile: addDerivedInfoForFile,
removeDerivedInfo: removeDerivedInfo,
blankSummary: blankSummary,
summarizeFileCoverage: summarizeFileCoverage,
summarizeCoverage: summarizeCoverage,
mergeFileCoverage: mergeFileCoverage,
mergeSummaryObjects: mergeSummaryObjects,
toYUICoverage: toYUICoverage,
incrementIgnoredTotals: incrementIgnoredTotals
};
/* istanbul ignore else: windows */
if (isNode) {
module.exports = exportables;
} else {
window.coverageUtils = exportables;
}
}(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));

View File

@ -0,0 +1,15 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Store = require('./store'),
Report = require('./report'),
Command = require('./command');
Store.loadAll();
Report.loadAll();
Command.loadAll();

View File

@ -0,0 +1,227 @@
var path = require('path'),
util = require('util'),
Report = require('./index'),
FileWriter = require('../util/file-writer'),
TreeSummarizer = require('../util/tree-summarizer'),
utils = require('../object-utils');
/**
* a `Report` implementation that produces a clover-style XML file.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('clover');
*
* @class CloverReport
* @module report
* @extends Report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the clover.xml will be written
* @param {String} [opts.file] the file name, defaulted to config attribute or 'clover.xml'
*/
function CloverReport(opts) {
Report.call(this);
opts = opts || {};
this.projectRoot = process.cwd();
this.dir = opts.dir || this.projectRoot;
this.file = opts.file || this.getDefaultConfig().file;
this.opts = opts;
}
CloverReport.TYPE = 'clover';
util.inherits(CloverReport, Report);
function asJavaPackage(node) {
return node.displayShortName().
replace(/\//g, '.').
replace(/\\/g, '.').
replace(/\.$/, '');
}
function asClassName(node) {
/*jslint regexp: true */
return node.fullPath().replace(/.*[\\\/]/, '');
}
function quote(thing) {
return '"' + thing + '"';
}
function attr(n, v) {
return ' ' + n + '=' + quote(v) + ' ';
}
function branchCoverageByLine(fileCoverage) {
var branchMap = fileCoverage.branchMap,
branches = fileCoverage.b,
ret = {};
Object.keys(branchMap).forEach(function (k) {
var line = branchMap[k].line,
branchData = branches[k];
ret[line] = ret[line] || [];
ret[line].push.apply(ret[line], branchData);
});
Object.keys(ret).forEach(function (k) {
var dataArray = ret[k],
covered = dataArray.filter(function (item) { return item > 0; }),
coverage = covered.length / dataArray.length * 100;
ret[k] = { covered: covered.length, total: dataArray.length, coverage: coverage };
});
return ret;
}
function addClassStats(node, fileCoverage, writer) {
fileCoverage = utils.incrementIgnoredTotals(fileCoverage);
var metrics = node.metrics,
branchByLine = branchCoverageByLine(fileCoverage),
fnMap,
lines;
writer.println('\t\t\t<file' +
attr('name', asClassName(node)) +
attr('path', node.fullPath()) +
'>');
writer.println('\t\t\t\t<metrics' +
attr('statements', metrics.lines.total) +
attr('coveredstatements', metrics.lines.covered) +
attr('conditionals', metrics.branches.total) +
attr('coveredconditionals', metrics.branches.covered) +
attr('methods', metrics.functions.total) +
attr('coveredmethods', metrics.functions.covered) +
'/>');
fnMap = fileCoverage.fnMap;
lines = fileCoverage.l;
Object.keys(lines).forEach(function (k) {
var str = '\t\t\t\t<line' +
attr('num', k) +
attr('count', lines[k]),
branchDetail = branchByLine[k];
if (!branchDetail) {
str += ' type="stmt" ';
} else {
str += ' type="cond" ' +
attr('truecount', branchDetail.covered) +
attr('falsecount', (branchDetail.total - branchDetail.covered));
}
writer.println(str + '/>');
});
writer.println('\t\t\t</file>');
}
function walk(node, collector, writer, level, projectRoot) {
var metrics,
totalFiles = 0,
totalPackages = 0,
totalLines = 0,
tempLines = 0;
if (level === 0) {
metrics = node.metrics;
writer.println('<?xml version="1.0" encoding="UTF-8"?>');
writer.println('<coverage' +
attr('generated', Date.now()) +
'clover="3.2.0">');
writer.println('\t<project' +
attr('timestamp', Date.now()) +
attr('name', 'All Files') +
'>');
node.children.filter(function (child) { return child.kind === 'dir'; }).
forEach(function (child) {
totalPackages += 1;
child.children.filter(function (child) { return child.kind !== 'dir'; }).
forEach(function (child) {
Object.keys(collector.fileCoverageFor(child.fullPath()).l).forEach(function (k){
tempLines = k;
});
totalLines += Number(tempLines);
totalFiles += 1;
});
});
writer.println('\t\t<metrics' +
attr('statements', metrics.lines.total) +
attr('coveredstatements', metrics.lines.covered) +
attr('conditionals', metrics.branches.total) +
attr('coveredconditionals', metrics.branches.covered) +
attr('methods', metrics.functions.total) +
attr('coveredmethods', metrics.functions.covered) +
attr('elements', metrics.lines.total + metrics.branches.total + metrics.functions.total) +
attr('coveredelements', metrics.lines.covered + metrics.branches.covered + metrics.functions.covered) +
attr('complexity', 0) +
attr('packages', totalPackages) +
attr('files', totalFiles) +
attr('classes', totalFiles) +
attr('loc', totalLines) +
attr('ncloc', totalLines) +
'/>');
}
if (node.packageMetrics) {
metrics = node.packageMetrics;
writer.println('\t\t<package' +
attr('name', asJavaPackage(node)) +
'>');
writer.println('\t\t\t<metrics' +
attr('statements', metrics.lines.total) +
attr('coveredstatements', metrics.lines.covered) +
attr('conditionals', metrics.branches.total) +
attr('coveredconditionals', metrics.branches.covered) +
attr('methods', metrics.functions.total) +
attr('coveredmethods', metrics.functions.covered) +
'/>');
node.children.filter(function (child) { return child.kind !== 'dir'; }).
forEach(function (child) {
addClassStats(child, collector.fileCoverageFor(child.fullPath()), writer);
});
writer.println('\t\t</package>');
}
node.children.filter(function (child) { return child.kind === 'dir'; }).
forEach(function (child) {
walk(child, collector, writer, level + 1, projectRoot);
});
if (level === 0) {
writer.println('\t</project>');
writer.println('</coverage>');
}
}
Report.mix(CloverReport, {
synopsis: function () {
return 'XML coverage report that can be consumed by the clover tool';
},
getDefaultConfig: function () {
return { file: 'clover.xml' };
},
writeReport: function (collector, sync) {
var summarizer = new TreeSummarizer(),
outputFile = path.join(this.dir, this.file),
writer = this.opts.writer || new FileWriter(sync),
projectRoot = this.projectRoot,
that = this,
tree,
root;
collector.files().forEach(function (key) {
summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key)));
});
tree = summarizer.getTreeSummary();
root = tree.root;
writer.on('done', function () { that.emit('done'); });
writer.writeFile(outputFile, function (contentWriter) {
walk(root, collector, contentWriter, 0, projectRoot);
writer.done();
});
}
});
module.exports = CloverReport;

View File

@ -0,0 +1,221 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
util = require('util'),
Report = require('./index'),
FileWriter = require('../util/file-writer'),
TreeSummarizer = require('../util/tree-summarizer'),
utils = require('../object-utils');
/**
* a `Report` implementation that produces a cobertura-style XML file that conforms to the
* http://cobertura.sourceforge.net/xml/coverage-04.dtd DTD.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('cobertura');
*
* @class CoberturaReport
* @module report
* @extends Report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the cobertura-coverage.xml will be written
*/
function CoberturaReport(opts) {
Report.call(this);
opts = opts || {};
this.projectRoot = process.cwd();
this.dir = opts.dir || this.projectRoot;
this.file = opts.file || this.getDefaultConfig().file;
this.opts = opts;
}
CoberturaReport.TYPE = 'cobertura';
util.inherits(CoberturaReport, Report);
function asJavaPackage(node) {
return node.displayShortName().
replace(/\//g, '.').
replace(/\\/g, '.').
replace(/\.$/, '');
}
function asClassName(node) {
/*jslint regexp: true */
return node.fullPath().replace(/.*[\\\/]/, '');
}
function quote(thing) {
return '"' + thing + '"';
}
function attr(n, v) {
return ' ' + n + '=' + quote(v) + ' ';
}
function branchCoverageByLine(fileCoverage) {
var branchMap = fileCoverage.branchMap,
branches = fileCoverage.b,
ret = {};
Object.keys(branchMap).forEach(function (k) {
var line = branchMap[k].line,
branchData = branches[k];
ret[line] = ret[line] || [];
ret[line].push.apply(ret[line], branchData);
});
Object.keys(ret).forEach(function (k) {
var dataArray = ret[k],
covered = dataArray.filter(function (item) { return item > 0; }),
coverage = covered.length / dataArray.length * 100;
ret[k] = { covered: covered.length, total: dataArray.length, coverage: coverage };
});
return ret;
}
function addClassStats(node, fileCoverage, writer, projectRoot) {
fileCoverage = utils.incrementIgnoredTotals(fileCoverage);
var metrics = node.metrics,
branchByLine = branchCoverageByLine(fileCoverage),
fnMap,
lines;
writer.println('\t\t<class' +
attr('name', asClassName(node)) +
attr('filename', path.relative(projectRoot, node.fullPath())) +
attr('line-rate', metrics.lines.pct / 100.0) +
attr('branch-rate', metrics.branches.pct / 100.0) +
'>');
writer.println('\t\t<methods>');
fnMap = fileCoverage.fnMap;
Object.keys(fnMap).forEach(function (k) {
var name = fnMap[k].name,
hits = fileCoverage.f[k];
writer.println(
'\t\t\t<method' +
attr('name', name) +
attr('hits', hits) +
attr('signature', '()V') + //fake out a no-args void return
'>'
);
//Add the function definition line and hits so that jenkins cobertura plugin records method hits
writer.println(
'\t\t\t\t<lines>' +
'<line' +
attr('number', fnMap[k].line) +
attr('hits', fileCoverage.f[k]) +
'/>' +
'</lines>'
);
writer.println('\t\t\t</method>');
});
writer.println('\t\t</methods>');
writer.println('\t\t<lines>');
lines = fileCoverage.l;
Object.keys(lines).forEach(function (k) {
var str = '\t\t\t<line' +
attr('number', k) +
attr('hits', lines[k]),
branchDetail = branchByLine[k];
if (!branchDetail) {
str += attr('branch', false);
} else {
str += attr('branch', true) +
attr('condition-coverage', branchDetail.coverage +
'% (' + branchDetail.covered + '/' + branchDetail.total + ')');
}
writer.println(str + '/>');
});
writer.println('\t\t</lines>');
writer.println('\t\t</class>');
}
function walk(node, collector, writer, level, projectRoot) {
var metrics;
if (level === 0) {
metrics = node.metrics;
writer.println('<?xml version="1.0" ?>');
writer.println('<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">');
writer.println('<coverage' +
attr('lines-valid', metrics.lines.total) +
attr('lines-covered', metrics.lines.covered) +
attr('line-rate', metrics.lines.pct / 100.0) +
attr('branches-valid', metrics.branches.total) +
attr('branches-covered', metrics.branches.covered) +
attr('branch-rate', metrics.branches.pct / 100.0) +
attr('timestamp', Date.now()) +
'complexity="0" version="0.1">');
writer.println('<sources>');
writer.println('\t<source>' + projectRoot + '</source>');
writer.println('</sources>');
writer.println('<packages>');
}
if (node.packageMetrics) {
metrics = node.packageMetrics;
writer.println('\t<package' +
attr('name', asJavaPackage(node)) +
attr('line-rate', metrics.lines.pct / 100.0) +
attr('branch-rate', metrics.branches.pct / 100.0) +
'>');
writer.println('\t<classes>');
node.children.filter(function (child) { return child.kind !== 'dir'; }).
forEach(function (child) {
addClassStats(child, collector.fileCoverageFor(child.fullPath()), writer, projectRoot);
});
writer.println('\t</classes>');
writer.println('\t</package>');
}
node.children.filter(function (child) { return child.kind === 'dir'; }).
forEach(function (child) {
walk(child, collector, writer, level + 1, projectRoot);
});
if (level === 0) {
writer.println('</packages>');
writer.println('</coverage>');
}
}
Report.mix(CoberturaReport, {
synopsis: function () {
return 'XML coverage report that can be consumed by the cobertura tool';
},
getDefaultConfig: function () {
return { file: 'cobertura-coverage.xml' };
},
writeReport: function (collector, sync) {
var summarizer = new TreeSummarizer(),
outputFile = path.join(this.dir, this.file),
writer = this.opts.writer || new FileWriter(sync),
projectRoot = this.projectRoot,
that = this,
tree,
root;
collector.files().forEach(function (key) {
summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key)));
});
tree = summarizer.getTreeSummary();
root = tree.root;
writer.on('done', function () { that.emit('done'); });
writer.writeFile(outputFile, function (contentWriter) {
walk(root, collector, contentWriter, 0, projectRoot);
writer.done();
});
}
});
module.exports = CoberturaReport;

View File

@ -0,0 +1,51 @@
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Report = require('../index');
var supportsColor = require('supports-color');
module.exports = {
watermarks: function () {
return {
statements: [ 50, 80 ],
lines: [ 50, 80 ],
functions: [ 50, 80],
branches: [ 50, 80 ]
};
},
classFor: function (type, metrics, watermarks) {
var mark = watermarks[type],
value = metrics[type].pct;
return value >= mark[1] ? 'high' : value >= mark[0] ? 'medium' : 'low';
},
colorize: function (str, clazz) {
/* istanbul ignore if: untestable in batch mode */
var colors = {
low: '31;1',
medium: '33;1',
high: '32;1'
};
if (supportsColor && colors[clazz]) {
return '\u001b[' + colors[clazz] + 'm' + str + '\u001b[0m';
}
return str;
},
defaultReportConfig: function () {
var cfg = {};
Report.getReportList().forEach(function (type) {
var rpt = Report.create(type),
c = rpt.getDefaultConfig();
if (c) {
cfg[type] = c;
}
});
return cfg;
}
};

View File

@ -0,0 +1,572 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
/*jshint maxlen: 300 */
var handlebars = require('handlebars').create(),
defaults = require('./common/defaults'),
path = require('path'),
fs = require('fs'),
util = require('util'),
FileWriter = require('../util/file-writer'),
Report = require('./index'),
Store = require('../store'),
InsertionText = require('../util/insertion-text'),
TreeSummarizer = require('../util/tree-summarizer'),
utils = require('../object-utils'),
templateFor = function (name) { return handlebars.compile(fs.readFileSync(path.resolve(__dirname, 'templates', name + '.txt'), 'utf8')); },
headerTemplate = templateFor('head'),
footerTemplate = templateFor('foot'),
detailTemplate = handlebars.compile([
'<tr>',
'<td class="line-count quiet">{{#show_lines}}{{maxLines}}{{/show_lines}}</td>',
'<td class="line-coverage quiet">{{#show_line_execution_counts fileCoverage}}{{maxLines}}{{/show_line_execution_counts}}</td>',
'<td class="text"><pre class="prettyprint lang-js">{{#show_code structured}}{{/show_code}}</pre></td>',
'</tr>\n'
].join('')),
summaryTableHeader = [
'<div class="pad1">',
'<table class="coverage-summary">',
'<thead>',
'<tr>',
' <th data-col="file" data-fmt="html" data-html="true" class="file">File</th>',
' <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>',
' <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>',
' <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>',
' <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>',
' <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>',
' <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>',
' <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>',
'</tr>',
'</thead>',
'<tbody>'
].join('\n'),
summaryLineTemplate = handlebars.compile([
'<tr>',
'<td class="file {{reportClasses.statements}}" data-value="{{file}}"><a href="{{output}}">{{file}}</a></td>',
'<td data-value="{{metrics.statements.pct}}" class="pic {{reportClasses.statements}}"><div class="chart">{{#show_picture}}{{metrics.statements.pct}}{{/show_picture}}</div></td>',
'<td data-value="{{metrics.statements.pct}}" class="pct {{reportClasses.statements}}">{{metrics.statements.pct}}%</td>',
'<td data-value="{{metrics.statements.total}}" class="abs {{reportClasses.statements}}">{{metrics.statements.covered}}/{{metrics.statements.total}}</td>',
'<td data-value="{{metrics.branches.pct}}" class="pct {{reportClasses.branches}}">{{metrics.branches.pct}}%</td>',
'<td data-value="{{metrics.branches.total}}" class="abs {{reportClasses.branches}}">{{metrics.branches.covered}}/{{metrics.branches.total}}</td>',
'<td data-value="{{metrics.functions.pct}}" class="pct {{reportClasses.functions}}">{{metrics.functions.pct}}%</td>',
'<td data-value="{{metrics.functions.total}}" class="abs {{reportClasses.functions}}">{{metrics.functions.covered}}/{{metrics.functions.total}}</td>',
'<td data-value="{{metrics.lines.pct}}" class="pct {{reportClasses.lines}}">{{metrics.lines.pct}}%</td>',
'<td data-value="{{metrics.lines.total}}" class="abs {{reportClasses.lines}}">{{metrics.lines.covered}}/{{metrics.lines.total}}</td>',
'</tr>\n'
].join('\n\t')),
summaryTableFooter = [
'</tbody>',
'</table>',
'</div>'
].join('\n'),
lt = '\u0001',
gt = '\u0002',
RE_LT = /</g,
RE_GT = />/g,
RE_AMP = /&/g,
RE_lt = /\u0001/g,
RE_gt = /\u0002/g;
handlebars.registerHelper('show_picture', function (opts) {
var num = Number(opts.fn(this)),
rest,
cls = '';
if (isFinite(num)) {
if (num === 100) {
cls = ' cover-full';
}
num = Math.floor(num);
rest = 100 - num;
return '<div class="cover-fill' + cls + '" style="width: ' + num + '%;"></div>' +
'<div class="cover-empty" style="width:' + rest + '%;"></div>';
} else {
return '';
}
});
handlebars.registerHelper('if_has_ignores', function (metrics, opts) {
return (metrics.statements.skipped +
metrics.functions.skipped +
metrics.branches.skipped) === 0 ? '' : opts.fn(this);
});
handlebars.registerHelper('show_ignores', function (metrics) {
var statements = metrics.statements.skipped,
functions = metrics.functions.skipped,
branches = metrics.branches.skipped,
result;
if (statements === 0 && functions === 0 && branches === 0) {
return '<span class="ignore-none">none</span>';
}
result = [];
if (statements >0) { result.push(statements === 1 ? '1 statement': statements + ' statements'); }
if (functions >0) { result.push(functions === 1 ? '1 function' : functions + ' functions'); }
if (branches >0) { result.push(branches === 1 ? '1 branch' : branches + ' branches'); }
return result.join(', ');
});
handlebars.registerHelper('show_lines', function (opts) {
var maxLines = Number(opts.fn(this)),
i,
array = [];
for (i = 0; i < maxLines; i += 1) {
array[i] = i + 1;
}
return array.join('\n');
});
handlebars.registerHelper('show_line_execution_counts', function (context, opts) {
var lines = context.l,
maxLines = Number(opts.fn(this)),
i,
lineNumber,
array = [],
covered,
value = '';
for (i = 0; i < maxLines; i += 1) {
lineNumber = i + 1;
value = '&nbsp;';
covered = 'neutral';
if (lines.hasOwnProperty(lineNumber)) {
if (lines[lineNumber] > 0) {
covered = 'yes';
value = lines[lineNumber] + '×';
} else {
covered = 'no';
}
}
array.push('<span class="cline-any cline-' + covered + '">' + value + '</span>');
}
return array.join('\n');
});
function customEscape(text) {
text = text.toString();
return text.replace(RE_AMP, '&amp;')
.replace(RE_LT, '&lt;')
.replace(RE_GT, '&gt;')
.replace(RE_lt, '<')
.replace(RE_gt, '>');
}
handlebars.registerHelper('show_code', function (context /*, opts */) {
var array = [];
context.forEach(function (item) {
array.push(customEscape(item.text) || '&nbsp;');
});
return array.join('\n');
});
function title(str) {
return ' title="' + str + '" ';
}
function annotateLines(fileCoverage, structuredText) {
var lineStats = fileCoverage.l;
if (!lineStats) { return; }
Object.keys(lineStats).forEach(function (lineNumber) {
var count = lineStats[lineNumber];
if (structuredText[lineNumber]) {
structuredText[lineNumber].covered = count > 0 ? 'yes' : 'no';
}
});
structuredText.forEach(function (item) {
if (item.covered === null) {
item.covered = 'neutral';
}
});
}
function annotateStatements(fileCoverage, structuredText) {
var statementStats = fileCoverage.s,
statementMeta = fileCoverage.statementMap;
Object.keys(statementStats).forEach(function (stName) {
var count = statementStats[stName],
meta = statementMeta[stName],
type = count > 0 ? 'yes' : 'no',
startCol = meta.start.column,
endCol = meta.end.column + 1,
startLine = meta.start.line,
endLine = meta.end.line,
openSpan = lt + 'span class="' + (meta.skip ? 'cstat-skip' : 'cstat-no') + '"' + title('statement not covered') + gt,
closeSpan = lt + '/span' + gt,
text;
if (type === 'no') {
if (endLine !== startLine) {
endLine = startLine;
endCol = structuredText[startLine].text.originalLength();
}
text = structuredText[startLine].text;
text.wrap(startCol,
openSpan,
startLine === endLine ? endCol : text.originalLength(),
closeSpan);
}
});
}
function annotateFunctions(fileCoverage, structuredText) {
var fnStats = fileCoverage.f,
fnMeta = fileCoverage.fnMap;
if (!fnStats) { return; }
Object.keys(fnStats).forEach(function (fName) {
var count = fnStats[fName],
meta = fnMeta[fName],
type = count > 0 ? 'yes' : 'no',
startCol = meta.loc.start.column,
endCol = meta.loc.end.column + 1,
startLine = meta.loc.start.line,
endLine = meta.loc.end.line,
openSpan = lt + 'span class="' + (meta.skip ? 'fstat-skip' : 'fstat-no') + '"' + title('function not covered') + gt,
closeSpan = lt + '/span' + gt,
text;
if (type === 'no') {
if (endLine !== startLine) {
endLine = startLine;
endCol = structuredText[startLine].text.originalLength();
}
text = structuredText[startLine].text;
text.wrap(startCol,
openSpan,
startLine === endLine ? endCol : text.originalLength(),
closeSpan);
}
});
}
function annotateBranches(fileCoverage, structuredText) {
var branchStats = fileCoverage.b,
branchMeta = fileCoverage.branchMap;
if (!branchStats) { return; }
Object.keys(branchStats).forEach(function (branchName) {
var branchArray = branchStats[branchName],
sumCount = branchArray.reduce(function (p, n) { return p + n; }, 0),
metaArray = branchMeta[branchName].locations,
i,
count,
meta,
type,
startCol,
endCol,
startLine,
endLine,
openSpan,
closeSpan,
text;
if (sumCount > 0) { //only highlight if partial branches are missing
for (i = 0; i < branchArray.length; i += 1) {
count = branchArray[i];
meta = metaArray[i];
type = count > 0 ? 'yes' : 'no';
startCol = meta.start.column;
endCol = meta.end.column + 1;
startLine = meta.start.line;
endLine = meta.end.line;
openSpan = lt + 'span class="branch-' + i + ' ' + (meta.skip ? 'cbranch-skip' : 'cbranch-no') + '"' + title('branch not covered') + gt;
closeSpan = lt + '/span' + gt;
if (count === 0) { //skip branches taken
if (endLine !== startLine) {
endLine = startLine;
endCol = structuredText[startLine].text.originalLength();
}
text = structuredText[startLine].text;
if (branchMeta[branchName].type === 'if') { // and 'if' is a special case since the else branch might not be visible, being non-existent
text.insertAt(startCol, lt + 'span class="' + (meta.skip ? 'skip-if-branch' : 'missing-if-branch') + '"' +
title((i === 0 ? 'if' : 'else') + ' path not taken') + gt +
(i === 0 ? 'I' : 'E') + lt + '/span' + gt, true, false);
} else {
text.wrap(startCol,
openSpan,
startLine === endLine ? endCol : text.originalLength(),
closeSpan);
}
}
}
}
});
}
function getReportClass(stats, watermark) {
var coveragePct = stats.pct,
identity = 1;
if (coveragePct * identity === coveragePct) {
return coveragePct >= watermark[1] ? 'high' : coveragePct >= watermark[0] ? 'medium' : 'low';
} else {
return '';
}
}
function cleanPath(name) {
var SEP = path.sep || '/';
return (SEP !== '/') ? name.split(SEP).join('/') : name;
}
function isEmptySourceStore(sourceStore) {
if (!sourceStore) {
return true;
}
var cache = sourceStore.sourceCache;
return cache && !Object.keys(cache).length;
}
/**
* a `Report` implementation that produces HTML coverage reports.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('html');
*
*
* @class HtmlReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to generate reports. Defaults to `./html-report`
*/
function HtmlReport(opts) {
Report.call(this);
this.opts = opts || {};
this.opts.dir = this.opts.dir || path.resolve(process.cwd(), 'html-report');
this.opts.sourceStore = isEmptySourceStore(this.opts.sourceStore) ?
Store.create('fslookup') : this.opts.sourceStore;
this.opts.linkMapper = this.opts.linkMapper || this.standardLinkMapper();
this.opts.writer = this.opts.writer || null;
this.opts.templateData = { datetime: Date() };
this.opts.watermarks = this.opts.watermarks || defaults.watermarks();
}
HtmlReport.TYPE = 'html';
util.inherits(HtmlReport, Report);
Report.mix(HtmlReport, {
synopsis: function () {
return 'Navigable HTML coverage report for every file and directory';
},
getPathHtml: function (node, linkMapper) {
var parent = node.parent,
nodePath = [],
linkPath = [],
i;
while (parent) {
nodePath.push(parent);
parent = parent.parent;
}
for (i = 0; i < nodePath.length; i += 1) {
linkPath.push('<a href="' + linkMapper.ancestor(node, i + 1) + '">' +
(cleanPath(nodePath[i].relativeName) || 'all files') + '</a>');
}
linkPath.reverse();
return linkPath.length > 0 ? linkPath.join(' / ') + ' ' +
cleanPath(node.displayShortName()) : '/';
},
fillTemplate: function (node, templateData) {
var opts = this.opts,
linkMapper = opts.linkMapper;
templateData.entity = node.name || 'All files';
templateData.metrics = node.metrics;
templateData.reportClass = getReportClass(node.metrics.statements, opts.watermarks.statements);
templateData.pathHtml = this.getPathHtml(node, linkMapper);
templateData.base = {
css: linkMapper.asset(node, 'base.css')
};
templateData.sorter = {
js: linkMapper.asset(node, 'sorter.js'),
image: linkMapper.asset(node, 'sort-arrow-sprite.png')
};
templateData.prettify = {
js: linkMapper.asset(node, 'prettify.js'),
css: linkMapper.asset(node, 'prettify.css')
};
},
writeDetailPage: function (writer, node, fileCoverage) {
var opts = this.opts,
sourceStore = opts.sourceStore,
templateData = opts.templateData,
sourceText = fileCoverage.code && Array.isArray(fileCoverage.code) ?
fileCoverage.code.join('\n') + '\n' : sourceStore.get(fileCoverage.path),
code = sourceText.split(/(?:\r?\n)|\r/),
count = 0,
structured = code.map(function (str) { count += 1; return { line: count, covered: null, text: new InsertionText(str, true) }; }),
context;
structured.unshift({ line: 0, covered: null, text: new InsertionText("") });
this.fillTemplate(node, templateData);
writer.write(headerTemplate(templateData));
writer.write('<pre><table class="coverage">\n');
annotateLines(fileCoverage, structured);
//note: order is important, since statements typically result in spanning the whole line and doing branches late
//causes mismatched tags
annotateBranches(fileCoverage, structured);
annotateFunctions(fileCoverage, structured);
annotateStatements(fileCoverage, structured);
structured.shift();
context = {
structured: structured,
maxLines: structured.length,
fileCoverage: fileCoverage
};
writer.write(detailTemplate(context));
writer.write('</table></pre>\n');
writer.write(footerTemplate(templateData));
},
writeIndexPage: function (writer, node) {
var linkMapper = this.opts.linkMapper,
templateData = this.opts.templateData,
children = Array.prototype.slice.apply(node.children),
watermarks = this.opts.watermarks;
children.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
this.fillTemplate(node, templateData);
writer.write(headerTemplate(templateData));
writer.write(summaryTableHeader);
children.forEach(function (child) {
var metrics = child.metrics,
reportClasses = {
statements: getReportClass(metrics.statements, watermarks.statements),
lines: getReportClass(metrics.lines, watermarks.lines),
functions: getReportClass(metrics.functions, watermarks.functions),
branches: getReportClass(metrics.branches, watermarks.branches)
},
data = {
metrics: metrics,
reportClasses: reportClasses,
file: cleanPath(child.displayShortName()),
output: linkMapper.fromParent(child)
};
writer.write(summaryLineTemplate(data) + '\n');
});
writer.write(summaryTableFooter);
writer.write(footerTemplate(templateData));
},
writeFiles: function (writer, node, dir, collector) {
var that = this,
indexFile = path.resolve(dir, 'index.html'),
childFile;
if (this.opts.verbose) { console.error('Writing ' + indexFile); }
writer.writeFile(indexFile, function (contentWriter) {
that.writeIndexPage(contentWriter, node);
});
node.children.forEach(function (child) {
if (child.kind === 'dir') {
that.writeFiles(writer, child, path.resolve(dir, child.relativeName), collector);
} else {
childFile = path.resolve(dir, child.relativeName + '.html');
if (that.opts.verbose) { console.error('Writing ' + childFile); }
writer.writeFile(childFile, function (contentWriter) {
that.writeDetailPage(contentWriter, child, collector.fileCoverageFor(child.fullPath()));
});
}
});
},
standardLinkMapper: function () {
return {
fromParent: function (node) {
var relativeName = cleanPath(node.relativeName);
return node.kind === 'dir' ? relativeName + 'index.html' : relativeName + '.html';
},
ancestorHref: function (node, num) {
var href = '',
notDot = function(part) {
return part !== '.';
},
separated,
levels,
i,
j;
for (i = 0; i < num; i += 1) {
separated = cleanPath(node.relativeName).split('/').filter(notDot);
levels = separated.length - 1;
for (j = 0; j < levels; j += 1) {
href += '../';
}
node = node.parent;
}
return href;
},
ancestor: function (node, num) {
return this.ancestorHref(node, num) + 'index.html';
},
asset: function (node, name) {
var i = 0,
parent = node.parent;
while (parent) { i += 1; parent = parent.parent; }
return this.ancestorHref(node, i) + name;
}
};
},
writeReport: function (collector, sync) {
var opts = this.opts,
dir = opts.dir,
summarizer = new TreeSummarizer(),
writer = opts.writer || new FileWriter(sync),
that = this,
tree,
copyAssets = function (subdir) {
var srcDir = path.resolve(__dirname, '..', 'assets', subdir);
fs.readdirSync(srcDir).forEach(function (f) {
var resolvedSource = path.resolve(srcDir, f),
resolvedDestination = path.resolve(dir, f),
stat = fs.statSync(resolvedSource);
if (stat.isFile()) {
if (opts.verbose) {
console.log('Write asset: ' + resolvedDestination);
}
writer.copyFile(resolvedSource, resolvedDestination);
}
});
};
collector.files().forEach(function (key) {
summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(collector.fileCoverageFor(key)));
});
tree = summarizer.getTreeSummary();
[ '.', 'vendor'].forEach(function (subdir) {
copyAssets(subdir);
});
writer.on('done', function () { that.emit('done'); });
//console.log(JSON.stringify(tree.root, undefined, 4));
this.writeFiles(writer, tree.root, dir, collector);
writer.done();
}
});
module.exports = HtmlReport;

View File

@ -0,0 +1,104 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
EventEmitter = require('events').EventEmitter,
Factory = require('../util/factory'),
factory = new Factory('report', __dirname, false);
/**
* An abstraction for producing coverage reports.
* This class is both the base class as well as a factory for `Report` implementations.
* All reports are event emitters and are expected to emit a `done` event when
* the report writing is complete.
*
* See also the `Reporter` class for easily producing multiple coverage reports
* with a single call.
*
* Usage
* -----
*
* var Report = require('istanbul').Report,
* report = Report.create('html'),
* collector = new require('istanbul').Collector;
*
* collector.add(coverageObject);
* report.on('done', function () { console.log('done'); });
* report.writeReport(collector);
*
* @class Report
* @module report
* @main report
* @constructor
* @protected
* @param {Object} options Optional. The options supported by a specific store implementation.
*/
function Report(/* options */) {
EventEmitter.call(this);
}
util.inherits(Report, EventEmitter);
//add register, create, mix, loadAll, getReportList as class methods
factory.bindClassMethods(Report);
/**
* registers a new report implementation.
* @method register
* @static
* @param {Function} constructor the constructor function for the report. This function must have a
* `TYPE` property of type String, that will be used in `Report.create()`
*/
/**
* returns a report implementation of the specified type.
* @method create
* @static
* @param {String} type the type of report to create
* @param {Object} opts Optional. Options specific to the report implementation
* @return {Report} a new store of the specified type
*/
/**
* returns the list of available reports as an array of strings
* @method getReportList
* @static
* @return an array of supported report formats
*/
var proto = {
/**
* returns a one-line summary of the report
* @method synopsis
* @return {String} a description of what the report is about
*/
synopsis: function () {
throw new Error('synopsis must be overridden');
},
/**
* returns a config object that has override-able keys settable via config
* @method getDefaultConfig
* @return {Object|null} an object representing keys that can be overridden via
* the istanbul configuration where the values are the defaults used when
* not specified. A null return implies no config attributes
*/
getDefaultConfig: function () {
return null;
},
/**
* writes the report for a set of coverage objects added to a collector.
* @method writeReport
* @param {Collector} collector the collector for getting the set of files and coverage
* @param {Boolean} sync true if reports must be written synchronously, false if they can be written using asynchronous means (e.g. stream.write)
*/
writeReport: function (/* collector, sync */) {
throw new Error('writeReport: must be overridden');
}
};
Object.keys(proto).forEach(function (k) {
Report.prototype[k] = proto[k];
});
module.exports = Report;

View File

@ -0,0 +1,75 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
objectUtils = require('../object-utils'),
Writer = require('../util/file-writer'),
util = require('util'),
Report = require('./index');
/**
* a `Report` implementation that produces a coverage JSON object with summary info only.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('json-summary');
*
*
* @class JsonSummaryReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to write the `coverage-summary.json` file. Defaults to `process.cwd()`
*/
function JsonSummaryReport(opts) {
this.opts = opts || {};
this.opts.dir = this.opts.dir || process.cwd();
this.opts.file = this.opts.file || this.getDefaultConfig().file;
this.opts.writer = this.opts.writer || null;
}
JsonSummaryReport.TYPE = 'json-summary';
util.inherits(JsonSummaryReport, Report);
Report.mix(JsonSummaryReport, {
synopsis: function () {
return 'prints a summary coverage object as JSON to a file';
},
getDefaultConfig: function () {
return {
file: 'coverage-summary.json'
};
},
writeReport: function (collector, sync) {
var outputFile = path.resolve(this.opts.dir, this.opts.file),
writer = this.opts.writer || new Writer(sync),
that = this;
var summaries = [],
finalSummary;
collector.files().forEach(function (file) {
summaries.push(objectUtils.summarizeFileCoverage(collector.fileCoverageFor(file)));
});
finalSummary = objectUtils.mergeSummaryObjects.apply(null, summaries);
writer.on('done', function () { that.emit('done'); });
writer.writeFile(outputFile, function (contentWriter) {
contentWriter.println("{");
contentWriter.write('"total":');
contentWriter.write(JSON.stringify(finalSummary));
collector.files().forEach(function (key) {
contentWriter.println(",");
contentWriter.write(JSON.stringify(key));
contentWriter.write(":");
contentWriter.write(JSON.stringify(objectUtils.summarizeFileCoverage(collector.fileCoverageFor(key))));
});
contentWriter.println("}");
});
writer.done();
}
});
module.exports = JsonSummaryReport;

View File

@ -0,0 +1,69 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
Writer = require('../util/file-writer'),
util = require('util'),
Report = require('./index');
/**
* a `Report` implementation that produces a coverage JSON object.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('json');
*
*
* @class JsonReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to write the `coverage-final.json` file. Defaults to `process.cwd()`
*/
function JsonReport(opts) {
this.opts = opts || {};
this.opts.dir = this.opts.dir || process.cwd();
this.opts.file = this.opts.file || this.getDefaultConfig().file;
this.opts.writer = this.opts.writer || null;
}
JsonReport.TYPE = 'json';
util.inherits(JsonReport, Report);
Report.mix(JsonReport, {
synopsis: function () {
return 'prints the coverage object as JSON to a file';
},
getDefaultConfig: function () {
return {
file: 'coverage-final.json'
};
},
writeReport: function (collector, sync) {
var outputFile = path.resolve(this.opts.dir, this.opts.file),
writer = this.opts.writer || new Writer(sync),
that = this;
writer.on('done', function () { that.emit('done'); });
writer.writeFile(outputFile, function (contentWriter) {
var first = true;
contentWriter.println("{");
collector.files().forEach(function (key) {
if (first) {
first = false;
} else {
contentWriter.println(",");
}
contentWriter.write(JSON.stringify(key));
contentWriter.write(":");
contentWriter.write(JSON.stringify(collector.fileCoverageFor(key)));
});
contentWriter.println("}");
});
writer.done();
}
});
module.exports = JsonReport;

View File

@ -0,0 +1,65 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
util = require('util'),
mkdirp = require('mkdirp'),
Report = require('./index'),
LcovOnlyReport = require('./lcovonly'),
HtmlReport = require('./html');
/**
* a `Report` implementation that produces an LCOV coverage file and an associated HTML report from coverage objects.
* The name and behavior of this report is designed to ease migration for projects that currently use `yuitest_coverage`
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('lcov');
*
*
* @class LcovReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the `lcov.info` file.
* HTML files are written in a subdirectory called `lcov-report`. Defaults to `process.cwd()`
*/
function LcovReport(opts) {
Report.call(this);
opts = opts || {};
var baseDir = path.resolve(opts.dir || process.cwd()),
htmlDir = path.resolve(baseDir, 'lcov-report');
mkdirp.sync(baseDir);
this.lcov = new LcovOnlyReport({ dir: baseDir, watermarks: opts.watermarks });
this.html = new HtmlReport({ dir: htmlDir, watermarks: opts.watermarks, sourceStore: opts.sourceStore});
}
LcovReport.TYPE = 'lcov';
util.inherits(LcovReport, Report);
Report.mix(LcovReport, {
synopsis: function () {
return 'combined lcovonly and html report that generates an lcov.info file as well as HTML';
},
writeReport: function (collector, sync) {
var handler = this.handleDone.bind(this);
this.inProgress = 2;
this.lcov.on('done', handler);
this.html.on('done', handler);
this.lcov.writeReport(collector, sync);
this.html.writeReport(collector, sync);
},
handleDone: function () {
this.inProgress -= 1;
if (this.inProgress === 0) {
this.emit('done');
}
}
});
module.exports = LcovReport;

View File

@ -0,0 +1,103 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
Writer = require('../util/file-writer'),
util = require('util'),
Report = require('./index'),
utils = require('../object-utils');
/**
* a `Report` implementation that produces an LCOV coverage file from coverage objects.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('lcovonly');
*
*
* @class LcovOnlyReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the `lcov.info` file. Defaults to `process.cwd()`
*/
function LcovOnlyReport(opts) {
this.opts = opts || {};
this.opts.dir = this.opts.dir || process.cwd();
this.opts.file = this.opts.file || this.getDefaultConfig().file;
this.opts.writer = this.opts.writer || null;
}
LcovOnlyReport.TYPE = 'lcovonly';
util.inherits(LcovOnlyReport, Report);
Report.mix(LcovOnlyReport, {
synopsis: function () {
return 'lcov coverage report that can be consumed by the lcov tool';
},
getDefaultConfig: function () {
return { file: 'lcov.info' };
},
writeFileCoverage: function (writer, fc) {
var functions = fc.f,
functionMap = fc.fnMap,
lines = fc.l,
branches = fc.b,
branchMap = fc.branchMap,
summary = utils.summarizeFileCoverage(fc);
writer.println('TN:'); //no test name
writer.println('SF:' + fc.path);
Object.keys(functions).forEach(function (key) {
var meta = functionMap[key];
writer.println('FN:' + [ meta.line, meta.name ].join(','));
});
writer.println('FNF:' + summary.functions.total);
writer.println('FNH:' + summary.functions.covered);
Object.keys(functions).forEach(function (key) {
var stats = functions[key],
meta = functionMap[key];
writer.println('FNDA:' + [ stats, meta.name ].join(','));
});
Object.keys(lines).forEach(function (key) {
var stat = lines[key];
writer.println('DA:' + [ key, stat ].join(','));
});
writer.println('LF:' + summary.lines.total);
writer.println('LH:' + summary.lines.covered);
Object.keys(branches).forEach(function (key) {
var branchArray = branches[key],
meta = branchMap[key],
line = meta.line,
i = 0;
branchArray.forEach(function (b) {
writer.println('BRDA:' + [line, key, i, b].join(','));
i += 1;
});
});
writer.println('BRF:' + summary.branches.total);
writer.println('BRH:' + summary.branches.covered);
writer.println('end_of_record');
},
writeReport: function (collector, sync) {
var outputFile = path.resolve(this.opts.dir, this.opts.file),
writer = this.opts.writer || new Writer(sync),
that = this;
writer.on('done', function () { that.emit('done'); });
writer.writeFile(outputFile, function (contentWriter) {
collector.files().forEach(function (key) {
that.writeFileCoverage(contentWriter, collector.fileCoverageFor(key));
});
});
writer.done();
}
});
module.exports = LcovOnlyReport;

View File

@ -0,0 +1,41 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
Report = require('./index');
/**
* a `Report` implementation that does nothing. Use to specify that no reporting
* is needed.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('none');
*
*
* @class NoneReport
* @extends Report
* @module report
* @constructor
*/
function NoneReport() {
Report.call(this);
}
NoneReport.TYPE = 'none';
util.inherits(NoneReport, Report);
Report.mix(NoneReport, {
synopsis: function () {
return 'Does nothing. Useful to override default behavior and suppress reporting entirely';
},
writeReport: function (/* collector, sync */) {
//noop
this.emit('done');
}
});
module.exports = NoneReport;

View File

@ -0,0 +1,92 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
util = require('util'),
mkdirp = require('mkdirp'),
fs = require('fs'),
utils = require('../object-utils'),
Report = require('./index');
/**
* a `Report` implementation that produces system messages interpretable by TeamCity.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('teamcity');
*
* @class TeamcityReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the text coverage report will be written, when writing to a file
* @param {String} [opts.file] the filename for the report. When omitted, the report is written to console
*/
function TeamcityReport(opts) {
Report.call(this);
opts = opts || {};
this.dir = opts.dir || process.cwd();
this.file = opts.file;
this.blockName = opts.blockName || this.getDefaultConfig().blockName;
}
TeamcityReport.TYPE = 'teamcity';
util.inherits(TeamcityReport, Report);
function lineForKey(value, teamcityVar) {
return '##teamcity[buildStatisticValue key=\'' + teamcityVar + '\' value=\'' + value + '\']';
}
Report.mix(TeamcityReport, {
synopsis: function () {
return 'report with system messages that can be interpreted with TeamCity';
},
getDefaultConfig: function () {
return { file: null , blockName: 'Code Coverage Summary'};
},
writeReport: function (collector /*, sync */) {
var summaries = [],
finalSummary,
lines = [],
text;
collector.files().forEach(function (file) {
summaries.push(utils.summarizeFileCoverage(collector.fileCoverageFor(file)));
});
finalSummary = utils.mergeSummaryObjects.apply(null, summaries);
lines.push('');
lines.push('##teamcity[blockOpened name=\''+ this.blockName +'\']');
//Statements Covered
lines.push(lineForKey(finalSummary.statements.pct, 'CodeCoverageB'));
//Methods Covered
lines.push(lineForKey(finalSummary.functions.covered, 'CodeCoverageAbsMCovered'));
lines.push(lineForKey(finalSummary.functions.total, 'CodeCoverageAbsMTotal'));
lines.push(lineForKey(finalSummary.functions.pct, 'CodeCoverageM'));
//Lines Covered
lines.push(lineForKey(finalSummary.lines.covered, 'CodeCoverageAbsLCovered'));
lines.push(lineForKey(finalSummary.lines.total, 'CodeCoverageAbsLTotal'));
lines.push(lineForKey(finalSummary.lines.pct, 'CodeCoverageL'));
lines.push('##teamcity[blockClosed name=\''+ this.blockName +'\']');
text = lines.join('\n');
if (this.file) {
mkdirp.sync(this.dir);
fs.writeFileSync(path.join(this.dir, this.file), text, 'utf8');
} else {
console.log(text);
}
this.emit('done');
}
});
module.exports = TeamcityReport;

View File

@ -0,0 +1,20 @@
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at {{datetime}}
</div>
</div>
{{#if prettify}}
<script src="{{prettify.js}}"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
{{/if}}
<script src="{{sorter.js}}"></script>
</body>
</html>

View File

@ -0,0 +1,60 @@
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for {{entity}}</title>
<meta charset="utf-8" />
{{#if prettify}}
<link rel="stylesheet" href="{{prettify.css}}" />
{{/if}}
<link rel="stylesheet" href="{{base.css}}" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url({{sorter.image}});
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
{{{pathHtml}}}
</h1>
<div class='clearfix'>
{{#with metrics.statements}}
<div class='fl pad1y space-right2'>
<span class="strong">{{pct}}% </span>
<span class="quiet">Statements</span>
<span class='fraction'>{{covered}}/{{total}}</span>
</div>
{{/with}}
{{#with metrics.branches}}
<div class='fl pad1y space-right2'>
<span class="strong">{{pct}}% </span>
<span class="quiet">Branches</span>
<span class='fraction'>{{covered}}/{{total}}</span>
</div>
{{/with}}
{{#with metrics.functions}}
<div class='fl pad1y space-right2'>
<span class="strong">{{pct}}% </span>
<span class="quiet">Functions</span>
<span class='fraction'>{{covered}}/{{total}}</span>
</div>
{{/with}}
{{#with metrics.lines}}
<div class='fl pad1y space-right2'>
<span class="strong">{{pct}}% </span>
<span class="quiet">Lines</span>
<span class='fraction'>{{covered}}/{{total}}</span>
</div>
{{/with}}
{{#if_has_ignores metrics}}
<div class='fl pad1y'>
<span class="strong">{{#show_ignores metrics}}{{/show_ignores}}</span>
<span class="quiet">Ignored</span> &nbsp;&nbsp;&nbsp;&nbsp;
</div>
{{/if_has_ignores}}
</div>
</div>
<div class='status-line {{reportClass}}'></div>

View File

@ -0,0 +1,50 @@
var LcovOnly = require('./lcovonly'),
util = require('util');
/**
* a `Report` implementation that produces an LCOV coverage and prints it
* to standard out.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('text-lcov');
*
* @class TextLcov
* @module report
* @extends LcovOnly
* @constructor
* @param {Object} opts optional
* @param {String} [opts.log] the method used to log to console.
*/
function TextLcov(opts) {
var that = this;
LcovOnly.call(this);
this.opts = opts || {};
this.opts.log = this.opts.log || console.log;
this.opts.writer = {
println: function (ln) {
that.opts.log(ln);
}
};
}
TextLcov.TYPE = 'text-lcov';
util.inherits(TextLcov, LcovOnly);
LcovOnly.super_.mix(TextLcov, {
writeReport: function (collector) {
var that = this,
writer = this.opts.writer;
collector.files().forEach(function (key) {
that.writeFileCoverage(writer, collector.fileCoverageFor(key));
});
this.emit('done');
}
});
module.exports = TextLcov;

View File

@ -0,0 +1,93 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
util = require('util'),
mkdirp = require('mkdirp'),
defaults = require('./common/defaults'),
fs = require('fs'),
utils = require('../object-utils'),
Report = require('./index');
/**
* a `Report` implementation that produces text output for overall coverage in summary format.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('text-summary');
*
* @class TextSummaryReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the text coverage report will be written, when writing to a file
* @param {String} [opts.file] the filename for the report. When omitted, the report is written to console
*/
function TextSummaryReport(opts) {
Report.call(this);
opts = opts || {};
this.dir = opts.dir || process.cwd();
this.file = opts.file;
this.watermarks = opts.watermarks || defaults.watermarks();
}
TextSummaryReport.TYPE = 'text-summary';
util.inherits(TextSummaryReport, Report);
function lineForKey(summary, key, watermarks) {
var metrics = summary[key],
skipped,
result,
clazz = defaults.classFor(key, summary, watermarks);
key = key.substring(0, 1).toUpperCase() + key.substring(1);
if (key.length < 12) { key += ' '.substring(0, 12 - key.length); }
result = [ key , ':', metrics.pct + '%', '(', metrics.covered + '/' + metrics.total, ')'].join(' ');
skipped = metrics.skipped;
if (skipped > 0) {
result += ', ' + skipped + ' ignored';
}
return defaults.colorize(result, clazz);
}
Report.mix(TextSummaryReport, {
synopsis: function () {
return 'text report that prints a coverage summary across all files, typically to console';
},
getDefaultConfig: function () {
return { file: null };
},
writeReport: function (collector /*, sync */) {
var summaries = [],
finalSummary,
lines = [],
watermarks = this.watermarks,
text;
collector.files().forEach(function (file) {
summaries.push(utils.summarizeFileCoverage(collector.fileCoverageFor(file)));
});
finalSummary = utils.mergeSummaryObjects.apply(null, summaries);
lines.push('');
lines.push('=============================== Coverage summary ===============================');
lines.push.apply(lines, [
lineForKey(finalSummary, 'statements', watermarks),
lineForKey(finalSummary, 'branches', watermarks),
lineForKey(finalSummary, 'functions', watermarks),
lineForKey(finalSummary, 'lines', watermarks)
]);
lines.push('================================================================================');
text = lines.join('\n');
if (this.file) {
mkdirp.sync(this.dir);
fs.writeFileSync(path.join(this.dir, this.file), text, 'utf8');
} else {
console.log(text);
}
this.emit('done');
}
});
module.exports = TextSummaryReport;

View File

@ -0,0 +1,234 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
mkdirp = require('mkdirp'),
util = require('util'),
fs = require('fs'),
defaults = require('./common/defaults'),
Report = require('./index'),
TreeSummarizer = require('../util/tree-summarizer'),
utils = require('../object-utils'),
PCT_COLS = 9,
MISSING_COL = 15,
TAB_SIZE = 1,
DELIM = ' |',
COL_DELIM = '-|';
/**
* a `Report` implementation that produces text output in a detailed table.
*
* Usage
* -----
*
* var report = require('istanbul').Report.create('text');
*
* @class TextReport
* @extends Report
* @module report
* @constructor
* @param {Object} opts optional
* @param {String} [opts.dir] the directory in which to the text coverage report will be written, when writing to a file
* @param {String} [opts.file] the filename for the report. When omitted, the report is written to console
* @param {Number} [opts.maxCols] the max column width of the report. By default, the width of the report is adjusted based on the length of the paths
* to be reported.
*/
function TextReport(opts) {
Report.call(this);
opts = opts || {};
this.dir = opts.dir || process.cwd();
this.file = opts.file;
this.summary = opts.summary;
this.maxCols = opts.maxCols || 0;
this.watermarks = opts.watermarks || defaults.watermarks();
}
TextReport.TYPE = 'text';
util.inherits(TextReport, Report);
function padding(num, ch) {
var str = '',
i;
ch = ch || ' ';
for (i = 0; i < num; i += 1) {
str += ch;
}
return str;
}
function fill(str, width, right, tabs, clazz) {
tabs = tabs || 0;
str = String(str);
var leadingSpaces = tabs * TAB_SIZE,
remaining = width - leadingSpaces,
leader = padding(leadingSpaces),
fmtStr = '',
fillStr,
strlen = str.length;
if (remaining > 0) {
if (remaining >= strlen) {
fillStr = padding(remaining - strlen);
fmtStr = right ? fillStr + str : str + fillStr;
} else {
fmtStr = str.substring(strlen - remaining);
fmtStr = '... ' + fmtStr.substring(4);
}
}
fmtStr = defaults.colorize(fmtStr, clazz);
return leader + fmtStr;
}
function formatName(name, maxCols, level, clazz) {
return fill(name, maxCols, false, level, clazz);
}
function formatPct(pct, clazz, width) {
return fill(pct, width || PCT_COLS, true, 0, clazz);
}
function nodeName(node) {
return node.displayShortName() || 'All files';
}
function tableHeader(maxNameCols) {
var elements = [];
elements.push(formatName('File', maxNameCols, 0));
elements.push(formatPct('% Stmts'));
elements.push(formatPct('% Branch'));
elements.push(formatPct('% Funcs'));
elements.push(formatPct('% Lines'));
elements.push(formatPct('Uncovered Lines', undefined, MISSING_COL));
return elements.join(' |') + ' |';
}
function collectMissingLines(kind, linesCovered) {
var missingLines = [];
if (kind !== 'file') {
return [];
}
Object.keys(linesCovered).forEach(function (key) {
if (!linesCovered[key]) {
missingLines.push(key);
}
});
return missingLines;
}
function tableRow(node, maxNameCols, level, watermarks) {
var name = nodeName(node),
statements = node.metrics.statements.pct,
branches = node.metrics.branches.pct,
functions = node.metrics.functions.pct,
lines = node.metrics.lines.pct,
missingLines = collectMissingLines(node.kind, node.metrics.linesCovered),
elements = [];
elements.push(formatName(name, maxNameCols, level, defaults.classFor('statements', node.metrics, watermarks)));
elements.push(formatPct(statements, defaults.classFor('statements', node.metrics, watermarks)));
elements.push(formatPct(branches, defaults.classFor('branches', node.metrics, watermarks)));
elements.push(formatPct(functions, defaults.classFor('functions', node.metrics, watermarks)));
elements.push(formatPct(lines, defaults.classFor('lines', node.metrics, watermarks)));
elements.push(formatPct(missingLines.join(','), 'low', MISSING_COL));
return elements.join(DELIM) + DELIM;
}
function findNameWidth(node, level, last) {
last = last || 0;
level = level || 0;
var idealWidth = TAB_SIZE * level + nodeName(node).length;
if (idealWidth > last) {
last = idealWidth;
}
node.children.forEach(function (child) {
last = findNameWidth(child, level + 1, last);
});
return last;
}
function makeLine(nameWidth) {
var name = padding(nameWidth, '-'),
pct = padding(PCT_COLS, '-'),
elements = [];
elements.push(name);
elements.push(pct);
elements.push(pct);
elements.push(pct);
elements.push(pct);
elements.push(padding(MISSING_COL, '-'));
return elements.join(COL_DELIM) + COL_DELIM;
}
function walk(node, nameWidth, array, level, watermarks) {
var line;
if (level === 0) {
line = makeLine(nameWidth);
array.push(line);
array.push(tableHeader(nameWidth));
array.push(line);
} else {
array.push(tableRow(node, nameWidth, level, watermarks));
}
node.children.forEach(function (child) {
walk(child, nameWidth, array, level + 1, watermarks);
});
if (level === 0) {
array.push(line);
array.push(tableRow(node, nameWidth, level, watermarks));
array.push(line);
}
}
Report.mix(TextReport, {
synopsis: function () {
return 'text report that prints a coverage line for every file, typically to console';
},
getDefaultConfig: function () {
return { file: null, maxCols: 0 };
},
writeReport: function (collector /*, sync */) {
var summarizer = new TreeSummarizer(),
tree,
root,
nameWidth,
statsWidth = 4 * (PCT_COLS + 2) + MISSING_COL,
maxRemaining,
strings = [],
text;
collector.files().forEach(function (key) {
summarizer.addFileCoverageSummary(key, utils.summarizeFileCoverage(
collector.fileCoverageFor(key)
));
});
tree = summarizer.getTreeSummary();
root = tree.root;
nameWidth = findNameWidth(root);
if (this.maxCols > 0) {
maxRemaining = this.maxCols - statsWidth - 2;
if (nameWidth > maxRemaining) {
nameWidth = maxRemaining;
}
}
walk(root, nameWidth, strings, 0, this.watermarks);
text = strings.join('\n') + '\n';
if (this.file) {
mkdirp.sync(this.dir);
fs.writeFileSync(path.join(this.dir, this.file), text, 'utf8');
} else {
console.log(text);
}
this.emit('done');
}
});
module.exports = TextReport;

View File

@ -0,0 +1,111 @@
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Report = require('./report'),
configuration = require('./config'),
inputError = require('./util/input-error');
/**
* convenience mechanism to write one or more reports ensuring that config
* options are respected.
* Usage
* -----
*
* var fs = require('fs'),
* reporter = new require('istanbul').Reporter(),
* collector = new require('istanbul').Collector(),
* sync = true;
*
* collector.add(JSON.parse(fs.readFileSync('coverage.json', 'utf8')));
* reporter.add('lcovonly');
* reporter.addAll(['clover', 'cobertura']);
* reporter.write(collector, sync, function () { console.log('done'); });
*
* @class Reporter
* @param {Configuration} cfg the config object, a falsy value will load the
* default configuration instead
* @param {String} dir the directory in which to write the reports, may be falsy
* to use config or global defaults
* @constructor
* @module main
*/
function Reporter(cfg, dir) {
this.config = cfg || configuration.loadFile();
this.dir = dir || this.config.reporting.dir();
this.reports = {};
}
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;
rptConfig.dir = this.dir;
rptConfig.watermarks = config.reporting.watermarks();
try {
this.reports[fmt] = Report.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 and calls the callback when done
* @method write
* @param {Collector} collector the collector having the coverage data
* @param {Boolean} sync true to write reports synchronously
* @param {Function} callback the callback to call when done. When `sync`
* is true, the callback will be called in the same process tick.
*/
write: function (collector, sync, callback) {
var reports = this.reports,
verbose = this.config.verbose,
handler = this.handleDone.bind(this, callback);
this.inProgress = Object.keys(reports).length;
Object.keys(reports).forEach(function (name) {
var report = reports[name];
if (verbose) {
console.error('Write report: ' + name);
}
report.on('done', handler);
report.writeReport(collector, sync);
});
},
/*
* handles listening on all reports to be completed before calling the callback
* @method handleDone
* @private
* @param {Function} callback the callback to call when all reports are
* written
*/
handleDone: function (callback) {
this.inProgress -= 1;
if (this.inProgress === 0) {
return callback();
}
}
};
module.exports = Reporter;

View File

@ -0,0 +1,61 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
fs = require('fs'),
Store = require('./index');
/**
* a `Store` implementation that doesn't actually store anything. It assumes that keys
* are absolute file paths, and contents are contents of those files.
* Thus, `set` for this store is no-op, `get` returns the
* contents of the filename that the key represents, `hasKey` returns true if the key
* supplied is a valid file path and `keys` always returns an empty array.
*
* Usage
* -----
*
* var store = require('istanbul').Store.create('fslookup');
*
*
* @class LookupStore
* @extends Store
* @module store
* @constructor
*/
function LookupStore(opts) {
Store.call(this, opts);
}
LookupStore.TYPE = 'fslookup';
util.inherits(LookupStore, Store);
Store.mix(LookupStore, {
keys: function () {
return [];
},
get: function (key) {
return fs.readFileSync(key, 'utf8');
},
hasKey: function (key) {
var stats;
try {
stats = fs.statSync(key);
return stats.isFile();
} catch (ex) {
return false;
}
},
set: function (key /*, contents */) {
if (!this.hasKey(key)) {
throw new Error('Attempt to set contents for non-existent file [' + key + '] on a fslookup store');
}
return key;
}
});
module.exports = LookupStore;

View File

@ -0,0 +1,123 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var Factory = require('../util/factory'),
factory = new Factory('store', __dirname, false);
/**
* An abstraction for keeping track of content against some keys (e.g.
* original source, instrumented source, coverage objects against file names).
* This class is both the base class as well as a factory for `Store` implementations.
*
* Usage
* -----
*
* var Store = require('istanbul').Store,
* store = Store.create('memory');
*
* //basic use
* store.set('foo', 'foo-content');
* var content = store.get('foo');
*
* //keys and values
* store.keys().forEach(function (key) {
* console.log(key + ':\n' + store.get(key);
* });
* if (store.hasKey('bar') { console.log(store.get('bar'); }
*
*
* //syntactic sugar
* store.setObject('foo', { foo: true });
* console.log(store.getObject('foo').foo);
*
* store.dispose();
*
* @class Store
* @constructor
* @module store
* @param {Object} options Optional. The options supported by a specific store implementation.
* @main store
*/
function Store(/* options */) {}
//add register, create, mix, loadAll, getStoreList as class methods
factory.bindClassMethods(Store);
/**
* registers a new store implementation.
* @method register
* @static
* @param {Function} constructor the constructor function for the store. This function must have a
* `TYPE` property of type String, that will be used in `Store.create()`
*/
/**
* returns a store implementation of the specified type.
* @method create
* @static
* @param {String} type the type of store to create
* @param {Object} opts Optional. Options specific to the store implementation
* @return {Store} a new store of the specified type
*/
Store.prototype = {
/**
* sets some content associated with a specific key. The manner in which
* duplicate keys are handled for multiple `set()` calls with the same
* key is implementation-specific.
*
* @method set
* @param {String} key the key for the content
* @param {String} contents the contents for the key
*/
set: function (/* key, contents */) { throw new Error("set: must be overridden"); },
/**
* returns the content associated to a specific key or throws if the key
* was not `set`
* @method get
* @param {String} key the key for which to get the content
* @return {String} the content for the specified key
*/
get: function (/* key */) { throw new Error("get: must be overridden"); },
/**
* returns a list of all known keys
* @method keys
* @return {Array} an array of seen keys
*/
keys: function () { throw new Error("keys: must be overridden"); },
/**
* returns true if the key is one for which a `get()` call would work.
* @method hasKey
* @param {String} key
* @return true if the key is valid for this store, false otherwise
*/
hasKey: function (/* key */) { throw new Error("hasKey: must be overridden"); },
/**
* lifecycle method to dispose temporary resources associated with the store
* @method dispose
*/
dispose: function () {},
/**
* sugar method to return an object associated with a specific key. Throws
* if the content set against the key was not a valid JSON string.
* @method getObject
* @param {String} key the key for which to return the associated object
* @return {Object} the object corresponding to the key
*/
getObject: function (key) {
return JSON.parse(this.get(key));
},
/**
* sugar method to set an object against a specific key.
* @method setObject
* @param {String} key the key for the object
* @param {Object} object the object to be stored
*/
setObject: function (key, object) {
return this.set(key, JSON.stringify(object));
}
};
module.exports = Store;

View File

@ -0,0 +1,56 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
Store = require('./index');
/**
* a `Store` implementation using an in-memory object.
*
* Usage
* -----
*
* var store = require('istanbul').Store.create('memory');
*
*
* @class MemoryStore
* @extends Store
* @module store
* @constructor
*/
function MemoryStore() {
Store.call(this);
this.map = {};
}
MemoryStore.TYPE = 'memory';
util.inherits(MemoryStore, Store);
Store.mix(MemoryStore, {
set: function (key, contents) {
this.map[key] = contents;
},
get: function (key) {
if (!this.hasKey(key)) {
throw new Error('Unable to find entry for [' + key + ']');
}
return this.map[key];
},
hasKey: function (key) {
return this.map.hasOwnProperty(key);
},
keys: function () {
return Object.keys(this.map);
},
dispose: function () {
this.map = {};
}
});
module.exports = MemoryStore;

View File

@ -0,0 +1,81 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
path = require('path'),
os = require('os'),
fs = require('fs'),
mkdirp = require('mkdirp'),
Store = require('./index');
function makeTempDir() {
var dir = path.join(os.tmpdir ? os.tmpdir() : /* istanbul ignore next */ (process.env.TMPDIR || '/tmp'), 'ts' + new Date().getTime());
mkdirp.sync(dir);
return dir;
}
/**
* a `Store` implementation using temporary files.
*
* Usage
* -----
*
* var store = require('istanbul').Store.create('tmp');
*
*
* @class TmpStore
* @extends Store
* @module store
* @param {Object} opts Optional.
* @param {String} [opts.tmp] a pre-existing directory to use as the `tmp` directory. When not specified, a random directory
* is created under `os.tmpdir()`
* @constructor
*/
function TmpStore(opts) {
opts = opts || {};
this.tmp = opts.tmp || makeTempDir();
this.map = {};
this.seq = 0;
this.prefix = 't' + new Date().getTime() + '-';
}
TmpStore.TYPE = 'tmp';
util.inherits(TmpStore, Store);
Store.mix(TmpStore, {
generateTmpFileName: function () {
this.seq += 1;
return path.join(this.tmp, this.prefix + this.seq + '.tmp');
},
set: function (key, contents) {
var tmpFile = this.generateTmpFileName();
fs.writeFileSync(tmpFile, contents, 'utf8');
this.map[key] = tmpFile;
},
get: function (key) {
var tmpFile = this.map[key];
if (!tmpFile) { throw new Error('Unable to find tmp entry for [' + tmpFile + ']'); }
return fs.readFileSync(tmpFile, 'utf8');
},
hasKey: function (key) {
return !!this.map[key];
},
keys: function () {
return Object.keys(this.map);
},
dispose: function () {
var map = this.map;
Object.keys(map).forEach(function (key) {
fs.unlinkSync(map[key]);
});
this.map = {};
}
});
module.exports = TmpStore;

View File

@ -0,0 +1,88 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
path = require('path'),
fs = require('fs'),
abbrev = require('abbrev');
function Factory(kind, dir, allowAbbreviations) {
this.kind = kind;
this.dir = dir;
this.allowAbbreviations = allowAbbreviations;
this.classMap = {};
this.abbreviations = null;
}
Factory.prototype = {
knownTypes: function () {
var keys = Object.keys(this.classMap);
keys.sort();
return keys;
},
resolve: function (abbreviatedType) {
if (!this.abbreviations) {
this.abbreviations = abbrev(this.knownTypes());
}
return this.abbreviations[abbreviatedType];
},
register: function (constructor) {
var type = constructor.TYPE;
if (!type) { throw new Error('Could not register ' + this.kind + ' constructor [no TYPE property]: ' + util.inspect(constructor)); }
this.classMap[type] = constructor;
this.abbreviations = null;
},
create: function (type, opts) {
var allowAbbrev = this.allowAbbreviations,
realType = allowAbbrev ? this.resolve(type) : type,
Cons;
Cons = realType ? this.classMap[realType] : null;
if (!Cons) { throw new Error('Invalid ' + this.kind + ' [' + type + '], allowed values are ' + this.knownTypes().join(', ')); }
return new Cons(opts);
},
loadStandard: function (dir) {
var that = this;
fs.readdirSync(dir).forEach(function (file) {
if (file !== 'index.js' && file.indexOf('.js') === file.length - 3) {
try {
that.register(require(path.resolve(dir, file)));
} catch (ex) {
console.error(ex.message);
console.error(ex.stack);
throw new Error('Could not register ' + that.kind + ' from file ' + file);
}
}
});
},
bindClassMethods: function (Cons) {
var tmpKind = this.kind.charAt(0).toUpperCase() + this.kind.substring(1), //ucfirst
allowAbbrev = this.allowAbbreviations;
Cons.mix = Factory.mix;
Cons.register = this.register.bind(this);
Cons.create = this.create.bind(this);
Cons.loadAll = this.loadStandard.bind(this, this.dir);
Cons['get' + tmpKind + 'List'] = this.knownTypes.bind(this);
if (allowAbbrev) {
Cons['resolve' + tmpKind + 'Name'] = this.resolve.bind(this);
}
}
};
Factory.mix = function (cons, proto) {
Object.keys(proto).forEach(function (key) {
cons.prototype[key] = proto[key];
});
};
module.exports = Factory;

View File

@ -0,0 +1,76 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var async = require('async'),
glob = require('glob'),
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
glob(includes.join(' '), opts, function (err, files) {
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 || {};
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;
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,154 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
util = require('util'),
fs = require('fs'),
async = require('async'),
mkdirp = require('mkdirp'),
writer = require('./writer'),
Writer = writer.Writer,
ContentWriter = writer.ContentWriter;
function extend(cons, proto) {
Object.keys(proto).forEach(function (k) {
cons.prototype[k] = proto[k];
});
}
function BufferedContentWriter() {
ContentWriter.call(this);
this.content = '';
}
util.inherits(BufferedContentWriter, ContentWriter);
extend(BufferedContentWriter, {
write: function (str) {
this.content += str;
},
getContent: function () {
return this.content;
}
});
function StreamContentWriter(stream) {
ContentWriter.call(this);
this.stream = stream;
}
util.inherits(StreamContentWriter, ContentWriter);
extend(StreamContentWriter, {
write: function (str) {
this.stream.write(str);
}
});
function SyncFileWriter() {
Writer.call(this);
}
util.inherits(SyncFileWriter, Writer);
extend(SyncFileWriter, {
writeFile: function (file, callback) {
mkdirp.sync(path.dirname(file));
var cw = new BufferedContentWriter();
callback(cw);
fs.writeFileSync(file, cw.getContent(), 'utf8');
},
done: function () {
this.emit('done'); //everything already done
}
});
function AsyncFileWriter() {
this.queue = async.queue(this.processFile.bind(this), 20);
this.openFileMap = {};
}
util.inherits(AsyncFileWriter, Writer);
extend(AsyncFileWriter, {
writeFile: function (file, callback) {
this.openFileMap[file] = true;
this.queue.push({ file: file, callback: callback });
},
processFile: function (task, cb) {
var file = task.file,
userCallback = task.callback,
that = this,
stream,
contentWriter;
mkdirp.sync(path.dirname(file));
stream = fs.createWriteStream(file);
stream.on('close', function () {
delete that.openFileMap[file];
cb();
that.checkDone();
});
stream.on('error', function (err) { that.emit('error', err); });
contentWriter = new StreamContentWriter(stream);
userCallback(contentWriter);
stream.end();
},
done: function () {
this.doneCalled = true;
this.checkDone();
},
checkDone: function () {
if (!this.doneCalled) { return; }
if (Object.keys(this.openFileMap).length === 0) {
this.emit('done');
}
}
});
/**
* a concrete writer implementation that can write files synchronously or
* asynchronously based on the constructor argument passed to it.
*
* Usage
* -----
*
* var sync = true,
* fileWriter = new require('istanbul').FileWriter(sync);
*
* fileWriter.on('done', function () { console.log('done'); });
* fileWriter.copyFile('/foo/bar.jpg', '/baz/bar.jpg');
* fileWriter.writeFile('/foo/index.html', function (contentWriter) {
* contentWriter.println('<html>');
* contentWriter.println('</html>');
* });
* fileWriter.done(); // will emit the `done` event when all files are written
*
* @class FileWriter
* @extends Writer
* @module io
* @param sync
* @constructor
*/
function FileWriter(sync) {
Writer.call(this);
var that = this;
this.delegate = sync ? new SyncFileWriter() : new AsyncFileWriter();
this.delegate.on('error', function (err) { that.emit('error', err); });
this.delegate.on('done', function () { that.emit('done'); });
}
util.inherits(FileWriter, Writer);
extend(FileWriter, {
copyFile: function (source, dest) {
mkdirp.sync(path.dirname(dest));
fs.writeFileSync(dest, fs.readFileSync(source));
},
writeFile: function (file, callback) {
this.delegate.writeFile(file, callback);
},
done: function () {
this.delegate.done();
}
});
module.exports = FileWriter;

View File

@ -0,0 +1,30 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var OPT_PREFIX = " ",
OPT_START = OPT_PREFIX.length,
TEXT_START = 14,
STOP = 80,
wrap = require('wordwrap')(TEXT_START, STOP),
paraWrap = require('wordwrap')(1, STOP);
function formatPara(text) {
return paraWrap(text);
}
function formatOption(option, helpText) {
var formattedText = wrap(helpText);
if (option.length > TEXT_START - OPT_START - 2) {
return OPT_PREFIX + option + '\n' + formattedText;
} else {
return OPT_PREFIX + option + formattedText.substring((OPT_PREFIX + option).length);
}
}
module.exports = {
formatPara: formatPara,
formatOption: formatOption
};

View File

@ -0,0 +1,12 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
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,109 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
function InsertionText(text, consumeBlanks) {
this.text = text;
this.origLength = text.length;
this.offsets = [];
this.consumeBlanks = consumeBlanks;
this.startPos = this.findFirstNonBlank();
this.endPos = this.findLastNonBlank();
}
var WHITE_RE = /[ \f\n\r\t\v\u00A0\u2028\u2029]/;
InsertionText.prototype = {
findFirstNonBlank: function () {
var pos = -1,
text = this.text,
len = text.length,
i;
for (i = 0; i < len; i += 1) {
if (!text.charAt(i).match(WHITE_RE)) {
pos = i;
break;
}
}
return pos;
},
findLastNonBlank: function () {
var text = this.text,
len = text.length,
pos = text.length + 1,
i;
for (i = len - 1; i >= 0; i -= 1) {
if (!text.charAt(i).match(WHITE_RE)) {
pos = i;
break;
}
}
return pos;
},
originalLength: function () {
return this.origLength;
},
insertAt: function (col, str, insertBefore, consumeBlanks) {
consumeBlanks = typeof consumeBlanks === 'undefined' ? this.consumeBlanks : consumeBlanks;
col = col > this.originalLength() ? this.originalLength() : col;
col = col < 0 ? 0 : col;
if (consumeBlanks) {
if (col <= this.startPos) {
col = 0;
}
if (col > this.endPos) {
col = this.origLength;
}
}
var len = str.length,
offset = this.findOffset(col, len, insertBefore),
realPos = col + offset,
text = this.text;
this.text = text.substring(0, realPos) + str + text.substring(realPos);
return this;
},
findOffset: function (pos, len, insertBefore) {
var offsets = this.offsets,
offsetObj,
cumulativeOffset = 0,
i;
for (i = 0; i < offsets.length; i += 1) {
offsetObj = offsets[i];
if (offsetObj.pos < pos || (offsetObj.pos === pos && !insertBefore)) {
cumulativeOffset += offsetObj.len;
}
if (offsetObj.pos >= pos) {
break;
}
}
if (offsetObj && offsetObj.pos === pos) {
offsetObj.len += len;
} else {
offsets.splice(i, 0, { pos: pos, len: len });
}
return cumulativeOffset;
},
wrap: function (startPos, startText, endPos, endText, consumeBlanks) {
this.insertAt(startPos, startText, true, consumeBlanks);
this.insertAt(endPos, endText, false, consumeBlanks);
return this;
},
wrapLine: function (startText, endText) {
this.wrap(0, startText, this.originalLength(), endText);
},
toString: function () {
return this.text;
}
};
module.exports = InsertionText;

View File

@ -0,0 +1,13 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
fs = require('fs'),
pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', '..', 'package.json'), 'utf8'));
module.exports = {
NAME: pkg.name,
VERSION: pkg.version
};

View File

@ -0,0 +1,213 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var path = require('path'),
SEP = path.sep || '/',
utils = require('../object-utils');
function commonArrayPrefix(first, second) {
var len = first.length < second.length ? first.length : second.length,
i,
ret = [];
for (i = 0; i < len; i += 1) {
if (first[i] === second[i]) {
ret.push(first[i]);
} else {
break;
}
}
return ret;
}
function findCommonArrayPrefix(args) {
if (args.length === 0) {
return [];
}
var separated = args.map(function (arg) { return arg.split(SEP); }),
ret = separated.pop();
if (separated.length === 0) {
return ret.slice(0, ret.length - 1);
} else {
return separated.reduce(commonArrayPrefix, ret);
}
}
function Node(fullName, kind, metrics) {
this.name = fullName;
this.fullName = fullName;
this.kind = kind;
this.metrics = metrics || null;
this.parent = null;
this.children = [];
}
Node.prototype = {
displayShortName: function () {
return this.relativeName;
},
fullPath: function () {
return this.fullName;
},
addChild: function (child) {
this.children.push(child);
child.parent = this;
},
toJSON: function () {
return {
name: this.name,
relativeName: this.relativeName,
fullName: this.fullName,
kind: this.kind,
metrics: this.metrics,
parent: this.parent === null ? null : this.parent.name,
children: this.children.map(function (node) { return node.toJSON(); })
};
}
};
function TreeSummary(summaryMap, commonPrefix) {
this.prefix = commonPrefix;
this.convertToTree(summaryMap, commonPrefix);
}
TreeSummary.prototype = {
getNode: function (shortName) {
return this.map[shortName];
},
convertToTree: function (summaryMap, arrayPrefix) {
var nodes = [],
rootPath = arrayPrefix.join(SEP) + SEP,
root = new Node(rootPath, 'dir'),
tmp,
tmpChildren,
seen = {},
filesUnderRoot = false;
seen[rootPath] = root;
Object.keys(summaryMap).forEach(function (key) {
var metrics = summaryMap[key],
node,
parentPath,
parent;
node = new Node(key, 'file', metrics);
seen[key] = node;
nodes.push(node);
parentPath = path.dirname(key) + SEP;
if (parentPath === SEP + SEP || parentPath === '.' + SEP) {
parentPath = SEP + '__root__' + SEP;
}
parent = seen[parentPath];
if (!parent) {
parent = new Node(parentPath, 'dir');
root.addChild(parent);
seen[parentPath] = parent;
}
parent.addChild(node);
if (parent === root) { filesUnderRoot = true; }
});
if (filesUnderRoot && arrayPrefix.length > 0) {
arrayPrefix.pop(); //start at one level above
tmp = root;
tmpChildren = tmp.children;
tmp.children = [];
root = new Node(arrayPrefix.join(SEP) + SEP, 'dir');
root.addChild(tmp);
tmpChildren.forEach(function (child) {
if (child.kind === 'dir') {
root.addChild(child);
} else {
tmp.addChild(child);
}
});
}
this.fixupNodes(root, arrayPrefix.join(SEP) + SEP);
this.calculateMetrics(root);
this.root = root;
this.map = {};
this.indexAndSortTree(root, this.map);
},
fixupNodes: function (node, prefix, parent) {
var that = this;
if (node.name.indexOf(prefix) === 0) {
node.name = node.name.substring(prefix.length);
}
if (node.name.charAt(0) === SEP) {
node.name = node.name.substring(1);
}
if (parent) {
if (parent.name !== '__root__' + SEP) {
node.relativeName = node.name.substring(parent.name.length);
} else {
node.relativeName = node.name;
}
} else {
node.relativeName = node.name.substring(prefix.length);
}
node.children.forEach(function (child) {
that.fixupNodes(child, prefix, node);
});
},
calculateMetrics: function (entry) {
var that = this,
fileChildren;
if (entry.kind !== 'dir') {return; }
entry.children.forEach(function (child) {
that.calculateMetrics(child);
});
entry.metrics = utils.mergeSummaryObjects.apply(
null,
entry.children.map(function (child) { return child.metrics; })
);
// calclulate "java-style" package metrics where there is no hierarchy
// across packages
fileChildren = entry.children.filter(function (n) { return n.kind !== 'dir'; });
if (fileChildren.length > 0) {
entry.packageMetrics = utils.mergeSummaryObjects.apply(
null,
fileChildren.map(function (child) { return child.metrics; })
);
} else {
entry.packageMetrics = null;
}
},
indexAndSortTree: function (node, map) {
var that = this;
map[node.name] = node;
node.children.sort(function (a, b) {
a = a.relativeName;
b = b.relativeName;
return a < b ? -1 : a > b ? 1 : 0;
});
node.children.forEach(function (child) {
that.indexAndSortTree(child, map);
});
},
toJSON: function () {
return {
prefix: this.prefix,
root: this.root.toJSON()
};
}
};
function TreeSummarizer() {
this.summaryMap = {};
}
TreeSummarizer.prototype = {
addFileCoverageSummary: function (filePath, metrics) {
this.summaryMap[filePath] = metrics;
},
getTreeSummary: function () {
var commonArrayPrefix = findCommonArrayPrefix(Object.keys(this.summaryMap));
return new TreeSummary(this.summaryMap, commonArrayPrefix);
}
};
module.exports = TreeSummarizer;

View File

@ -0,0 +1,92 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var util = require('util'),
EventEmitter = require('events').EventEmitter;
function extend(cons, proto) {
Object.keys(proto).forEach(function (k) {
cons.prototype[k] = proto[k];
});
}
/**
* abstract interfaces for writing content
* @class ContentWriter
* @module io
* @main io
* @constructor
*/
//abstract interface for writing content
function ContentWriter() {
}
ContentWriter.prototype = {
/**
* writes the specified string as-is
* @method write
* @param {String} str the string to write
*/
write: /* istanbul ignore next: abstract method */ function (/* str */) {
throw new Error('write: must be overridden');
},
/**
* writes the specified string with a newline at the end
* @method println
* @param {String} str the string to write
*/
println: function (str) { this.write(str + '\n'); }
};
/**
* abstract interface for writing files and assets. The caller is expected to
* call `done` on the writer after it has finished writing all the required
* files. The writer is an event-emitter that emits a `done` event when `done`
* is called on it *and* all files have successfully been written.
*
* @class Writer
* @constructor
*/
function Writer() {
EventEmitter.call(this);
}
util.inherits(Writer, EventEmitter);
extend(Writer, {
/**
* allows writing content to a file using a callback that is passed a content writer
* @method writeFile
* @param {String} file the name of the file to write
* @param {Function} callback the callback that is called as `callback(contentWriter)`
*/
writeFile: /* istanbul ignore next: abstract method */ function (/* file, callback */) {
throw new Error('writeFile: must be overridden');
},
/**
* copies a file from source to destination
* @method copyFile
* @param {String} source the file to copy, found on the file system
* @param {String} dest the destination path
*/
copyFile: /* istanbul ignore next: abstract method */ function (/* source, dest */) {
throw new Error('copyFile: must be overridden');
},
/**
* marker method to indicate that the caller is done with this writer object
* The writer is expected to emit a `done` event only after this method is called
* and it is truly done.
* @method done
*/
done: /* istanbul ignore next: abstract method */ function () {
throw new Error('done: must be overridden');
}
});
module.exports = {
Writer: Writer,
ContentWriter: ContentWriter
};

View File

@ -0,0 +1,49 @@
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
//EXPERIMENTAL code: do not rely on this in anyway until the docs say it is allowed
var path = require('path'),
yuiRegexp = /yui-nodejs\.js$/;
module.exports = function (matchFn, transformFn, verbose) {
return function (file) {
if (!file.match(yuiRegexp)) {
return;
}
var YMain = require(file),
YUI,
loaderFn,
origGet;
if (YMain.YUI) {
YUI = YMain.YUI;
loaderFn = YUI.Env && YUI.Env.mods && YUI.Env.mods['loader-base'] ? YUI.Env.mods['loader-base'].fn : null;
if (!loaderFn) { return; }
if (verbose) { console.log('Applying YUI load post-hook'); }
YUI.Env.mods['loader-base'].fn = function (Y) {
loaderFn.call(null, Y);
origGet = Y.Get._exec;
Y.Get._exec = function (data, url, cb) {
if (matchFn(url) || matchFn(path.resolve(url))) { //allow for relative paths as well
if (verbose) {
console.log('Transforming [' + url + ']');
}
try {
data = transformFn(data, url);
} catch (ex) {
console.error('Error transforming: ' + url + ' return original code');
console.error(ex.message || ex);
if (ex.stack) { console.error(ex.stack); }
}
}
return origGet.call(Y, data, url, cb);
};
return Y;
};
}
};
};

View File

@ -0,0 +1,19 @@
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.
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 <COPYRIGHT HOLDER> 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,27 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
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 names of the Mozilla Foundation nor the names of project
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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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,116 @@
## Escodegen
[![npm version](https://badge.fury.io/js/escodegen.svg)](http://badge.fury.io/js/escodegen)
[![Build Status](https://secure.travis-ci.org/estools/escodegen.svg)](http://travis-ci.org/estools/escodegen)
[![Dependency Status](https://david-dm.org/estools/escodegen.svg)](https://david-dm.org/estools/escodegen)
[![devDependency Status](https://david-dm.org/estools/escodegen/dev-status.svg)](https://david-dm.org/estools/escodegen#info=devDependencies)
Escodegen ([escodegen](http://github.com/estools/escodegen)) is an
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
(also popularly known as [JavaScript](http://en.wikipedia.org/wiki/JavaScript))
code generator from [Mozilla's Parser API](https://developer.mozilla.org/en/SpiderMonkey/Parser_API)
AST. See the [online generator](https://estools.github.io/escodegen/demo/index.html)
for a demo.
### Install
Escodegen can be used in a web browser:
<script src="escodegen.browser.js"></script>
escodegen.browser.js can be found in tagged revisions on GitHub.
Or in a Node.js application via npm:
npm install escodegen
### Usage
A simple example: the program
escodegen.generate({
type: 'BinaryExpression',
operator: '+',
left: { type: 'Literal', value: 40 },
right: { type: 'Literal', value: 2 }
});
produces the string `'40 + 2'`.
See the [API page](https://github.com/estools/escodegen/wiki/API) for
options. To run the tests, execute `npm test` in the root directory.
### Building browser bundle / minified browser bundle
At first, execute `npm install` to install the all dev dependencies.
After that,
npm run-script build
will generate `escodegen.browser.js`, which can be used in browser environments.
And,
npm run-script build-min
will generate the minified file `escodegen.browser.min.js`.
### License
#### Escodegen
Copyright (C) 2012 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
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.
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 <COPYRIGHT HOLDER> 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.
#### source-map
SourceNodeMocks has a limited interface of mozilla/source-map SourceNode implementations.
Copyright (c) 2009-2011, Mozilla Foundation and contributors
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 names of the Mozilla Foundation nor the names of project
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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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,77 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true node:true */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
esprima = require('esprima'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: escodegen [options] file...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options,
esprimaOptions = {
raw: true,
tokens: true,
range: true,
comment: true
};
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'));
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8'),
syntax = esprima.parse(content, esprimaOptions);
if (options.comment) {
escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
}
console.log(escodegen.generate(syntax, options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,64 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true node:true */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: esgenerate [options] file.json ...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options;
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'))
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8');
console.log(escodegen.generate(JSON.parse(content), options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,91 @@
{
"_from": "escodegen@1.8.x",
"_id": "escodegen@1.8.1",
"_inBundle": false,
"_integrity": "sha1-WltTr0aTEQvrsIZ6o0MN07cKEBg=",
"_location": "/istanbul/escodegen",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "escodegen@1.8.x",
"name": "escodegen",
"escapedName": "escodegen",
"rawSpec": "1.8.x",
"saveSpec": null,
"fetchSpec": "1.8.x"
},
"_requiredBy": [
"/istanbul"
],
"_resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.8.1.tgz",
"_shasum": "5a5b53af4693110bebb0867aa3430dd3b70a1018",
"_spec": "escodegen@1.8.x",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul",
"bin": {
"esgenerate": "./bin/esgenerate.js",
"escodegen": "./bin/escodegen.js"
},
"bugs": {
"url": "https://github.com/estools/escodegen/issues"
},
"bundleDependencies": false,
"dependencies": {
"esprima": "^2.7.1",
"estraverse": "^1.9.1",
"esutils": "^2.0.2",
"optionator": "^0.8.1",
"source-map": "~0.2.0"
},
"deprecated": false,
"description": "ECMAScript code generator",
"devDependencies": {
"acorn": "^2.7.0",
"bluebird": "^2.3.11",
"bower-registry-client": "^0.2.1",
"chai": "^1.10.0",
"commonjs-everywhere": "^0.9.7",
"gulp": "^3.8.10",
"gulp-eslint": "^0.2.0",
"gulp-mocha": "^2.0.0",
"semver": "^5.1.0"
},
"engines": {
"node": ">=0.12.0"
},
"files": [
"LICENSE.BSD",
"LICENSE.source-map",
"README.md",
"bin",
"escodegen.js",
"package.json"
],
"homepage": "http://github.com/estools/escodegen",
"license": "BSD-2-Clause",
"main": "escodegen.js",
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"url": "http://github.com/Constellation"
}
],
"name": "escodegen",
"optionalDependencies": {
"source-map": "~0.2.0"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/estools/escodegen.git"
},
"scripts": {
"build": "cjsify -a path: tools/entry-point.js > escodegen.browser.js",
"build-min": "cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js",
"lint": "gulp lint",
"release": "node tools/release.js",
"test": "gulp travis",
"unit-test": "gulp test"
},
"version": "1.8.1"
}

View File

@ -0,0 +1,174 @@
2016-08-23: Version 2.7.3
* Fix tokenizer confusion with a comment (issue 1493, 1516)
2016-02-02: Version 2.7.2
* Fix out-of-bound error location in an invalid string literal (issue 1457)
* Fix shorthand object destructuring defaults in variable declarations (issue 1459)
2015-12-10: Version 2.7.1
* Do not allow trailing comma in a variable declaration (issue 1360)
* Fix assignment to `let` in non-strict mode (issue 1376)
* Fix missing delegate property in YieldExpression (issue 1407)
2015-10-22: Version 2.7.0
* Fix the handling of semicolon in a break statement (issue 1044)
* Run the test suite with major web browsers (issue 1259, 1317)
* Allow `let` as an identifier in non-strict mode (issue 1289)
* Attach orphaned comments as `innerComments` (issue 1328)
* Add the support for token delegator (issue 1332)
2015-09-01: Version 2.6.0
* Properly allow or prohibit `let` in a binding identifier/pattern (issue 1048, 1098)
* Add sourceType field for Program node (issue 1159)
* Ensure that strict mode reserved word binding throw an error (issue 1171)
* Run the test suite with Node.js and IE 11 on Windows (issue 1294)
* Allow binding pattern with no initializer in a for statement (issue 1301)
2015-07-31: Version 2.5.0
* Run the test suite in a browser environment (issue 1004)
* Ensure a comma between imported default binding and named imports (issue 1046)
* Distinguish `yield` as a keyword vs an identifier (issue 1186)
* Support ES6 meta property `new.target` (issue 1203)
* Fix the syntax node for yield with expression (issue 1223)
* Fix the check of duplicated proto in property names (issue 1225)
* Fix ES6 Unicode escape in identifier name (issue 1229)
* Support ES6 IdentifierStart and IdentifierPart (issue 1232)
* Treat await as a reserved word when parsing as a module (issue 1234)
* Recognize identifier characters from Unicode SMP (issue 1244)
* Ensure that export and import can be followed by a comma (issue 1250)
* Fix yield operator precedence (issue 1262)
2015-07-01: Version 2.4.1
* Fix some cases of comment attachment (issue 1071, 1175)
* Fix the handling of destructuring in function arguments (issue 1193)
* Fix invalid ranges in assignment expression (issue 1201)
2015-06-26: Version 2.4.0
* Support ES6 for-of iteration (issue 1047)
* Support ES6 spread arguments (issue 1169)
* Minimize npm payload (issue 1191)
2015-06-16: Version 2.3.0
* Support ES6 generator (issue 1033)
* Improve parsing of regular expressions with `u` flag (issue 1179)
2015-04-17: Version 2.2.0
* Support ES6 import and export declarations (issue 1000)
* Fix line terminator before arrow not recognized as error (issue 1009)
* Support ES6 destructuring (issue 1045)
* Support ES6 template literal (issue 1074)
* Fix the handling of invalid/incomplete string escape sequences (issue 1106)
* Fix ES3 static member access restriction (issue 1120)
* Support for `super` in ES6 class (issue 1147)
2015-03-09: Version 2.1.0
* Support ES6 class (issue 1001)
* Support ES6 rest parameter (issue 1011)
* Expand the location of property getter, setter, and methods (issue 1029)
* Enable TryStatement transition to a single handler (issue 1031)
* Support ES6 computed property name (issue 1037)
* Tolerate unclosed block comment (issue 1041)
* Support ES6 lexical declaration (issue 1065)
2015-02-06: Version 2.0.0
* Support ES6 arrow function (issue 517)
* Support ES6 Unicode code point escape (issue 521)
* Improve the speed and accuracy of comment attachment (issue 522)
* Support ES6 default parameter (issue 519)
* Support ES6 regular expression flags (issue 557)
* Fix scanning of implicit octal literals (issue 565)
* Fix the handling of automatic semicolon insertion (issue 574)
* Support ES6 method definition (issue 620)
* Support ES6 octal integer literal (issue 621)
* Support ES6 binary integer literal (issue 622)
* Support ES6 object literal property value shorthand (issue 624)
2015-03-03: Version 1.2.5
* Fix scanning of implicit octal literals (issue 565)
2015-02-05: Version 1.2.4
* Fix parsing of LeftHandSideExpression in ForInStatement (issue 560)
* Fix the handling of automatic semicolon insertion (issue 574)
2015-01-18: Version 1.2.3
* Fix division by this (issue 616)
2014-05-18: Version 1.2.2
* Fix duplicated tokens when collecting comments (issue 537)
2014-05-04: Version 1.2.1
* Ensure that Program node may still have leading comments (issue 536)
2014-04-29: Version 1.2.0
* Fix semicolon handling for expression statement (issue 462, 533)
* Disallow escaped characters in regular expression flags (issue 503)
* Performance improvement for location tracking (issue 520)
* Improve the speed of comment attachment (issue 522)
2014-03-26: Version 1.1.1
* Fix token handling of forward slash after an array literal (issue 512)
2014-03-23: Version 1.1.0
* Optionally attach comments to the owning syntax nodes (issue 197)
* Simplify binary parsing with stack-based shift reduce (issue 352)
* Always include the raw source of literals (issue 376)
* Add optional input source information (issue 386)
* Tokenizer API for pure lexical scanning (issue 398)
* Improve the web site and its online demos (issue 337, 400, 404)
* Performance improvement for location tracking (issue 417, 424)
* Support HTML comment syntax (issue 451)
* Drop support for legacy browsers (issue 474)
2013-08-27: Version 1.0.4
* Minimize the payload for packages (issue 362)
* Fix missing cases on an empty switch statement (issue 436)
* Support escaped ] in regexp literal character classes (issue 442)
* Tolerate invalid left-hand side expression (issue 130)
2013-05-17: Version 1.0.3
* Variable declaration needs at least one declarator (issue 391)
* Fix benchmark's variance unit conversion (issue 397)
* IE < 9: \v should be treated as vertical tab (issue 405)
* Unary expressions should always have prefix: true (issue 418)
* Catch clause should only accept an identifier (issue 423)
* Tolerate setters without parameter (issue 426)
2012-11-02: Version 1.0.2
Improvement:
* Fix esvalidate JUnit output upon a syntax error (issue 374)
2012-10-28: Version 1.0.1
Improvements:
* esvalidate understands shebang in a Unix shell script (issue 361)
* esvalidate treats fatal parsing failure as an error (issue 361)
* Reduce Node.js package via .npmignore (issue 362)
2012-10-22: Version 1.0.0
Initial release.

View File

@ -0,0 +1,21 @@
Copyright (c) jQuery Foundation, Inc. and Contributors, 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.
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 <COPYRIGHT HOLDER> 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,27 @@
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima)
[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima)
[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima)
[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima)
**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance,
standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
parser written in ECMAScript (also popularly known as
[JavaScript](https://en.wikipedia.org/wiki/JavaScript)).
Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat),
with the help of [many contributors](https://github.com/jquery/esprima/contributors).
### Features
- Full support for ECMAScript 6 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm))
- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/spec.md) as standardized by [ESTree project](https://github.com/estree/estree)
- Optional tracking of syntax node location (index-based and line-column)
- [Heavily tested](http://esprima.org/test/ci.html) (~1250 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima))
Esprima serves as a **building block** for some JavaScript
language tools, from [code instrumentation](http://esprima.org/demo/functiontrace.html)
to [editor autocompletion](http://esprima.org/demo/autocomplete.html).
Esprima runs on many popular web browsers, as well as other ECMAScript platforms such as
[Rhino](http://www.mozilla.org/rhino), [Nashorn](http://openjdk.java.net/projects/nashorn/), and [Node.js](https://npmjs.org/package/esprima).
For more information, check the web site [esprima.org](http://esprima.org).

View File

@ -0,0 +1,126 @@
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, 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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, content, options, syntax;
if (typeof require === 'function') {
fs = require('fs');
esprima = require('esprima');
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esparse.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esparse [options] file.js');
console.log();
console.log('Available options:');
console.log();
console.log(' --comment Gather all line and block comments in an array');
console.log(' --loc Include line-column location info for each syntax node');
console.log(' --range Include index-based range for each syntax node');
console.log(' --raw Display the raw value of literals');
console.log(' --tokens List all tokens in an array');
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)');
console.log(' -v, --version Shows program version');
console.log();
process.exit(1);
}
if (process.argv.length <= 2) {
showUsage();
}
options = {};
process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry === '--comment') {
options.comment = true;
} else if (entry === '--loc') {
options.loc = true;
} else if (entry === '--range') {
options.range = true;
} else if (entry === '--raw') {
options.raw = true;
} else if (entry === '--tokens') {
options.tokens = true;
} else if (entry === '--tolerant') {
options.tolerant = true;
} else if (entry.slice(0, 2) === '--') {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
} else if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
}
});
if (typeof fname !== 'string') {
console.log('Error: no input file.');
process.exit(1);
}
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
function adjustRegexLiteral(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
try {
content = fs.readFileSync(fname, 'utf-8');
syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4));
} catch (e) {
console.log('Error: ' + e.message);
process.exit(1);
}

View File

@ -0,0 +1,199 @@
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, 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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */
var fs, system, esprima, options, fnames, count;
if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files
if (typeof phantom === 'object') {
fs = require('fs');
system = require('system');
esprima = require('./esprima');
} else if (typeof require === 'function') {
fs = require('fs');
esprima = require('esprima');
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
}
// Shims to Node.js objects when running under PhantomJS 1.7+.
if (typeof phantom === 'object') {
fs.readFileSync = fs.read;
process = {
argv: [].slice.call(system.args),
exit: phantom.exit
};
process.argv.unshift('phantomjs');
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esvalidate [options] file.js');
console.log();
console.log('Available options:');
console.log();
console.log(' --format=type Set the report format, plain (default) or junit');
console.log(' -v, --version Print program version');
console.log();
process.exit(1);
}
if (process.argv.length <= 2) {
showUsage();
}
options = {
format: 'plain'
};
fnames = [];
process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry.slice(0, 9) === '--format=') {
options.format = entry.slice(9);
if (options.format !== 'plain' && options.format !== 'junit') {
console.log('Error: unknown report format ' + options.format + '.');
process.exit(1);
}
} else if (entry.slice(0, 2) === '--') {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
} else {
fnames.push(entry);
}
});
if (fnames.length === 0) {
console.log('Error: no input file.');
process.exit(1);
}
if (options.format === 'junit') {
console.log('<?xml version="1.0" encoding="UTF-8"?>');
console.log('<testsuites>');
}
count = 0;
fnames.forEach(function (fname) {
var content, timestamp, syntax, name;
try {
content = fs.readFileSync(fname, 'utf-8');
if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length);
}
timestamp = Date.now();
syntax = esprima.parse(content, { tolerant: true });
if (options.format === 'junit') {
name = fname;
if (name.lastIndexOf('/') >= 0) {
name = name.slice(name.lastIndexOf('/') + 1);
}
console.log('<testsuite name="' + fname + '" errors="0" ' +
' failures="' + syntax.errors.length + '" ' +
' tests="' + syntax.errors.length + '" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) +
'">');
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' +
' time="0">');
console.log(' <error type="SyntaxError" message="' + error.message + '">' +
error.message + '(' + name + ':' + error.lineNumber + ')' +
'</error>');
console.log(' </testcase>');
});
console.log('</testsuite>');
} else if (options.format === 'plain') {
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
msg = fname + ':' + error.lineNumber + ': ' + msg;
console.log(msg);
++count;
});
}
} catch (e) {
++count;
if (options.format === 'junit') {
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">');
console.log(' <testcase name="' + e.message + '" ' + ' time="0">');
console.log(' <error type="ParseError" message="' + e.message + '">' +
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') +
')</error>');
console.log(' </testcase>');
console.log('</testsuite>');
} else {
console.log('Error: ' + e.message);
}
}
});
if (options.format === 'junit') {
console.log('</testsuites>');
}
if (count > 0) {
process.exit(1);
}
if (count === 0 && typeof phantom === 'object') {
process.exit(0);
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,125 @@
{
"_from": "esprima@2.7.x",
"_id": "esprima@2.7.3",
"_inBundle": false,
"_integrity": "sha1-luO3DVd59q1JzQMmc9HDEnZ7pYE=",
"_location": "/istanbul/esprima",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "esprima@2.7.x",
"name": "esprima",
"escapedName": "esprima",
"rawSpec": "2.7.x",
"saveSpec": null,
"fetchSpec": "2.7.x"
},
"_requiredBy": [
"/istanbul",
"/istanbul/escodegen"
],
"_resolved": "https://registry.npmjs.org/esprima/-/esprima-2.7.3.tgz",
"_shasum": "96e3b70d5779f6ad49cd032673d1c312767ba581",
"_spec": "esprima@2.7.x",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul",
"author": {
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com"
},
"bin": {
"esparse": "./bin/esparse.js",
"esvalidate": "./bin/esvalidate.js"
},
"bugs": {
"url": "https://github.com/jquery/esprima/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"devDependencies": {
"codecov.io": "~0.1.6",
"escomplex-js": "1.2.0",
"eslint": "~1.7.2",
"everything.js": "~1.0.3",
"glob": "^5.0.15",
"istanbul": "~0.4.0",
"jscs": "~2.3.5",
"json-diff": "~0.3.1",
"karma": "^0.13.11",
"karma-chrome-launcher": "^0.2.1",
"karma-detect-browsers": "^2.0.2",
"karma-firefox-launcher": "^0.1.6",
"karma-ie-launcher": "^0.2.0",
"karma-mocha": "^0.2.0",
"karma-safari-launcher": "^0.1.1",
"karma-sauce-launcher": "^0.2.14",
"lodash": "^3.10.0",
"mocha": "^2.3.3",
"node-tick-processor": "~0.0.2",
"regenerate": "~1.2.1",
"temp": "~0.8.3",
"unicode-7.0.0": "~0.1.5"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"bin",
"unit-tests.js",
"esprima.js"
],
"homepage": "http://esprima.org",
"keywords": [
"ast",
"ecmascript",
"javascript",
"parser",
"syntax"
],
"license": "BSD-2-Clause",
"main": "esprima.js",
"maintainers": [
{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"url": "http://ariya.ofilabs.com"
}
],
"name": "esprima",
"repository": {
"type": "git",
"url": "git+https://github.com/jquery/esprima.git"
},
"scripts": {
"all-tests": "npm run generate-fixtures && npm run unit-tests && npm run grammar-tests && npm run regression-tests",
"analyze-coverage": "istanbul cover test/unit-tests.js",
"appveyor": "npm run all-tests && npm run browser-tests && npm run dynamic-analysis",
"benchmark": "node test/benchmarks.js",
"benchmark-quick": "node test/benchmarks.js quick",
"browser-tests": "npm run generate-fixtures && cd test && karma start --single-run",
"check-coverage": "istanbul check-coverage --statement 100 --branch 100 --function 100",
"check-version": "node test/check-version.js",
"circleci": "npm test && npm run codecov && npm run downstream",
"codecov": "istanbul report cobertura && codecov < ./coverage/cobertura-coverage.xml",
"complexity": "node test/check-complexity.js",
"downstream": "node test/downstream.js",
"droneio": "npm test && npm run saucelabs-evergreen && npm run saucelabs-ie && npm run saucelabs-safari",
"dynamic-analysis": "npm run analyze-coverage && npm run check-coverage",
"eslint": "node node_modules/eslint/bin/eslint.js -c .lintrc esprima.js",
"generate-fixtures": "node tools/generate-fixtures.js",
"generate-regex": "node tools/generate-identifier-regex.js",
"grammar-tests": "node test/grammar-tests.js",
"jscs": "jscs -p crockford esprima.js && jscs -p crockford test/*.js",
"profile": "node --prof test/profile.js && mv isolate*.log v8.log && node-tick-processor",
"regression-tests": "node test/regression-tests.js",
"saucelabs-evergreen": "cd test && karma start saucelabs-evergreen.conf.js",
"saucelabs-ie": "cd test && karma start saucelabs-ie.conf.js",
"saucelabs-safari": "cd test && karma start saucelabs-safari.conf.js",
"static-analysis": "npm run check-version && npm run jscs && npm run eslint && npm run complexity",
"test": "npm run all-tests && npm run static-analysis && npm run dynamic-analysis",
"travis": "npm test",
"unit-tests": "node test/unit-tests.js"
},
"version": "2.7.3"
}

View File

@ -0,0 +1,25 @@
(MIT License)
Copyright (c) 2013 [Ramesh Nair](http://www.hiddentao.com/)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,104 @@
# fast-levenshtein - Levenshtein algorithm in Javascript
[![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein)
[![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein)
[![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein)
[![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao)
An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support.
## Features
* Works in node.js and in the browser.
* Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)).
* Locale-sensitive string comparisions if needed.
* Comprehensive test suite and performance benchmark.
* Small: <1 KB minified and gzipped
## Installation
### node.js
Install using [npm](http://npmjs.org/):
```bash
$ npm install fast-levenshtein
```
### Browser
Using bower:
```bash
$ bower install fast-levenshtein
```
If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object.
## Examples
**Default usage**
```javascript
var levenshtein = require('fast-levenshtein');
var distance = levenshtein.get('back', 'book'); // 2
var distance = levenshtein.get('我愛你', '我叫你'); // 1
```
**Locale-sensitive string comparisons**
It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons:
```javascript
var levenshtein = require('fast-levenshtein');
levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true});
// 1
```
## Building and Testing
To build the code and run the tests:
```bash
$ npm install -g grunt-cli
$ npm install
$ npm run build
```
## Performance
_Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._
Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM):
```bash
Running suite Implementation comparison [benchmark/speed.js]...
>> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled)
>> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled)
>> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled)
>> natural x 255 ops/sec ±0.76% (88 runs sampled)
>> levenshtein x 180 ops/sec ±3.55% (86 runs sampled)
>> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled)
Benchmark done.
Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component
```
You can run this benchmark yourself by doing:
```bash
$ npm install
$ npm run build
$ npm run benchmark
```
## Contributing
If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes.
See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details.
## License
MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md)

View File

@ -0,0 +1,136 @@
(function() {
'use strict';
var collator;
try {
collator = (typeof Intl !== "undefined" && typeof Intl.Collator !== "undefined") ? Intl.Collator("generic", { sensitivity: "base" }) : null;
} catch (err){
console.log("Collator could not be initialized and wouldn't be used");
}
// arrays to re-use
var prevRow = [],
str2Char = [];
/**
* Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
*/
var Levenshtein = {
/**
* Calculate levenshtein distance of the two strings.
*
* @param str1 String the first string.
* @param str2 String the second string.
* @param [options] Additional options.
* @param [options.useCollator] Use `Intl.Collator` for locale-sensitive string comparison.
* @return Integer the levenshtein distance (0 and above).
*/
get: function(str1, str2, options) {
var useCollator = (options && collator && options.useCollator);
var str1Len = str1.length,
str2Len = str2.length;
// base cases
if (str1Len === 0) return str2Len;
if (str2Len === 0) return str1Len;
// two rows
var curCol, nextCol, i, j, tmp;
// initialise previous row
for (i=0; i<str2Len; ++i) {
prevRow[i] = i;
str2Char[i] = str2.charCodeAt(i);
}
prevRow[str2Len] = str2Len;
var strCmp;
if (useCollator) {
// calculate current row distance from previous row using collator
for (i = 0; i < str1Len; ++i) {
nextCol = i + 1;
for (j = 0; j < str2Len; ++j) {
curCol = nextCol;
// substution
strCmp = 0 === collator.compare(str1.charAt(i), String.fromCharCode(str2Char[j]));
nextCol = prevRow[j] + (strCmp ? 0 : 1);
// insertion
tmp = curCol + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// deletion
tmp = prevRow[j + 1] + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// copy current col value into previous (in preparation for next iteration)
prevRow[j] = curCol;
}
// copy last col value into previous (in preparation for next iteration)
prevRow[j] = nextCol;
}
}
else {
// calculate current row distance from previous row without collator
for (i = 0; i < str1Len; ++i) {
nextCol = i + 1;
for (j = 0; j < str2Len; ++j) {
curCol = nextCol;
// substution
strCmp = str1.charCodeAt(i) === str2Char[j];
nextCol = prevRow[j] + (strCmp ? 0 : 1);
// insertion
tmp = curCol + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// deletion
tmp = prevRow[j + 1] + 1;
if (nextCol > tmp) {
nextCol = tmp;
}
// copy current col value into previous (in preparation for next iteration)
prevRow[j] = curCol;
}
// copy last col value into previous (in preparation for next iteration)
prevRow[j] = nextCol;
}
}
return nextCol;
}
};
// amd
if (typeof define !== "undefined" && define !== null && define.amd) {
define(function() {
return Levenshtein;
});
}
// commonjs
else if (typeof module !== "undefined" && module !== null && typeof exports !== "undefined" && module.exports === exports) {
module.exports = Levenshtein;
}
// web worker
else if (typeof self !== "undefined" && typeof self.postMessage === 'function' && typeof self.importScripts === 'function') {
self.Levenshtein = Levenshtein;
}
// browser main thread
else if (typeof window !== "undefined" && window !== null) {
window.Levenshtein = Levenshtein;
}
}());

View File

@ -0,0 +1,72 @@
{
"_from": "fast-levenshtein@~2.0.4",
"_id": "fast-levenshtein@2.0.6",
"_inBundle": false,
"_integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=",
"_location": "/istanbul/fast-levenshtein",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "fast-levenshtein@~2.0.4",
"name": "fast-levenshtein",
"escapedName": "fast-levenshtein",
"rawSpec": "~2.0.4",
"saveSpec": null,
"fetchSpec": "~2.0.4"
},
"_requiredBy": [
"/istanbul/optionator"
],
"_resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
"_shasum": "3d8a5c66883a16a30ca8643e851f19baa7797917",
"_spec": "fast-levenshtein@~2.0.4",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul/node_modules/optionator",
"author": {
"name": "Ramesh Nair",
"email": "ram@hiddentao.com",
"url": "http://www.hiddentao.com/"
},
"bugs": {
"url": "https://github.com/hiddentao/fast-levenshtein/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Efficient implementation of Levenshtein algorithm with locale-specific collator support.",
"devDependencies": {
"chai": "~1.5.0",
"grunt": "~0.4.1",
"grunt-benchmark": "~0.2.0",
"grunt-cli": "^1.2.0",
"grunt-contrib-jshint": "~0.4.3",
"grunt-contrib-uglify": "~0.2.0",
"grunt-mocha-test": "~0.2.2",
"grunt-npm-install": "~0.1.0",
"load-grunt-tasks": "~0.6.0",
"lodash": "^4.0.1",
"mocha": "~1.9.0"
},
"files": [
"levenshtein.js"
],
"homepage": "https://github.com/hiddentao/fast-levenshtein#readme",
"keywords": [
"levenshtein",
"distance",
"string"
],
"license": "MIT",
"main": "levenshtein.js",
"name": "fast-levenshtein",
"repository": {
"type": "git",
"url": "git+https://github.com/hiddentao/fast-levenshtein.git"
},
"scripts": {
"benchmark": "grunt benchmark",
"build": "grunt build",
"prepublish": "npm run build",
"test": "mocha"
},
"version": "2.0.6"
}

View File

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -0,0 +1,377 @@
[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Dependency Status](https://david-dm.org/isaacs/node-glob.svg)](https://david-dm.org/isaacs/node-glob) [![devDependency Status](https://david-dm.org/isaacs/node-glob/dev-status.svg)](https://david-dm.org/isaacs/node-glob#info=devDependencies) [![optionalDependency Status](https://david-dm.org/isaacs/node-glob/optional-status.svg)](https://david-dm.org/isaacs/node-glob#info=optionalDependencies)
# Glob
Match files using the patterns the shell uses, like stars and stuff.
This is a glob implementation in JavaScript. It uses the `minimatch`
library to do its matching.
![](oh-my-glob.gif)
## Usage
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
## Glob Primer
"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.
Before parsing the path part patterns, braced sections are expanded
into a set. Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within. Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
The following characters have special magic meaning when used in a
path portion:
* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
If the first character of the range is `!` or `^` then it matches
any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
provided
* `**` If a "globstar" is alone in a path portion, then it matches
zero or more directories and subdirectories searching for matches.
It does not crawl symlinked directories.
### Dots
If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.
You can make glob treat dots as normal characters by setting
`dot:true` in the options.
### Basename Matching
If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.
### Negation
The intent for negation would be for a pattern starting with `!` to
match everything that *doesn't* match the supplied pattern. However,
the implementation is weird, and for the time being, this should be
avoided. The behavior is deprecated in version 5, and will be removed
entirely in version 6.
### Empty Sets
If no matching files are found, then an empty array is returned. This
differs from the shell, where the pattern itself is returned. For
example:
$ echo a*s*d*f
a*s*d*f
To get the bash-style behavior, set the `nonull:true` in the options.
### See Also:
* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)
## glob.hasMagic(pattern, [options])
Returns `true` if there are any special characters in the pattern, and
`false` otherwise.
Note that the options affect the results. If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.
## glob(pattern, [options], cb)
* `pattern` {String} Pattern to be matched
* `options` {Object}
* `cb` {Function}
* `err` {Error | null}
* `matches` {Array<String>} filenames found matching the pattern
Perform an asynchronous glob search.
## glob.sync(pattern, [options])
* `pattern` {String} Pattern to be matched
* `options` {Object}
* return: {Array<String>} filenames found matching the pattern
Perform a synchronous glob search.
## Class: glob.Glob
Create a Glob object by instantiating the `glob.Glob` class.
```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```
It's an EventEmitter, and starts walking the filesystem to find matches
immediately.
### new glob.Glob(pattern, [options], [cb])
* `pattern` {String} pattern to search for
* `options` {Object}
* `cb` {Function} Called when an error occurs, or matches are found
* `err` {Error | null}
* `matches` {Array<String>} filenames found matching the pattern
Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.
### Properties
* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`. There
is no way at this time to continue a glob search after aborting, but
you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object. Each field has the following possible
values:
* `false` - Path does not exist
* `true` - Path exists
* `'DIR'` - Path exists, and is not a directory
* `'FILE'` - Path exists, and is a directory
* `[file, entries, ...]` - Path exists, is a directory, and the
array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
to minimize unnecessary syscalls. It is stored on the instantiated
Glob object, and may be re-used.
### Events
* `end` When the matching is finished, this is emitted with all the
matches found. If the `nonull` option is set, and no match was found,
then the `matches` list contains the original pattern. The matches
are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the matched.
* `error` Emitted when an unexpected error is encountered, or whenever
any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.
### Methods
* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever
### Options
All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior. Also, some have been added,
or have glob-specific ramifications.
All options are false by default, unless otherwise noted.
All options are added to the Glob object, as well.
If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls. At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.
* `cwd` The current working directory in which to search. Defaults
to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
Note that an explicit dot in a portion of the pattern will always
match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
"mounted" onto the root setting, so that a valid filesystem path is
returned. Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches. Note that this
requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results. This reduces performance
somewhat, and is completely unnecessary, unless `readdir` is presumed
to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
read a directory, a warning will be printed to stderr. Set the
`silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
read a directory, the process will just continue on in search of
other matches. Set the `strict` option to raise an error in these
cases.
* `cache` See `cache` property above. Pass in a previously generated
cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
unnecessary stat calls. While it should not normally be necessary
to set this, you may pass the statCache from one glob() call to the
options object of another, if you know that the filesystem will not
change between calls. (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links. You may pass in a
previously generated `symlinks` object to save `lstat` calls when
resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
same file showing up multiple times in the result set. By default,
this implementation prevents duplicates in the result set. Set this
flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
containing the pattern itself. This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match. Note: on
case-insensitive filesystems, non-magic patterns will match by
default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
contain any slash characters. That is, `*.js` would be treated as
equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files. (Note: to match
*only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of patterns to exclude matches.
* `follow` Follow symlinked directories when expanding `**` patterns.
Note that this can result in a lot of duplicate references in the
presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
In the case of a symlink that cannot be resolved, the full absolute
path to the matched entry is returned (though it will usually be a
broken symlink)
* `nonegate` Suppress deprecated `negate` behavior. (See below.)
Default=true
* `nocomment` Suppress deprecated `comment` behavior. (See below.)
Default=true
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern. This prevents infinite loops and duplicates and the like.
If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
### Comments and Negation
**Note**: In version 5 of this module, negation and comments are
**disabled** by default. You can explicitly set `nonegate:false` or
`nocomment:false` to re-enable them. They are going away entirely in
version 6.
The intent for negation would be for a pattern starting with `!` to
match everything that *doesn't* match the supplied pattern. However,
the implementation is weird. It is better to use the `ignore` option
to set a pattern or set of patterns to exclude from matches. If you
want the "everything except *x*" type of behavior, you can use `**` as
the main pattern, and set an `ignore` for the things to exclude.
The comments feature is added in minimatch, primarily to more easily
support use cases like ignore files, where a `#` at the start of a
line makes the pattern "empty". However, in the context of a
straightforward filesystem globber, "comments" don't make much sense.
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will always
be interpreted as escape characters, not path separators.
Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`. On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.
## Race Conditions
Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.
As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.
As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead. However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.
Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast majority
of operations, this is never a problem.
## Contributing
Any change to behavior (including bugfixes) must come with a test.
Patches that fail tests or reduce performance will be rejected.
```
# to run tests
npm test
# to re-generate test fixtures
npm run test-regen
# to benchmark against bash/zsh
npm run bench
# to profile javascript
npm run prof
```

View File

@ -0,0 +1,245 @@
exports.alphasort = alphasort
exports.alphasorti = alphasorti
exports.setopts = setopts
exports.ownProp = ownProp
exports.makeAbs = makeAbs
exports.finish = finish
exports.mark = mark
exports.isIgnored = isIgnored
exports.childrenIgnored = childrenIgnored
function ownProp (obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field)
}
var path = require("path")
var minimatch = require("minimatch")
var isAbsolute = require("path-is-absolute")
var Minimatch = minimatch.Minimatch
function alphasorti (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase())
}
function alphasort (a, b) {
return a.localeCompare(b)
}
function setupIgnores (self, options) {
self.ignore = options.ignore || []
if (!Array.isArray(self.ignore))
self.ignore = [self.ignore]
if (self.ignore.length) {
self.ignore = self.ignore.map(ignoreMap)
}
}
function ignoreMap (pattern) {
var gmatcher = null
if (pattern.slice(-3) === '/**') {
var gpattern = pattern.replace(/(\/\*\*)+$/, '')
gmatcher = new Minimatch(gpattern)
}
return {
matcher: new Minimatch(pattern),
gmatcher: gmatcher
}
}
function setopts (self, pattern, options) {
if (!options)
options = {}
// base-matching: just use globstar for that.
if (options.matchBase && -1 === pattern.indexOf("/")) {
if (options.noglobstar) {
throw new Error("base matching requires globstar")
}
pattern = "**/" + pattern
}
self.silent = !!options.silent
self.pattern = pattern
self.strict = options.strict !== false
self.realpath = !!options.realpath
self.realpathCache = options.realpathCache || Object.create(null)
self.follow = !!options.follow
self.dot = !!options.dot
self.mark = !!options.mark
self.nodir = !!options.nodir
if (self.nodir)
self.mark = true
self.sync = !!options.sync
self.nounique = !!options.nounique
self.nonull = !!options.nonull
self.nosort = !!options.nosort
self.nocase = !!options.nocase
self.stat = !!options.stat
self.noprocess = !!options.noprocess
self.maxLength = options.maxLength || Infinity
self.cache = options.cache || Object.create(null)
self.statCache = options.statCache || Object.create(null)
self.symlinks = options.symlinks || Object.create(null)
setupIgnores(self, options)
self.changedCwd = false
var cwd = process.cwd()
if (!ownProp(options, "cwd"))
self.cwd = cwd
else {
self.cwd = options.cwd
self.changedCwd = path.resolve(options.cwd) !== cwd
}
self.root = options.root || path.resolve(self.cwd, "/")
self.root = path.resolve(self.root)
if (process.platform === "win32")
self.root = self.root.replace(/\\/g, "/")
self.nomount = !!options.nomount
// disable comments and negation unless the user explicitly
// passes in false as the option.
options.nonegate = options.nonegate === false ? false : true
options.nocomment = options.nocomment === false ? false : true
deprecationWarning(options)
self.minimatch = new Minimatch(pattern, options)
self.options = self.minimatch.options
}
// TODO(isaacs): remove entirely in v6
// exported to reset in tests
exports.deprecationWarned
function deprecationWarning(options) {
if (!options.nonegate || !options.nocomment) {
if (process.noDeprecation !== true && !exports.deprecationWarned) {
var msg = 'glob WARNING: comments and negation will be disabled in v6'
if (process.throwDeprecation)
throw new Error(msg)
else if (process.traceDeprecation)
console.trace(msg)
else
console.error(msg)
exports.deprecationWarned = true
}
}
}
function finish (self) {
var nou = self.nounique
var all = nou ? [] : Object.create(null)
for (var i = 0, l = self.matches.length; i < l; i ++) {
var matches = self.matches[i]
if (!matches || Object.keys(matches).length === 0) {
if (self.nonull) {
// do like the shell, and spit out the literal glob
var literal = self.minimatch.globSet[i]
if (nou)
all.push(literal)
else
all[literal] = true
}
} else {
// had matches
var m = Object.keys(matches)
if (nou)
all.push.apply(all, m)
else
m.forEach(function (m) {
all[m] = true
})
}
}
if (!nou)
all = Object.keys(all)
if (!self.nosort)
all = all.sort(self.nocase ? alphasorti : alphasort)
// at *some* point we statted all of these
if (self.mark) {
for (var i = 0; i < all.length; i++) {
all[i] = self._mark(all[i])
}
if (self.nodir) {
all = all.filter(function (e) {
return !(/\/$/.test(e))
})
}
}
if (self.ignore.length)
all = all.filter(function(m) {
return !isIgnored(self, m)
})
self.found = all
}
function mark (self, p) {
var abs = makeAbs(self, p)
var c = self.cache[abs]
var m = p
if (c) {
var isDir = c === 'DIR' || Array.isArray(c)
var slash = p.slice(-1) === '/'
if (isDir && !slash)
m += '/'
else if (!isDir && slash)
m = m.slice(0, -1)
if (m !== p) {
var mabs = makeAbs(self, m)
self.statCache[mabs] = self.statCache[abs]
self.cache[mabs] = self.cache[abs]
}
}
return m
}
// lotta situps...
function makeAbs (self, f) {
var abs = f
if (f.charAt(0) === '/') {
abs = path.join(self.root, f)
} else if (isAbsolute(f) || f === '') {
abs = f
} else if (self.changedCwd) {
abs = path.resolve(self.cwd, f)
} else {
abs = path.resolve(f)
}
return abs
}
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
function isIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
})
}
function childrenIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return !!(item.gmatcher && item.gmatcher.match(path))
})
}

View File

@ -0,0 +1,752 @@
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, then stat(PREFIX) and
// add to matches if it succeeds. END.
//
// If inGlobStar and PREFIX is symlink and points to dir
// set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
// If fail, END
//
// with ENTRIES
// If pattern[n] is GLOBSTAR
// // handle the case where the globstar match is empty
// // by pruning it out, and testing the resulting pattern
// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
// // handle other cases.
// for ENTRY in ENTRIES (not dotfiles)
// // attach globstar + tail onto the entry
// // Mark that this entry is a globstar match
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
// else // not globstar
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
// Test ENTRY against pattern[n]
// If fails, continue
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
// Cache all stats and readdirs results to minimize syscall. Since all
// we ever care about is existence and directory-ness, we can just keep
// `true` for files, and [children,...] for directories, or `false` for
// things that don't exist.
module.exports = glob
var fs = require('fs')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var globSync = require('./sync.js')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
var once = require('once')
function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
}
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
glob.hasMagic = function (pattern, options_) {
var options = util._extend({}, options_)
options.noprocess = true
var g = new Glob(pattern, options)
var set = g.minimatch.set
if (set.length > 1)
return true
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== 'string')
return true
}
return false
}
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
if (options && options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return new GlobSync(pattern, options)
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb)
setopts(this, pattern, options)
this._didRealPath = false
// process each pattern in the minimatch set
var n = this.minimatch.set.length
// The matches are stored as {<filename>: true,...} so that
// duplicates are automagically pruned.
// Later, we do an Object.keys() on these.
// Keep them as a list so we can fill in when nonull is set.
this.matches = new Array(n)
if (typeof cb === 'function') {
cb = once(cb)
this.on('error', cb)
this.on('end', function (matches) {
cb(null, matches)
})
}
var self = this
var n = this.minimatch.set.length
this._processing = 0
this.matches = new Array(n)
this._emitQueue = []
this._processQueue = []
this.paused = false
if (this.noprocess)
return this
if (n === 0)
return done()
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false, done)
}
function done () {
--self._processing
if (self._processing <= 0)
self._finish()
}
}
Glob.prototype._finish = function () {
assert(this instanceof Glob)
if (this.aborted)
return
if (this.realpath && !this._didRealpath)
return this._realpath()
common.finish(this)
this.emit('end', this.found)
}
Glob.prototype._realpath = function () {
if (this._didRealpath)
return
this._didRealpath = true
var n = this.matches.length
if (n === 0)
return this._finish()
var self = this
for (var i = 0; i < this.matches.length; i++)
this._realpathSet(i, next)
function next () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] = Object.create(null)
found.forEach(function (p, i) {
// If there's a problem with the stat, then it means that
// one or more of the links in the realpath couldn't be
// resolved. just return the abs value in that case.
p = self._makeAbs(p)
fs.realpath(p, self.realpathCache, function (er, real) {
if (!er)
set[real] = true
else if (er.syscall === 'stat')
set[p] = true
else
self.emit('error', er) // srsly wtf right here
if (--n === 0) {
self.matches[index] = set
cb()
}
})
})
}
Glob.prototype._mark = function (p) {
return common.mark(this, p)
}
Glob.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
Glob.prototype.abort = function () {
this.aborted = true
this.emit('abort')
}
Glob.prototype.pause = function () {
if (!this.paused) {
this.paused = true
this.emit('pause')
}
}
Glob.prototype.resume = function () {
if (this.paused) {
this.emit('resume')
this.paused = false
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0)
this._emitQueue.length = 0
for (var i = 0; i < eq.length; i ++) {
var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2], p[3])
}
}
}
}
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
assert(this instanceof Glob)
assert(typeof cb === 'function')
if (this.aborted)
return
this._processing++
if (this.paused) {
this._processQueue.push([pattern, index, inGlobStar, cb])
return
}
//console.error('PROCESS %d', this._processing, pattern)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// see if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index, cb)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip _processing
if (childrenIgnored(this, read))
return cb()
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
// if the abs isn't a dir, then nothing can match!
if (!entries)
return cb()
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return cb()
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return cb()
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
this._process([e].concat(remain), index, inGlobStar, cb)
}
cb()
}
Glob.prototype._emitMatch = function (index, e) {
if (this.aborted)
return
if (this.matches[index][e])
return
if (isIgnored(this, e))
return
if (this.paused) {
this._emitQueue.push([index, e])
return
}
var abs = this._makeAbs(e)
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
if (this.mark)
e = this._mark(e)
this.matches[index][e] = true
var st = this.statCache[abs]
if (st)
this.emit('stat', e, st)
this.emit('match', e)
}
Glob.prototype._readdirInGlobStar = function (abs, cb) {
if (this.aborted)
return
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false, cb)
var lstatkey = 'lstat\0' + abs
var self = this
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er)
return cb()
var isSym = lstat.isSymbolicLink()
self.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && !lstat.isDirectory()) {
self.cache[abs] = 'FILE'
cb()
} else
self._readdir(abs, false, cb)
}
}
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
if (this.aborted)
return
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
if (!cb)
return
//console.error('RD %j %j', +inGlobStar, abs)
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return cb()
if (Array.isArray(c))
return cb(null, c)
}
var self = this
fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
return function (er, entries) {
if (er)
self._readdirError(abs, er, cb)
else
self._readdirEntries(abs, entries, cb)
}
}
Glob.prototype._readdirEntries = function (abs, entries, cb) {
if (this.aborted)
return
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
return cb(null, entries)
}
Glob.prototype._readdirError = function (f, er, cb) {
if (this.aborted)
return
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
this.cache[this._makeAbs(f)] = 'FILE'
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict) {
this.emit('error', er)
// If the error is handled, then we abort
// if not, we threw out of here
this.abort()
}
if (!this.silent)
console.error('glob error', er)
break
}
return cb()
}
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
//console.error('pgs2', prefix, remain[0], entries)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return cb()
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false, cb)
var isSym = this.symlinks[abs]
var len = entries.length
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return cb()
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true, cb)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true, cb)
}
cb()
}
Glob.prototype._processSimple = function (prefix, index, cb) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var self = this
this._stat(prefix, function (er, exists) {
self._processSimple2(prefix, index, er, exists, cb)
})
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
//console.error('ps2', prefix, exists)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return cb()
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
cb()
}
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return cb()
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return cb(null, c)
if (needDir && c === 'FILE')
return cb()
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (stat !== undefined) {
if (stat === false)
return cb(null, stat)
else {
var type = stat.isDirectory() ? 'DIR' : 'FILE'
if (needDir && type === 'FILE')
return cb()
else
return cb(null, type, stat)
}
}
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
return fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
self._stat2(f, abs, er, stat, cb)
})
} else {
self._stat2(f, abs, er, lstat, cb)
}
}
}
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
if (er) {
this.statCache[abs] = false
return cb()
}
var needDir = f.slice(-1) === '/'
this.statCache[abs] = stat
if (abs.slice(-1) === '/' && !stat.isDirectory())
return cb(null, false, stat)
var c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c !== 'DIR')
return cb()
return cb(null, c, stat)
}

View File

@ -0,0 +1,75 @@
{
"_from": "glob@^5.0.15",
"_id": "glob@5.0.15",
"_inBundle": false,
"_integrity": "sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=",
"_location": "/istanbul/glob",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "glob@^5.0.15",
"name": "glob",
"escapedName": "glob",
"rawSpec": "^5.0.15",
"saveSpec": null,
"fetchSpec": "^5.0.15"
},
"_requiredBy": [
"/istanbul"
],
"_resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz",
"_shasum": "1bc936b9e02f4a603fcc222ecf7633d30b8b93b1",
"_spec": "glob@^5.0.15",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/node-glob/issues"
},
"bundleDependencies": false,
"dependencies": {
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "2 || 3",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"deprecated": false,
"description": "a little globber",
"devDependencies": {
"mkdirp": "0",
"rimraf": "^2.2.8",
"tap": "^1.1.4",
"tick": "0.0.6"
},
"engines": {
"node": "*"
},
"files": [
"glob.js",
"sync.js",
"common.js"
],
"homepage": "https://github.com/isaacs/node-glob#readme",
"license": "ISC",
"main": "glob.js",
"name": "glob",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-glob.git"
},
"scripts": {
"bench": "bash benchmark.sh",
"benchclean": "node benchclean.js",
"prepublish": "npm run benchclean",
"prof": "bash prof.sh && cat profile.txt",
"profclean": "rm -f v8.log profile.txt",
"test": "tap test/*.js --cov",
"test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js"
},
"version": "5.0.15"
}

View File

@ -0,0 +1,460 @@
module.exports = globSync
globSync.GlobSync = GlobSync
var fs = require('fs')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var Glob = require('./glob.js').Glob
var util = require('util')
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var common = require('./common.js')
var alphasort = common.alphasort
var alphasorti = common.alphasorti
var setopts = common.setopts
var ownProp = common.ownProp
var childrenIgnored = common.childrenIgnored
function globSync (pattern, options) {
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
return new GlobSync(pattern, options).found
}
function GlobSync (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this instanceof GlobSync))
return new GlobSync(pattern, options)
setopts(this, pattern, options)
if (this.noprocess)
return this
var n = this.minimatch.set.length
this.matches = new Array(n)
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false)
}
this._finish()
}
GlobSync.prototype._finish = function () {
assert(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
var set = self.matches[index] = Object.create(null)
for (var p in matchset) {
try {
p = self._makeAbs(p)
var real = fs.realpathSync(p, self.realpathCache)
set[real] = true
} catch (er) {
if (er.syscall === 'stat')
set[self._makeAbs(p)] = true
else
throw er
}
}
})
}
common.finish(this)
}
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
assert(this instanceof GlobSync)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// See if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip processing
if (childrenIgnored(this, read))
return
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
}
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// if the abs isn't a dir, then nothing can match!
if (!entries)
return
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix.slice(-1) !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this.matches[index][e] = true
}
// This was the last one, and no stats were needed
return
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix)
newPattern = [prefix, e]
else
newPattern = [e]
this._process(newPattern.concat(remain), index, inGlobStar)
}
}
GlobSync.prototype._emitMatch = function (index, e) {
var abs = this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[this._makeAbs(e)]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
if (this.stat)
this._stat(e)
}
GlobSync.prototype._readdirInGlobStar = function (abs) {
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false)
var entries
var lstat
var stat
try {
lstat = fs.lstatSync(abs)
} catch (er) {
// lstat failed, doesn't exist
return null
}
var isSym = lstat.isSymbolicLink()
this.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && !lstat.isDirectory())
this.cache[abs] = 'FILE'
else
entries = this._readdir(abs, false)
return entries
}
GlobSync.prototype._readdir = function (abs, inGlobStar) {
var entries
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return null
if (Array.isArray(c))
return c
}
try {
return this._readdirEntries(abs, fs.readdirSync(abs))
} catch (er) {
this._readdirError(abs, er)
return null
}
}
GlobSync.prototype._readdirEntries = function (abs, entries) {
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
// mark and cache dir-ness
return entries
}
GlobSync.prototype._readdirError = function (f, er) {
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
this.cache[this._makeAbs(f)] = 'FILE'
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict)
throw er
if (!this.silent)
console.error('glob error', er)
break
}
}
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false)
var len = entries.length
var isSym = this.symlinks[abs]
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true)
}
}
GlobSync.prototype._processSimple = function (prefix, index) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var exists = this._stat(prefix)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this.matches[index][prefix] = true
}
// Returns either 'DIR', 'FILE', or false
GlobSync.prototype._stat = function (f) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return false
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return c
if (needDir && c === 'FILE')
return false
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (!stat) {
var lstat
try {
lstat = fs.lstatSync(abs)
} catch (er) {
return false
}
if (lstat.isSymbolicLink()) {
try {
stat = fs.statSync(abs)
} catch (er) {
stat = lstat
}
} else {
stat = lstat
}
}
this.statCache[abs] = stat
var c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c !== 'DIR')
return false
return c
}
GlobSync.prototype._mark = function (p) {
return common.mark(this, p)
}
GlobSync.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}

View File

@ -0,0 +1,22 @@
Copyright (c) George Zahariev
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,196 @@
# levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" />
__Light ECMAScript (JavaScript) Value Notation__
Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments).
Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.3.0.
__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose.
npm install levn
For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev).
## Quick Examples
```js
var parse = require('levn').parse;
parse('Number', '2'); // 2
parse('String', '2'); // '2'
parse('String', 'levn'); // 'levn'
parse('String', 'a b'); // 'a b'
parse('Boolean', 'true'); // true
parse('Date', '#2011-11-11#'); // (Date object)
parse('Date', '2011-11-11'); // (Date object)
parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi
parse('RegExp', 're'); // /re/
parse('Int', '2'); // 2
parse('Number | String', 'str'); // 'str'
parse('Number | String', '2'); // 2
parse('[Number]', '[1,2,3]'); // [1,2,3]
parse('(String, Boolean)', '(hi, false)'); // ['hi', false]
parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2}
// at the top level, you can ommit surrounding delimiters
parse('[Number]', '1,2,3'); // [1,2,3]
parse('(String, Boolean)', 'hi, false'); // ['hi', false]
parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2}
// wildcard - auto choose type
parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}]
```
## Usage
`require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions.
```js
// parse(type, input, options);
parse('[Number]', '1,2,3'); // [1, 2, 3]
// parsedTypeParse(parsedType, input, options);
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
### parse(type, input, options)
`parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value.
##### arguments
* type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
parse('[Number]', '1,2,3'); // [1, 2, 3]
```
### parsedTypeParse(parsedType, input, options)
`parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function.
##### arguments
* type - `Object` - the type in the parsed type format which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
## Levn Format
Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`.
If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options).
* `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"`
* `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')`
* `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi`
* `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents
* `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`.
* `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`).
* `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`.
* Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`.
If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information:
* If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`.
* If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`.
* If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`.
* If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`.
* If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`).
* If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`.
If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list.
Whitespace between special characters and elements is inconsequential.
## Options
Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions.
### Explicit
A `Boolean`. By default it is `false`.
__Example:__
```js
parse('RegExp', 're', {explicit: false}); // /re/
parse('RegExp', 're', {explicit: true}); // Error: ... does not type check...
parse('RegExp | String', 're', {explicit: true}); // 're'
```
`explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section.
### customTypes
An `Object`. Empty `{}` by default.
__Example:__
```js
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function (x) {
return x % 2 === 0;
},
cast: function (x) {
return {type: 'Just', value: parseInt(x)};
}
}
}
}
parse('Even', '2', options); // 2
parse('Even', '3', options); // Error: Value: "3" does not type check...
```
__Another Example:__
```js
function Person(name, age){
this.name = name;
this.age = age;
}
var options = {
customTypes: {
Person: {
typeOf: 'Object',
validate: function (x) {
x instanceof Person;
},
cast: function (value, options, typesCast) {
var name, age;
if ({}.toString.call(value).slice(8, -1) !== 'Object') {
return {type: 'Nothing'};
}
name = typesCast(value.name, [{type: 'String'}], options);
age = typesCast(value.age, [{type: 'Numger'}], options);
return {type: 'Just', value: new Person(name, age)};
}
}
}
parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25}
```
`customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check.
`cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly.
## Technical About
`levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@ -0,0 +1,298 @@
// Generated by LiveScript 1.4.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(value, options){
switch (toString$.call(value).slice(8, -1)) {
case 'Array':
return typeCast(value, {
type: 'Array'
}, options);
case 'Object':
return typeCast(value, {
type: 'Object'
}, options);
default:
return {
type: 'Just',
value: typesCast(value, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], (options.explicit = true, options))
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: +it
};
},
Float: function(it){
return {
type: 'Just',
value: +it
};
},
Date: function(value, options){
var that;
if (that = /^\#([\s\S]*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(value, options){
return castArray(value, {
of: [{
type: '*'
}]
}, options);
},
Object: function(value, options){
return castFields(value, {
of: {}
}, options);
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'([\s\S]*)'$/)) {
return {
type: 'Just',
value: that[1].replace(/\\'/g, "'")
};
} else if (that = it.match(/^"([\s\S]*)"$/)) {
return {
type: 'Just',
value: that[1].replace(/\\"/g, '"')
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function castArray(node, type, options){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(typesCast(element, typeOf, options));
}
return results$;
}())
};
}
function castTuple(node, type, options){
var result, i, i$, ref$, len$, types, cast;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
i = 0;
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
types = ref$[i$];
cast = typesCast(node[i], types, options);
if (toString$.call(cast).slice(8, -1) !== 'Undefined') {
result.push(cast);
}
i++;
}
if (node.length <= i) {
return {
type: 'Just',
value: result
};
} else {
return {
type: 'Nothing'
};
}
}
function castFields(node, type, options){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, resultObj$ = {};
for (key in ref$ = node) {
value = ref$[key];
resultObj$[typesCast(key, [{
type: 'String'
}], options)] = typesCast(value, typeOf[key] || [{
type: '*'
}], options);
}
return resultObj$;
}())
};
}
function typeCast(node, typeObj, options){
var type, structure, castFunc, ref$;
type = typeObj.type, structure = typeObj.structure;
if (type) {
castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type];
if (!castFunc) {
throw new Error("Type not defined: " + type + ".");
}
return castFunc(node, options, typesCast);
} else {
switch (structure) {
case 'array':
return castArray(node, typeObj, options);
case 'tuple':
return castTuple(node, typeObj, options);
case 'fields':
return castFields(node, typeObj, options);
}
}
}
function typesCast(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value, {
customTypes: options.customTypes
})) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = typesCast;
}).call(this);

View File

@ -0,0 +1,285 @@
// Generated by LiveScript 1.2.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(it){
switch (toString$.call(it).slice(8, -1)) {
case 'Array':
return coerceType(it, {
type: 'Array'
});
case 'Object':
return coerceType(it, {
type: 'Object'
});
default:
return {
type: 'Just',
value: coerceTypes(it, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], {
explicit: true
})
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: parseInt(it)
};
},
Float: function(it){
return {
type: 'Just',
value: parseFloat(it)
};
},
Date: function(value, options){
var that;
if (that = /^\#(.*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(it){
return coerceArray(it, {
of: [{
type: '*'
}]
});
},
Object: function(it){
return coerceFields(it, {
of: {}
});
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'(.*)'$/)) {
return {
type: 'Just',
value: that[1]
};
} else if (that = it.match(/^"(.*)"$/)) {
return {
type: 'Just',
value: that[1]
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function coerceArray(node, type){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(coerceTypes(element, typeOf));
}
return results$;
}())
};
}
function coerceTuple(node, type){
var result, i$, ref$, len$, i, types, that;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
i = i$;
types = ref$[i$];
if (that = coerceTypes(node[i], types)) {
result.push(that);
}
}
return {
type: 'Just',
value: result
};
}
function coerceFields(node, type){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, results$ = {};
for (key in ref$ = node) {
value = ref$[key];
results$[key] = coerceTypes(value, typeOf[key] || [{
type: '*'
}]);
}
return results$;
}())
};
}
function coerceType(node, typeObj, options){
var type, structure, coerceFunc;
type = typeObj.type, structure = typeObj.structure;
if (type) {
coerceFunc = types[type];
return coerceFunc(node, options);
} else {
switch (structure) {
case 'array':
return coerceArray(node, typeObj);
case 'tuple':
return coerceTuple(node, typeObj);
case 'fields':
return coerceFields(node, typeObj);
}
}
}
function coerceTypes(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value)) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = coerceTypes;
}).call(this);

View File

@ -0,0 +1,22 @@
// Generated by LiveScript 1.4.0
(function(){
var parseString, cast, parseType, VERSION, parsedTypeParse, parse;
parseString = require('./parse-string');
cast = require('./cast');
parseType = require('type-check').parseType;
VERSION = '0.3.0';
parsedTypeParse = function(parsedType, string, options){
options == null && (options = {});
options.explicit == null && (options.explicit = false);
options.customTypes == null && (options.customTypes = {});
return cast(parseString(parsedType, string, options), parsedType, options);
};
parse = function(type, string, options){
return parsedTypeParse(parseType(type), string, options);
};
module.exports = {
VERSION: VERSION,
parse: parse,
parsedTypeParse: parsedTypeParse
};
}).call(this);

View File

@ -0,0 +1,113 @@
// Generated by LiveScript 1.4.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, arg$, hasDelimiters){
var open, close, result, untilTest;
open = arg$[0], close = arg$[1];
if (hasDelimiters) {
consumeOp(tokens, open);
}
result = [];
untilTest = "," + (hasDelimiters ? close : '');
while (tokens.length && (hasDelimiters && tokens[0] !== close)) {
result.push(consumeElement(tokens, untilTest));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, close);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, untilTest, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
untilTest = "," + (hasDelimiters ? '}' : '');
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = consumeValue(tokens, ':');
consumeOp(tokens, ':');
result[key] = consumeElement(tokens, untilTest);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeValue(tokens, untilTest){
var out;
untilTest == null && (untilTest = '');
out = '';
while (tokens.length && -1 === untilTest.indexOf(tokens[0])) {
out += tokens.shift();
}
return out;
}
function consumeElement(tokens, untilTest){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return consumeValue(tokens, untilTest);
}
}
function consumeTopLevel(tokens, types, options){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
return finalResult;
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*');
module.exports = function(types, string, options){
var tokens, node;
options == null && (options = {});
if (!options.explicit && types.length === 1 && types[0].type === 'String') {
return "'" + string.replace(/\\'/g, "\\\\'") + "'";
}
tokens = reject(not$, string.split(tokenRegex));
node = consumeTopLevel(tokens, types, options);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
function not$(x){ return !x; }
}).call(this);

View File

@ -0,0 +1,102 @@
// Generated by LiveScript 1.2.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, delimiters, hasDelimiters){
var result;
if (hasDelimiters) {
consumeOp(tokens, delimiters[0]);
}
result = [];
while (tokens.length && tokens[0] !== delimiters[1]) {
result.push(consumeElement(tokens));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, delimiters[1]);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = tokens.shift();
consumeOp(tokens, ':');
result[key] = consumeElement(tokens);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeElement(tokens){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return tokens.shift();
}
}
function consumeTopLevel(tokens, types){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (types.length === 1 && (structure || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
if (tokens.length && origTokens.length) {
throw new Error("Unable to parse " + JSON.stringify(origTokens) + " of type " + JSON.stringify(types) + ".");
} else {
return finalResult;
}
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:[^"]|\\\\")*")|(\'(?:[^\']|\\\\\')*\')|(#.*#)|(/(?:\\\\/|[^/])*/[gimy]*)|([' + special + '])|([^\\s' + special + ']+)|\\s*');
module.exports = function(string, types){
var tokens, node;
tokens = reject(function(it){
return !it || /^\s+$/.test(it);
}, string.split(tokenRegex));
node = consumeTopLevel(tokens, types);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
}).call(this);

View File

@ -0,0 +1,77 @@
{
"_from": "levn@~0.3.0",
"_id": "levn@0.3.0",
"_inBundle": false,
"_integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=",
"_location": "/istanbul/levn",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "levn@~0.3.0",
"name": "levn",
"escapedName": "levn",
"rawSpec": "~0.3.0",
"saveSpec": null,
"fetchSpec": "~0.3.0"
},
"_requiredBy": [
"/istanbul/optionator"
],
"_resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz",
"_shasum": "3b09924edf9f083c0490fdd4c0bc4421e04764ee",
"_spec": "levn@~0.3.0",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul/node_modules/optionator",
"author": {
"name": "George Zahariev",
"email": "z@georgezahariev.com"
},
"bugs": {
"url": "https://github.com/gkz/levn/issues"
},
"bundleDependencies": false,
"dependencies": {
"prelude-ls": "~1.1.2",
"type-check": "~0.3.2"
},
"deprecated": false,
"description": "Light ECMAScript (JavaScript) Value Notation - human written, concise, typed, flexible",
"devDependencies": {
"istanbul": "~0.4.1",
"livescript": "~1.4.0",
"mocha": "~2.3.4"
},
"engines": {
"node": ">= 0.8.0"
},
"files": [
"lib",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/gkz/levn",
"keywords": [
"levn",
"light",
"ecmascript",
"value",
"notation",
"json",
"typed",
"human",
"concise",
"typed",
"flexible"
],
"license": "MIT",
"main": "./lib/",
"name": "levn",
"repository": {
"type": "git",
"url": "git://github.com/gkz/levn.git"
},
"scripts": {
"test": "make test"
},
"version": "0.3.0"
}

View File

@ -0,0 +1,52 @@
# 0.8.2
- fix bug #18 - detect missing value when flag is last item
- update dependencies
# 0.8.1
- update `fast-levenshtein` dependency
# 0.8.0
- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int`
# 0.7.1
- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects`
# 0.7.0
- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag
- added `typeAliases` option
- added `parseArgv` which takes an array and parses with the first two items sliced off
- changed enum help style
- bug fixes (#12)
- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects
# 0.6.0
- added `defaults` lib-option flag, allowing one to set default properties for all options
- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only
# 0.5.0
- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help
# 0.4.0
- add `mergeRepeatedObjects` setting
# 0.3.0
- add `concatRepeatedArrays` setting
- add `overrideRequired` option setting
- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue
# 0.2.2
- bug fixes
# 0.2.1
- improved interpolation
- added changelog
# 0.2.0
- add dependency checks to options - added `dependsOn` as an option property
- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate`
# 0.1.1
- update dependencies
# 0.1.0
- initial release

View File

@ -0,0 +1,22 @@
Copyright (c) George Zahariev
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,236 @@
# Optionator
<a name="optionator" />
Optionator is a JavaScript option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator).
For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo).
[About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format)
## Why?
The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not.
With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant).
If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application.
$ cmd --halp
Invalid option '--halp' - perhaps you meant '--help'?
$ cmd --count str
Invalid value for option 'count' - expected type Int, received value: str.
Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier.
## About
Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types.
MIT license. Version 0.8.2
npm install optionator
For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev).
## Usage
`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions.
```js
var optionator = require('optionator')({
prepend: 'Usage: cmd [options]',
append: 'Version 1.0.0',
options: [{
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'displays help'
}, {
option: 'count',
alias: 'c',
type: 'Int',
description: 'number of things',
example: 'cmd --count 2'
}]
});
var options = optionator.parseArgv(process.argv);
if (options.help) {
console.log(optionator.generateHelp());
}
...
```
### parse(input, parseOptions)
`parse` processes the `input` according to your settings, and returns an object with the results.
##### arguments
* input - `[String] | Object | String` - the input you wish to parse
* parseOptions - `{slice: Int}` - all options optional
- `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`)
##### returns
`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key.
##### example
```js
parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']}
parse('--count 2 positional'); // {count: 2, _: ['positional']}
parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']}
```
### parseArgv(input)
`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements.
##### arguments
* input - `[String]` - the input you wish to parse
##### returns
See "returns" section in "parse"
##### example
```js
parseArgv(process.argv);
```
### generateHelp(helpOptions)
`generateHelp` produces help text based on your settings.
##### arguments
* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional
- `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false`
- `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2`
##### returns
`String` - the generated help text
##### example
```js
generateHelp(); /*
"Usage: cmd [options] positional
-h, --help displays help
-c, --count Int number of things
Version 1.0.0
"*/
```
### generateHelpForOption(optionName)
`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`.
##### arguments
* optionName - `String` - the name of the option to display
##### returns
`String` - the generated help text for the option
##### example
```js
generateHelpForOption('count'); /*
"-c, --count Int
description: number of things
example: cmd --count 2
"*/
```
## Settings Format
When your `require('optionator')`, you get a function that takes in a settings object. This object has the type:
{
prepend: String,
append: String,
options: [{heading: String} | {
option: String,
alias: [String] | String,
type: String,
enum: [String],
default: String,
restPositional: Boolean,
required: Boolean,
overrideRequired: Boolean,
dependsOn: [String] | String,
concatRepeatedArrays: Boolean | (Boolean, Object),
mergeRepeatedObjects: Boolean,
description: String,
longDescription: String,
example: [String] | String
}],
helpStyle: {
aliasSeparator: String,
typeSeparator: String,
descriptionSeparator: String,
initialIndent: Int,
secondaryIndent: Int,
maxPadFactor: Number
},
mutuallyExclusive: [[String | [String]]],
concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object
mergeRepeatedObjects: Boolean, // deprecated, set in defaults object
positionalAnywhere: Boolean,
typeAliases: Object,
defaults: Object
}
All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array.
### Top Level Properties
* `prepend` is an optional string to be placed before the options in the help text
* `append` is an optional string to be placed after the options in the help text
* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified
* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text
* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present
* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack`
* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String`
* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property
#### Heading Properties
* `heading` a required string, the name of the heading
#### Option Properties
* `option` the required name of the option - use dash-case, without the leading dashes
* `alias` is an optional string or array of strings which specify any aliases for the option
* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it
* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type`
* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type`
* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument
* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined
* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags
* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']`
You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma.
* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}`
* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set
* `description` is an optional string, which will be displayed next to the option in the help text
* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used
* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used
#### Help Style Properties
* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,'
* `typeSeparator` is an optional string, separates the type from the names - default: ' '
* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' '
* `initialIndent` is an optional int - the amount of indent for options - default: 2
* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4
* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5
## Argument Format
At the highest level there are two types of arguments: named, and positional.
Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`).
There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value.
For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages.
You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`.
Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`.
Everything after an `--` is positional, even if it looks like a named argument.
You may optionally use `=` to separate option names from values, for example: `--count=2`.
If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`.
If duplicate named arguments are present, the last one will be taken.
## Technical About
`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library.

View File

@ -0,0 +1,247 @@
// Generated by LiveScript 1.5.0
(function(){
var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp;
ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines;
ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
wordwrap = require('wordwrap');
getPreText = function(option, arg$, maxWidth){
var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap;
mainName = option.option, shortNames = (ref$ = option.shortNames) != null
? ref$
: [], longNames = (ref$ = option.longNames) != null
? ref$
: [], type = option.type, description = option.description;
aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent;
if (option.negateName) {
mainName = "no-" + mainName;
if (longNames) {
longNames = map(function(it){
return "no-" + it;
}, longNames);
}
}
names = mainName.length === 1
? [mainName].concat(shortNames, longNames)
: shortNames.concat([mainName], longNames);
namesString = map(nameToRaw, names).join(aliasSeparator);
namesStringLen = namesString.length;
typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator;
typeSeparatorStringLen = typeSeparatorString.length;
if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) {
wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth);
return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, '');
} else {
return namesString + "" + (option.boolean
? ''
: typeSeparatorString + "" + type);
}
};
setHelpStyleDefaults = function(helpStyle){
helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', ');
helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' ');
helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = ' ');
helpStyle.initialIndent == null && (helpStyle.initialIndent = 2);
helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4);
helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5);
};
generateHelpForOption = function(getOption, arg$){
var stdout, helpStyle, ref$;
stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null
? ref$
: {};
setHelpStyleDefaults(helpStyle);
return function(optionName){
var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator;
maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
wrap = maxWidth ? wordwrap(maxWidth) : id;
try {
option = getOption(dasherize(optionName));
} catch (e$) {
e = e$;
return e.message;
}
pre = getPreText(option, helpStyle);
defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : '';
restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : '';
description = option.longDescription || option.description && sentencize(option.description);
fullDescription = description && restPositionalString
? description + " " + restPositionalString
: (that = description || restPositionalString) ? that : '';
preDescription = 'description:';
descriptionString = !fullDescription
? ''
: maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth
? "\n" + preDescription + "\n" + wrap(fullDescription)
: "\n" + preDescription + " " + fullDescription;
exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1
? "\nexamples:\n" + unlines(examples)
: "\nexample: " + examples[0]) : '';
seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : '';
return pre + "" + seperator + defaultString + descriptionString + exampleString;
};
};
generateHelp = function(arg$){
var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent;
options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null
? ref$
: {}, stdout = arg$.stdout;
setHelpStyleDefaults(helpStyle);
aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent;
return function(arg$){
var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap;
ref$ = arg$ != null
? arg$
: {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate;
maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
output = [];
out = function(it){
return output.push(it != null ? it : '');
};
if (prepend) {
out(interpolate ? interp(prepend, interpolate) : prepend);
out();
}
data = [];
optionCount = 0;
totalPreLen = 0;
preLens = [];
for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) {
item = ref$[i$];
if (showHidden || !item.hidden) {
if (that = item.heading) {
data.push({
type: 'heading',
value: that
});
} else {
pre = getPreText(item, helpStyle, maxWidth);
descParts = [];
if ((that = item.description) != null) {
descParts.push(that);
}
if (that = item['enum']) {
descParts.push("either: " + naturalJoin(that));
}
if (item['default'] && !item.negateName) {
descParts.push("default: " + item['default']);
}
desc = descParts.join(' - ');
data.push({
type: 'option',
pre: pre,
desc: desc,
descLen: desc.length
});
preLen = pre.length;
optionCount++;
totalPreLen += preLen;
preLens.push(preLen);
}
}
}
sortedPreLens = sort(preLens);
maxPreLen = sortedPreLens[sortedPreLens.length - 1];
preLenMean = initialIndent + totalPreLen / optionCount;
x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen;
for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) {
preLen = sortedPreLens[i$];
if (preLen <= x) {
padAmount = preLen;
break;
}
}
descSepLen = descriptionSeparator.length;
if (maxWidth != null) {
fullWrapCount = 0;
partialWrapCount = 0;
for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
item = data[i$];
if (item.type === 'option') {
pre = item.pre, desc = item.desc, descLen = item.descLen;
if (descLen === 0) {
item.wrap = 'none';
} else {
preLen = max(padAmount, pre.length) + initialIndent + descSepLen;
totalLen = preLen + descLen;
if (totalLen > maxWidth) {
if (descLen / 2.5 > maxWidth - preLen) {
fullWrapCount++;
item.wrap = 'full';
} else {
partialWrapCount++;
item.wrap = 'partial';
}
} else {
item.wrap = 'none';
}
}
}
}
}
initialSpace = repeatString$(' ', initialIndent);
wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5;
for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
i = i$;
item = data[i$];
if (item.type === 'heading') {
if (i !== 0) {
out();
}
out(item.value + ":");
} else {
pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap;
if (maxWidth != null) {
if (wrapAllFull || wrap === 'full') {
wrap = wordwrap(initialIndent + secondaryIndent, maxWidth);
out(initialSpace + "" + pre + "\n" + wrap(desc));
continue;
} else if (wrap === 'partial') {
wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth);
out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, ''));
continue;
}
}
if (descLen === 0) {
out(initialSpace + "" + pre);
} else {
out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc);
}
}
}
if (append) {
out();
out(interpolate ? interp(append, interpolate) : append);
}
return unlines(output);
};
};
function pad(str, num){
var len, padAmount;
len = str.length;
padAmount = num - len;
return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0);
}
function sentencize(str){
var first, rest, period;
first = str.charAt(0).toUpperCase();
rest = str.slice(1);
period = /[\.!\?]$/.test(str) ? '' : '.';
return first + "" + rest + period;
}
function interp(string, object){
return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){
var ref$;
return (ref$ = object[key]) != null
? ref$
: "{{" + key + "}}";
});
}
module.exports = {
generateHelp: generateHelp,
generateHelpForOption: generateHelpForOption
};
function repeatString$(str, n){
for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str;
return r;
}
}).call(this);

View File

@ -0,0 +1,465 @@
// Generated by LiveScript 1.5.0
(function(){
var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice;
VERSION = '0.8.2';
ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize;
deepIs = require('deep-is');
ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption;
ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType;
parseLevn = require('levn').parsedTypeParse;
camelizeKeys = function(obj){
var key, value, resultObj$ = {};
for (key in obj) {
value = obj[key];
resultObj$[camelize(key)] = value;
}
return resultObj$;
};
parseString = function(string){
var assignOpt, regex, replaceRegex, result, this$ = this;
assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*=';
regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g');
replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$');
result = map(function(it){
return it.replace(replaceRegex, '$1$2');
}, string.match(regex) || []);
return result;
};
main = function(libOptions){
var opts, defaults, required, traverse, getOption, parse;
opts = {};
defaults = {};
required = [];
if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') {
libOptions.stdout = process.stdout;
}
libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true);
libOptions.typeAliases == null && (libOptions.typeAliases = {});
libOptions.defaults == null && (libOptions.defaults = {});
if (libOptions.concatRepeatedArrays != null) {
libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays;
}
if (libOptions.mergeRepeatedObjects != null) {
libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects;
}
traverse = function(options){
var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames, this$ = this;
if (toString$.call(options).slice(8, -1) !== 'Array') {
throw new Error('No options defined.');
}
for (i$ = 0, len$ = options.length; i$ < len$; ++i$) {
option = options[i$];
if (option.heading == null) {
name = option.option;
if (opts[name] != null) {
throw new Error("Option '" + name + "' already defined.");
}
for (k in ref$ = libOptions.defaults) {
v = ref$[k];
option[k] == null && (option[k] = v);
}
if (option.type === 'Boolean') {
option.boolean == null && (option.boolean = true);
}
if (option.parsedType == null) {
if (!option.type) {
throw new Error("No type defined for option '" + name + "'.");
}
try {
type = (that = libOptions.typeAliases[option.type]) != null
? that
: option.type;
option.parsedType = parseType(type);
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message);
}
}
if (option['default']) {
try {
defaults[name] = parseLevn(option.parsedType, option['default']);
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message);
}
}
if (option['enum'] && !option.parsedPossiblities) {
parsedPossibilities = [];
parsedType = option.parsedType;
for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) {
possibility = ref$[j$];
try {
parsedPossibilities.push(parseLevn(parsedType, possibility));
} catch (e$) {
e = e$;
throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message);
}
}
option.parsedPossibilities = parsedPossibilities;
}
if (that = option.dependsOn) {
if (that.length) {
ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1);
dependsType = rawDependsType.toLowerCase();
if (dependsOpts.length) {
if (dependsType === 'and' || dependsType === 'or') {
option.dependsOn = [dependsType].concat(slice$.call(dependsOpts));
} else {
throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'");
}
} else {
if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') {
option.dependsOn = null;
} else {
option.dependsOn = ['and', rawDependsType];
}
}
} else {
option.dependsOn = null;
}
}
if (option.required) {
required.push(name);
}
opts[name] = option;
if (option.concatRepeatedArrays != null) {
cra = option.concatRepeatedArrays;
if ('Boolean' === toString$.call(cra).slice(8, -1)) {
option.concatRepeatedArrays = [cra, {}];
} else if (cra.length === 1) {
option.concatRepeatedArrays = [cra[0], {}];
} else if (cra.length !== 2) {
throw new Error("Invalid setting for concatRepeatedArrays");
}
}
if (option.alias || option.aliases) {
if (name === 'NUM') {
throw new Error("-NUM option can't have aliases.");
}
if (option.alias) {
option.aliases == null && (option.aliases = [].concat(option.alias));
}
for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) {
alias = ref$[j$];
if (opts[alias] != null) {
throw new Error("Option '" + alias + "' already defined.");
}
opts[alias] = option;
}
ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1];
option.shortNames == null && (option.shortNames = shortNames);
option.longNames == null && (option.longNames = longNames);
}
if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') {
option.negateName = true;
}
}
}
function fn$(it){
return it.length === 1;
}
};
traverse(libOptions.options);
getOption = function(name){
var opt, possiblyMeant;
opt = opts[name];
if (opt == null) {
possiblyMeant = closestString(keys(opts), name);
throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.'));
}
return opt;
};
parse = function(input, arg$){
var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName;
slice = (arg$ != null
? arg$
: {}).slice;
obj = {};
positional = [];
restPositional = false;
overrideRequired = false;
prop = null;
setValue = function(name, value){
var opt, val, cra, e, currentType;
opt = getOption(name);
if (opt.boolean) {
val = value;
} else {
try {
cra = opt.concatRepeatedArrays;
if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') {
val = [parseLevn(opt.parsedType[0].of, value)];
} else {
val = parseLevn(opt.parsedType, value);
}
} catch (e$) {
e = e$;
throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + ".");
}
if (opt['enum'] && !any(function(it){
return deepIs(it, val);
}, opt.parsedPossibilities)) {
throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + ".");
}
}
currentType = toString$.call(obj[name]).slice(8, -1);
if (obj[name] != null) {
if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') {
obj[name] = obj[name].concat(val);
} else if (opt.mergeRepeatedObjects && currentType === 'Object') {
import$(obj[name], val);
} else {
obj[name] = val;
}
} else {
obj[name] = val;
}
if (opt.restPositional) {
restPositional = true;
}
if (opt.overrideRequired) {
overrideRequired = true;
}
};
setDefaults = function(){
var name, ref$, value;
for (name in ref$ = defaults) {
value = ref$[name];
if (obj[name] == null) {
obj[name] = value;
}
}
};
checkRequired = function(){
var i$, ref$, len$, name;
if (overrideRequired) {
return;
}
for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) {
name = ref$[i$];
if (!obj[name]) {
throw new Error("Option " + nameToRaw(name) + " is required.");
}
}
};
mutuallyExclusiveError = function(first, second){
throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time.");
};
checkMutuallyExclusive = function(){
var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt;
rules = libOptions.mutuallyExclusive;
if (!rules) {
return;
}
for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) {
rule = rules[i$];
present = null;
for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) {
element = rule[j$];
if (toString$.call(element).slice(8, -1) === 'Array') {
for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) {
opt = element[k$];
if (opt in obj) {
if (present != null) {
mutuallyExclusiveError(present, opt);
} else {
present = opt;
break;
}
}
}
} else {
if (element in obj) {
if (present != null) {
mutuallyExclusiveError(present, element);
} else {
present = element;
}
}
}
}
}
};
checkDependency = function(option){
var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption;
dependsOn = option.dependsOn;
if (!dependsOn || option.dependenciesMet) {
return true;
}
type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1);
for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) {
targetOptionName = targetOptionNames[i$];
targetOption = obj[targetOptionName];
if (targetOption && checkDependency(targetOption)) {
if (type === 'or') {
return true;
}
} else if (type === 'and') {
throw new Error("The option '" + option.option + "' did not have its dependencies met.");
}
}
if (type === 'and') {
return true;
} else {
throw new Error("The option '" + option.option + "' did not meet any of its dependencies.");
}
};
checkDependencies = function(){
var name;
for (name in obj) {
checkDependency(opts[name]);
}
};
checkProp = function(){
if (prop) {
throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required.");
}
};
switch (toString$.call(input).slice(8, -1)) {
case 'String':
args = parseString(input.slice(slice != null ? slice : 0));
break;
case 'Array':
args = input.slice(slice != null ? slice : 2);
break;
case 'Object':
obj = {};
for (key in input) {
value = input[key];
if (key !== '_') {
option = getOption(dasherize(key));
if (parsedTypeCheck(option.parsedType, value)) {
obj[option.option] = value;
} else {
throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'.");
}
}
}
checkMutuallyExclusive();
checkDependencies();
setDefaults();
checkRequired();
return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$;
default:
throw new Error("Invalid argument to 'parse': " + input + ".");
}
for (i$ = 0, len$ = args.length; i$ < len$; ++i$) {
arg = args[i$];
if (arg === '--') {
restPositional = true;
} else if (restPositional) {
positional.push(arg);
} else {
if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) {
result = that;
checkProp();
short = result[1].length === 1;
argName = result[2];
usingAssign = result[3] != null;
val = result[4];
if (usingAssign && val == null) {
throw new Error("No value for '" + argName + "' specified.");
}
if (short) {
flags = chars(argName);
len = flags.length;
for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) {
i = j$;
flag = flags[j$];
opt = getOption(flag);
name = opt.option;
if (restPositional) {
positional.push(flag);
} else if (i === len - 1) {
if (usingAssign) {
valPrime = opt.boolean ? parseLevn([{
type: 'Boolean'
}], val) : val;
setValue(name, valPrime);
} else if (opt.boolean) {
setValue(name, true);
} else {
prop = name;
}
} else if (opt.boolean) {
setValue(name, true);
} else {
throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags.");
}
}
} else {
negated = false;
if (that = argName.match(/^no-(.+)$/)) {
negated = true;
noedName = that[1];
opt = getOption(noedName);
} else {
opt = getOption(argName);
}
name = opt.option;
if (opt.boolean) {
valPrime = usingAssign ? parseLevn([{
type: 'Boolean'
}], val) : true;
if (negated) {
setValue(name, !valPrime);
} else {
setValue(name, valPrime);
}
} else {
if (negated) {
throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'.");
}
if (usingAssign) {
setValue(name, val);
} else {
prop = name;
}
}
}
} else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) {
opt = opts.NUM;
if (!opt) {
throw new Error('No -NUM option defined.');
}
setValue(opt.option, that[1]);
} else {
if (prop) {
setValue(prop, arg);
prop = null;
} else {
positional.push(arg);
if (!libOptions.positionalAnywhere) {
restPositional = true;
}
}
}
}
}
checkProp();
checkMutuallyExclusive();
checkDependencies();
setDefaults();
checkRequired();
return ref$ = camelizeKeys(obj), ref$._ = positional, ref$;
};
return {
parse: parse,
parseArgv: function(it){
return parse(it, {
slice: 2
});
},
generateHelp: generateHelp(libOptions),
generateHelpForOption: generateHelpForOption(getOption, libOptions)
};
};
main.VERSION = VERSION;
module.exports = main;
function import$(obj, src){
var own = {}.hasOwnProperty;
for (var key in src) if (own.call(src, key)) obj[key] = src[key];
return obj;
}
}).call(this);

View File

@ -0,0 +1,54 @@
// Generated by LiveScript 1.5.0
(function(){
var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin;
prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy;
fl = require('fast-levenshtein');
closestString = function(possibilities, input){
var distances, ref$, string, distance, this$ = this;
if (!possibilities.length) {
return;
}
distances = map(function(it){
var ref$, longer, shorter;
ref$ = input.length > it.length
? [input, it]
: [it, input], longer = ref$[0], shorter = ref$[1];
return {
string: it,
distance: fl.get(longer, shorter)
};
})(
possibilities);
ref$ = sortBy(function(it){
return it.distance;
}, distances)[0], string = ref$.string, distance = ref$.distance;
return string;
};
nameToRaw = function(name){
if (name.length === 1 || name === 'NUM') {
return "-" + name;
} else {
return "--" + name;
}
};
dasherize = function(string){
if (/^[A-Z]/.test(string)) {
return string;
} else {
return prelude.dasherize(string);
}
};
naturalJoin = function(array){
if (array.length < 3) {
return array.join(' or ');
} else {
return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1];
}
};
module.exports = {
closestString: closestString,
nameToRaw: nameToRaw,
dasherize: dasherize,
naturalJoin: naturalJoin
};
}).call(this);

View File

@ -0,0 +1,74 @@
{
"_from": "optionator@^0.8.1",
"_id": "optionator@0.8.2",
"_inBundle": false,
"_integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=",
"_location": "/istanbul/optionator",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "optionator@^0.8.1",
"name": "optionator",
"escapedName": "optionator",
"rawSpec": "^0.8.1",
"saveSpec": null,
"fetchSpec": "^0.8.1"
},
"_requiredBy": [
"/istanbul/escodegen"
],
"_resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz",
"_shasum": "364c5e409d3f4d6301d6c0b4c05bba50180aeb64",
"_spec": "optionator@^0.8.1",
"_where": "/home/manfred/enviPath/ketcher2/ketcher/node_modules/istanbul/node_modules/escodegen",
"author": {
"name": "George Zahariev",
"email": "z@georgezahariev.com"
},
"bugs": {
"url": "https://github.com/gkz/optionator/issues"
},
"bundleDependencies": false,
"dependencies": {
"deep-is": "~0.1.3",
"fast-levenshtein": "~2.0.4",
"levn": "~0.3.0",
"prelude-ls": "~1.1.2",
"type-check": "~0.3.2",
"wordwrap": "~1.0.0"
},
"deprecated": false,
"description": "option parsing and help generation",
"devDependencies": {
"istanbul": "~0.4.1",
"livescript": "~1.5.0",
"mocha": "~3.0.2"
},
"engines": {
"node": ">= 0.8.0"
},
"files": [
"lib",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/gkz/optionator",
"keywords": [
"options",
"flags",
"option parsing",
"cli"
],
"license": "MIT",
"main": "./lib/",
"name": "optionator",
"repository": {
"type": "git",
"url": "git://github.com/gkz/optionator.git"
},
"scripts": {
"test": "make test"
},
"version": "0.8.2"
}

View File

@ -0,0 +1,18 @@
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,5 @@
var resolve = require('../');
resolve('tap', { basedir: __dirname }, function (err, res) {
if (err) console.error(err)
else console.log(res)
});

View File

@ -0,0 +1,3 @@
var resolve = require('../');
var res = resolve.sync('tap', { basedir: __dirname });
console.log(res);

View File

@ -0,0 +1,5 @@
var core = require('./lib/core');
exports = module.exports = require('./lib/async');
exports.core = core;
exports.isCore = function (x) { return core[x] };
exports.sync = require('./lib/sync');

View File

@ -0,0 +1,192 @@
var core = require('./core');
var fs = require('fs');
var path = require('path');
var caller = require('./caller.js');
var nodeModulesPaths = require('./node-modules-paths.js');
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
module.exports = function resolve (x, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (!opts) opts = {};
if (typeof x !== 'string') {
return process.nextTick(function () {
cb(new Error('path must be a string'));
});
}
var isFile = opts.isFile || function (file, cb) {
fs.stat(file, function (err, stat) {
if (err && err.code === 'ENOENT') cb(null, false)
else if (err) cb(err)
else cb(null, stat.isFile() || stat.isFIFO())
});
};
var readFile = opts.readFile || fs.readFile;
var extensions = opts.extensions || [ '.js' ];
var y = opts.basedir || path.dirname(caller());
opts.paths = opts.paths || [];
if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
var res = path.resolve(y, x);
if (x === '..') res += '/';
if (/\/$/.test(x) && res === y) {
loadAsDirectory(res, opts.package, onfile);
}
else loadAsFile(res, opts.package, onfile);
}
else loadNodeModules(x, y, function (err, n, pkg) {
if (err) cb(err)
else if (n) cb(null, n, pkg)
else if (core[x]) return cb(null, x);
else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
});
function onfile (err, m, pkg) {
if (err) cb(err)
else if (m) cb(null, m, pkg)
else loadAsDirectory(res, function (err, d, pkg) {
if (err) cb(err)
else if (d) cb(null, d, pkg)
else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
})
}
function loadAsFile (x, pkg, cb) {
if (typeof pkg === 'function') {
cb = pkg;
pkg = undefined;
}
var exts = [''].concat(extensions);
load(exts, x, pkg)
function load (exts, x, pkg) {
if (exts.length === 0) return cb(null, undefined, pkg);
var file = x + exts[0];
if (pkg) onpkg(null, pkg)
else loadpkg(path.dirname(file), onpkg);
function onpkg (err, pkg_, dir) {
pkg = pkg_;
if (err) return cb(err)
if (dir && pkg && opts.pathFilter) {
var rfile = path.relative(dir, file);
var rel = rfile.slice(0, rfile.length - exts[0].length);
var r = opts.pathFilter(pkg, x, rel);
if (r) return load(
[''].concat(extensions.slice()),
path.resolve(dir, r),
pkg
);
}
isFile(file, onex);
}
function onex (err, ex) {
if (err) cb(err)
else if (!ex) load(exts.slice(1), x, pkg)
else cb(null, file, pkg)
}
}
}
function loadpkg (dir, cb) {
if (dir === '' || dir === '/') return cb(null);
if (process.platform === 'win32' && /^\w:[\\\/]*$/.test(dir)) {
return cb(null);
}
if (/[\\\/]node_modules[\\\/]*$/.test(dir)) return cb(null);
var pkgfile = path.join(dir, 'package.json');
isFile(pkgfile, function (err, ex) {
// on err, ex is false
if (!ex) return loadpkg(
path.dirname(dir), cb
);
readFile(pkgfile, function (err, body) {
if (err) cb(err);
try { var pkg = JSON.parse(body) }
catch (err) {}
if (pkg && opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
cb(null, pkg, dir);
});
});
}
function loadAsDirectory (x, fpkg, cb) {
if (typeof fpkg === 'function') {
cb = fpkg;
fpkg = opts.package;
}
var pkgfile = path.join(x, '/package.json');
isFile(pkgfile, function (err, ex) {
if (err) return cb(err);
if (!ex) return loadAsFile(path.join(x, '/index'), fpkg, cb);
readFile(pkgfile, function (err, body) {
if (err) return cb(err);
try {
var pkg = JSON.parse(body);
}
catch (err) {}
if (opts.packageFilter) {
pkg = opts.packageFilter(pkg, pkgfile);
}
if (pkg.main) {
if (pkg.main === '.' || pkg.main === './'){
pkg.main = 'index'
}
loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
if (err) return cb(err);
if (m) return cb(null, m, pkg);
if (!pkg) return loadAsFile(path.join(x, '/index'), pkg, cb);
var dir = path.resolve(x, pkg.main);
loadAsDirectory(dir, pkg, function (err, n, pkg) {
if (err) return cb(err);
if (n) return cb(null, n, pkg);
loadAsFile(path.join(x, '/index'), pkg, cb);
});
});
return;
}
loadAsFile(path.join(x, '/index'), pkg, cb);
});
});
}
function loadNodeModules (x, start, cb) {
(function process (dirs) {
if (dirs.length === 0) return cb(null, undefined);
var dir = dirs[0];
var file = path.join(dir, '/', x);
loadAsFile(file, undefined, onfile);
function onfile (err, m, pkg) {
if (err) return cb(err);
if (m) return cb(null, m, pkg);
loadAsDirectory(path.join(dir, '/', x), undefined, ondir);
}
function ondir (err, n, pkg) {
if (err) return cb(err);
if (n) return cb(null, n, pkg);
process(dirs.slice(1));
}
})(nodeModulesPaths(start, opts));
}
};

View File

@ -0,0 +1,8 @@
module.exports = function () {
// see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
var origPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) { return stack };
var stack = (new Error()).stack;
Error.prepareStackTrace = origPrepareStackTrace;
return stack[2].getFileName();
};

Some files were not shown because too many files have changed in this diff Show More