parent
7486f16873
commit
e9b6e47ab8
5485 changed files with 42639 additions and 461559 deletions
@ -1,4 +1,10 @@ |
||||
const algorithm = require('./dist/solar-calculation'); |
||||
|
||||
const myJD = algorithm.dateToJD(new Date()) |
||||
console.log(algorithm.getSunInformation(new Date(), 3.597031, 98.678513)); |
||||
console.log(new Date().toString()); |
||||
console.log(algorithm.getSunInformation(new Date('Sat Apr 14 2018 12:02:33 GMT+0700 (WIB)'), 3.597031, 98.678513)); |
||||
console.log(algorithm.dateToJD(new Date('Sat Apr 14 2018 12:02:33 GMT+0700 (WIB)'))) |
||||
console.log(algorithm.getHourAngle( |
||||
algorithm.dateToJD(new Date('Sat Apr 14 2018 12:02:33 GMT+0700 (WIB)')), |
||||
algorithm.CLIENT_lw |
||||
)); |
@ -0,0 +1 @@ |
||||
../mocha/bin/_mocha |
@ -1 +0,0 @@ |
||||
../color-support/bin.js |
@ -1 +0,0 @@ |
||||
../coveralls/bin/coveralls.js |
@ -1 +0,0 @@ |
||||
../esprima/bin/esparse.js |
@ -1 +0,0 @@ |
||||
../esprima/bin/esvalidate.js |
@ -1 +0,0 @@ |
||||
../har-validator/bin/har-validator |
@ -0,0 +1 @@ |
||||
../he/bin/he |
@ -1 +0,0 @@ |
||||
../js-yaml/bin/js-yaml.js |
@ -0,0 +1 @@ |
||||
../mocha/bin/mocha |
@ -1 +0,0 @@ |
||||
../nyc/bin/nyc.js |
@ -1 +0,0 @@ |
||||
../opener/opener.js |
@ -1 +0,0 @@ |
||||
../rimraf/bin.js |
@ -1 +0,0 @@ |
||||
../sshpk/bin/sshpk-conv |
@ -1 +0,0 @@ |
||||
../sshpk/bin/sshpk-sign |
@ -1 +0,0 @@ |
||||
../sshpk/bin/sshpk-verify |
@ -1 +0,0 @@ |
||||
../tap/bin/run.js |
@ -1 +0,0 @@ |
||||
../tap-mocha-reporter/index.js |
@ -1 +0,0 @@ |
||||
../tap-parser/bin/cmd.js |
@ -1 +0,0 @@ |
||||
../uuid/bin/uuid |
@ -1 +0,0 @@ |
||||
../which/bin/which |
@ -1,4 +0,0 @@ |
||||
'use strict'; |
||||
module.exports = function () { |
||||
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; |
||||
}; |
@ -1,109 +0,0 @@ |
||||
{ |
||||
"_from": "ansi-regex@^2.0.0", |
||||
"_id": "ansi-regex@2.1.1", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", |
||||
"_location": "/ansi-regex", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "ansi-regex@^2.0.0", |
||||
"name": "ansi-regex", |
||||
"escapedName": "ansi-regex", |
||||
"rawSpec": "^2.0.0", |
||||
"saveSpec": null, |
||||
"fetchSpec": "^2.0.0" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/has-ansi", |
||||
"/strip-ansi" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", |
||||
"_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df", |
||||
"_spec": "ansi-regex@^2.0.0", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/has-ansi", |
||||
"author": { |
||||
"name": "Sindre Sorhus", |
||||
"email": "sindresorhus@gmail.com", |
||||
"url": "sindresorhus.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/chalk/ansi-regex/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"deprecated": false, |
||||
"description": "Regular expression for matching ANSI escape codes", |
||||
"devDependencies": { |
||||
"ava": "0.17.0", |
||||
"xo": "0.16.0" |
||||
}, |
||||
"engines": { |
||||
"node": ">=0.10.0" |
||||
}, |
||||
"files": [ |
||||
"index.js" |
||||
], |
||||
"homepage": "https://github.com/chalk/ansi-regex#readme", |
||||
"keywords": [ |
||||
"ansi", |
||||
"styles", |
||||
"color", |
||||
"colour", |
||||
"colors", |
||||
"terminal", |
||||
"console", |
||||
"cli", |
||||
"string", |
||||
"tty", |
||||
"escape", |
||||
"formatting", |
||||
"rgb", |
||||
"256", |
||||
"shell", |
||||
"xterm", |
||||
"command-line", |
||||
"text", |
||||
"regex", |
||||
"regexp", |
||||
"re", |
||||
"match", |
||||
"test", |
||||
"find", |
||||
"pattern" |
||||
], |
||||
"license": "MIT", |
||||
"maintainers": [ |
||||
{ |
||||
"name": "Sindre Sorhus", |
||||
"email": "sindresorhus@gmail.com", |
||||
"url": "sindresorhus.com" |
||||
}, |
||||
{ |
||||
"name": "Joshua Appelman", |
||||
"email": "jappelman@xebia.com", |
||||
"url": "jbnicolai.com" |
||||
}, |
||||
{ |
||||
"name": "JD Ballard", |
||||
"email": "i.am.qix@gmail.com", |
||||
"url": "github.com/qix-" |
||||
} |
||||
], |
||||
"name": "ansi-regex", |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git+https://github.com/chalk/ansi-regex.git" |
||||
}, |
||||
"scripts": { |
||||
"test": "xo && ava --verbose", |
||||
"view-supported": "node fixtures/view-codes.js" |
||||
}, |
||||
"version": "2.1.1", |
||||
"xo": { |
||||
"rules": { |
||||
"guard-for-in": 0, |
||||
"no-loop-func": 0 |
||||
} |
||||
} |
||||
} |
@ -1,39 +0,0 @@ |
||||
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) |
||||
|
||||
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) |
||||
|
||||
|
||||
## Install |
||||
|
||||
``` |
||||
$ npm install --save ansi-regex |
||||
``` |
||||
|
||||
|
||||
## Usage |
||||
|
||||
```js |
||||
const ansiRegex = require('ansi-regex'); |
||||
|
||||
ansiRegex().test('\u001b[4mcake\u001b[0m'); |
||||
//=> true |
||||
|
||||
ansiRegex().test('cake'); |
||||
//=> false |
||||
|
||||
'\u001b[4mcake\u001b[0m'.match(ansiRegex()); |
||||
//=> ['\u001b[4m', '\u001b[0m'] |
||||
``` |
||||
|
||||
## FAQ |
||||
|
||||
### Why do you test for codes not in the ECMA 48 standard? |
||||
|
||||
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. |
||||
|
||||
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. |
||||
|
||||
|
||||
## License |
||||
|
||||
MIT © [Sindre Sorhus](http://sindresorhus.com) |
@ -1,65 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
function assembleStyles () { |
||||
var styles = { |
||||
modifiers: { |
||||
reset: [0, 0], |
||||
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
|
||||
dim: [2, 22], |
||||
italic: [3, 23], |
||||
underline: [4, 24], |
||||
inverse: [7, 27], |
||||
hidden: [8, 28], |
||||
strikethrough: [9, 29] |
||||
}, |
||||
colors: { |
||||
black: [30, 39], |
||||
red: [31, 39], |
||||
green: [32, 39], |
||||
yellow: [33, 39], |
||||
blue: [34, 39], |
||||
magenta: [35, 39], |
||||
cyan: [36, 39], |
||||
white: [37, 39], |
||||
gray: [90, 39] |
||||
}, |
||||
bgColors: { |
||||
bgBlack: [40, 49], |
||||
bgRed: [41, 49], |
||||
bgGreen: [42, 49], |
||||
bgYellow: [43, 49], |
||||
bgBlue: [44, 49], |
||||
bgMagenta: [45, 49], |
||||
bgCyan: [46, 49], |
||||
bgWhite: [47, 49] |
||||
} |
||||
}; |
||||
|
||||
// fix humans
|
||||
styles.colors.grey = styles.colors.gray; |
||||
|
||||
Object.keys(styles).forEach(function (groupName) { |
||||
var group = styles[groupName]; |
||||
|
||||
Object.keys(group).forEach(function (styleName) { |
||||
var style = group[styleName]; |
||||
|
||||
styles[styleName] = group[styleName] = { |
||||
open: '\u001b[' + style[0] + 'm', |
||||
close: '\u001b[' + style[1] + 'm' |
||||
}; |
||||
}); |
||||
|
||||
Object.defineProperty(styles, groupName, { |
||||
value: group, |
||||
enumerable: false |
||||
}); |
||||
}); |
||||
|
||||
return styles; |
||||
} |
||||
|
||||
Object.defineProperty(module, 'exports', { |
||||
enumerable: true, |
||||
get: assembleStyles |
||||
}); |
@ -1,21 +0,0 @@ |
||||
The MIT License (MIT) |
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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. |
@ -1,90 +0,0 @@ |
||||
{ |
||||
"_from": "ansi-styles@^2.2.1", |
||||
"_id": "ansi-styles@2.2.1", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", |
||||
"_location": "/ansi-styles", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "ansi-styles@^2.2.1", |
||||
"name": "ansi-styles", |
||||
"escapedName": "ansi-styles", |
||||
"rawSpec": "^2.2.1", |
||||
"saveSpec": null, |
||||
"fetchSpec": "^2.2.1" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/chalk" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", |
||||
"_shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe", |
||||
"_spec": "ansi-styles@^2.2.1", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/chalk", |
||||
"author": { |
||||
"name": "Sindre Sorhus", |
||||
"email": "sindresorhus@gmail.com", |
||||
"url": "sindresorhus.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/chalk/ansi-styles/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"deprecated": false, |
||||
"description": "ANSI escape codes for styling strings in the terminal", |
||||
"devDependencies": { |
||||
"mocha": "*" |
||||
}, |
||||
"engines": { |
||||
"node": ">=0.10.0" |
||||
}, |
||||
"files": [ |
||||
"index.js" |
||||
], |
||||
"homepage": "https://github.com/chalk/ansi-styles#readme", |
||||
"keywords": [ |
||||
"ansi", |
||||
"styles", |
||||
"color", |
||||
"colour", |
||||
"colors", |
||||
"terminal", |
||||
"console", |
||||
"cli", |
||||
"string", |
||||
"tty", |
||||
"escape", |
||||
"formatting", |
||||
"rgb", |
||||
"256", |
||||
"shell", |
||||
"xterm", |
||||
"log", |
||||
"logging", |
||||
"command-line", |
||||
"text" |
||||
], |
||||
"license": "MIT", |
||||
"maintainers": [ |
||||
{ |
||||
"name": "Sindre Sorhus", |
||||
"email": "sindresorhus@gmail.com", |
||||
"url": "sindresorhus.com" |
||||
}, |
||||
{ |
||||
"name": "Joshua Appelman", |
||||
"email": "jappelman@xebia.com", |
||||
"url": "jbnicolai.com" |
||||
} |
||||
], |
||||
"name": "ansi-styles", |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git+https://github.com/chalk/ansi-styles.git" |
||||
}, |
||||
"scripts": { |
||||
"test": "mocha" |
||||
}, |
||||
"version": "2.2.1" |
||||
} |
@ -1,86 +0,0 @@ |
||||
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) |
||||
|
||||
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal |
||||
|
||||
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. |
||||
|
||||
![](screenshot.png) |
||||
|
||||
|
||||
## Install |
||||
|
||||
``` |
||||
$ npm install --save ansi-styles |
||||
``` |
||||
|
||||
|
||||
## Usage |
||||
|
||||
```js |
||||
var ansi = require('ansi-styles'); |
||||
|
||||
console.log(ansi.green.open + 'Hello world!' + ansi.green.close); |
||||
``` |
||||
|
||||
|
||||
## API |
||||
|
||||
Each style has an `open` and `close` property. |
||||
|
||||
|
||||
## Styles |
||||
|
||||
### Modifiers |
||||
|
||||
- `reset` |
||||
- `bold` |
||||
- `dim` |
||||
- `italic` *(not widely supported)* |
||||
- `underline` |
||||
- `inverse` |
||||
- `hidden` |
||||
- `strikethrough` *(not widely supported)* |
||||
|
||||
### Colors |
||||
|
||||
- `black` |
||||
- `red` |
||||
- `green` |
||||
- `yellow` |
||||
- `blue` |
||||
- `magenta` |
||||
- `cyan` |
||||
- `white` |
||||
- `gray` |
||||
|
||||
### Background colors |
||||
|
||||
- `bgBlack` |
||||
- `bgRed` |
||||
- `bgGreen` |
||||
- `bgYellow` |
||||
- `bgBlue` |
||||
- `bgMagenta` |
||||
- `bgCyan` |
||||
- `bgWhite` |
||||
|
||||
|
||||
## Advanced usage |
||||
|
||||
By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. |
||||
|
||||
- `ansi.modifiers` |
||||
- `ansi.colors` |
||||
- `ansi.bgColors` |
||||
|
||||
|
||||
###### Example |
||||
|
||||
```js |
||||
console.log(ansi.colors.green.open); |
||||
``` |
||||
|
||||
|
||||
## License |
||||
|
||||
MIT © [Sindre Sorhus](http://sindresorhus.com) |
@ -1,185 +0,0 @@ |
||||
1.0.10 / 2018-02-15 |
||||
------------------ |
||||
|
||||
- Use .concat instead of + for arrays, #122. |
||||
|
||||
|
||||
1.0.9 / 2016-09-29 |
||||
------------------ |
||||
|
||||
- Rerelease after 1.0.8 - deps cleanup. |
||||
|
||||
|
||||
1.0.8 / 2016-09-29 |
||||
------------------ |
||||
|
||||
- Maintenance (deps bump, fix node 6.5+ tests, coverage report). |
||||
|
||||
|
||||
1.0.7 / 2016-03-17 |
||||
------------------ |
||||
|
||||
- Teach `addArgument` to accept string arg names. #97, @tomxtobin. |
||||
|
||||
|
||||
1.0.6 / 2016-02-06 |
||||
------------------ |
||||
|
||||
- Maintenance: moved to eslint & updated CS. |
||||
|
||||
|
||||
1.0.5 / 2016-02-05 |
||||
------------------ |
||||
|
||||
- Removed lodash dependency to significantly reduce install size. |
||||
Thanks to @mourner. |
||||
|
||||
|
||||
1.0.4 / 2016-01-17 |
||||
------------------ |
||||
|
||||
- Maintenance: lodash update to 4.0.0. |
||||
|
||||
|
||||
1.0.3 / 2015-10-27 |
||||
------------------ |
||||
|
||||
- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. |
||||
|
||||
|
||||
1.0.2 / 2015-03-22 |
||||
------------------ |
||||
|
||||
- Relaxed lodash version dependency. |
||||
|
||||
|
||||
1.0.1 / 2015-02-20 |
||||
------------------ |
||||
|
||||
- Changed dependencies to be compatible with ancient nodejs. |
||||
|
||||
|
||||
1.0.0 / 2015-02-19 |
||||
------------------ |
||||
|
||||
- Maintenance release. |
||||
- Replaced `underscore` with `lodash`. |
||||
- Bumped version to 1.0.0 to better reflect semver meaning. |
||||
- HISTORY.md -> CHANGELOG.md |
||||
|
||||
|
||||
0.1.16 / 2013-12-01 |
||||
------------------- |
||||
|
||||
- Maintenance release. Updated dependencies and docs. |
||||
|
||||
|
||||
0.1.15 / 2013-05-13 |
||||
------------------- |
||||
|
||||
- Fixed #55, @trebor89 |
||||
|
||||
|
||||
0.1.14 / 2013-05-12 |
||||
------------------- |
||||
|
||||
- Fixed #62, @maxtaco |
||||
|
||||
|
||||
0.1.13 / 2013-04-08 |
||||
------------------- |
||||
|
||||
- Added `.npmignore` to reduce package size |
||||
|
||||
|
||||
0.1.12 / 2013-02-10 |
||||
------------------- |
||||
|
||||
- Fixed conflictHandler (#46), @hpaulj |
||||
|
||||
|
||||
0.1.11 / 2013-02-07 |
||||
------------------- |
||||
|
||||
- Multiple bugfixes, @hpaulj |
||||
- Added 70+ tests (ported from python), @hpaulj |
||||
- Added conflictHandler, @applepicke |
||||
- Added fromfilePrefixChar, @hpaulj |
||||
|
||||
|
||||
0.1.10 / 2012-12-30 |
||||
------------------- |
||||
|
||||
- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) |
||||
support, thanks to @hpaulj |
||||
- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj |
||||
|
||||
|
||||
0.1.9 / 2012-12-27 |
||||
------------------ |
||||
|
||||
- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj |
||||
- Fixed default value behavior with `*` positionals, thanks to @hpaulj |
||||
- Improve `getDefault()` behavior, thanks to @hpaulj |
||||
- Imrove negative argument parsing, thanks to @hpaulj |
||||
|
||||
|
||||
0.1.8 / 2012-12-01 |
||||
------------------ |
||||
|
||||
- Fixed parser parents (issue #19), thanks to @hpaulj |
||||
- Fixed negative argument parse (issue #20), thanks to @hpaulj |
||||
|
||||
|
||||
0.1.7 / 2012-10-14 |
||||
------------------ |
||||
|
||||
- Fixed 'choices' argument parse (issue #16) |
||||
- Fixed stderr output (issue #15) |
||||
|
||||
|
||||
0.1.6 / 2012-09-09 |
||||
------------------ |
||||
|
||||
- Fixed check for conflict of options (thanks to @tomxtobin) |
||||
|
||||
|
||||
0.1.5 / 2012-09-03 |
||||
------------------ |
||||
|
||||
- Fix parser #setDefaults method (thanks to @tomxtobin) |
||||
|
||||
|
||||
0.1.4 / 2012-07-30 |
||||
------------------ |
||||
|
||||
- Fixed pseudo-argument support (thanks to @CGamesPlay) |
||||
- Fixed addHelp default (should be true), if not set (thanks to @benblank) |
||||
|
||||
|
||||
0.1.3 / 2012-06-27 |
||||
------------------ |
||||
|
||||
- Fixed formatter api name: Formatter -> HelpFormatter |
||||
|
||||
|
||||
0.1.2 / 2012-05-29 |
||||
------------------ |
||||
|
||||
- Added basic tests |
||||
- Removed excess whitespace in help |
||||
- Fixed error reporting, when parcer with subcommands |
||||
called with empty arguments |
||||
|
||||
|
||||
0.1.1 / 2012-05-23 |
||||
------------------ |
||||
|
||||
- Fixed line wrapping in help formatter |
||||
- Added better error reporting on invalid arguments |
||||
|
||||
|
||||
0.1.0 / 2012-05-16 |
||||
------------------ |
||||
|
||||
- First release. |
@ -1,21 +0,0 @@ |
||||
(The MIT License) |
||||
|
||||
Copyright (C) 2012 by Vitaly Puzrin |
||||
|
||||
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. |
@ -1,257 +0,0 @@ |
||||
argparse |
||||
======== |
||||
|
||||
[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) |
||||
[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) |
||||
|
||||
CLI arguments parser for node.js. Javascript port of python's |
||||
[argparse](http://docs.python.org/dev/library/argparse.html) module |
||||
(original version 3.2). That's a full port, except some very rare options, |
||||
recorded in issue tracker. |
||||
|
||||
**NB. Difference with original.** |
||||
|
||||
- Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). |
||||
- Use `defaultValue` instead of `default`. |
||||
- Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and |
||||
similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` |
||||
(aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and |
||||
`SUPPRESS`. |
||||
|
||||
|
||||
Example |
||||
======= |
||||
|
||||
test.js file: |
||||
|
||||
```javascript |
||||
#!/usr/bin/env node |
||||
'use strict'; |
||||
|
||||
var ArgumentParser = require('../lib/argparse').ArgumentParser; |
||||
var parser = new ArgumentParser({ |
||||
version: '0.0.1', |
||||
addHelp:true, |
||||
description: 'Argparse example' |
||||
}); |
||||
parser.addArgument( |
||||
[ '-f', '--foo' ], |
||||
{ |
||||
help: 'foo bar' |
||||
} |
||||
); |
||||
parser.addArgument( |
||||
[ '-b', '--bar' ], |
||||
{ |
||||
help: 'bar foo' |
||||
} |
||||
); |
||||
parser.addArgument( |
||||
'--baz', |
||||
{ |
||||
help: 'baz bar' |
||||
} |
||||
); |
||||
var args = parser.parseArgs(); |
||||
console.dir(args); |
||||
``` |
||||
|
||||
Display help: |
||||
|
||||
``` |
||||
$ ./test.js -h |
||||
usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] |
||||
|
||||
Argparse example |
||||
|
||||
Optional arguments: |
||||
-h, --help Show this help message and exit. |
||||
-v, --version Show program's version number and exit. |
||||
-f FOO, --foo FOO foo bar |
||||
-b BAR, --bar BAR bar foo |
||||
--baz BAZ baz bar |
||||
``` |
||||
|
||||
Parse arguments: |
||||
|
||||
``` |
||||
$ ./test.js -f=3 --bar=4 --baz 5 |
||||
{ foo: '3', bar: '4', baz: '5' } |
||||
``` |
||||
|
||||
More [examples](https://github.com/nodeca/argparse/tree/master/examples). |
||||
|
||||
|
||||
ArgumentParser objects |
||||
====================== |
||||
|
||||
``` |
||||
new ArgumentParser({parameters hash}); |
||||
``` |
||||
|
||||
Creates a new ArgumentParser object. |
||||
|
||||
**Supported params:** |
||||
|
||||
- ```description``` - Text to display before the argument help. |
||||
- ```epilog``` - Text to display after the argument help. |
||||
- ```addHelp``` - Add a -h/–help option to the parser. (default: true) |
||||
- ```argumentDefault``` - Set the global default value for arguments. (default: null) |
||||
- ```parents``` - A list of ArgumentParser objects whose arguments should also be included. |
||||
- ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) |
||||
- ```formatterClass``` - A class for customizing the help output. |
||||
- ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) |
||||
- ```usage``` - The string describing the program usage (default: generated) |
||||
- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. |
||||
|
||||
**Not supported yet** |
||||
|
||||
- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. |
||||
|
||||
|
||||
Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) |
||||
|
||||
|
||||
addArgument() method |
||||
==================== |
||||
|
||||
``` |
||||
ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) |
||||
``` |
||||
|
||||
Defines how a single command-line argument should be parsed. |
||||
|
||||
- ```name or flag or [name] or [flags...]``` - Either a positional name |
||||
(e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array |
||||
of a single positional name (e.g., `['foo']`), or an array of options |
||||
(e.g., `['-f', '--foo']`). |
||||
|
||||
Options: |
||||
|
||||
- ```action``` - The basic type of action to be taken when this argument is encountered at the command line. |
||||
- ```nargs```- The number of command-line arguments that should be consumed. |
||||
- ```constant``` - A constant value required by some action and nargs selections. |
||||
- ```defaultValue``` - The value produced if the argument is absent from the command line. |
||||
- ```type``` - The type to which the command-line argument should be converted. |
||||
- ```choices``` - A container of the allowable values for the argument. |
||||
- ```required``` - Whether or not the command-line option may be omitted (optionals only). |
||||
- ```help``` - A brief description of what the argument does. |
||||
- ```metavar``` - A name for the argument in usage messages. |
||||
- ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). |
||||
|
||||
Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) |
||||
|
||||
|
||||
Action (some details) |
||||
================ |
||||
|
||||
ArgumentParser objects associate command-line arguments with actions. |
||||
These actions can do just about anything with the command-line arguments associated |
||||
with them, though most actions simply add an attribute to the object returned by |
||||
parseArgs(). The action keyword argument specifies how the command-line arguments |
||||
should be handled. The supported actions are: |
||||
|
||||
- ```store``` - Just stores the argument’s value. This is the default action. |
||||
- ```storeConst``` - Stores value, specified by the const keyword argument. |
||||
(Note that the const keyword argument defaults to the rather unhelpful None.) |
||||
The 'storeConst' action is most commonly used with optional arguments, that |
||||
specify some sort of flag. |
||||
- ```storeTrue``` and ```storeFalse``` - Stores values True and False |
||||
respectively. These are special cases of 'storeConst'. |
||||
- ```append``` - Stores a list, and appends each argument value to the list. |
||||
This is useful to allow an option to be specified multiple times. |
||||
- ```appendConst``` - Stores a list, and appends value, specified by the |
||||
const keyword argument to the list. (Note, that the const keyword argument defaults |
||||
is None.) The 'appendConst' action is typically used when multiple arguments need |
||||
to store constants to the same list. |
||||
- ```count``` - Counts the number of times a keyword argument occurs. For example, |
||||
used for increasing verbosity levels. |
||||
- ```help``` - Prints a complete help message for all the options in the current |
||||
parser and then exits. By default a help action is automatically added to the parser. |
||||
See ArgumentParser for details of how the output is created. |
||||
- ```version``` - Prints version information and exit. Expects a `version=` |
||||
keyword argument in the addArgument() call. |
||||
|
||||
Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) |
||||
|
||||
|
||||
Sub-commands |
||||
============ |
||||
|
||||
ArgumentParser.addSubparsers() |
||||
|
||||
Many programs split their functionality into a number of sub-commands, for |
||||
example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, |
||||
and `svn commit`. Splitting up functionality this way can be a particularly good |
||||
idea when a program performs several different functions which require different |
||||
kinds of command-line arguments. `ArgumentParser` supports creation of such |
||||
sub-commands with `addSubparsers()` method. The `addSubparsers()` method is |
||||
normally called with no arguments and returns an special action object. |
||||
This object has a single method `addParser()`, which takes a command name and |
||||
any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object |
||||
that can be modified as usual. |
||||
|
||||
Example: |
||||
|
||||
sub_commands.js |
||||
```javascript |
||||
#!/usr/bin/env node |
||||
'use strict'; |
||||
|
||||
var ArgumentParser = require('../lib/argparse').ArgumentParser; |
||||
var parser = new ArgumentParser({ |
||||
version: '0.0.1', |
||||
addHelp:true, |
||||
description: 'Argparse examples: sub-commands', |
||||
}); |
||||
|
||||
var subparsers = parser.addSubparsers({ |
||||
title:'subcommands', |
||||
dest:"subcommand_name" |
||||
}); |
||||
|
||||
var bar = subparsers.addParser('c1', {addHelp:true}); |
||||
bar.addArgument( |
||||
[ '-f', '--foo' ], |
||||
{ |
||||
action: 'store', |
||||
help: 'foo3 bar3' |
||||
} |
||||
); |
||||
var bar = subparsers.addParser( |
||||
'c2', |
||||
{aliases:['co'], addHelp:true} |
||||
); |
||||
bar.addArgument( |
||||
[ '-b', '--bar' ], |
||||
{ |
||||
action: 'store', |
||||
type: 'int', |
||||
help: 'foo3 bar3' |
||||
} |
||||
); |
||||
|
||||
var args = parser.parseArgs(); |
||||
console.dir(args); |
||||
|
||||
``` |
||||
|
||||
Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) |
||||
|
||||
|
||||
Contributors |
||||
============ |
||||
|
||||
- [Eugene Shkuropat](https://github.com/shkuropat) |
||||
- [Paul Jacobson](https://github.com/hpaulj) |
||||
|
||||
[others](https://github.com/nodeca/argparse/graphs/contributors) |
||||
|
||||
License |
||||
======= |
||||
|
||||
Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). |
||||
Released under the MIT license. See |
||||
[LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. |
||||
|
||||
|
@ -1,3 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
module.exports = require('./lib/argparse'); |
@ -1,146 +0,0 @@ |
||||
/** |
||||
* class Action |
||||
* |
||||
* Base class for all actions |
||||
* Do not call in your code, use this class only for inherits your own action |
||||
* |
||||
* Information about how to convert command line strings to Javascript objects. |
||||
* Action objects are used by an ArgumentParser to represent the information |
||||
* needed to parse a single argument from one or more strings from the command |
||||
* line. The keyword arguments to the Action constructor are also all attributes |
||||
* of Action instances. |
||||
* |
||||
* ##### Allowed keywords: |
||||
* |
||||
* - `store` |
||||
* - `storeConstant` |
||||
* - `storeTrue` |
||||
* - `storeFalse` |
||||
* - `append` |
||||
* - `appendConstant` |
||||
* - `count` |
||||
* - `help` |
||||
* - `version` |
||||
* |
||||
* Information about action options see [[Action.new]] |
||||
* |
||||
* See also [original guide](http://docs.python.org/dev/library/argparse.html#action)
|
||||
* |
||||
**/ |
||||
|
||||
'use strict'; |
||||
|
||||
|
||||
// Constants
|
||||
var c = require('./const'); |
||||
|
||||
|
||||
/** |
||||
* new Action(options) |
||||
* |
||||
* Base class for all actions. Used only for inherits |
||||
* |
||||
* |
||||
* ##### Options: |
||||
* |
||||
* - `optionStrings` A list of command-line option strings for the action. |
||||
* - `dest` Attribute to hold the created object(s) |
||||
* - `nargs` The number of command-line arguments that should be consumed. |
||||
* By default, one argument will be consumed and a single value will be |
||||
* produced. |
||||
* - `constant` Default value for an action with no value. |
||||
* - `defaultValue` The value to be produced if the option is not specified. |
||||
* - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If |
||||
* None, 'string'. |
||||
* - `choices` The choices available. |
||||
* - `required` True if the action must always be specified at the command |
||||
* line. |
||||
* - `help` The help describing the argument. |
||||
* - `metavar` The name to be used for the option's argument with the help |
||||
* string. If None, the 'dest' value will be used as the name. |
||||
* |
||||
* ##### nargs supported values: |
||||
* |
||||
* - `N` (an integer) consumes N arguments (and produces a list) |
||||
* - `?` consumes zero or one arguments |
||||
* - `*` consumes zero or more arguments (and produces a list) |
||||
* - `+` consumes one or more arguments (and produces a list) |
||||
* |
||||
* Note: that the difference between the default and nargs=1 is that with the |
||||
* default, a single value will be produced, while with nargs=1, a list |
||||
* containing a single value will be produced. |
||||
**/ |
||||
var Action = module.exports = function Action(options) { |
||||
options = options || {}; |
||||
this.optionStrings = options.optionStrings || []; |
||||
this.dest = options.dest; |
||||
this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null; |
||||
this.constant = typeof options.constant !== 'undefined' ? options.constant : null; |
||||
this.defaultValue = options.defaultValue; |
||||
this.type = typeof options.type !== 'undefined' ? options.type : null; |
||||
this.choices = typeof options.choices !== 'undefined' ? options.choices : null; |
||||
this.required = typeof options.required !== 'undefined' ? options.required : false; |
||||
this.help = typeof options.help !== 'undefined' ? options.help : null; |
||||
this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null; |
||||
|
||||
if (!(this.optionStrings instanceof Array)) { |
||||
throw new Error('optionStrings should be an array'); |
||||
} |
||||
if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') { |
||||
throw new Error('required should be a boolean'); |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* Action#getName -> String |
||||
* |
||||
* Tells action name |
||||
**/ |
||||
Action.prototype.getName = function () { |
||||
if (this.optionStrings.length > 0) { |
||||
return this.optionStrings.join('/'); |
||||
} else if (this.metavar !== null && this.metavar !== c.SUPPRESS) { |
||||
return this.metavar; |
||||
} else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) { |
||||
return this.dest; |
||||
} |
||||
return null; |
||||
}; |
||||
|
||||
/** |
||||
* Action#isOptional -> Boolean |
||||
* |
||||
* Return true if optional |
||||
**/ |
||||
Action.prototype.isOptional = function () { |
||||
return !this.isPositional(); |
||||
}; |
||||
|
||||
/** |
||||
* Action#isPositional -> Boolean |
||||
* |
||||
* Return true if positional |
||||
**/ |
||||
Action.prototype.isPositional = function () { |
||||
return (this.optionStrings.length === 0); |
||||
}; |
||||
|
||||
/** |
||||
* Action#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Should be implemented in inherited classes |
||||
* |
||||
* ##### Example |
||||
* |
||||
* ActionCount.prototype.call = function (parser, namespace, values, optionString) { |
||||
* namespace.set(this.dest, (namespace[this.dest] || 0) + 1); |
||||
* }; |
||||
* |
||||
**/ |
||||
Action.prototype.call = function () { |
||||
throw new Error('.call() not defined');// Not Implemented error
|
||||
}; |
@ -1,53 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionAppend |
||||
* |
||||
* This action stores a list, and appends each argument value to the list. |
||||
* This is useful to allow an option to be specified multiple times. |
||||
* This class inherided from [[Action]] |
||||
* |
||||
**/ |
||||
|
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../action'); |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionAppend(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
* Note: options.nargs should be optional for constants |
||||
* and more then zero for other |
||||
**/ |
||||
var ActionAppend = module.exports = function ActionAppend(options) { |
||||
options = options || {}; |
||||
if (this.nargs <= 0) { |
||||
throw new Error('nargs for append actions must be > 0; if arg ' + |
||||
'strings are not supplying the value to append, ' + |
||||
'the append const action may be more appropriate'); |
||||
} |
||||
if (!!this.constant && this.nargs !== c.OPTIONAL) { |
||||
throw new Error('nargs must be OPTIONAL to supply const'); |
||||
} |
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionAppend, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionAppend#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Save result in namespace object |
||||
**/ |
||||
ActionAppend.prototype.call = function (parser, namespace, values) { |
||||
var items = (namespace[this.dest] || []).slice(); |
||||
items.push(values); |
||||
namespace.set(this.dest, items); |
||||
}; |
@ -1,47 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionAppendConstant |
||||
* |
||||
* This stores a list, and appends the value specified by |
||||
* the const keyword argument to the list. |
||||
* (Note that the const keyword argument defaults to null.) |
||||
* The 'appendConst' action is typically useful when multiple |
||||
* arguments need to store constants to the same list. |
||||
* |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
|
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../../action'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionAppendConstant(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { |
||||
options = options || {}; |
||||
options.nargs = 0; |
||||
if (typeof options.constant === 'undefined') { |
||||
throw new Error('constant option is required for appendAction'); |
||||
} |
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionAppendConstant, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionAppendConstant#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Save result in namespace object |
||||
**/ |
||||
ActionAppendConstant.prototype.call = function (parser, namespace) { |
||||
var items = [].concat(namespace[this.dest] || []); |
||||
items.push(this.constant); |
||||
namespace.set(this.dest, items); |
||||
}; |
@ -1,40 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionCount |
||||
* |
||||
* This counts the number of times a keyword argument occurs. |
||||
* For example, this is useful for increasing verbosity levels |
||||
* |
||||
* This class inherided from [[Action]] |
||||
* |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../action'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionCount(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionCount = module.exports = function ActionCount(options) { |
||||
options = options || {}; |
||||
options.nargs = 0; |
||||
|
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionCount, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionCount#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Save result in namespace object |
||||
**/ |
||||
ActionCount.prototype.call = function (parser, namespace) { |
||||
namespace.set(this.dest, (namespace[this.dest] || 0) + 1); |
||||
}; |
@ -1,47 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionHelp |
||||
* |
||||
* Support action for printing help |
||||
* This class inherided from [[Action]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../action'); |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionHelp(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionHelp = module.exports = function ActionHelp(options) { |
||||
options = options || {}; |
||||
if (options.defaultValue !== null) { |
||||
options.defaultValue = options.defaultValue; |
||||
} else { |
||||
options.defaultValue = c.SUPPRESS; |
||||
} |
||||
options.dest = (options.dest !== null ? options.dest : c.SUPPRESS); |
||||
options.nargs = 0; |
||||
Action.call(this, options); |
||||
|
||||
}; |
||||
util.inherits(ActionHelp, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionHelp#call(parser, namespace, values, optionString) |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Print help and exit |
||||
**/ |
||||
ActionHelp.prototype.call = function (parser) { |
||||
parser.printHelp(); |
||||
parser.exit(); |
||||
}; |
@ -1,50 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionStore |
||||
* |
||||
* This action just stores the argument’s value. This is the default action. |
||||
* |
||||
* This class inherited from [[Action]] |
||||
* |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../action'); |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
|
||||
/*:nodoc:* |
||||
* new ActionStore(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionStore = module.exports = function ActionStore(options) { |
||||
options = options || {}; |
||||
if (this.nargs <= 0) { |
||||
throw new Error('nargs for store actions must be > 0; if you ' + |
||||
'have nothing to store, actions such as store ' + |
||||
'true or store const may be more appropriate'); |
||||
|
||||
} |
||||
if (typeof this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) { |
||||
throw new Error('nargs must be OPTIONAL to supply const'); |
||||
} |
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionStore, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionStore#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Save result in namespace object |
||||
**/ |
||||
ActionStore.prototype.call = function (parser, namespace, values) { |
||||
namespace.set(this.dest, values); |
||||
}; |
@ -1,43 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionStoreConstant |
||||
* |
||||
* This action stores the value specified by the const keyword argument. |
||||
* (Note that the const keyword argument defaults to the rather unhelpful null.) |
||||
* The 'store_const' action is most commonly used with optional |
||||
* arguments that specify some sort of flag. |
||||
* |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../../action'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionStoreConstant(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { |
||||
options = options || {}; |
||||
options.nargs = 0; |
||||
if (typeof options.constant === 'undefined') { |
||||
throw new Error('constant option is required for storeAction'); |
||||
} |
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionStoreConstant, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionStoreConstant#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Save result in namespace object |
||||
**/ |
||||
ActionStoreConstant.prototype.call = function (parser, namespace) { |
||||
namespace.set(this.dest, this.constant); |
||||
}; |
@ -1,27 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionStoreFalse |
||||
* |
||||
* This action store the values False respectively. |
||||
* This is special cases of 'storeConst' |
||||
* |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
|
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var ActionStoreConstant = require('./constant'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionStoreFalse(options) |
||||
* - options (object): hash of options see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionStoreFalse = module.exports = function ActionStoreFalse(options) { |
||||
options = options || {}; |
||||
options.constant = false; |
||||
options.defaultValue = options.defaultValue !== null ? options.defaultValue : true; |
||||
ActionStoreConstant.call(this, options); |
||||
}; |
||||
util.inherits(ActionStoreFalse, ActionStoreConstant); |
@ -1,26 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionStoreTrue |
||||
* |
||||
* This action store the values True respectively. |
||||
* This isspecial cases of 'storeConst' |
||||
* |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var ActionStoreConstant = require('./constant'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionStoreTrue(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { |
||||
options = options || {}; |
||||
options.constant = true; |
||||
options.defaultValue = options.defaultValue !== null ? options.defaultValue : false; |
||||
ActionStoreConstant.call(this, options); |
||||
}; |
||||
util.inherits(ActionStoreTrue, ActionStoreConstant); |
@ -1,149 +0,0 @@ |
||||
/** internal |
||||
* class ActionSubparsers |
||||
* |
||||
* Support the creation of such sub-commands with the addSubparsers() |
||||
* |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
var format = require('util').format; |
||||
|
||||
|
||||
var Action = require('../action'); |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
// Errors
|
||||
var argumentErrorHelper = require('../argument/error'); |
||||
|
||||
|
||||
/*:nodoc:* |
||||
* new ChoicesPseudoAction(name, help) |
||||
* |
||||
* Create pseudo action for correct help text |
||||
* |
||||
**/ |
||||
function ChoicesPseudoAction(name, help) { |
||||
var options = { |
||||
optionStrings: [], |
||||
dest: name, |
||||
help: help |
||||
}; |
||||
|
||||
Action.call(this, options); |
||||
} |
||||
|
||||
util.inherits(ChoicesPseudoAction, Action); |
||||
|
||||
/** |
||||
* new ActionSubparsers(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
function ActionSubparsers(options) { |
||||
options = options || {}; |
||||
options.dest = options.dest || c.SUPPRESS; |
||||
options.nargs = c.PARSER; |
||||
|
||||
this.debug = (options.debug === true); |
||||
|
||||
this._progPrefix = options.prog; |
||||
this._parserClass = options.parserClass; |
||||
this._nameParserMap = {}; |
||||
this._choicesActions = []; |
||||
|
||||
options.choices = this._nameParserMap; |
||||
Action.call(this, options); |
||||
} |
||||
|
||||
util.inherits(ActionSubparsers, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionSubparsers#addParser(name, options) -> ArgumentParser |
||||
* - name (string): sub-command name |
||||
* - options (object): see [[ArgumentParser.new]] |
||||
* |
||||
* Note: |
||||
* addParser supports an additional aliases option, |
||||
* which allows multiple strings to refer to the same subparser. |
||||
* This example, like svn, aliases co as a shorthand for checkout |
||||
* |
||||
**/ |
||||
ActionSubparsers.prototype.addParser = function (name, options) { |
||||
var parser; |
||||
|
||||
var self = this; |
||||
|
||||
options = options || {}; |
||||
|
||||
options.debug = (this.debug === true); |
||||
|
||||
// set program from the existing prefix
|
||||
if (!options.prog) { |
||||
options.prog = this._progPrefix + ' ' + name; |
||||
} |
||||
|
||||
var aliases = options.aliases || []; |
||||
|
||||
// create a pseudo-action to hold the choice help
|
||||
if (!!options.help || typeof options.help === 'string') { |
||||
var help = options.help; |
||||
delete options.help; |
||||
|
||||
var choiceAction = new ChoicesPseudoAction(name, help); |
||||
this._choicesActions.push(choiceAction); |
||||
} |
||||
|
||||
// create the parser and add it to the map
|
||||
parser = new this._parserClass(options); |
||||
this._nameParserMap[name] = parser; |
||||
|
||||
// make parser available under aliases also
|
||||
aliases.forEach(function (alias) { |
||||
self._nameParserMap[alias] = parser; |
||||
}); |
||||
|
||||
return parser; |
||||
}; |
||||
|
||||
ActionSubparsers.prototype._getSubactions = function () { |
||||
return this._choicesActions; |
||||
}; |
||||
|
||||
/*:nodoc:* |
||||
* ActionSubparsers#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Call the action. Parse input aguments |
||||
**/ |
||||
ActionSubparsers.prototype.call = function (parser, namespace, values) { |
||||
var parserName = values[0]; |
||||
var argStrings = values.slice(1); |
||||
|
||||
// set the parser name if requested
|
||||
if (this.dest !== c.SUPPRESS) { |
||||
namespace[this.dest] = parserName; |
||||
} |
||||
|
||||
// select the parser
|
||||
if (this._nameParserMap[parserName]) { |
||||
parser = this._nameParserMap[parserName]; |
||||
} else { |
||||
throw argumentErrorHelper(format( |
||||
'Unknown parser "%s" (choices: [%s]).', |
||||
parserName, |
||||
Object.keys(this._nameParserMap).join(', ') |
||||
)); |
||||
} |
||||
|
||||
// parse all the remaining options into the namespace
|
||||
parser.parseArgs(argStrings, namespace); |
||||
}; |
||||
|
||||
module.exports = ActionSubparsers; |
@ -1,47 +0,0 @@ |
||||
/*:nodoc:* |
||||
* class ActionVersion |
||||
* |
||||
* Support action for printing program version |
||||
* This class inherited from [[Action]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var Action = require('../action'); |
||||
|
||||
//
|
||||
// Constants
|
||||
//
|
||||
var c = require('../const'); |
||||
|
||||
/*:nodoc:* |
||||
* new ActionVersion(options) |
||||
* - options (object): options hash see [[Action.new]] |
||||
* |
||||
**/ |
||||
var ActionVersion = module.exports = function ActionVersion(options) { |
||||
options = options || {}; |
||||
options.defaultValue = (options.defaultValue ? options.defaultValue : c.SUPPRESS); |
||||
options.dest = (options.dest || c.SUPPRESS); |
||||
options.nargs = 0; |
||||
this.version = options.version; |
||||
Action.call(this, options); |
||||
}; |
||||
util.inherits(ActionVersion, Action); |
||||
|
||||
/*:nodoc:* |
||||
* ActionVersion#call(parser, namespace, values, optionString) -> Void |
||||
* - parser (ArgumentParser): current parser |
||||
* - namespace (Namespace): namespace for output data |
||||
* - values (Array): parsed values |
||||
* - optionString (Array): input option string(not parsed) |
||||
* |
||||
* Print version and exit |
||||
**/ |
||||
ActionVersion.prototype.call = function (parser) { |
||||
var version = this.version || parser.version; |
||||
var formatter = parser._getFormatter(); |
||||
formatter.addText(version); |
||||
parser.exit(0, formatter.formatHelp()); |
||||
}; |
@ -1,482 +0,0 @@ |
||||
/** internal |
||||
* class ActionContainer |
||||
* |
||||
* Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] |
||||
**/ |
||||
|
||||
'use strict'; |
||||
|
||||
var format = require('util').format; |
||||
|
||||
// Constants
|
||||
var c = require('./const'); |
||||
|
||||
var $$ = require('./utils'); |
||||
|
||||
//Actions
|
||||
var ActionHelp = require('./action/help'); |
||||
var ActionAppend = require('./action/append'); |
||||
var ActionAppendConstant = require('./action/append/constant'); |
||||
var ActionCount = require('./action/count'); |
||||
var ActionStore = require('./action/store'); |
||||
var ActionStoreConstant = require('./action/store/constant'); |
||||
var ActionStoreTrue = require('./action/store/true'); |
||||
var ActionStoreFalse = require('./action/store/false'); |
||||
var ActionVersion = require('./action/version'); |
||||
var ActionSubparsers = require('./action/subparsers'); |
||||
|
||||
// Errors
|
||||
var argumentErrorHelper = require('./argument/error'); |
||||
|
||||
/** |
||||
* new ActionContainer(options) |
||||
* |
||||
* Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] |
||||
* |
||||
* ##### Options: |
||||
* |
||||
* - `description` -- A description of what the program does |
||||
* - `prefixChars` -- Characters that prefix optional arguments |
||||
* - `argumentDefault` -- The default value for all arguments |
||||
* - `conflictHandler` -- The conflict handler to use for duplicate arguments |
||||
**/ |
||||
var ActionContainer = module.exports = function ActionContainer(options) { |
||||
options = options || {}; |
||||
|
||||
this.description = options.description; |
||||
this.argumentDefault = options.argumentDefault; |
||||
this.prefixChars = options.prefixChars || ''; |
||||
this.conflictHandler = options.conflictHandler; |
||||
|
||||
// set up registries
|
||||
this._registries = {}; |
||||
|
||||
// register actions
|
||||
this.register('action', null, ActionStore); |
||||
this.register('action', 'store', ActionStore); |
||||
this.register('action', 'storeConst', ActionStoreConstant); |
||||
this.register('action', 'storeTrue', ActionStoreTrue); |
||||
this.register('action', 'storeFalse', ActionStoreFalse); |
||||
this.register('action', 'append', ActionAppend); |
||||
this.register('action', 'appendConst', ActionAppendConstant); |
||||
this.register('action', 'count', ActionCount); |
||||
this.register('action', 'help', ActionHelp); |
||||
this.register('action', 'version', ActionVersion); |
||||
this.register('action', 'parsers', ActionSubparsers); |
||||
|
||||
// raise an exception if the conflict handler is invalid
|
||||
this._getHandler(); |
||||
|
||||
// action storage
|
||||
this._actions = []; |
||||
this._optionStringActions = {}; |
||||
|
||||
// groups
|
||||
this._actionGroups = []; |
||||
this._mutuallyExclusiveGroups = []; |
||||
|
||||
// defaults storage
|
||||
this._defaults = {}; |
||||
|
||||
// determines whether an "option" looks like a negative number
|
||||
// -1, -1.5 -5e+4
|
||||
this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); |
||||
|
||||
// whether or not there are any optionals that look like negative
|
||||
// numbers -- uses a list so it can be shared and edited
|
||||
this._hasNegativeNumberOptionals = []; |
||||
}; |
||||
|
||||
// Groups must be required, then ActionContainer already defined
|
||||
var ArgumentGroup = require('./argument/group'); |
||||
var MutuallyExclusiveGroup = require('./argument/exclusive'); |
||||
|
||||
//
|
||||
// Registration methods
|
||||
//
|
||||
|
||||
/** |
||||
* ActionContainer#register(registryName, value, object) -> Void |
||||
* - registryName (String) : object type action|type |
||||
* - value (string) : keyword |
||||
* - object (Object|Function) : handler |
||||
* |
||||
* Register handlers |
||||
**/ |
||||
ActionContainer.prototype.register = function (registryName, value, object) { |
||||
this._registries[registryName] = this._registries[registryName] || {}; |
||||
this._registries[registryName][value] = object; |
||||
}; |
||||
|
||||
ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { |
||||
if (arguments.length < 3) { |
||||
defaultValue = null; |
||||
} |
||||
return this._registries[registryName][value] || defaultValue; |
||||
}; |
||||
|
||||
//
|
||||
// Namespace default accessor methods
|
||||
//
|
||||
|
||||
/** |
||||
* ActionContainer#setDefaults(options) -> Void |
||||
* - options (object):hash of options see [[Action.new]] |
||||
* |
||||
* Set defaults |
||||
**/ |
||||
ActionContainer.prototype.setDefaults = function (options) { |
||||
options = options || {}; |
||||
for (var property in options) { |
||||
if ($$.has(options, property)) { |
||||
this._defaults[property] = options[property]; |
||||
} |
||||
} |
||||
|
||||
// if these defaults match any existing arguments, replace the previous
|
||||
// default on the object with the new one
|
||||
this._actions.forEach(function (action) { |
||||
if ($$.has(options, action.dest)) { |
||||
action.defaultValue = options[action.dest]; |
||||
} |
||||
}); |
||||
}; |
||||
|
||||
/** |
||||
* ActionContainer#getDefault(dest) -> Mixed |
||||
* - dest (string): action destination |
||||
* |
||||
* Return action default value |
||||
**/ |
||||
ActionContainer.prototype.getDefault = function (dest) { |
||||
var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null; |
||||
|
||||
this._actions.forEach(function (action) { |
||||
if (action.dest === dest && $$.has(action, 'defaultValue')) { |
||||
result = action.defaultValue; |
||||
} |
||||
}); |
||||
|
||||
return result; |
||||
}; |
||||
//
|
||||
// Adding argument actions
|
||||
//
|
||||
|
||||
/** |
||||
* ActionContainer#addArgument(args, options) -> Object |
||||
* - args (String|Array): argument key, or array of argument keys |
||||
* - options (Object): action objects see [[Action.new]] |
||||
* |
||||
* #### Examples |
||||
* - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... }) |
||||
* - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... }) |
||||
* - addArgument('--baz', { action: 'store', nargs: 1, ... }) |
||||
**/ |
||||
ActionContainer.prototype.addArgument = function (args, options) { |
||||
args = args; |
||||
options = options || {}; |
||||
|
||||
if (typeof args === 'string') { |
||||
args = [ args ]; |
||||
} |
||||
if (!Array.isArray(args)) { |
||||
throw new TypeError('addArgument first argument should be a string or an array'); |
||||
} |
||||
if (typeof options !== 'object' || Array.isArray(options)) { |
||||
throw new TypeError('addArgument second argument should be a hash'); |
||||
} |
||||
|
||||
// if no positional args are supplied or only one is supplied and
|
||||
// it doesn't look like an option string, parse a positional argument
|
||||
if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { |
||||
if (args && !!options.dest) { |
||||
throw new Error('dest supplied twice for positional argument'); |
||||
} |
||||
options = this._getPositional(args, options); |
||||
|
||||
// otherwise, we're adding an optional argument
|
||||
} else { |
||||
options = this._getOptional(args, options); |
||||
} |
||||
|
||||
// if no default was supplied, use the parser-level default
|
||||
if (typeof options.defaultValue === 'undefined') { |
||||
var dest = options.dest; |
||||
if ($$.has(this._defaults, dest)) { |
||||
options.defaultValue = this._defaults[dest]; |
||||
} else if (typeof this.argumentDefault !== 'undefined') { |
||||
options.defaultValue = this.argumentDefault; |
||||
} |
||||
} |
||||
|
||||
// create the action object, and add it to the parser
|
||||
var ActionClass = this._popActionClass(options); |
||||
if (typeof ActionClass !== 'function') { |
||||
throw new Error(format('Unknown action "%s".', ActionClass)); |
||||
} |
||||
var action = new ActionClass(options); |
||||
|
||||
// throw an error if the action type is not callable
|
||||
var typeFunction = this._registryGet('type', action.type, action.type); |
||||
if (typeof typeFunction !== 'function') { |
||||
throw new Error(format('"%s" is not callable', typeFunction)); |
||||
} |
||||
|
||||
return this._addAction(action); |
||||
}; |
||||
|
||||
/** |
||||
* ActionContainer#addArgumentGroup(options) -> ArgumentGroup |
||||
* - options (Object): hash of options see [[ArgumentGroup.new]] |
||||
* |
||||
* Create new arguments groups |
||||
**/ |
||||
ActionContainer.prototype.addArgumentGroup = function (options) { |
||||
var group = new ArgumentGroup(this, options); |
||||
this._actionGroups.push(group); |
||||
return group; |
||||
}; |
||||
|
||||
/** |
||||
* ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup |
||||
* - options (Object): {required: false} |
||||
* |
||||
* Create new mutual exclusive groups |
||||
**/ |
||||
ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { |
||||
var group = new MutuallyExclusiveGroup(this, options); |
||||
this._mutuallyExclusiveGroups.push(group); |
||||
return group; |
||||
}; |
||||
|
||||
ActionContainer.prototype._addAction = function (action) { |
||||
var self = this; |
||||
|
||||
// resolve any conflicts
|
||||
this._checkConflict(action); |
||||
|
||||
// add to actions list
|
||||
this._actions.push(action); |
||||
action.container = this; |
||||
|
||||
// index the action by any option strings it has
|
||||
action.optionStrings.forEach(function (optionString) { |
||||
self._optionStringActions[optionString] = action; |
||||
}); |
||||
|
||||
// set the flag if any option strings look like negative numbers
|
||||
action.optionStrings.forEach(function (optionString) { |
||||
if (optionString.match(self._regexpNegativeNumber)) { |
||||
if (!self._hasNegativeNumberOptionals.some(Boolean)) { |
||||
self._hasNegativeNumberOptionals.push(true); |
||||
} |
||||
} |
||||
}); |
||||
|
||||
// return the created action
|
||||
return action; |
||||
}; |
||||
|
||||
ActionContainer.prototype._removeAction = function (action) { |
||||
var actionIndex = this._actions.indexOf(action); |
||||
if (actionIndex >= 0) { |
||||
this._actions.splice(actionIndex, 1); |
||||
} |
||||
}; |
||||
|
||||
ActionContainer.prototype._addContainerActions = function (container) { |
||||
// collect groups by titles
|
||||
var titleGroupMap = {}; |
||||
this._actionGroups.forEach(function (group) { |
||||
if (titleGroupMap[group.title]) { |
||||
throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); |
||||
} |
||||
titleGroupMap[group.title] = group; |
||||
}); |
||||
|
||||
// map each action to its group
|
||||
var groupMap = {}; |
||||
function actionHash(action) { |
||||
// unique (hopefully?) string suitable as dictionary key
|
||||
return action.getName(); |
||||
} |
||||
container._actionGroups.forEach(function (group) { |
||||
// if a group with the title exists, use that, otherwise
|
||||
// create a new group matching the container's group
|
||||
if (!titleGroupMap[group.title]) { |
||||
titleGroupMap[group.title] = this.addArgumentGroup({ |
||||
title: group.title, |
||||
description: group.description |
||||
}); |
||||
} |
||||
|
||||
// map the actions to their new group
|
||||
group._groupActions.forEach(function (action) { |
||||
groupMap[actionHash(action)] = titleGroupMap[group.title]; |
||||
}); |
||||
}, this); |
||||
|
||||
// add container's mutually exclusive groups
|
||||
// NOTE: if add_mutually_exclusive_group ever gains title= and
|
||||
// description= then this code will need to be expanded as above
|
||||
var mutexGroup; |
||||
container._mutuallyExclusiveGroups.forEach(function (group) { |
||||
mutexGroup = this.addMutuallyExclusiveGroup({ |
||||
required: group.required |
||||
}); |
||||
// map the actions to their new mutex group
|
||||
group._groupActions.forEach(function (action) { |
||||
groupMap[actionHash(action)] = mutexGroup; |
||||
}); |
||||
}, this); // forEach takes a 'this' argument
|
||||
|
||||
// add all actions to this container or their group
|
||||
container._actions.forEach(function (action) { |
||||
var key = actionHash(action); |
||||
if (groupMap[key]) { |
||||
groupMap[key]._addAction(action); |
||||
} else { |
||||
this._addAction(action); |
||||
} |
||||
}); |
||||
}; |
||||
|
||||
ActionContainer.prototype._getPositional = function (dest, options) { |
||||
if (Array.isArray(dest)) { |
||||
dest = dest[0]; |
||||
} |
||||
// make sure required is not specified
|
||||
if (options.required) { |
||||
throw new Error('"required" is an invalid argument for positionals.'); |
||||
} |
||||
|
||||
// mark positional arguments as required if at least one is
|
||||
// always required
|
||||
if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) { |
||||
options.required = true; |
||||
} |
||||
if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') { |
||||
options.required = true; |
||||
} |
||||
|
||||
// return the keyword arguments with no option strings
|
||||
options.dest = dest; |
||||
options.optionStrings = []; |
||||
return options; |
||||
}; |
||||
|
||||
ActionContainer.prototype._getOptional = function (args, options) { |
||||
var prefixChars = this.prefixChars; |
||||
var optionStrings = []; |
||||
var optionStringsLong = []; |
||||
|
||||
// determine short and long option strings
|
||||
args.forEach(function (optionString) { |
||||
// error on strings that don't start with an appropriate prefix
|
||||
if (prefixChars.indexOf(optionString[0]) < 0) { |
||||
throw new Error(format('Invalid option string "%s": must start with a "%s".', |
||||
optionString, |
||||
prefixChars |
||||
)); |
||||
} |
||||
|
||||
// strings starting with two prefix characters are long options
|
||||
optionStrings.push(optionString); |
||||
if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { |
||||
optionStringsLong.push(optionString); |
||||
} |
||||
}); |
||||
|
||||
// infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
|
||||
var dest = options.dest || null; |
||||
delete options.dest; |
||||
|
||||
if (!dest) { |
||||
var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0]; |
||||
dest = $$.trimChars(optionStringDest, this.prefixChars); |
||||
|
||||
if (dest.length === 0) { |
||||
throw new Error( |
||||
format('dest= is required for options like "%s"', optionStrings.join(', ')) |
||||
); |
||||
} |
||||
dest = dest.replace(/-/g, '_'); |
||||
} |
||||
|
||||
// return the updated keyword arguments
|
||||
options.dest = dest; |
||||
options.optionStrings = optionStrings; |
||||
|
||||
return options; |
||||
}; |
||||
|
||||
ActionContainer.prototype._popActionClass = function (options, defaultValue) { |
||||
defaultValue = defaultValue || null; |
||||
|
||||
var action = (options.action || defaultValue); |
||||
delete options.action; |
||||
|
||||
var actionClass = this._registryGet('action', action, action); |
||||
return actionClass; |
||||
}; |
||||
|
||||
ActionContainer.prototype._getHandler = function () { |
||||
var handlerString = this.conflictHandler; |
||||
var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString); |
||||
var func = this[handlerFuncName]; |
||||
if (typeof func === 'undefined') { |
||||
var msg = 'invalid conflict resolution value: ' + handlerString; |
||||
throw new Error(msg); |
||||
} else { |
||||
return func; |
||||
} |
||||
}; |
||||
|
||||
ActionContainer.prototype._checkConflict = function (action) { |
||||
var optionStringActions = this._optionStringActions; |
||||
var conflictOptionals = []; |
||||
|
||||
// find all options that conflict with this option
|
||||
// collect pairs, the string, and an existing action that it conflicts with
|
||||
action.optionStrings.forEach(function (optionString) { |
||||
var conflOptional = optionStringActions[optionString]; |
||||
if (typeof conflOptional !== 'undefined') { |
||||
conflictOptionals.push([ optionString, conflOptional ]); |
||||
} |
||||
}); |
||||
|
||||
if (conflictOptionals.length > 0) { |
||||
var conflictHandler = this._getHandler(); |
||||
conflictHandler.call(this, action, conflictOptionals); |
||||
} |
||||
}; |
||||
|
||||
ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { |
||||
var conflicts = conflOptionals.map(function (pair) { return pair[0]; }); |
||||
conflicts = conflicts.join(', '); |
||||
throw argumentErrorHelper( |
||||
action, |
||||
format('Conflicting option string(s): %s', conflicts) |
||||
); |
||||
}; |
||||
|
||||
ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { |
||||
// remove all conflicting options
|
||||
var self = this; |
||||
conflOptionals.forEach(function (pair) { |
||||
var optionString = pair[0]; |
||||
var conflictingAction = pair[1]; |
||||
// remove the conflicting option string
|
||||
var i = conflictingAction.optionStrings.indexOf(optionString); |
||||
if (i >= 0) { |
||||
conflictingAction.optionStrings.splice(i, 1); |
||||
} |
||||
delete self._optionStringActions[optionString]; |
||||
// if the option now has no option string, remove it from the
|
||||
// container holding it
|
||||
if (conflictingAction.optionStrings.length === 0) { |
||||
conflictingAction.container._removeAction(conflictingAction); |
||||
} |
||||
}); |
||||
}; |
@ -1,14 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
module.exports.ArgumentParser = require('./argument_parser.js'); |
||||
module.exports.Namespace = require('./namespace'); |
||||
module.exports.Action = require('./action'); |
||||
module.exports.HelpFormatter = require('./help/formatter.js'); |
||||
module.exports.Const = require('./const.js'); |
||||
|
||||
module.exports.ArgumentDefaultsHelpFormatter = |
||||
require('./help/added_formatters.js').ArgumentDefaultsHelpFormatter; |
||||
module.exports.RawDescriptionHelpFormatter = |
||||
require('./help/added_formatters.js').RawDescriptionHelpFormatter; |
||||
module.exports.RawTextHelpFormatter = |
||||
require('./help/added_formatters.js').RawTextHelpFormatter; |
@ -1,50 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
|
||||
var format = require('util').format; |
||||
|
||||
|
||||
var ERR_CODE = 'ARGError'; |
||||
|
||||
/*:nodoc:* |
||||
* argumentError(argument, message) -> TypeError |
||||
* - argument (Object): action with broken argument |
||||
* - message (String): error message |
||||
* |
||||
* Error format helper. An error from creating or using an argument |
||||
* (optional or positional). The string value of this exception |
||||
* is the message, augmented with information |
||||
* about the argument that caused it. |
||||
* |
||||
* #####Example |
||||
* |
||||
* var argumentErrorHelper = require('./argument/error'); |
||||
* if (conflictOptionals.length > 0) { |
||||
* throw argumentErrorHelper( |
||||
* action, |
||||
* format('Conflicting option string(s): %s', conflictOptionals.join(', ')) |
||||
* ); |
||||
* } |
||||
* |
||||
**/ |
||||
module.exports = function (argument, message) { |
||||
var argumentName = null; |
||||
var errMessage; |
||||
var err; |
||||
|
||||
if (argument.getName) { |
||||
argumentName = argument.getName(); |
||||
} else { |
||||
argumentName = '' + argument; |
||||
} |
||||
|
||||
if (!argumentName) { |
||||
errMessage = message; |
||||
} else { |
||||
errMessage = format('argument "%s": %s', argumentName, message); |
||||
} |
||||
|
||||
err = new TypeError(errMessage); |
||||
err.code = ERR_CODE; |
||||
return err; |
||||
}; |
@ -1,54 +0,0 @@ |
||||
/** internal |
||||
* class MutuallyExclusiveGroup |
||||
* |
||||
* Group arguments. |
||||
* By default, ArgumentParser groups command-line arguments |
||||
* into “positional arguments” and “optional arguments” |
||||
* when displaying help messages. When there is a better |
||||
* conceptual grouping of arguments than this default one, |
||||
* appropriate groups can be created using the addArgumentGroup() method |
||||
* |
||||
* This class inherited from [[ArgumentContainer]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var ArgumentGroup = require('./group'); |
||||
|
||||
/** |
||||
* new MutuallyExclusiveGroup(container, options) |
||||
* - container (object): main container |
||||
* - options (object): options.required -> true/false |
||||
* |
||||
* `required` could be an argument itself, but making it a property of |
||||
* the options argument is more consistent with the JS adaptation of the Python) |
||||
**/ |
||||
var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { |
||||
var required; |
||||
options = options || {}; |
||||
required = options.required || false; |
||||
ArgumentGroup.call(this, container); |
||||
this.required = required; |
||||
|
||||
}; |
||||
util.inherits(MutuallyExclusiveGroup, ArgumentGroup); |
||||
|
||||
|
||||
MutuallyExclusiveGroup.prototype._addAction = function (action) { |
||||
var msg; |
||||
if (action.required) { |
||||
msg = 'mutually exclusive arguments must be optional'; |
||||
throw new Error(msg); |
||||
} |
||||
action = this._container._addAction(action); |
||||
this._groupActions.push(action); |
||||
return action; |
||||
}; |
||||
|
||||
|
||||
MutuallyExclusiveGroup.prototype._removeAction = function (action) { |
||||
this._container._removeAction(action); |
||||
this._groupActions.remove(action); |
||||
}; |
||||
|
@ -1,75 +0,0 @@ |
||||
/** internal |
||||
* class ArgumentGroup |
||||
* |
||||
* Group arguments. |
||||
* By default, ArgumentParser groups command-line arguments |
||||
* into “positional arguments” and “optional arguments” |
||||
* when displaying help messages. When there is a better |
||||
* conceptual grouping of arguments than this default one, |
||||
* appropriate groups can be created using the addArgumentGroup() method |
||||
* |
||||
* This class inherited from [[ArgumentContainer]] |
||||
**/ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
var ActionContainer = require('../action_container'); |
||||
|
||||
|
||||
/** |
||||
* new ArgumentGroup(container, options) |
||||
* - container (object): main container |
||||
* - options (object): hash of group options |
||||
* |
||||
* #### options |
||||
* - **prefixChars** group name prefix |
||||
* - **argumentDefault** default argument value |
||||
* - **title** group title |
||||
* - **description** group description |
||||
* |
||||
**/ |
||||
var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { |
||||
|
||||
options = options || {}; |
||||
|
||||
// add any missing keyword arguments by checking the container
|
||||
options.conflictHandler = (options.conflictHandler || container.conflictHandler); |
||||
options.prefixChars = (options.prefixChars || container.prefixChars); |
||||
options.argumentDefault = (options.argumentDefault || container.argumentDefault); |
||||
|
||||
ActionContainer.call(this, options); |
||||
|
||||
// group attributes
|
||||
this.title = options.title; |
||||
this._groupActions = []; |
||||
|
||||
// share most attributes with the container
|
||||
this._container = container; |
||||
this._registries = container._registries; |
||||
this._actions = container._actions; |
||||
this._optionStringActions = container._optionStringActions; |
||||
this._defaults = container._defaults; |
||||
this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; |
||||
this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; |
||||
}; |
||||
util.inherits(ArgumentGroup, ActionContainer); |
||||
|
||||
|
||||
ArgumentGroup.prototype._addAction = function (action) { |
||||
// Parent add action
|
||||
action = ActionContainer.prototype._addAction.call(this, action); |
||||
this._groupActions.push(action); |
||||
return action; |
||||
}; |
||||
|
||||
|
||||
ArgumentGroup.prototype._removeAction = function (action) { |
||||
// Parent remove action
|
||||
ActionContainer.prototype._removeAction.call(this, action); |
||||
var actionIndex = this._groupActions.indexOf(action); |
||||
if (actionIndex >= 0) { |
||||
this._groupActions.splice(actionIndex, 1); |
||||
} |
||||
}; |
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,21 +0,0 @@ |
||||
//
|
||||
// Constants
|
||||
//
|
||||
|
||||
'use strict'; |
||||
|
||||
module.exports.EOL = '\n'; |
||||
|
||||
module.exports.SUPPRESS = '==SUPPRESS=='; |
||||
|
||||
module.exports.OPTIONAL = '?'; |
||||
|
||||
module.exports.ZERO_OR_MORE = '*'; |
||||
|
||||
module.exports.ONE_OR_MORE = '+'; |
||||
|
||||
module.exports.PARSER = 'A...'; |
||||
|
||||
module.exports.REMAINDER = '...'; |
||||
|
||||
module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'; |
@ -1,87 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
var util = require('util'); |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
var $$ = require('../utils'); |
||||
var HelpFormatter = require('./formatter.js'); |
||||
|
||||
/** |
||||
* new RawDescriptionHelpFormatter(options) |
||||
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) |
||||
* |
||||
* Help message formatter which adds default values to argument help. |
||||
* |
||||
* Only the name of this class is considered a public API. All the methods |
||||
* provided by the class are considered an implementation detail. |
||||
**/ |
||||
|
||||
function ArgumentDefaultsHelpFormatter(options) { |
||||
HelpFormatter.call(this, options); |
||||
} |
||||
|
||||
util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); |
||||
|
||||
ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { |
||||
var help = action.help; |
||||
if (action.help.indexOf('%(defaultValue)s') === -1) { |
||||
if (action.defaultValue !== c.SUPPRESS) { |
||||
var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ]; |
||||
if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { |
||||
help += ' (default: %(defaultValue)s)'; |
||||
} |
||||
} |
||||
} |
||||
return help; |
||||
}; |
||||
|
||||
module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; |
||||
|
||||
/** |
||||
* new RawDescriptionHelpFormatter(options) |
||||
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) |
||||
* |
||||
* Help message formatter which retains any formatting in descriptions. |
||||
* |
||||
* Only the name of this class is considered a public API. All the methods |
||||
* provided by the class are considered an implementation detail. |
||||
**/ |
||||
|
||||
function RawDescriptionHelpFormatter(options) { |
||||
HelpFormatter.call(this, options); |
||||
} |
||||
|
||||
util.inherits(RawDescriptionHelpFormatter, HelpFormatter); |
||||
|
||||
RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { |
||||
var lines = text.split('\n'); |
||||
lines = lines.map(function (line) { |
||||
return $$.trimEnd(indent + line); |
||||
}); |
||||
return lines.join('\n'); |
||||
}; |
||||
module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; |
||||
|
||||
/** |
||||
* new RawTextHelpFormatter(options) |
||||
* new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) |
||||
* |
||||
* Help message formatter which retains formatting of all help text. |
||||
* |
||||
* Only the name of this class is considered a public API. All the methods |
||||
* provided by the class are considered an implementation detail. |
||||
**/ |
||||
|
||||
function RawTextHelpFormatter(options) { |
||||
RawDescriptionHelpFormatter.call(this, options); |
||||
} |
||||
|
||||
util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); |
||||
|
||||
RawTextHelpFormatter.prototype._splitLines = function (text) { |
||||
return text.split('\n'); |
||||
}; |
||||
|
||||
module.exports.RawTextHelpFormatter = RawTextHelpFormatter; |
@ -1,795 +0,0 @@ |
||||
/** |
||||
* class HelpFormatter |
||||
* |
||||
* Formatter for generating usage messages and argument help strings. Only the |
||||
* name of this class is considered a public API. All the methods provided by |
||||
* the class are considered an implementation detail. |
||||
* |
||||
* Do not call in your code, use this class only for inherits your own forvatter |
||||
* |
||||
* ToDo add [additonal formatters][1] |
||||
* |
||||
* [1]:http://docs.python.org/dev/library/argparse.html#formatter-class
|
||||
**/ |
||||
'use strict'; |
||||
|
||||
var sprintf = require('sprintf-js').sprintf; |
||||
|
||||
// Constants
|
||||
var c = require('../const'); |
||||
|
||||
var $$ = require('../utils'); |
||||
|
||||
|
||||
/*:nodoc:* internal |
||||
* new Support(parent, heding) |
||||
* - parent (object): parent section |
||||
* - heading (string): header string |
||||
* |
||||
**/ |
||||
function Section(parent, heading) { |
||||
this._parent = parent; |
||||
this._heading = heading; |
||||
this._items = []; |
||||
} |
||||
|
||||
/*:nodoc:* internal |
||||
* Section#addItem(callback) -> Void |
||||
* - callback (array): tuple with function and args |
||||
* |
||||
* Add function for single element |
||||
**/ |
||||
Section.prototype.addItem = function (callback) { |
||||
this._items.push(callback); |
||||
}; |
||||
|
||||
/*:nodoc:* internal |
||||
* Section#formatHelp(formatter) -> string |
||||
* - formatter (HelpFormatter): current formatter |
||||
* |
||||
* Form help section string |
||||
* |
||||
**/ |
||||
Section.prototype.formatHelp = function (formatter) { |
||||
var itemHelp, heading; |
||||
|
||||
// format the indented section
|
||||
if (this._parent) { |
||||
formatter._indent(); |
||||
} |
||||
|
||||
itemHelp = this._items.map(function (item) { |
||||
var obj, func, args; |
||||
|
||||
obj = formatter; |
||||
func = item[0]; |
||||
args = item[1]; |
||||
return func.apply(obj, args); |
||||
}); |
||||
itemHelp = formatter._joinParts(itemHelp); |
||||
|
||||
if (this._parent) { |
||||
formatter._dedent(); |
||||
} |
||||
|
||||
// return nothing if the section was empty
|
||||
if (!itemHelp) { |
||||
return ''; |
||||
} |
||||
|
||||
// add the heading if the section was non-empty
|
||||
heading = ''; |
||||
if (this._heading && this._heading !== c.SUPPRESS) { |
||||
var currentIndent = formatter.currentIndent; |
||||
heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL; |
||||
} |
||||
|
||||
// join the section-initialize newline, the heading and the help
|
||||
return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]); |
||||
}; |
||||
|
||||
/** |
||||
* new HelpFormatter(options) |
||||
* |
||||
* #### Options: |
||||
* - `prog`: program name |
||||
* - `indentIncriment`: indent step, default value 2 |
||||
* - `maxHelpPosition`: max help position, default value = 24 |
||||
* - `width`: line width |
||||
* |
||||
**/ |
||||
var HelpFormatter = module.exports = function HelpFormatter(options) { |
||||
options = options || {}; |
||||
|
||||
this._prog = options.prog; |
||||
|
||||
this._maxHelpPosition = options.maxHelpPosition || 24; |
||||
this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); |
||||
|
||||
this._currentIndent = 0; |
||||
this._indentIncriment = options.indentIncriment || 2; |
||||
this._level = 0; |
||||
this._actionMaxLength = 0; |
||||
|
||||
this._rootSection = new Section(null); |
||||
this._currentSection = this._rootSection; |
||||
|
||||
this._whitespaceMatcher = new RegExp('\\s+', 'g'); |
||||
this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g'); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._indent = function () { |
||||
this._currentIndent += this._indentIncriment; |
||||
this._level += 1; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._dedent = function () { |
||||
this._currentIndent -= this._indentIncriment; |
||||
this._level -= 1; |
||||
if (this._currentIndent < 0) { |
||||
throw new Error('Indent decreased below 0.'); |
||||
} |
||||
}; |
||||
|
||||
HelpFormatter.prototype._addItem = function (func, args) { |
||||
this._currentSection.addItem([ func, args ]); |
||||
}; |
||||
|
||||
//
|
||||
// Message building methods
|
||||
//
|
||||
|
||||
/** |
||||
* HelpFormatter#startSection(heading) -> Void |
||||
* - heading (string): header string |
||||
* |
||||
* Start new help section |
||||
* |
||||
* See alse [code example][1] |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.startSection(actionGroup.title); |
||||
* formatter.addText(actionGroup.description); |
||||
* formatter.addArguments(actionGroup._groupActions); |
||||
* formatter.endSection(); |
||||
* |
||||
**/ |
||||
HelpFormatter.prototype.startSection = function (heading) { |
||||
this._indent(); |
||||
var section = new Section(this._currentSection, heading); |
||||
var func = section.formatHelp.bind(section); |
||||
this._addItem(func, [ this ]); |
||||
this._currentSection = section; |
||||
}; |
||||
|
||||
/** |
||||
* HelpFormatter#endSection -> Void |
||||
* |
||||
* End help section |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.startSection(actionGroup.title); |
||||
* formatter.addText(actionGroup.description); |
||||
* formatter.addArguments(actionGroup._groupActions); |
||||
* formatter.endSection(); |
||||
**/ |
||||
HelpFormatter.prototype.endSection = function () { |
||||
this._currentSection = this._currentSection._parent; |
||||
this._dedent(); |
||||
}; |
||||
|
||||
/** |
||||
* HelpFormatter#addText(text) -> Void |
||||
* - text (string): plain text |
||||
* |
||||
* Add plain text into current section |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.startSection(actionGroup.title); |
||||
* formatter.addText(actionGroup.description); |
||||
* formatter.addArguments(actionGroup._groupActions); |
||||
* formatter.endSection(); |
||||
* |
||||
**/ |
||||
HelpFormatter.prototype.addText = function (text) { |
||||
if (text && text !== c.SUPPRESS) { |
||||
this._addItem(this._formatText, [ text ]); |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void |
||||
* - usage (string): usage text |
||||
* - actions (array): actions list |
||||
* - groups (array): groups list |
||||
* - prefix (string): usage prefix |
||||
* |
||||
* Add usage data into current section |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.addUsage(this.usage, this._actions, []); |
||||
* return formatter.formatHelp(); |
||||
* |
||||
**/ |
||||
HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { |
||||
if (usage !== c.SUPPRESS) { |
||||
this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]); |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* HelpFormatter#addArgument(action) -> Void |
||||
* - action (object): action |
||||
* |
||||
* Add argument into current section |
||||
* |
||||
* Single variant of [[HelpFormatter#addArguments]] |
||||
**/ |
||||
HelpFormatter.prototype.addArgument = function (action) { |
||||
if (action.help !== c.SUPPRESS) { |
||||
var self = this; |
||||
|
||||
// find all invocations
|
||||
var invocations = [ this._formatActionInvocation(action) ]; |
||||
var invocationLength = invocations[0].length; |
||||
|
||||
var actionLength; |
||||
|
||||
if (action._getSubactions) { |
||||
this._indent(); |
||||
action._getSubactions().forEach(function (subaction) { |
||||
|
||||
var invocationNew = self._formatActionInvocation(subaction); |
||||
invocations.push(invocationNew); |
||||
invocationLength = Math.max(invocationLength, invocationNew.length); |
||||
|
||||
}); |
||||
this._dedent(); |
||||
} |
||||
|
||||
// update the maximum item length
|
||||
actionLength = invocationLength + this._currentIndent; |
||||
this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); |
||||
|
||||
// add the item to the list
|
||||
this._addItem(this._formatAction, [ action ]); |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* HelpFormatter#addArguments(actions) -> Void |
||||
* - actions (array): actions list |
||||
* |
||||
* Mass add arguments into current section |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.startSection(actionGroup.title); |
||||
* formatter.addText(actionGroup.description); |
||||
* formatter.addArguments(actionGroup._groupActions); |
||||
* formatter.endSection(); |
||||
* |
||||
**/ |
||||
HelpFormatter.prototype.addArguments = function (actions) { |
||||
var self = this; |
||||
actions.forEach(function (action) { |
||||
self.addArgument(action); |
||||
}); |
||||
}; |
||||
|
||||
//
|
||||
// Help-formatting methods
|
||||
//
|
||||
|
||||
/** |
||||
* HelpFormatter#formatHelp -> string |
||||
* |
||||
* Format help |
||||
* |
||||
* ##### Example |
||||
* |
||||
* formatter.addText(this.epilog); |
||||
* return formatter.formatHelp(); |
||||
* |
||||
**/ |
||||
HelpFormatter.prototype.formatHelp = function () { |
||||
var help = this._rootSection.formatHelp(this); |
||||
if (help) { |
||||
help = help.replace(this._longBreakMatcher, c.EOL + c.EOL); |
||||
help = $$.trimChars(help, c.EOL) + c.EOL; |
||||
} |
||||
return help; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._joinParts = function (partStrings) { |
||||
return partStrings.filter(function (part) { |
||||
return (part && part !== c.SUPPRESS); |
||||
}).join(''); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { |
||||
if (!prefix && typeof prefix !== 'string') { |
||||
prefix = 'usage: '; |
||||
} |
||||
|
||||
actions = actions || []; |
||||
groups = groups || []; |
||||
|
||||
|
||||
// if usage is specified, use that
|
||||
if (usage) { |
||||
usage = sprintf(usage, { prog: this._prog }); |
||||
|
||||
// if no optionals or positionals are available, usage is just prog
|
||||
} else if (!usage && actions.length === 0) { |
||||
usage = this._prog; |
||||
|
||||
// if optionals and positionals are available, calculate usage
|
||||
} else if (!usage) { |
||||
var prog = this._prog; |
||||
var optionals = []; |
||||
var positionals = []; |
||||
var actionUsage; |
||||
var textWidth; |
||||
|
||||
// split optionals from positionals
|
||||
actions.forEach(function (action) { |
||||
if (action.isOptional()) { |
||||
optionals.push(action); |
||||
} else { |
||||
positionals.push(action); |
||||
} |
||||
}); |
||||
|
||||
// build full usage string
|
||||
actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); |
||||
usage = [ prog, actionUsage ].join(' '); |
||||
|
||||
// wrap the usage parts if it's too long
|
||||
textWidth = this._width - this._currentIndent; |
||||
if ((prefix.length + usage.length) > textWidth) { |
||||
|
||||
// break usage into wrappable parts
|
||||
var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); |
||||
var optionalUsage = this._formatActionsUsage(optionals, groups); |
||||
var positionalUsage = this._formatActionsUsage(positionals, groups); |
||||
|
||||
|
||||
var optionalParts = optionalUsage.match(regexpPart); |
||||
var positionalParts = positionalUsage.match(regexpPart) || []; |
||||
|
||||
if (optionalParts.join(' ') !== optionalUsage) { |
||||
throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); |
||||
} |
||||
if (positionalParts.join(' ') !== positionalUsage) { |
||||
throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); |
||||
} |
||||
|
||||
// helper for wrapping lines
|
||||
/*eslint-disable func-style*/ // node 0.10 compat
|
||||
var _getLines = function (parts, indent, prefix) { |
||||
var lines = []; |
||||
var line = []; |
||||
|
||||
var lineLength = prefix ? prefix.length - 1 : indent.length - 1; |
||||
|
||||
parts.forEach(function (part) { |
||||
if (lineLength + 1 + part.length > textWidth) { |
||||
lines.push(indent + line.join(' ')); |
||||
line = []; |
||||
lineLength = indent.length - 1; |
||||
} |
||||
line.push(part); |
||||
lineLength += part.length + 1; |
||||
}); |
||||
|
||||
if (line) { |
||||
lines.push(indent + line.join(' ')); |
||||
} |
||||
if (prefix) { |
||||
lines[0] = lines[0].substr(indent.length); |
||||
} |
||||
return lines; |
||||
}; |
||||
|
||||
var lines, indent, parts; |
||||
// if prog is short, follow it with optionals or positionals
|
||||
if (prefix.length + prog.length <= 0.75 * textWidth) { |
||||
indent = $$.repeat(' ', (prefix.length + prog.length + 1)); |
||||
if (optionalParts) { |
||||
lines = [].concat( |
||||
_getLines([ prog ].concat(optionalParts), indent, prefix), |
||||
_getLines(positionalParts, indent) |
||||
); |
||||
} else if (positionalParts) { |
||||
lines = _getLines([ prog ].concat(positionalParts), indent, prefix); |
||||
} else { |
||||
lines = [ prog ]; |
||||
} |
||||
|
||||
// if prog is long, put it on its own line
|
||||
} else { |
||||
indent = $$.repeat(' ', prefix.length); |
||||
parts = optionalParts.concat(positionalParts); |
||||
lines = _getLines(parts, indent); |
||||
if (lines.length > 1) { |
||||
lines = [].concat( |
||||
_getLines(optionalParts, indent), |
||||
_getLines(positionalParts, indent) |
||||
); |
||||
} |
||||
lines = [ prog ].concat(lines); |
||||
} |
||||
// join lines into usage
|
||||
usage = lines.join(c.EOL); |
||||
} |
||||
} |
||||
|
||||
// prefix with 'usage:'
|
||||
return prefix + usage + c.EOL + c.EOL; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { |
||||
// find group indices and identify actions in groups
|
||||
var groupActions = []; |
||||
var inserts = []; |
||||
var self = this; |
||||
|
||||
groups.forEach(function (group) { |
||||
var end; |
||||
var i; |
||||
|
||||
var start = actions.indexOf(group._groupActions[0]); |
||||
if (start >= 0) { |
||||
end = start + group._groupActions.length; |
||||
|
||||
//if (actions.slice(start, end) === group._groupActions) {
|
||||
if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) { |
||||
group._groupActions.forEach(function (action) { |
||||
groupActions.push(action); |
||||
}); |
||||
|
||||
if (!group.required) { |
||||
if (inserts[start]) { |
||||
inserts[start] += ' ['; |
||||
} else { |
||||
inserts[start] = '['; |
||||
} |
||||
inserts[end] = ']'; |
||||
} else { |
||||
if (inserts[start]) { |
||||
inserts[start] += ' ('; |
||||
} else { |
||||
inserts[start] = '('; |
||||
} |
||||
inserts[end] = ')'; |
||||
} |
||||
for (i = start + 1; i < end; i += 1) { |
||||
inserts[i] = '|'; |
||||
} |
||||
} |
||||
} |
||||
}); |
||||
|
||||
// collect all actions format strings
|
||||
var parts = []; |
||||
|
||||
actions.forEach(function (action, actionIndex) { |
||||
var part; |
||||
var optionString; |
||||
var argsDefault; |
||||
var argsString; |
||||
|
||||
// suppressed arguments are marked with None
|
||||
// remove | separators for suppressed arguments
|
||||
if (action.help === c.SUPPRESS) { |
||||
parts.push(null); |
||||
if (inserts[actionIndex] === '|') { |
||||
inserts.splice(actionIndex, actionIndex); |
||||
} else if (inserts[actionIndex + 1] === '|') { |
||||
inserts.splice(actionIndex + 1, actionIndex + 1); |
||||
} |
||||
|
||||
// produce all arg strings
|
||||
} else if (!action.isOptional()) { |
||||
part = self._formatArgs(action, action.dest); |
||||
|
||||
// if it's in a group, strip the outer []
|
||||
if (groupActions.indexOf(action) >= 0) { |
||||
if (part[0] === '[' && part[part.length - 1] === ']') { |
||||
part = part.slice(1, -1); |
||||
} |
||||
} |
||||
// add the action string to the list
|
||||
parts.push(part); |
||||
|
||||
// produce the first way to invoke the option in brackets
|
||||
} else { |
||||
optionString = action.optionStrings[0]; |
||||
|
||||
// if the Optional doesn't take a value, format is: -s or --long
|
||||
if (action.nargs === 0) { |
||||
part = '' + optionString; |
||||
|
||||
// if the Optional takes a value, format is: -s ARGS or --long ARGS
|
||||
} else { |
||||
argsDefault = action.dest.toUpperCase(); |
||||
argsString = self._formatArgs(action, argsDefault); |
||||
part = optionString + ' ' + argsString; |
||||
} |
||||
// make it look optional if it's not required or in a group
|
||||
if (!action.required && groupActions.indexOf(action) < 0) { |
||||
part = '[' + part + ']'; |
||||
} |
||||
// add the action string to the list
|
||||
parts.push(part); |
||||
} |
||||
}); |
||||
|
||||
// insert things at the necessary indices
|
||||
for (var i = inserts.length - 1; i >= 0; --i) { |
||||
if (inserts[i] !== null) { |
||||
parts.splice(i, 0, inserts[i]); |
||||
} |
||||
} |
||||
|
||||
// join all the action items with spaces
|
||||
var text = parts.filter(function (part) { |
||||
return !!part; |
||||
}).join(' '); |
||||
|
||||
// clean up separators for mutually exclusive groups
|
||||
text = text.replace(/([\[(]) /g, '$1'); // remove spaces
|
||||
text = text.replace(/ ([\])])/g, '$1'); |
||||
text = text.replace(/\[ *\]/g, ''); // remove empty groups
|
||||
text = text.replace(/\( *\)/g, ''); |
||||
text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups
|
||||
|
||||
text = text.trim(); |
||||
|
||||
// return the text
|
||||
return text; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatText = function (text) { |
||||
text = sprintf(text, { prog: this._prog }); |
||||
var textWidth = this._width - this._currentIndent; |
||||
var indentIncriment = $$.repeat(' ', this._currentIndent); |
||||
return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatAction = function (action) { |
||||
var self = this; |
||||
|
||||
var helpText; |
||||
var helpLines; |
||||
var parts; |
||||
var indentFirst; |
||||
|
||||
// determine the required width and the entry label
|
||||
var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); |
||||
var helpWidth = this._width - helpPosition; |
||||
var actionWidth = helpPosition - this._currentIndent - 2; |
||||
var actionHeader = this._formatActionInvocation(action); |
||||
|
||||
// no help; start on same line and add a final newline
|
||||
if (!action.help) { |
||||
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; |
||||
|
||||
// short action name; start on the same line and pad two spaces
|
||||
} else if (actionHeader.length <= actionWidth) { |
||||
actionHeader = $$.repeat(' ', this._currentIndent) + |
||||
actionHeader + |
||||
' ' + |
||||
$$.repeat(' ', actionWidth - actionHeader.length); |
||||
indentFirst = 0; |
||||
|
||||
// long action name; start on the next line
|
||||
} else { |
||||
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL; |
||||
indentFirst = helpPosition; |
||||
} |
||||
|
||||
// collect the pieces of the action help
|
||||
parts = [ actionHeader ]; |
||||
|
||||
// if there was help for the action, add lines of help text
|
||||
if (action.help) { |
||||
helpText = this._expandHelp(action); |
||||
helpLines = this._splitLines(helpText, helpWidth); |
||||
parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL); |
||||
helpLines.slice(1).forEach(function (line) { |
||||
parts.push($$.repeat(' ', helpPosition) + line + c.EOL); |
||||
}); |
||||
|
||||
// or add a newline if the description doesn't end with one
|
||||
} else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) { |
||||
parts.push(c.EOL); |
||||
} |
||||
// if there are any sub-actions, add their help as well
|
||||
if (action._getSubactions) { |
||||
this._indent(); |
||||
action._getSubactions().forEach(function (subaction) { |
||||
parts.push(self._formatAction(subaction)); |
||||
}); |
||||
this._dedent(); |
||||
} |
||||
// return a single string
|
||||
return this._joinParts(parts); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatActionInvocation = function (action) { |
||||
if (!action.isOptional()) { |
||||
var format_func = this._metavarFormatter(action, action.dest); |
||||
var metavars = format_func(1); |
||||
return metavars[0]; |
||||
} |
||||
|
||||
var parts = []; |
||||
var argsDefault; |
||||
var argsString; |
||||
|
||||
// if the Optional doesn't take a value, format is: -s, --long
|
||||
if (action.nargs === 0) { |
||||
parts = parts.concat(action.optionStrings); |
||||
|
||||
// if the Optional takes a value, format is: -s ARGS, --long ARGS
|
||||
} else { |
||||
argsDefault = action.dest.toUpperCase(); |
||||
argsString = this._formatArgs(action, argsDefault); |
||||
action.optionStrings.forEach(function (optionString) { |
||||
parts.push(optionString + ' ' + argsString); |
||||
}); |
||||
} |
||||
return parts.join(', '); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { |
||||
var result; |
||||
|
||||
if (action.metavar || action.metavar === '') { |
||||
result = action.metavar; |
||||
} else if (action.choices) { |
||||
var choices = action.choices; |
||||
|
||||
if (typeof choices === 'string') { |
||||
choices = choices.split('').join(', '); |
||||
} else if (Array.isArray(choices)) { |
||||
choices = choices.join(','); |
||||
} else { |
||||
choices = Object.keys(choices).join(','); |
||||
} |
||||
result = '{' + choices + '}'; |
||||
} else { |
||||
result = metavarDefault; |
||||
} |
||||
|
||||
return function (size) { |
||||
if (Array.isArray(result)) { |
||||
return result; |
||||
} |
||||
|
||||
var metavars = []; |
||||
for (var i = 0; i < size; i += 1) { |
||||
metavars.push(result); |
||||
} |
||||
return metavars; |
||||
}; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { |
||||
var result; |
||||
var metavars; |
||||
|
||||
var buildMetavar = this._metavarFormatter(action, metavarDefault); |
||||
|
||||
switch (action.nargs) { |
||||
/*eslint-disable no-undefined*/ |
||||
case undefined: |
||||
case null: |
||||
metavars = buildMetavar(1); |
||||
result = '' + metavars[0]; |
||||
break; |
||||
case c.OPTIONAL: |
||||
metavars = buildMetavar(1); |
||||
result = '[' + metavars[0] + ']'; |
||||
break; |
||||
case c.ZERO_OR_MORE: |
||||
metavars = buildMetavar(2); |
||||
result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; |
||||
break; |
||||
case c.ONE_OR_MORE: |
||||
metavars = buildMetavar(2); |
||||
result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; |
||||
break; |
||||
case c.REMAINDER: |
||||
result = '...'; |
||||
break; |
||||
case c.PARSER: |
||||
metavars = buildMetavar(1); |
||||
result = metavars[0] + ' ...'; |
||||
break; |
||||
default: |
||||
metavars = buildMetavar(action.nargs); |
||||
result = metavars.join(' '); |
||||
} |
||||
return result; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._expandHelp = function (action) { |
||||
var params = { prog: this._prog }; |
||||
|
||||
Object.keys(action).forEach(function (actionProperty) { |
||||
var actionValue = action[actionProperty]; |
||||
|
||||
if (actionValue !== c.SUPPRESS) { |
||||
params[actionProperty] = actionValue; |
||||
} |
||||
}); |
||||
|
||||
if (params.choices) { |
||||
if (typeof params.choices === 'string') { |
||||
params.choices = params.choices.split('').join(', '); |
||||
} else if (Array.isArray(params.choices)) { |
||||
params.choices = params.choices.join(', '); |
||||
} else { |
||||
params.choices = Object.keys(params.choices).join(', '); |
||||
} |
||||
} |
||||
|
||||
return sprintf(this._getHelpString(action), params); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._splitLines = function (text, width) { |
||||
var lines = []; |
||||
var delimiters = [ ' ', '.', ',', '!', '?' ]; |
||||
var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); |
||||
|
||||
text = text.replace(/[\n\|\t]/g, ' '); |
||||
|
||||
text = text.trim(); |
||||
text = text.replace(this._whitespaceMatcher, ' '); |
||||
|
||||
// Wraps the single paragraph in text (a string) so every line
|
||||
// is at most width characters long.
|
||||
text.split(c.EOL).forEach(function (line) { |
||||
if (width >= line.length) { |
||||
lines.push(line); |
||||
return; |
||||
} |
||||
|
||||
var wrapStart = 0; |
||||
var wrapEnd = width; |
||||
var delimiterIndex = 0; |
||||
while (wrapEnd <= line.length) { |
||||
if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { |
||||
delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; |
||||
wrapEnd = wrapStart + delimiterIndex + 1; |
||||
} |
||||
lines.push(line.substring(wrapStart, wrapEnd)); |
||||
wrapStart = wrapEnd; |
||||
wrapEnd += width; |
||||
} |
||||
if (wrapStart < line.length) { |
||||
lines.push(line.substring(wrapStart, wrapEnd)); |
||||
} |
||||
}); |
||||
|
||||
return lines; |
||||
}; |
||||
|
||||
HelpFormatter.prototype._fillText = function (text, width, indent) { |
||||
var lines = this._splitLines(text, width); |
||||
lines = lines.map(function (line) { |
||||
return indent + line; |
||||
}); |
||||
return lines.join(c.EOL); |
||||
}; |
||||
|
||||
HelpFormatter.prototype._getHelpString = function (action) { |
||||
return action.help; |
||||
}; |
@ -1,76 +0,0 @@ |
||||
/** |
||||
* class Namespace |
||||
* |
||||
* Simple object for storing attributes. Implements equality by attribute names |
||||
* and values, and provides a simple string representation. |
||||
* |
||||
* See also [original guide][1] |
||||
* |
||||
* [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object
|
||||
**/ |
||||
'use strict'; |
||||
|
||||
var $$ = require('./utils'); |
||||
|
||||
/** |
||||
* new Namespace(options) |
||||
* - options(object): predefined propertis for result object |
||||
* |
||||
**/ |
||||
var Namespace = module.exports = function Namespace(options) { |
||||
$$.extend(this, options); |
||||
}; |
||||
|
||||
/** |
||||
* Namespace#isset(key) -> Boolean |
||||
* - key (string|number): property name |
||||
* |
||||
* Tells whenever `namespace` contains given `key` or not. |
||||
**/ |
||||
Namespace.prototype.isset = function (key) { |
||||
return $$.has(this, key); |
||||
}; |
||||
|
||||
/** |
||||
* Namespace#set(key, value) -> self |
||||
* -key (string|number|object): propery name |
||||
* -value (mixed): new property value |
||||
* |
||||
* Set the property named key with value. |
||||
* If key object then set all key properties to namespace object |
||||
**/ |
||||
Namespace.prototype.set = function (key, value) { |
||||
if (typeof (key) === 'object') { |
||||
$$.extend(this, key); |
||||
} else { |
||||
this[key] = value; |
||||
} |
||||
return this; |
||||
}; |
||||
|
||||
/** |
||||
* Namespace#get(key, defaultValue) -> mixed |
||||
* - key (string|number): property name |
||||
* - defaultValue (mixed): default value |
||||
* |
||||
* Return the property key or defaulValue if not set |
||||
**/ |
||||
Namespace.prototype.get = function (key, defaultValue) { |
||||
return !this[key] ? defaultValue : this[key]; |
||||
}; |
||||
|
||||
/** |
||||
* Namespace#unset(key, defaultValue) -> mixed |
||||
* - key (string|number): property name |
||||
* - defaultValue (mixed): default value |
||||
* |
||||
* Return data[key](and delete it) or defaultValue |
||||
**/ |
||||
Namespace.prototype.unset = function (key, defaultValue) { |
||||
var value = this[key]; |
||||
if (value !== null) { |
||||
delete this[key]; |
||||
return value; |
||||
} |
||||
return defaultValue; |
||||
}; |
@ -1,57 +0,0 @@ |
||||
'use strict'; |
||||
|
||||
exports.repeat = function (str, num) { |
||||
var result = ''; |
||||
for (var i = 0; i < num; i++) { result += str; } |
||||
return result; |
||||
}; |
||||
|
||||
exports.arrayEqual = function (a, b) { |
||||
if (a.length !== b.length) { return false; } |
||||
for (var i = 0; i < a.length; i++) { |
||||
if (a[i] !== b[i]) { return false; } |
||||
} |
||||
return true; |
||||
}; |
||||
|
||||
exports.trimChars = function (str, chars) { |
||||
var start = 0; |
||||
var end = str.length - 1; |
||||
while (chars.indexOf(str.charAt(start)) >= 0) { start++; } |
||||
while (chars.indexOf(str.charAt(end)) >= 0) { end--; } |
||||
return str.slice(start, end + 1); |
||||
}; |
||||
|
||||
exports.capitalize = function (str) { |
||||
return str.charAt(0).toUpperCase() + str.slice(1); |
||||
}; |
||||
|
||||
exports.arrayUnion = function () { |
||||
var result = []; |
||||
for (var i = 0, values = {}; i < arguments.length; i++) { |
||||
var arr = arguments[i]; |
||||
for (var j = 0; j < arr.length; j++) { |
||||
if (!values[arr[j]]) { |
||||
values[arr[j]] = true; |
||||
result.push(arr[j]); |
||||
} |
||||
} |
||||
} |
||||
return result; |
||||
}; |
||||
|
||||
function has(obj, key) { |
||||
return Object.prototype.hasOwnProperty.call(obj, key); |
||||
} |
||||
|
||||
exports.has = has; |
||||
|
||||
exports.extend = function (dest, src) { |
||||
for (var i in src) { |
||||
if (has(src, i)) { dest[i] = src[i]; } |
||||
} |
||||
}; |
||||
|
||||
exports.trimEnd = function (str) { |
||||
return str.replace(/\s+$/g, ''); |
||||
}; |
@ -1,71 +0,0 @@ |
||||
{ |
||||
"_from": "argparse@^1.0.7", |
||||
"_id": "argparse@1.0.10", |
||||
"_inBundle": false, |
||||
"_integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", |
||||
"_location": "/argparse", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "argparse@^1.0.7", |
||||
"name": "argparse", |
||||
"escapedName": "argparse", |
||||
"rawSpec": "^1.0.7", |
||||
"saveSpec": null, |
||||
"fetchSpec": "^1.0.7" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/coveralls/js-yaml", |
||||
"/js-yaml" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", |
||||
"_shasum": "bcd6791ea5ae09725e17e5ad988134cd40b3d911", |
||||
"_spec": "argparse@^1.0.7", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/coveralls/node_modules/js-yaml", |
||||
"bugs": { |
||||
"url": "https://github.com/nodeca/argparse/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"contributors": [ |
||||
{ |
||||
"name": "Eugene Shkuropat" |
||||
}, |
||||
{ |
||||
"name": "Paul Jacobson" |
||||
} |
||||
], |
||||
"dependencies": { |
||||
"sprintf-js": "~1.0.2" |
||||
}, |
||||
"deprecated": false, |
||||
"description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library", |
||||
"devDependencies": { |
||||
"eslint": "^2.13.1", |
||||
"istanbul": "^0.4.5", |
||||
"mocha": "^3.1.0", |
||||
"ndoc": "^5.0.1" |
||||
}, |
||||
"files": [ |
||||
"index.js", |
||||
"lib/" |
||||
], |
||||
"homepage": "https://github.com/nodeca/argparse#readme", |
||||
"keywords": [ |
||||
"cli", |
||||
"parser", |
||||
"argparse", |
||||
"option", |
||||
"args" |
||||
], |
||||
"license": "MIT", |
||||
"name": "argparse", |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git+https://github.com/nodeca/argparse.git" |
||||
}, |
||||
"scripts": { |
||||
"test": "make test" |
||||
}, |
||||
"version": "1.0.10" |
||||
} |
@ -1,2 +0,0 @@ |
||||
node_modules |
||||
*.log |
@ -1,4 +0,0 @@ |
||||
language: node_js |
||||
node_js: |
||||
- 0.8 |
||||
- 0.10 |
@ -1,19 +0,0 @@ |
||||
Copyright (c) 2011 Mark Cavage, All rights reserved. |
||||
|
||||
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 |
@ -1,50 +0,0 @@ |
||||
node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. |
||||
Currently BER encoding is supported; at some point I'll likely have to do DER. |
||||
|
||||
## Usage |
||||
|
||||
Mostly, if you're *actually* needing to read and write ASN.1, you probably don't |
||||
need this readme to explain what and why. If you have no idea what ASN.1 is, |
||||
see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc |
||||
|
||||
The source is pretty much self-explanatory, and has read/write methods for the |
||||
common types out there. |
||||
|
||||
### Decoding |
||||
|
||||
The following reads an ASN.1 sequence with a boolean. |
||||
|
||||
var Ber = require('asn1').Ber; |
||||
|
||||
var reader = new Ber.Reader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); |
||||
|
||||
reader.readSequence(); |
||||
console.log('Sequence len: ' + reader.length); |
||||
if (reader.peek() === Ber.Boolean) |
||||
console.log(reader.readBoolean()); |
||||
|
||||
### Encoding |
||||
|
||||
The following generates the same payload as above. |
||||
|
||||
var Ber = require('asn1').Ber; |
||||
|
||||
var writer = new Ber.Writer(); |
||||
|
||||
writer.startSequence(); |
||||
writer.writeBoolean(true); |
||||
writer.endSequence(); |
||||
|
||||
console.log(writer.buffer); |
||||
|
||||
## Installation |
||||
|
||||
npm install asn1 |
||||
|
||||
## License |
||||
|
||||
MIT. |
||||
|
||||
## Bugs |
||||
|
||||
See <https://github.com/mcavage/node-asn1/issues>. |
@ -1,13 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
|
||||
module.exports = { |
||||
|
||||
newInvalidAsn1Error: function(msg) { |
||||
var e = new Error(); |
||||
e.name = 'InvalidAsn1Error'; |
||||
e.message = msg || ''; |
||||
return e; |
||||
} |
||||
|
||||
}; |
@ -1,27 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
var errors = require('./errors'); |
||||
var types = require('./types'); |
||||
|
||||
var Reader = require('./reader'); |
||||
var Writer = require('./writer'); |
||||
|
||||
|
||||
///--- Exports
|
||||
|
||||
module.exports = { |
||||
|
||||
Reader: Reader, |
||||
|
||||
Writer: Writer |
||||
|
||||
}; |
||||
|
||||
for (var t in types) { |
||||
if (types.hasOwnProperty(t)) |
||||
module.exports[t] = types[t]; |
||||
} |
||||
for (var e in errors) { |
||||
if (errors.hasOwnProperty(e)) |
||||
module.exports[e] = errors[e]; |
||||
} |
@ -1,261 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
var assert = require('assert'); |
||||
|
||||
var ASN1 = require('./types'); |
||||
var errors = require('./errors'); |
||||
|
||||
|
||||
///--- Globals
|
||||
|
||||
var newInvalidAsn1Error = errors.newInvalidAsn1Error; |
||||
|
||||
|
||||
|
||||
///--- API
|
||||
|
||||
function Reader(data) { |
||||
if (!data || !Buffer.isBuffer(data)) |
||||
throw new TypeError('data must be a node Buffer'); |
||||
|
||||
this._buf = data; |
||||
this._size = data.length; |
||||
|
||||
// These hold the "current" state
|
||||
this._len = 0; |
||||
this._offset = 0; |
||||
} |
||||
|
||||
Object.defineProperty(Reader.prototype, 'length', { |
||||
enumerable: true, |
||||
get: function () { return (this._len); } |
||||
}); |
||||
|
||||
Object.defineProperty(Reader.prototype, 'offset', { |
||||
enumerable: true, |
||||
get: function () { return (this._offset); } |
||||
}); |
||||
|
||||
Object.defineProperty(Reader.prototype, 'remain', { |
||||
get: function () { return (this._size - this._offset); } |
||||
}); |
||||
|
||||
Object.defineProperty(Reader.prototype, 'buffer', { |
||||
get: function () { return (this._buf.slice(this._offset)); } |
||||
}); |
||||
|
||||
|
||||
/** |
||||
* Reads a single byte and advances offset; you can pass in `true` to make this |
||||
* a "peek" operation (i.e., get the byte, but don't advance the offset). |
||||
* |
||||
* @param {Boolean} peek true means don't move offset. |
||||
* @return {Number} the next byte, null if not enough data. |
||||
*/ |
||||
Reader.prototype.readByte = function(peek) { |
||||
if (this._size - this._offset < 1) |
||||
return null; |
||||
|
||||
var b = this._buf[this._offset] & 0xff; |
||||
|
||||
if (!peek) |
||||
this._offset += 1; |
||||
|
||||
return b; |
||||
}; |
||||
|
||||
|
||||
Reader.prototype.peek = function() { |
||||
return this.readByte(true); |
||||
}; |
||||
|
||||
|
||||
/** |
||||
* Reads a (potentially) variable length off the BER buffer. This call is |
||||
* not really meant to be called directly, as callers have to manipulate |
||||
* the internal buffer afterwards. |
||||
* |
||||
* As a result of this call, you can call `Reader.length`, until the |
||||
* next thing called that does a readLength. |
||||
* |
||||
* @return {Number} the amount of offset to advance the buffer. |
||||
* @throws {InvalidAsn1Error} on bad ASN.1 |
||||
*/ |
||||
Reader.prototype.readLength = function(offset) { |
||||
if (offset === undefined) |
||||
offset = this._offset; |
||||
|
||||
if (offset >= this._size) |
||||
return null; |
||||
|
||||
var lenB = this._buf[offset++] & 0xff; |
||||
if (lenB === null) |
||||
return null; |
||||
|
||||
if ((lenB & 0x80) == 0x80) { |
||||
lenB &= 0x7f; |
||||
|
||||
if (lenB == 0) |
||||
throw newInvalidAsn1Error('Indefinite length not supported'); |
||||
|
||||
if (lenB > 4) |
||||
throw newInvalidAsn1Error('encoding too long'); |
||||
|
||||
if (this._size - offset < lenB) |
||||
return null; |
||||
|
||||
this._len = 0; |
||||
for (var i = 0; i < lenB; i++) |
||||
this._len = (this._len << 8) + (this._buf[offset++] & 0xff); |
||||
|
||||
} else { |
||||
// Wasn't a variable length
|
||||
this._len = lenB; |
||||
} |
||||
|
||||
return offset; |
||||
}; |
||||
|
||||
|
||||
/** |
||||
* Parses the next sequence in this BER buffer. |
||||
* |
||||
* To get the length of the sequence, call `Reader.length`. |
||||
* |
||||
* @return {Number} the sequence's tag. |
||||
*/ |
||||
Reader.prototype.readSequence = function(tag) { |
||||
var seq = this.peek(); |
||||
if (seq === null) |
||||
return null; |
||||
if (tag !== undefined && tag !== seq) |
||||
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + |
||||
': got 0x' + seq.toString(16)); |
||||
|
||||
var o = this.readLength(this._offset + 1); // stored in `length`
|
||||
if (o === null) |
||||
return null; |
||||
|
||||
this._offset = o; |
||||
return seq; |
||||
}; |
||||
|
||||
|
||||
Reader.prototype.readInt = function() { |
||||
return this._readTag(ASN1.Integer); |
||||
}; |
||||
|
||||
|
||||
Reader.prototype.readBoolean = function() { |
||||
return (this._readTag(ASN1.Boolean) === 0 ? false : true); |
||||
}; |
||||
|
||||
|
||||
Reader.prototype.readEnumeration = function() { |
||||
return this._readTag(ASN1.Enumeration); |
||||
}; |
||||
|
||||
|
||||
Reader.prototype.readString = function(tag, retbuf) { |
||||
if (!tag) |
||||
tag = ASN1.OctetString; |
||||
|
||||
var b = this.peek(); |
||||
if (b === null) |
||||
return null; |
||||
|
||||
if (b !== tag) |
||||
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + |
||||
': got 0x' + b.toString(16)); |
||||
|
||||
var o = this.readLength(this._offset + 1); // stored in `length`
|
||||
|
||||
if (o === null) |
||||
return null; |
||||
|
||||
if (this.length > this._size - o) |
||||
return null; |
||||
|
||||
this._offset = o; |
||||
|
||||
if (this.length === 0) |
||||
return retbuf ? new Buffer(0) : ''; |
||||
|
||||
var str = this._buf.slice(this._offset, this._offset + this.length); |
||||
this._offset += this.length; |
||||
|
||||
return retbuf ? str : str.toString('utf8'); |
||||
}; |
||||
|
||||
Reader.prototype.readOID = function(tag) { |
||||
if (!tag) |
||||
tag = ASN1.OID; |
||||
|
||||
var b = this.readString(tag, true); |
||||
if (b === null) |
||||
return null; |
||||
|
||||
var values = []; |
||||
var value = 0; |
||||
|
||||
for (var i = 0; i < b.length; i++) { |
||||
var byte = b[i] & 0xff; |
||||
|
||||
value <<= 7; |
||||
value += byte & 0x7f; |
||||
if ((byte & 0x80) == 0) { |
||||
values.push(value); |
||||
value = 0; |
||||
} |
||||
} |
||||
|
||||
value = values.shift(); |
||||
values.unshift(value % 40); |
||||
values.unshift((value / 40) >> 0); |
||||
|
||||
return values.join('.'); |
||||
}; |
||||
|
||||
|
||||
Reader.prototype._readTag = function(tag) { |
||||
assert.ok(tag !== undefined); |
||||
|
||||
var b = this.peek(); |
||||
|
||||
if (b === null) |
||||
return null; |
||||
|
||||
if (b !== tag) |
||||
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + |
||||
': got 0x' + b.toString(16)); |
||||
|
||||
var o = this.readLength(this._offset + 1); // stored in `length`
|
||||
if (o === null) |
||||
return null; |
||||
|
||||
if (this.length > 4) |
||||
throw newInvalidAsn1Error('Integer too long: ' + this.length); |
||||
|
||||
if (this.length > this._size - o) |
||||
return null; |
||||
this._offset = o; |
||||
|
||||
var fb = this._buf[this._offset]; |
||||
var value = 0; |
||||
|
||||
for (var i = 0; i < this.length; i++) { |
||||
value <<= 8; |
||||
value |= (this._buf[this._offset++] & 0xff); |
||||
} |
||||
|
||||
if ((fb & 0x80) == 0x80 && i !== 4) |
||||
value -= (1 << (i * 8)); |
||||
|
||||
return value >> 0; |
||||
}; |
||||
|
||||
|
||||
|
||||
///--- Exported API
|
||||
|
||||
module.exports = Reader; |
@ -1,36 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
|
||||
module.exports = { |
||||
EOC: 0, |
||||
Boolean: 1, |
||||
Integer: 2, |
||||
BitString: 3, |
||||
OctetString: 4, |
||||
Null: 5, |
||||
OID: 6, |
||||
ObjectDescriptor: 7, |
||||
External: 8, |
||||
Real: 9, // float
|
||||
Enumeration: 10, |
||||
PDV: 11, |
||||
Utf8String: 12, |
||||
RelativeOID: 13, |
||||
Sequence: 16, |
||||
Set: 17, |
||||
NumericString: 18, |
||||
PrintableString: 19, |
||||
T61String: 20, |
||||
VideotexString: 21, |
||||
IA5String: 22, |
||||
UTCTime: 23, |
||||
GeneralizedTime: 24, |
||||
GraphicString: 25, |
||||
VisibleString: 26, |
||||
GeneralString: 28, |
||||
UniversalString: 29, |
||||
CharacterString: 30, |
||||
BMPString: 31, |
||||
Constructor: 32, |
||||
Context: 128 |
||||
}; |
@ -1,316 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
var assert = require('assert'); |
||||
var ASN1 = require('./types'); |
||||
var errors = require('./errors'); |
||||
|
||||
|
||||
///--- Globals
|
||||
|
||||
var newInvalidAsn1Error = errors.newInvalidAsn1Error; |
||||
|
||||
var DEFAULT_OPTS = { |
||||
size: 1024, |
||||
growthFactor: 8 |
||||
}; |
||||
|
||||
|
||||
///--- Helpers
|
||||
|
||||
function merge(from, to) { |
||||
assert.ok(from); |
||||
assert.equal(typeof(from), 'object'); |
||||
assert.ok(to); |
||||
assert.equal(typeof(to), 'object'); |
||||
|
||||
var keys = Object.getOwnPropertyNames(from); |
||||
keys.forEach(function(key) { |
||||
if (to[key]) |
||||
return; |
||||
|
||||
var value = Object.getOwnPropertyDescriptor(from, key); |
||||
Object.defineProperty(to, key, value); |
||||
}); |
||||
|
||||
return to; |
||||
} |
||||
|
||||
|
||||
|
||||
///--- API
|
||||
|
||||
function Writer(options) { |
||||
options = merge(DEFAULT_OPTS, options || {}); |
||||
|
||||
this._buf = new Buffer(options.size || 1024); |
||||
this._size = this._buf.length; |
||||
this._offset = 0; |
||||
this._options = options; |
||||
|
||||
// A list of offsets in the buffer where we need to insert
|
||||
// sequence tag/len pairs.
|
||||
this._seq = []; |
||||
} |
||||
|
||||
Object.defineProperty(Writer.prototype, 'buffer', { |
||||
get: function () { |
||||
if (this._seq.length) |
||||
throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)'); |
||||
|
||||
return (this._buf.slice(0, this._offset)); |
||||
} |
||||
}); |
||||
|
||||
Writer.prototype.writeByte = function(b) { |
||||
if (typeof(b) !== 'number') |
||||
throw new TypeError('argument must be a Number'); |
||||
|
||||
this._ensure(1); |
||||
this._buf[this._offset++] = b; |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeInt = function(i, tag) { |
||||
if (typeof(i) !== 'number') |
||||
throw new TypeError('argument must be a Number'); |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.Integer; |
||||
|
||||
var sz = 4; |
||||
|
||||
while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && |
||||
(sz > 1)) { |
||||
sz--; |
||||
i <<= 8; |
||||
} |
||||
|
||||
if (sz > 4) |
||||
throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff'); |
||||
|
||||
this._ensure(2 + sz); |
||||
this._buf[this._offset++] = tag; |
||||
this._buf[this._offset++] = sz; |
||||
|
||||
while (sz-- > 0) { |
||||
this._buf[this._offset++] = ((i & 0xff000000) >>> 24); |
||||
i <<= 8; |
||||
} |
||||
|
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeNull = function() { |
||||
this.writeByte(ASN1.Null); |
||||
this.writeByte(0x00); |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeEnumeration = function(i, tag) { |
||||
if (typeof(i) !== 'number') |
||||
throw new TypeError('argument must be a Number'); |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.Enumeration; |
||||
|
||||
return this.writeInt(i, tag); |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeBoolean = function(b, tag) { |
||||
if (typeof(b) !== 'boolean') |
||||
throw new TypeError('argument must be a Boolean'); |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.Boolean; |
||||
|
||||
this._ensure(3); |
||||
this._buf[this._offset++] = tag; |
||||
this._buf[this._offset++] = 0x01; |
||||
this._buf[this._offset++] = b ? 0xff : 0x00; |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeString = function(s, tag) { |
||||
if (typeof(s) !== 'string') |
||||
throw new TypeError('argument must be a string (was: ' + typeof(s) + ')'); |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.OctetString; |
||||
|
||||
var len = Buffer.byteLength(s); |
||||
this.writeByte(tag); |
||||
this.writeLength(len); |
||||
if (len) { |
||||
this._ensure(len); |
||||
this._buf.write(s, this._offset); |
||||
this._offset += len; |
||||
} |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeBuffer = function(buf, tag) { |
||||
if (typeof(tag) !== 'number') |
||||
throw new TypeError('tag must be a number'); |
||||
if (!Buffer.isBuffer(buf)) |
||||
throw new TypeError('argument must be a buffer'); |
||||
|
||||
this.writeByte(tag); |
||||
this.writeLength(buf.length); |
||||
this._ensure(buf.length); |
||||
buf.copy(this._buf, this._offset, 0, buf.length); |
||||
this._offset += buf.length; |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeStringArray = function(strings) { |
||||
if ((!strings instanceof Array)) |
||||
throw new TypeError('argument must be an Array[String]'); |
||||
|
||||
var self = this; |
||||
strings.forEach(function(s) { |
||||
self.writeString(s); |
||||
}); |
||||
}; |
||||
|
||||
// This is really to solve DER cases, but whatever for now
|
||||
Writer.prototype.writeOID = function(s, tag) { |
||||
if (typeof(s) !== 'string') |
||||
throw new TypeError('argument must be a string'); |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.OID; |
||||
|
||||
if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) |
||||
throw new Error('argument is not a valid OID string'); |
||||
|
||||
function encodeOctet(bytes, octet) { |
||||
if (octet < 128) { |
||||
bytes.push(octet); |
||||
} else if (octet < 16384) { |
||||
bytes.push((octet >>> 7) | 0x80); |
||||
bytes.push(octet & 0x7F); |
||||
} else if (octet < 2097152) { |
||||
bytes.push((octet >>> 14) | 0x80); |
||||
bytes.push(((octet >>> 7) | 0x80) & 0xFF); |
||||
bytes.push(octet & 0x7F); |
||||
} else if (octet < 268435456) { |
||||
bytes.push((octet >>> 21) | 0x80); |
||||
bytes.push(((octet >>> 14) | 0x80) & 0xFF); |
||||
bytes.push(((octet >>> 7) | 0x80) & 0xFF); |
||||
bytes.push(octet & 0x7F); |
||||
} else { |
||||
bytes.push(((octet >>> 28) | 0x80) & 0xFF); |
||||
bytes.push(((octet >>> 21) | 0x80) & 0xFF); |
||||
bytes.push(((octet >>> 14) | 0x80) & 0xFF); |
||||
bytes.push(((octet >>> 7) | 0x80) & 0xFF); |
||||
bytes.push(octet & 0x7F); |
||||
} |
||||
} |
||||
|
||||
var tmp = s.split('.'); |
||||
var bytes = []; |
||||
bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); |
||||
tmp.slice(2).forEach(function(b) { |
||||
encodeOctet(bytes, parseInt(b, 10)); |
||||
}); |
||||
|
||||
var self = this; |
||||
this._ensure(2 + bytes.length); |
||||
this.writeByte(tag); |
||||
this.writeLength(bytes.length); |
||||
bytes.forEach(function(b) { |
||||
self.writeByte(b); |
||||
}); |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.writeLength = function(len) { |
||||
if (typeof(len) !== 'number') |
||||
throw new TypeError('argument must be a Number'); |
||||
|
||||
this._ensure(4); |
||||
|
||||
if (len <= 0x7f) { |
||||
this._buf[this._offset++] = len; |
||||
} else if (len <= 0xff) { |
||||
this._buf[this._offset++] = 0x81; |
||||
this._buf[this._offset++] = len; |
||||
} else if (len <= 0xffff) { |
||||
this._buf[this._offset++] = 0x82; |
||||
this._buf[this._offset++] = len >> 8; |
||||
this._buf[this._offset++] = len; |
||||
} else if (len <= 0xffffff) { |
||||
this._buf[this._offset++] = 0x83; |
||||
this._buf[this._offset++] = len >> 16; |
||||
this._buf[this._offset++] = len >> 8; |
||||
this._buf[this._offset++] = len; |
||||
} else { |
||||
throw new InvalidAsn1ERror('Length too long (> 4 bytes)'); |
||||
} |
||||
}; |
||||
|
||||
Writer.prototype.startSequence = function(tag) { |
||||
if (typeof(tag) !== 'number') |
||||
tag = ASN1.Sequence | ASN1.Constructor; |
||||
|
||||
this.writeByte(tag); |
||||
this._seq.push(this._offset); |
||||
this._ensure(3); |
||||
this._offset += 3; |
||||
}; |
||||
|
||||
|
||||
Writer.prototype.endSequence = function() { |
||||
var seq = this._seq.pop(); |
||||
var start = seq + 3; |
||||
var len = this._offset - start; |
||||
|
||||
if (len <= 0x7f) { |
||||
this._shift(start, len, -2); |
||||
this._buf[seq] = len; |
||||
} else if (len <= 0xff) { |
||||
this._shift(start, len, -1); |
||||
this._buf[seq] = 0x81; |
||||
this._buf[seq + 1] = len; |
||||
} else if (len <= 0xffff) { |
||||
this._buf[seq] = 0x82; |
||||
this._buf[seq + 1] = len >> 8; |
||||
this._buf[seq + 2] = len; |
||||
} else if (len <= 0xffffff) { |
||||
this._shift(start, len, 1); |
||||
this._buf[seq] = 0x83; |
||||
this._buf[seq + 1] = len >> 16; |
||||
this._buf[seq + 2] = len >> 8; |
||||
this._buf[seq + 3] = len; |
||||
} else { |
||||
throw new InvalidAsn1Error('Sequence too long'); |
||||
} |
||||
}; |
||||
|
||||
|
||||
Writer.prototype._shift = function(start, len, shift) { |
||||
assert.ok(start !== undefined); |
||||
assert.ok(len !== undefined); |
||||
assert.ok(shift); |
||||
|
||||
this._buf.copy(this._buf, start + shift, start, start + len); |
||||
this._offset += shift; |
||||
}; |
||||
|
||||
Writer.prototype._ensure = function(len) { |
||||
assert.ok(len); |
||||
|
||||
if (this._size - this._offset < len) { |
||||
var sz = this._size * this._options.growthFactor; |
||||
if (sz - this._offset < len) |
||||
sz += len; |
||||
|
||||
var buf = new Buffer(sz); |
||||
|
||||
this._buf.copy(buf, 0, 0, this._offset); |
||||
this._buf = buf; |
||||
this._size = sz; |
||||
} |
||||
}; |
||||
|
||||
|
||||
|
||||
///--- Exported API
|
||||
|
||||
module.exports = Writer; |
@ -1,20 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
// If you have no idea what ASN.1 or BER is, see this:
|
||||
// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
|
||||
|
||||
var Ber = require('./ber/index'); |
||||
|
||||
|
||||
|
||||
///--- Exported API
|
||||
|
||||
module.exports = { |
||||
|
||||
Ber: Ber, |
||||
|
||||
BerReader: Ber.Reader, |
||||
|
||||
BerWriter: Ber.Writer |
||||
|
||||
}; |
@ -1,65 +0,0 @@ |
||||
{ |
||||
"_from": "asn1@~0.2.3", |
||||
"_id": "asn1@0.2.3", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=", |
||||
"_location": "/asn1", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "asn1@~0.2.3", |
||||
"name": "asn1", |
||||
"escapedName": "asn1", |
||||
"rawSpec": "~0.2.3", |
||||
"saveSpec": null, |
||||
"fetchSpec": "~0.2.3" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/sshpk" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", |
||||
"_shasum": "dac8787713c9966849fc8180777ebe9c1ddf3b86", |
||||
"_spec": "asn1@~0.2.3", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/sshpk", |
||||
"author": { |
||||
"name": "Mark Cavage", |
||||
"email": "mcavage@gmail.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/mcavage/node-asn1/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"contributors": [ |
||||
{ |
||||
"name": "David Gwynne", |
||||
"email": "loki@animata.net" |
||||
}, |
||||
{ |
||||
"name": "Yunong Xiao", |
||||
"email": "yunong@joyent.com" |
||||
}, |
||||
{ |
||||
"name": "Alex Wilson", |
||||
"email": "alex.wilson@joyent.com" |
||||
} |
||||
], |
||||
"dependencies": {}, |
||||
"deprecated": false, |
||||
"description": "Contains parsers and serializers for ASN.1 (currently BER only)", |
||||
"devDependencies": { |
||||
"tap": "0.4.8" |
||||
}, |
||||
"homepage": "https://github.com/mcavage/node-asn1#readme", |
||||
"license": "MIT", |
||||
"main": "lib/index.js", |
||||
"name": "asn1", |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git://github.com/mcavage/node-asn1.git" |
||||
}, |
||||
"scripts": { |
||||
"test": "tap ./tst" |
||||
}, |
||||
"version": "0.2.3" |
||||
} |
@ -1,208 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
var test = require('tap').test; |
||||
|
||||
|
||||
|
||||
///--- Globals
|
||||
|
||||
var BerReader; |
||||
|
||||
|
||||
|
||||
///--- Tests
|
||||
|
||||
test('load library', function(t) { |
||||
BerReader = require('../../lib/index').BerReader; |
||||
t.ok(BerReader); |
||||
try { |
||||
new BerReader(); |
||||
t.fail('Should have thrown'); |
||||
} catch (e) { |
||||
t.ok(e instanceof TypeError, 'Should have been a type error'); |
||||
} |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read byte', function(t) { |
||||
var reader = new BerReader(new Buffer([0xde])); |
||||
t.ok(reader); |
||||
t.equal(reader.readByte(), 0xde, 'wrong value'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 1 byte int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x01, 0x03])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), 0x03, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 2 byte int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x02, 0x7e, 0xde])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), 0x7ede, 'wrong value'); |
||||
t.equal(reader.length, 0x02, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 3 byte int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x03, 0x7e, 0xde, 0x03])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), 0x7ede03, 'wrong value'); |
||||
t.equal(reader.length, 0x03, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 4 byte int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x04, 0x7e, 0xde, 0x03, 0x01])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), 0x7ede0301, 'wrong value'); |
||||
t.equal(reader.length, 0x04, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 1 byte negative int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x01, 0xdc])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), -36, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 2 byte negative int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x02, 0xc0, 0x4e])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), -16306, 'wrong value'); |
||||
t.equal(reader.length, 0x02, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 3 byte negative int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x03, 0xff, 0x00, 0x19])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), -65511, 'wrong value'); |
||||
t.equal(reader.length, 0x03, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read 4 byte negative int', function(t) { |
||||
var reader = new BerReader(new Buffer([0x02, 0x04, 0x91, 0x7c, 0x22, 0x1f])); |
||||
t.ok(reader); |
||||
t.equal(reader.readInt(), -1854135777, 'wrong value'); |
||||
t.equal(reader.length, 0x04, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read boolean true', function(t) { |
||||
var reader = new BerReader(new Buffer([0x01, 0x01, 0xff])); |
||||
t.ok(reader); |
||||
t.equal(reader.readBoolean(), true, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read boolean false', function(t) { |
||||
var reader = new BerReader(new Buffer([0x01, 0x01, 0x00])); |
||||
t.ok(reader); |
||||
t.equal(reader.readBoolean(), false, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read enumeration', function(t) { |
||||
var reader = new BerReader(new Buffer([0x0a, 0x01, 0x20])); |
||||
t.ok(reader); |
||||
t.equal(reader.readEnumeration(), 0x20, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read string', function(t) { |
||||
var dn = 'cn=foo,ou=unit,o=test'; |
||||
var buf = new Buffer(dn.length + 2); |
||||
buf[0] = 0x04; |
||||
buf[1] = Buffer.byteLength(dn); |
||||
buf.write(dn, 2); |
||||
var reader = new BerReader(buf); |
||||
t.ok(reader); |
||||
t.equal(reader.readString(), dn, 'wrong value'); |
||||
t.equal(reader.length, dn.length, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('read sequence', function(t) { |
||||
var reader = new BerReader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); |
||||
t.ok(reader); |
||||
t.equal(reader.readSequence(), 0x30, 'wrong value'); |
||||
t.equal(reader.length, 0x03, 'wrong length'); |
||||
t.equal(reader.readBoolean(), true, 'wrong value'); |
||||
t.equal(reader.length, 0x01, 'wrong length'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('anonymous LDAPv3 bind', function(t) { |
||||
var BIND = new Buffer(14); |
||||
BIND[0] = 0x30; // Sequence
|
||||
BIND[1] = 12; // len
|
||||
BIND[2] = 0x02; // ASN.1 Integer
|
||||
BIND[3] = 1; // len
|
||||
BIND[4] = 0x04; // msgid (make up 4)
|
||||
BIND[5] = 0x60; // Bind Request
|
||||
BIND[6] = 7; // len
|
||||
BIND[7] = 0x02; // ASN.1 Integer
|
||||
BIND[8] = 1; // len
|
||||
BIND[9] = 0x03; // v3
|
||||
BIND[10] = 0x04; // String (bind dn)
|
||||
BIND[11] = 0; // len
|
||||
BIND[12] = 0x80; // ContextSpecific (choice)
|
||||
BIND[13] = 0; // simple bind
|
||||
|
||||
// Start testing ^^
|
||||
var ber = new BerReader(BIND); |
||||
t.equal(ber.readSequence(), 48, 'Not an ASN.1 Sequence'); |
||||
t.equal(ber.length, 12, 'Message length should be 12'); |
||||
t.equal(ber.readInt(), 4, 'Message id should have been 4'); |
||||
t.equal(ber.readSequence(), 96, 'Bind Request should have been 96'); |
||||
t.equal(ber.length, 7, 'Bind length should have been 7'); |
||||
t.equal(ber.readInt(), 3, 'LDAP version should have been 3'); |
||||
t.equal(ber.readString(), '', 'Bind DN should have been empty'); |
||||
t.equal(ber.length, 0, 'string length should have been 0'); |
||||
t.equal(ber.readByte(), 0x80, 'Should have been ContextSpecific (choice)'); |
||||
t.equal(ber.readByte(), 0, 'Should have been simple bind'); |
||||
t.equal(null, ber.readByte(), 'Should be out of data'); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('long string', function(t) { |
||||
var buf = new Buffer(256); |
||||
var o; |
||||
var s = |
||||
'2;649;CN=Red Hat CS 71GA Demo,O=Red Hat CS 71GA Demo,C=US;' + |
||||
'CN=RHCS Agent - admin01,UID=admin01,O=redhat,C=US [1] This is ' + |
||||
'Teena Vradmin\'s description.'; |
||||
buf[0] = 0x04; |
||||
buf[1] = 0x81; |
||||
buf[2] = 0x94; |
||||
buf.write(s, 3); |
||||
var ber = new BerReader(buf.slice(0, 3 + s.length)); |
||||
t.equal(ber.readString(), s); |
||||
t.end(); |
||||
}); |
@ -1,370 +0,0 @@ |
||||
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
|
||||
|
||||
var test = require('tap').test; |
||||
var sys = require('sys'); |
||||
|
||||
///--- Globals
|
||||
|
||||
var BerWriter; |
||||
|
||||
var BerReader; |
||||
|
||||
|
||||
///--- Tests
|
||||
|
||||
test('load library', function(t) { |
||||
BerWriter = require('../../lib/index').BerWriter; |
||||
t.ok(BerWriter); |
||||
t.ok(new BerWriter()); |
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write byte', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeByte(0xC2); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 1, 'Wrong length'); |
||||
t.equal(ber[0], 0xC2, 'value wrong'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 1 byte int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(0x7f); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 3, 'Wrong length for an int: ' + ber.length); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong (2) -> ' + ber[0]); |
||||
t.equal(ber[1], 0x01, 'length wrong(1) -> ' + ber[1]); |
||||
t.equal(ber[2], 0x7f, 'value wrong(3) -> ' + ber[2]); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 2 byte int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(0x7ffe); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 4, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x02, 'length wrong'); |
||||
t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0xfe, 'value wrong (byte 2)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 3 byte int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(0x7ffffe); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 5, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x03, 'length wrong'); |
||||
t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0xff, 'value wrong (byte 2)'); |
||||
t.equal(ber[4], 0xfe, 'value wrong (byte 3)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 4 byte int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(0x7ffffffe); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 6, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x04, 'length wrong'); |
||||
t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0xff, 'value wrong (byte 2)'); |
||||
t.equal(ber[4], 0xff, 'value wrong (byte 3)'); |
||||
t.equal(ber[5], 0xfe, 'value wrong (byte 4)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 1 byte negative int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(-128); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 3, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x01, 'length wrong'); |
||||
t.equal(ber[2], 0x80, 'value wrong (byte 1)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 2 byte negative int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(-22400); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 4, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x02, 'length wrong'); |
||||
t.equal(ber[2], 0xa8, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0x80, 'value wrong (byte 2)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 3 byte negative int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(-481653); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 5, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x03, 'length wrong'); |
||||
t.equal(ber[2], 0xf8, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0xa6, 'value wrong (byte 2)'); |
||||
t.equal(ber[4], 0x8b, 'value wrong (byte 3)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write 4 byte negative int', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeInt(-1522904131); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 6, 'Wrong length for an int'); |
||||
t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); |
||||
t.equal(ber[1], 0x04, 'length wrong'); |
||||
t.equal(ber[2], 0xa5, 'value wrong (byte 1)'); |
||||
t.equal(ber[3], 0x3a, 'value wrong (byte 2)'); |
||||
t.equal(ber[4], 0x53, 'value wrong (byte 3)'); |
||||
t.equal(ber[5], 0xbd, 'value wrong (byte 4)'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write boolean', function(t) { |
||||
var writer = new BerWriter(); |
||||
|
||||
writer.writeBoolean(true); |
||||
writer.writeBoolean(false); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 6, 'Wrong length'); |
||||
t.equal(ber[0], 0x01, 'tag wrong'); |
||||
t.equal(ber[1], 0x01, 'length wrong'); |
||||
t.equal(ber[2], 0xff, 'value wrong'); |
||||
t.equal(ber[3], 0x01, 'tag wrong'); |
||||
t.equal(ber[4], 0x01, 'length wrong'); |
||||
t.equal(ber[5], 0x00, 'value wrong'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('write string', function(t) { |
||||
var writer = new BerWriter(); |
||||
writer.writeString('hello world'); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 13, 'wrong length'); |
||||
t.equal(ber[0], 0x04, 'wrong tag'); |
||||
t.equal(ber[1], 11, 'wrong length'); |
||||
t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
test('write buffer', function(t) { |
||||
var writer = new BerWriter(); |
||||
// write some stuff to start with
|
||||
writer.writeString('hello world'); |
||||
var ber = writer.buffer; |
||||
var buf = new Buffer([0x04, 0x0b, 0x30, 0x09, 0x02, 0x01, 0x0f, 0x01, 0x01, |
||||
0xff, 0x01, 0x01, 0xff]); |
||||
writer.writeBuffer(buf.slice(2, buf.length), 0x04); |
||||
ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 26, 'wrong length'); |
||||
t.equal(ber[0], 0x04, 'wrong tag'); |
||||
t.equal(ber[1], 11, 'wrong length'); |
||||
t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value'); |
||||
t.equal(ber[13], buf[0], 'wrong tag'); |
||||
t.equal(ber[14], buf[1], 'wrong length'); |
||||
for (var i = 13, j = 0; i < ber.length && j < buf.length; i++, j++) { |
||||
t.equal(ber[i], buf[j], 'buffer contents not identical'); |
||||
} |
||||
t.end(); |
||||
}); |
||||
|
||||
test('write string array', function(t) { |
||||
var writer = new BerWriter(); |
||||
writer.writeStringArray(['hello world', 'fubar!']); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
|
||||
t.equal(ber.length, 21, 'wrong length'); |
||||
t.equal(ber[0], 0x04, 'wrong tag'); |
||||
t.equal(ber[1], 11, 'wrong length'); |
||||
t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value'); |
||||
|
||||
t.equal(ber[13], 0x04, 'wrong tag'); |
||||
t.equal(ber[14], 6, 'wrong length'); |
||||
t.equal(ber.slice(15).toString('utf8'), 'fubar!', 'wrong value'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('resize internal buffer', function(t) { |
||||
var writer = new BerWriter({size: 2}); |
||||
writer.writeString('hello world'); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 13, 'wrong length'); |
||||
t.equal(ber[0], 0x04, 'wrong tag'); |
||||
t.equal(ber[1], 11, 'wrong length'); |
||||
t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('sequence', function(t) { |
||||
var writer = new BerWriter({size: 25}); |
||||
writer.startSequence(); |
||||
writer.writeString('hello world'); |
||||
writer.endSequence(); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
console.log(ber); |
||||
t.equal(ber.length, 15, 'wrong length'); |
||||
t.equal(ber[0], 0x30, 'wrong tag'); |
||||
t.equal(ber[1], 13, 'wrong length'); |
||||
t.equal(ber[2], 0x04, 'wrong tag'); |
||||
t.equal(ber[3], 11, 'wrong length'); |
||||
t.equal(ber.slice(4).toString('utf8'), 'hello world', 'wrong value'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('nested sequence', function(t) { |
||||
var writer = new BerWriter({size: 25}); |
||||
writer.startSequence(); |
||||
writer.writeString('hello world'); |
||||
writer.startSequence(); |
||||
writer.writeString('hello world'); |
||||
writer.endSequence(); |
||||
writer.endSequence(); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 30, 'wrong length'); |
||||
t.equal(ber[0], 0x30, 'wrong tag'); |
||||
t.equal(ber[1], 28, 'wrong length'); |
||||
t.equal(ber[2], 0x04, 'wrong tag'); |
||||
t.equal(ber[3], 11, 'wrong length'); |
||||
t.equal(ber.slice(4, 15).toString('utf8'), 'hello world', 'wrong value'); |
||||
t.equal(ber[15], 0x30, 'wrong tag'); |
||||
t.equal(ber[16], 13, 'wrong length'); |
||||
t.equal(ber[17], 0x04, 'wrong tag'); |
||||
t.equal(ber[18], 11, 'wrong length'); |
||||
t.equal(ber.slice(19, 30).toString('utf8'), 'hello world', 'wrong value'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('LDAP bind message', function(t) { |
||||
var dn = 'cn=foo,ou=unit,o=test'; |
||||
var writer = new BerWriter(); |
||||
writer.startSequence(); |
||||
writer.writeInt(3); // msgid = 3
|
||||
writer.startSequence(0x60); // ldap bind
|
||||
writer.writeInt(3); // ldap v3
|
||||
writer.writeString(dn); |
||||
writer.writeByte(0x80); |
||||
writer.writeByte(0x00); |
||||
writer.endSequence(); |
||||
writer.endSequence(); |
||||
var ber = writer.buffer; |
||||
|
||||
t.ok(ber); |
||||
t.equal(ber.length, 35, 'wrong length (buffer)'); |
||||
t.equal(ber[0], 0x30, 'wrong tag'); |
||||
t.equal(ber[1], 33, 'wrong length'); |
||||
t.equal(ber[2], 0x02, 'wrong tag'); |
||||
t.equal(ber[3], 1, 'wrong length'); |
||||
t.equal(ber[4], 0x03, 'wrong value'); |
||||
t.equal(ber[5], 0x60, 'wrong tag'); |
||||
t.equal(ber[6], 28, 'wrong length'); |
||||
t.equal(ber[7], 0x02, 'wrong tag'); |
||||
t.equal(ber[8], 1, 'wrong length'); |
||||
t.equal(ber[9], 0x03, 'wrong value'); |
||||
t.equal(ber[10], 0x04, 'wrong tag'); |
||||
t.equal(ber[11], dn.length, 'wrong length'); |
||||
t.equal(ber.slice(12, 33).toString('utf8'), dn, 'wrong value'); |
||||
t.equal(ber[33], 0x80, 'wrong tag'); |
||||
t.equal(ber[34], 0x00, 'wrong len'); |
||||
|
||||
t.end(); |
||||
}); |
||||
|
||||
|
||||
test('Write OID', function(t) { |
||||
var oid = '1.2.840.113549.1.1.1'; |
||||
var writer = new BerWriter(); |
||||
writer.writeOID(oid); |
||||
|
||||
var ber = writer.buffer; |
||||
t.ok(ber); |
||||
console.log(require('util').inspect(ber)); |
||||
console.log(require('util').inspect(new Buffer([0x06, 0x09, 0x2a, 0x86, |
||||
0x48, 0x86, 0xf7, 0x0d, |
||||
0x01, 0x01, 0x01]))); |
||||
|
||||
t.end(); |
||||
}); |
@ -1,6 +0,0 @@ |
||||
Dave Eddy <dave@daveeddy.com> |
||||
Fred Kuo <fred.kuo@joyent.com> |
||||
Lars-Magnus Skog <ralphtheninja@riseup.net> |
||||
Mark Cavage <mcavage@gmail.com> |
||||
Patrick Mooney <pmooney@pfmooney.com> |
||||
Rob Gulewich <robert.gulewich@joyent.com> |
@ -1,8 +0,0 @@ |
||||
# assert-plus Changelog |
||||
|
||||
## 0.2.0 |
||||
|
||||
- Fix `assert.object(null)` so it throws |
||||
- Fix optional/arrayOf exports for non-type-of asserts |
||||
- Add optiona/arrayOf exports for Stream/Date/Regex/uuid |
||||
- Add basic unit test coverage |
@ -1,155 +0,0 @@ |
||||
# assert-plus |
||||
|
||||
This library is a super small wrapper over node's assert module that has two |
||||
things: (1) the ability to disable assertions with the environment variable |
||||
NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like |
||||
`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks |
||||
like this: |
||||
|
||||
```javascript |
||||
var assert = require('assert-plus'); |
||||
|
||||
function fooAccount(options, callback) { |
||||
assert.object(options, 'options'); |
||||
assert.number(options.id, 'options.id'); |
||||
assert.bool(options.isManager, 'options.isManager'); |
||||
assert.string(options.name, 'options.name'); |
||||
assert.arrayOfString(options.email, 'options.email'); |
||||
assert.func(callback, 'callback'); |
||||
|
||||
// Do stuff |
||||
callback(null, {}); |
||||
} |
||||
``` |
||||
|
||||
# API |
||||
|
||||
All methods that *aren't* part of node's core assert API are simply assumed to |
||||
take an argument, and then a string 'name' that's not a message; `AssertionError` |
||||
will be thrown if the assertion fails with a message like: |
||||
|
||||
AssertionError: foo (string) is required |
||||
at test (/home/mark/work/foo/foo.js:3:9) |
||||
at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1) |
||||
at Module._compile (module.js:446:26) |
||||
at Object..js (module.js:464:10) |
||||
at Module.load (module.js:353:31) |
||||
at Function._load (module.js:311:12) |
||||
at Array.0 (module.js:484:10) |
||||
at EventEmitter._tickCallback (node.js:190:38) |
||||
|
||||
from: |
||||
|
||||
```javascript |
||||
function test(foo) { |
||||
assert.string(foo, 'foo'); |
||||
} |
||||
``` |
||||
|
||||
There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`: |
||||
|
||||
```javascript |
||||
function test(foo) { |
||||
assert.arrayOfString(foo, 'foo'); |
||||
} |
||||
``` |
||||
|
||||
You can assert IFF an argument is not `undefined` (i.e., an optional arg): |
||||
|
||||
```javascript |
||||
assert.optionalString(foo, 'foo'); |
||||
``` |
||||
|
||||
Lastly, you can opt-out of assertion checking altogether by setting the |
||||
environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have |
||||
lots of assertions, and don't want to pay `typeof ()` taxes to v8 in |
||||
production. Be advised: The standard functions re-exported from `assert` are |
||||
also disabled in assert-plus if NDEBUG is specified. Using them directly from |
||||
the `assert` module avoids this behavior. |
||||
|
||||
The complete list of APIs is: |
||||
|
||||
* assert.array |
||||
* assert.bool |
||||
* assert.buffer |
||||
* assert.func |
||||
* assert.number |
||||
* assert.object |
||||
* assert.string |
||||
* assert.stream |
||||
* assert.date |
||||
* assert.regex |
||||
* assert.uuid |
||||
* assert.arrayOfArray |
||||
* assert.arrayOfBool |
||||
* assert.arrayOfBuffer |
||||
* assert.arrayOfFunc |
||||
* assert.arrayOfNumber |
||||
* assert.arrayOfObject |
||||
* assert.arrayOfString |
||||
* assert.arrayOfStream |
||||
* assert.arrayOfDate |
||||
* assert.arrayOfUuid |
||||
* assert.optionalArray |
||||
* assert.optionalBool |
||||
* assert.optionalBuffer |
||||
* assert.optionalFunc |
||||
* assert.optionalNumber |
||||
* assert.optionalObject |
||||
* assert.optionalString |
||||
* assert.optionalStream |
||||
* assert.optionalDate |
||||
* assert.optionalUuid |
||||
* assert.optionalArrayOfArray |
||||
* assert.optionalArrayOfBool |
||||
* assert.optionalArrayOfBuffer |
||||
* assert.optionalArrayOfFunc |
||||
* assert.optionalArrayOfNumber |
||||
* assert.optionalArrayOfObject |
||||
* assert.optionalArrayOfString |
||||
* assert.optionalArrayOfStream |
||||
* assert.optionalArrayOfDate |
||||
* assert.optionalArrayOfUuid |
||||
* assert.AssertionError |
||||
* assert.fail |
||||
* assert.ok |
||||
* assert.equal |
||||
* assert.notEqual |
||||
* assert.deepEqual |
||||
* assert.notDeepEqual |
||||
* assert.strictEqual |
||||
* assert.notStrictEqual |
||||
* assert.throws |
||||
* assert.doesNotThrow |
||||
* assert.ifError |
||||
|
||||
# Installation |
||||
|
||||
npm install assert-plus |
||||
|
||||
## License |
||||
|
||||
The MIT License (MIT) |
||||
Copyright (c) 2012 Mark Cavage |
||||
|
||||
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. |
||||
|
||||
## Bugs |
||||
|
||||
See <https://github.com/mcavage/node-assert-plus/issues>. |
@ -1,206 +0,0 @@ |
||||
// Copyright (c) 2012, Mark Cavage. All rights reserved.
|
||||
// Copyright 2015 Joyent, Inc.
|
||||
|
||||
var assert = require('assert'); |
||||
var Stream = require('stream').Stream; |
||||
var util = require('util'); |
||||
|
||||
|
||||
///--- Globals
|
||||
|
||||
/* JSSTYLED */ |
||||
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; |
||||
|
||||
|
||||
///--- Internal
|
||||
|
||||
function _capitalize(str) { |
||||
return (str.charAt(0).toUpperCase() + str.slice(1)); |
||||
} |
||||
|
||||
function _toss(name, expected, oper, arg, actual) { |
||||
throw new assert.AssertionError({ |
||||
message: util.format('%s (%s) is required', name, expected), |
||||
actual: (actual === undefined) ? typeof (arg) : actual(arg), |
||||
expected: expected, |
||||
operator: oper || '===', |
||||
stackStartFunction: _toss.caller |
||||
}); |
||||
} |
||||
|
||||
function _getClass(arg) { |
||||
return (Object.prototype.toString.call(arg).slice(8, -1)); |
||||
} |
||||
|
||||
function noop() { |
||||
// Why even bother with asserts?
|
||||
} |
||||
|
||||
|
||||
///--- Exports
|
||||
|
||||
var types = { |
||||
bool: { |
||||
check: function (arg) { return typeof (arg) === 'boolean'; } |
||||
}, |
||||
func: { |
||||
check: function (arg) { return typeof (arg) === 'function'; } |
||||
}, |
||||
string: { |
||||
check: function (arg) { return typeof (arg) === 'string'; } |
||||
}, |
||||
object: { |
||||
check: function (arg) { |
||||
return typeof (arg) === 'object' && arg !== null; |
||||
} |
||||
}, |
||||
number: { |
||||
check: function (arg) { |
||||
return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); |
||||
} |
||||
}, |
||||
buffer: { |
||||
check: function (arg) { return Buffer.isBuffer(arg); }, |
||||
operator: 'Buffer.isBuffer' |
||||
}, |
||||
array: { |
||||
check: function (arg) { return Array.isArray(arg); }, |
||||
operator: 'Array.isArray' |
||||
}, |
||||
stream: { |
||||
check: function (arg) { return arg instanceof Stream; }, |
||||
operator: 'instanceof', |
||||
actual: _getClass |
||||
}, |
||||
date: { |
||||
check: function (arg) { return arg instanceof Date; }, |
||||
operator: 'instanceof', |
||||
actual: _getClass |
||||
}, |
||||
regexp: { |
||||
check: function (arg) { return arg instanceof RegExp; }, |
||||
operator: 'instanceof', |
||||
actual: _getClass |
||||
}, |
||||
uuid: { |
||||
check: function (arg) { |
||||
return typeof (arg) === 'string' && UUID_REGEXP.test(arg); |
||||
}, |
||||
operator: 'isUUID' |
||||
} |
||||
}; |
||||
|
||||
function _setExports(ndebug) { |
||||
var keys = Object.keys(types); |
||||
var out; |
||||
|
||||
/* re-export standard assert */ |
||||
if (process.env.NODE_NDEBUG) { |
||||
out = noop; |
||||
} else { |
||||
out = function (arg, msg) { |
||||
if (!arg) { |
||||
_toss(msg, 'true', arg); |
||||
} |
||||
}; |
||||
} |
||||
|
||||
/* standard checks */ |
||||
keys.forEach(function (k) { |
||||
if (ndebug) { |
||||
out[k] = noop; |
||||
return; |
||||
} |
||||
var type = types[k]; |
||||
out[k] = function (arg, msg) { |
||||
if (!type.check(arg)) { |
||||
_toss(msg, k, type.operator, arg, type.actual); |
||||
} |
||||
}; |
||||
}); |
||||
|
||||
/* optional checks */ |
||||
keys.forEach(function (k) { |
||||
var name = 'optional' + _capitalize(k); |
||||
if (ndebug) { |
||||
out[name] = noop; |
||||
return; |
||||
} |
||||
var type = types[k]; |
||||
out[name] = function (arg, msg) { |
||||
if (arg === undefined || arg === null) { |
||||
return; |
||||
} |
||||
if (!type.check(arg)) { |
||||
_toss(msg, k, type.operator, arg, type.actual); |
||||
} |
||||
}; |
||||
}); |
||||
|
||||
/* arrayOf checks */ |
||||
keys.forEach(function (k) { |
||||
var name = 'arrayOf' + _capitalize(k); |
||||
if (ndebug) { |
||||
out[name] = noop; |
||||
return; |
||||
} |
||||
var type = types[k]; |
||||
var expected = '[' + k + ']'; |
||||
out[name] = function (arg, msg) { |
||||
if (!Array.isArray(arg)) { |
||||
_toss(msg, expected, type.operator, arg, type.actual); |
||||
} |
||||
var i; |
||||
for (i = 0; i < arg.length; i++) { |
||||
if (!type.check(arg[i])) { |
||||
_toss(msg, expected, type.operator, arg, type.actual); |
||||
} |
||||
} |
||||
}; |
||||
}); |
||||
|
||||
/* optionalArrayOf checks */ |
||||
keys.forEach(function (k) { |
||||
var name = 'optionalArrayOf' + _capitalize(k); |
||||
if (ndebug) { |
||||
out[name] = noop; |
||||
return; |
||||
} |
||||
var type = types[k]; |
||||
var expected = '[' + k + ']'; |
||||
out[name] = function (arg, msg) { |
||||
if (arg === undefined || arg === null) { |
||||
return; |
||||
} |
||||
if (!Array.isArray(arg)) { |
||||
_toss(msg, expected, type.operator, arg, type.actual); |
||||
} |
||||
var i; |
||||
for (i = 0; i < arg.length; i++) { |
||||
if (!type.check(arg[i])) { |
||||
_toss(msg, expected, type.operator, arg, type.actual); |
||||
} |
||||
} |
||||
}; |
||||
}); |
||||
|
||||
/* re-export built-in assertions */ |
||||
Object.keys(assert).forEach(function (k) { |
||||
if (k === 'AssertionError') { |
||||
out[k] = assert[k]; |
||||
return; |
||||
} |
||||
if (ndebug) { |
||||
out[k] = noop; |
||||
return; |
||||
} |
||||
out[k] = assert[k]; |
||||
}); |
||||
|
||||
/* export ourselves (for unit tests _only_) */ |
||||
out._setExports = _setExports; |
||||
|
||||
return out; |
||||
} |
||||
|
||||
module.exports = _setExports(process.env.NODE_NDEBUG); |
@ -1,82 +0,0 @@ |
||||
{ |
||||
"_from": "assert-plus@^0.2.0", |
||||
"_id": "assert-plus@0.2.0", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-104bh+ev/A24qttwIfP+SBAasjQ=", |
||||
"_location": "/assert-plus", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "assert-plus@^0.2.0", |
||||
"name": "assert-plus", |
||||
"escapedName": "assert-plus", |
||||
"rawSpec": "^0.2.0", |
||||
"saveSpec": null, |
||||
"fetchSpec": "^0.2.0" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/http-signature" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz", |
||||
"_shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234", |
||||
"_spec": "assert-plus@^0.2.0", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/http-signature", |
||||
"author": { |
||||
"name": "Mark Cavage", |
||||
"email": "mcavage@gmail.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/mcavage/node-assert-plus/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"contributors": [ |
||||
{ |
||||
"name": "Dave Eddy", |
||||
"email": "dave@daveeddy.com" |
||||
}, |
||||
{ |
||||
"name": "Fred Kuo", |
||||
"email": "fred.kuo@joyent.com" |
||||
}, |
||||
{ |
||||
"name": "Lars-Magnus Skog", |
||||
"email": "ralphtheninja@riseup.net" |
||||
}, |
||||
{ |
||||
"name": "Mark Cavage", |
||||
"email": "mcavage@gmail.com" |
||||
}, |
||||
{ |
||||
"name": "Patrick Mooney", |
||||
"email": "pmooney@pfmooney.com" |
||||
}, |
||||
{ |
||||
"name": "Rob Gulewich", |
||||
"email": "robert.gulewich@joyent.com" |
||||
} |
||||
], |
||||
"dependencies": {}, |
||||
"deprecated": false, |
||||
"description": "Extra assertions on top of node's assert module", |
||||
"devDependencies": { |
||||
"faucet": "0.0.1", |
||||
"tape": "4.2.2" |
||||
}, |
||||
"engines": { |
||||
"node": ">=0.8" |
||||
}, |
||||
"homepage": "https://github.com/mcavage/node-assert-plus#readme", |
||||
"license": "MIT", |
||||
"main": "./assert.js", |
||||
"name": "assert-plus", |
||||
"optionalDependencies": {}, |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git+https://github.com/mcavage/node-assert-plus.git" |
||||
}, |
||||
"scripts": { |
||||
"test": "tape tests/*.js | ./node_modules/.bin/faucet" |
||||
}, |
||||
"version": "0.2.0" |
||||
} |
@ -1,21 +0,0 @@ |
||||
The MIT License (MIT) |
||||
|
||||
Copyright (c) 2016 Alex Indigo |
||||
|
||||
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. |
@ -1,233 +0,0 @@ |
||||
# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) |
||||
|
||||
Minimal async jobs utility library, with streams support. |
||||
|
||||
[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) |
||||
[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) |
||||
[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) |
||||
|
||||
[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) |
||||
[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) |
||||
[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) |
||||
|
||||
<!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) --> |
||||
|
||||
AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. |
||||
Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. |
||||
|
||||
It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. |
||||
|
||||
| compression | size | |
||||
| :----------------- | -------: | |
||||
| asynckit.js | 12.34 kB | |
||||
| asynckit.min.js | 4.11 kB | |
||||
| asynckit.min.js.gz | 1.47 kB | |
||||
|
||||
|
||||
## Install |
||||
|
||||
```sh |
||||
$ npm install --save asynckit |
||||
``` |
||||
|
||||
## Examples |
||||
|
||||
### Parallel Jobs |
||||
|
||||
Runs iterator over provided array in parallel. Stores output in the `result` array, |
||||
on the matching positions. In unlikely event of an error from one of the jobs, |
||||
will terminate rest of the active jobs (if abort function is provided) |
||||
and return error along with salvaged data to the main callback function. |
||||
|
||||
#### Input Array |
||||
|
||||
```javascript |
||||
var parallel = require('asynckit').parallel |
||||
, assert = require('assert') |
||||
; |
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] |
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] |
||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] |
||||
, target = [] |
||||
; |
||||
|
||||
parallel(source, asyncJob, function(err, result) |
||||
{ |
||||
assert.deepEqual(result, expectedResult); |
||||
assert.deepEqual(target, expectedTarget); |
||||
}); |
||||
|
||||
// async job accepts one element from the array |
||||
// and a callback function |
||||
function asyncJob(item, cb) |
||||
{ |
||||
// different delays (in ms) per item |
||||
var delay = item * 25; |
||||
|
||||
// pretend different jobs take different time to finish |
||||
// and not in consequential order |
||||
var timeoutId = setTimeout(function() { |
||||
target.push(item); |
||||
cb(null, item * 2); |
||||
}, delay); |
||||
|
||||
// allow to cancel "leftover" jobs upon error |
||||
// return function, invoking of which will abort this job |
||||
return clearTimeout.bind(null, timeoutId); |
||||
} |
||||
``` |
||||
|
||||
More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). |
||||
|
||||
#### Input Object |
||||
|
||||
Also it supports named jobs, listed via object. |
||||
|
||||
```javascript |
||||
var parallel = require('asynckit/parallel') |
||||
, assert = require('assert') |
||||
; |
||||
|
||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } |
||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } |
||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] |
||||
, expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] |
||||
, target = [] |
||||
, keys = [] |
||||
; |
||||
|
||||
parallel(source, asyncJob, function(err, result) |
||||
{ |
||||
assert.deepEqual(result, expectedResult); |
||||
assert.deepEqual(target, expectedTarget); |
||||
assert.deepEqual(keys, expectedKeys); |
||||
}); |
||||
|
||||
// supports full value, key, callback (shortcut) interface |
||||
function asyncJob(item, key, cb) |
||||
{ |
||||
// different delays (in ms) per item |
||||
var delay = item * 25; |
||||
|
||||
// pretend different jobs take different time to finish |
||||
// and not in consequential order |
||||
var timeoutId = setTimeout(function() { |
||||
keys.push(key); |
||||
target.push(item); |
||||
cb(null, item * 2); |
||||
}, delay); |
||||
|
||||
// allow to cancel "leftover" jobs upon error |
||||
// return function, invoking of which will abort this job |
||||
return clearTimeout.bind(null, timeoutId); |
||||
} |
||||
``` |
||||
|
||||
More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). |
||||
|
||||
### Serial Jobs |
||||
|
||||
Runs iterator over provided array sequentially. Stores output in the `result` array, |
||||
on the matching positions. In unlikely event of an error from one of the jobs, |
||||
will not proceed to the rest of the items in the list |
||||
and return error along with salvaged data to the main callback function. |
||||
|
||||
#### Input Array |
||||
|
||||
```javascript |
||||
var serial = require('asynckit/serial') |
||||
, assert = require('assert') |
||||
; |
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] |
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] |
||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] |
||||
, target = [] |
||||
; |
||||
|
||||
serial(source, asyncJob, function(err, result) |
||||
{ |
||||
assert.deepEqual(result, expectedResult); |
||||
assert.deepEqual(target, expectedTarget); |
||||
}); |
||||
|
||||
// extended interface (item, key, callback) |
||||
// also supported for arrays |
||||
function asyncJob(item, key, cb) |
||||
{ |
||||
target.push(key); |
||||
|
||||
// it will be automatically made async |
||||
// even it iterator "returns" in the same event loop |
||||
cb(null, item * 2); |
||||
} |
||||
``` |
||||
|
||||
More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). |
||||
|
||||
#### Input Object |
||||
|
||||
Also it supports named jobs, listed via object. |
||||
|
||||
```javascript |
||||
var serial = require('asynckit').serial |
||||
, assert = require('assert') |
||||
; |
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] |
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] |
||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] |
||||
, target = [] |
||||
; |
||||
|
||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } |
||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } |
||||
, expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] |
||||
, target = [] |
||||
; |
||||
|
||||
|
||||
serial(source, asyncJob, function(err, result) |
||||
{ |
||||
assert.deepEqual(result, expectedResult); |
||||
assert.deepEqual(target, expectedTarget); |
||||
}); |
||||
|
||||
// shortcut interface (item, callback) |
||||
// works for object as well as for the arrays |
||||
function asyncJob(item, cb) |
||||
{ |
||||
target.push(item); |
||||
|
||||
// it will be automatically made async |
||||
// even it iterator "returns" in the same event loop |
||||
cb(null, item * 2); |
||||
} |
||||
``` |
||||
|
||||
More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). |
||||
|
||||
_Note: Since _object_ is an _unordered_ collection of properties, |
||||
it may produce unexpected results with sequential iterations. |
||||
Whenever order of the jobs' execution is important please use `serialOrdered` method._ |
||||
|
||||
### Ordered Serial Iterations |
||||
|
||||
TBD |
||||
|
||||
For example [compare-property](compare-property) package. |
||||
|
||||
### Streaming interface |
||||
|
||||
TBD |
||||
|
||||
## Want to Know More? |
||||
|
||||
More examples can be found in [test folder](test/). |
||||
|
||||
Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. |
||||
|
||||
## License |
||||
|
||||
AsyncKit is licensed under the MIT license. |
@ -1,76 +0,0 @@ |
||||
/* eslint no-console: "off" */ |
||||
|
||||
var asynckit = require('./') |
||||
, async = require('async') |
||||
, assert = require('assert') |
||||
, expected = 0 |
||||
; |
||||
|
||||
var Benchmark = require('benchmark'); |
||||
var suite = new Benchmark.Suite; |
||||
|
||||
var source = []; |
||||
for (var z = 1; z < 100; z++) |
||||
{ |
||||
source.push(z); |
||||
expected += z; |
||||
} |
||||
|
||||
suite |
||||
// add tests
|
||||
|
||||
.add('async.map', function(deferred) |
||||
{ |
||||
var total = 0; |
||||
|
||||
async.map(source, |
||||
function(i, cb) |
||||
{ |
||||
setImmediate(function() |
||||
{ |
||||
total += i; |
||||
cb(null, total); |
||||
}); |
||||
}, |
||||
function(err, result) |
||||
{ |
||||
assert.ifError(err); |
||||
assert.equal(result[result.length - 1], expected); |
||||
deferred.resolve(); |
||||
}); |
||||
}, {'defer': true}) |
||||
|
||||
|
||||
.add('asynckit.parallel', function(deferred) |
||||
{ |
||||
var total = 0; |
||||
|
||||
asynckit.parallel(source, |
||||
function(i, cb) |
||||
{ |
||||
setImmediate(function() |
||||
{ |
||||
total += i; |
||||
cb(null, total); |
||||
}); |
||||
}, |
||||
function(err, result) |
||||
{ |
||||
assert.ifError(err); |
||||
assert.equal(result[result.length - 1], expected); |
||||
deferred.resolve(); |
||||
}); |
||||
}, {'defer': true}) |
||||
|
||||
|
||||
// add listeners
|
||||
.on('cycle', function(ev) |
||||
{ |
||||
console.log(String(ev.target)); |
||||
}) |
||||
.on('complete', function() |
||||
{ |
||||
console.log('Fastest is ' + this.filter('fastest').map('name')); |
||||
}) |
||||
// run async
|
||||
.run({ 'async': true }); |
@ -1,6 +0,0 @@ |
||||
module.exports = |
||||
{ |
||||
parallel : require('./parallel.js'), |
||||
serial : require('./serial.js'), |
||||
serialOrdered : require('./serialOrdered.js') |
||||
}; |
@ -1,29 +0,0 @@ |
||||
// API
|
||||
module.exports = abort; |
||||
|
||||
/** |
||||
* Aborts leftover active jobs |
||||
* |
||||
* @param {object} state - current state object |
||||
*/ |
||||
function abort(state) |
||||
{ |
||||
Object.keys(state.jobs).forEach(clean.bind(state)); |
||||
|
||||
// reset leftover jobs
|
||||
state.jobs = {}; |
||||
} |
||||
|
||||
/** |
||||
* Cleans up leftover job by invoking abort function for the provided job id |
||||
* |
||||
* @this state |
||||
* @param {string|number} key - job id to abort |
||||
*/ |
||||
function clean(key) |
||||
{ |
||||
if (typeof this.jobs[key] == 'function') |
||||
{ |
||||
this.jobs[key](); |
||||
} |
||||
} |
@ -1,34 +0,0 @@ |
||||
var defer = require('./defer.js'); |
||||
|
||||
// API
|
||||
module.exports = async; |
||||
|
||||
/** |
||||
* Runs provided callback asynchronously |
||||
* even if callback itself is not |
||||
* |
||||
* @param {function} callback - callback to invoke |
||||
* @returns {function} - augmented callback |
||||
*/ |
||||
function async(callback) |
||||
{ |
||||
var isAsync = false; |
||||
|
||||
// check if async happened
|
||||
defer(function() { isAsync = true; }); |
||||
|
||||
return function async_callback(err, result) |
||||
{ |
||||
if (isAsync) |
||||
{ |
||||
callback(err, result); |
||||
} |
||||
else |
||||
{ |
||||
defer(function nextTick_callback() |
||||
{ |
||||
callback(err, result); |
||||
}); |
||||
} |
||||
}; |
||||
} |
@ -1,26 +0,0 @@ |
||||
module.exports = defer; |
||||
|
||||
/** |
||||
* Runs provided function on next iteration of the event loop |
||||
* |
||||
* @param {function} fn - function to run |
||||
*/ |
||||
function defer(fn) |
||||
{ |
||||
var nextTick = typeof setImmediate == 'function' |
||||
? setImmediate |
||||
: ( |
||||
typeof process == 'object' && typeof process.nextTick == 'function' |
||||
? process.nextTick |
||||
: null |
||||
); |
||||
|
||||
if (nextTick) |
||||
{ |
||||
nextTick(fn); |
||||
} |
||||
else |
||||
{ |
||||
setTimeout(fn, 0); |
||||
} |
||||
} |
@ -1,75 +0,0 @@ |
||||
var async = require('./async.js') |
||||
, abort = require('./abort.js') |
||||
; |
||||
|
||||
// API
|
||||
module.exports = iterate; |
||||
|
||||
/** |
||||
* Iterates over each job object |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {object} state - current job status |
||||
* @param {function} callback - invoked when all elements processed |
||||
*/ |
||||
function iterate(list, iterator, state, callback) |
||||
{ |
||||
// store current index
|
||||
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; |
||||
|
||||
state.jobs[key] = runJob(iterator, key, list[key], function(error, output) |
||||
{ |
||||
// don't repeat yourself
|
||||
// skip secondary callbacks
|
||||
if (!(key in state.jobs)) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
// clean up jobs
|
||||
delete state.jobs[key]; |
||||
|
||||
if (error) |
||||
{ |
||||
// don't process rest of the results
|
||||
// stop still active jobs
|
||||
// and reset the list
|
||||
abort(state); |
||||
} |
||||
else |
||||
{ |
||||
state.results[key] = output; |
||||
} |
||||
|
||||
// return salvaged results
|
||||
callback(error, state.results); |
||||
}); |
||||
} |
||||
|
||||
/** |
||||
* Runs iterator over provided job element |
||||
* |
||||
* @param {function} iterator - iterator to invoke |
||||
* @param {string|number} key - key/index of the element in the list of jobs |
||||
* @param {mixed} item - job description |
||||
* @param {function} callback - invoked after iterator is done with the job |
||||
* @returns {function|mixed} - job abort function or something else |
||||
*/ |
||||
function runJob(iterator, key, item, callback) |
||||
{ |
||||
var aborter; |
||||
|
||||
// allow shortcut if iterator expects only two arguments
|
||||
if (iterator.length == 2) |
||||
{ |
||||
aborter = iterator(item, async(callback)); |
||||
} |
||||
// otherwise go with full three arguments
|
||||
else |
||||
{ |
||||
aborter = iterator(item, key, async(callback)); |
||||
} |
||||
|
||||
return aborter; |
||||
} |
@ -1,91 +0,0 @@ |
||||
var streamify = require('./streamify.js') |
||||
, defer = require('./defer.js') |
||||
; |
||||
|
||||
// API
|
||||
module.exports = ReadableAsyncKit; |
||||
|
||||
/** |
||||
* Base constructor for all streams |
||||
* used to hold properties/methods |
||||
*/ |
||||
function ReadableAsyncKit() |
||||
{ |
||||
ReadableAsyncKit.super_.apply(this, arguments); |
||||
|
||||
// list of active jobs
|
||||
this.jobs = {}; |
||||
|
||||
// add stream methods
|
||||
this.destroy = destroy; |
||||
this._start = _start; |
||||
this._read = _read; |
||||
} |
||||
|
||||
/** |
||||
* Destroys readable stream, |
||||
* by aborting outstanding jobs |
||||
* |
||||
* @returns {void} |
||||
*/ |
||||
function destroy() |
||||
{ |
||||
if (this.destroyed) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
this.destroyed = true; |
||||
|
||||
if (typeof this.terminator == 'function') |
||||
{ |
||||
this.terminator(); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* Starts provided jobs in async manner |
||||
* |
||||
* @private |
||||
*/ |
||||
function _start() |
||||
{ |
||||
// first argument – runner function
|
||||
var runner = arguments[0] |
||||
// take away first argument
|
||||
, args = Array.prototype.slice.call(arguments, 1) |
||||
// second argument - input data
|
||||
, input = args[0] |
||||
// last argument - result callback
|
||||
, endCb = streamify.callback.call(this, args[args.length - 1]) |
||||
; |
||||
|
||||
args[args.length - 1] = endCb; |
||||
// third argument - iterator
|
||||
args[1] = streamify.iterator.call(this, args[1]); |
||||
|
||||
// allow time for proper setup
|
||||
defer(function() |
||||
{ |
||||
if (!this.destroyed) |
||||
{ |
||||
this.terminator = runner.apply(null, args); |
||||
} |
||||
else |
||||
{ |
||||
endCb(null, Array.isArray(input) ? [] : {}); |
||||
} |
||||
}.bind(this)); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* Implement _read to comply with Readable streams |
||||
* Doesn't really make sense for flowing object mode |
||||
* |
||||
* @private |
||||
*/ |
||||
function _read() |
||||
{ |
||||
|
||||
} |
@ -1,25 +0,0 @@ |
||||
var parallel = require('../parallel.js'); |
||||
|
||||
// API
|
||||
module.exports = ReadableParallel; |
||||
|
||||
/** |
||||
* Streaming wrapper to `asynckit.parallel` |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {stream.Readable#} |
||||
*/ |
||||
function ReadableParallel(list, iterator, callback) |
||||
{ |
||||
if (!(this instanceof ReadableParallel)) |
||||
{ |
||||
return new ReadableParallel(list, iterator, callback); |
||||
} |
||||
|
||||
// turn on object mode
|
||||
ReadableParallel.super_.call(this, {objectMode: true}); |
||||
|
||||
this._start(parallel, list, iterator, callback); |
||||
} |
@ -1,25 +0,0 @@ |
||||
var serial = require('../serial.js'); |
||||
|
||||
// API
|
||||
module.exports = ReadableSerial; |
||||
|
||||
/** |
||||
* Streaming wrapper to `asynckit.serial` |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {stream.Readable#} |
||||
*/ |
||||
function ReadableSerial(list, iterator, callback) |
||||
{ |
||||
if (!(this instanceof ReadableSerial)) |
||||
{ |
||||
return new ReadableSerial(list, iterator, callback); |
||||
} |
||||
|
||||
// turn on object mode
|
||||
ReadableSerial.super_.call(this, {objectMode: true}); |
||||
|
||||
this._start(serial, list, iterator, callback); |
||||
} |
@ -1,29 +0,0 @@ |
||||
var serialOrdered = require('../serialOrdered.js'); |
||||
|
||||
// API
|
||||
module.exports = ReadableSerialOrdered; |
||||
// expose sort helpers
|
||||
module.exports.ascending = serialOrdered.ascending; |
||||
module.exports.descending = serialOrdered.descending; |
||||
|
||||
/** |
||||
* Streaming wrapper to `asynckit.serialOrdered` |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} sortMethod - custom sort function |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {stream.Readable#} |
||||
*/ |
||||
function ReadableSerialOrdered(list, iterator, sortMethod, callback) |
||||
{ |
||||
if (!(this instanceof ReadableSerialOrdered)) |
||||
{ |
||||
return new ReadableSerialOrdered(list, iterator, sortMethod, callback); |
||||
} |
||||
|
||||
// turn on object mode
|
||||
ReadableSerialOrdered.super_.call(this, {objectMode: true}); |
||||
|
||||
this._start(serialOrdered, list, iterator, sortMethod, callback); |
||||
} |
@ -1,37 +0,0 @@ |
||||
// API
|
||||
module.exports = state; |
||||
|
||||
/** |
||||
* Creates initial state object |
||||
* for iteration over list |
||||
* |
||||
* @param {array|object} list - list to iterate over |
||||
* @param {function|null} sortMethod - function to use for keys sort, |
||||
* or `null` to keep them as is |
||||
* @returns {object} - initial state object |
||||
*/ |
||||
function state(list, sortMethod) |
||||
{ |
||||
var isNamedList = !Array.isArray(list) |
||||
, initState = |
||||
{ |
||||
index : 0, |
||||
keyedList: isNamedList || sortMethod ? Object.keys(list) : null, |
||||
jobs : {}, |
||||
results : isNamedList ? {} : [], |
||||
size : isNamedList ? Object.keys(list).length : list.length |
||||
} |
||||
; |
||||
|
||||
if (sortMethod) |
||||
{ |
||||
// sort array keys based on it's values
|
||||
// sort object's keys just on own merit
|
||||
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) |
||||
{ |
||||
return sortMethod(list[a], list[b]); |
||||
}); |
||||
} |
||||
|
||||
return initState; |
||||
} |
@ -1,141 +0,0 @@ |
||||
var async = require('./async.js'); |
||||
|
||||
// API
|
||||
module.exports = { |
||||
iterator: wrapIterator, |
||||
callback: wrapCallback |
||||
}; |
||||
|
||||
/** |
||||
* Wraps iterators with long signature |
||||
* |
||||
* @this ReadableAsyncKit# |
||||
* @param {function} iterator - function to wrap |
||||
* @returns {function} - wrapped function |
||||
*/ |
||||
function wrapIterator(iterator) |
||||
{ |
||||
var stream = this; |
||||
|
||||
return function(item, key, cb) |
||||
{ |
||||
var aborter |
||||
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) |
||||
; |
||||
|
||||
stream.jobs[key] = wrappedCb; |
||||
|
||||
// it's either shortcut (item, cb)
|
||||
if (iterator.length == 2) |
||||
{ |
||||
aborter = iterator(item, wrappedCb); |
||||
} |
||||
// or long format (item, key, cb)
|
||||
else |
||||
{ |
||||
aborter = iterator(item, key, wrappedCb); |
||||
} |
||||
|
||||
return aborter; |
||||
}; |
||||
} |
||||
|
||||
/** |
||||
* Wraps provided callback function |
||||
* allowing to execute snitch function before |
||||
* real callback |
||||
* |
||||
* @this ReadableAsyncKit# |
||||
* @param {function} callback - function to wrap |
||||
* @returns {function} - wrapped function |
||||
*/ |
||||
function wrapCallback(callback) |
||||
{ |
||||
var stream = this; |
||||
|
||||
var wrapped = function(error, result) |
||||
{ |
||||
return finisher.call(stream, error, result, callback); |
||||
}; |
||||
|
||||
return wrapped; |
||||
} |
||||
|
||||
/** |
||||
* Wraps provided iterator callback function |
||||
* makes sure snitch only called once, |
||||
* but passes secondary calls to the original callback |
||||
* |
||||
* @this ReadableAsyncKit# |
||||
* @param {function} callback - callback to wrap |
||||
* @param {number|string} key - iteration key |
||||
* @returns {function} wrapped callback |
||||
*/ |
||||
function wrapIteratorCallback(callback, key) |
||||
{ |
||||
var stream = this; |
||||
|
||||
return function(error, output) |
||||
{ |
||||
// don't repeat yourself
|
||||
if (!(key in stream.jobs)) |
||||
{ |
||||
callback(error, output); |
||||
return; |
||||
} |
||||
|
||||
// clean up jobs
|
||||
delete stream.jobs[key]; |
||||
|
||||
return streamer.call(stream, error, {key: key, value: output}, callback); |
||||
}; |
||||
} |
||||
|
||||
/** |
||||
* Stream wrapper for iterator callback |
||||
* |
||||
* @this ReadableAsyncKit# |
||||
* @param {mixed} error - error response |
||||
* @param {mixed} output - iterator output |
||||
* @param {function} callback - callback that expects iterator results |
||||
*/ |
||||
function streamer(error, output, callback) |
||||
{ |
||||
if (error && !this.error) |
||||
{ |
||||
this.error = error; |
||||
this.pause(); |
||||
this.emit('error', error); |
||||
// send back value only, as expected
|
||||
callback(error, output && output.value); |
||||
return; |
||||
} |
||||
|
||||
// stream stuff
|
||||
this.push(output); |
||||
|
||||
// back to original track
|
||||
// send back value only, as expected
|
||||
callback(error, output && output.value); |
||||
} |
||||
|
||||
/** |
||||
* Stream wrapper for finishing callback |
||||
* |
||||
* @this ReadableAsyncKit# |
||||
* @param {mixed} error - error response |
||||
* @param {mixed} output - iterator output |
||||
* @param {function} callback - callback that expects final results |
||||
*/ |
||||
function finisher(error, output, callback) |
||||
{ |
||||
// signal end of the stream
|
||||
// only for successfully finished streams
|
||||
if (!error) |
||||
{ |
||||
this.push(null); |
||||
} |
||||
|
||||
// back to original track
|
||||
callback(error, output); |
||||
} |
@ -1,29 +0,0 @@ |
||||
var abort = require('./abort.js') |
||||
, async = require('./async.js') |
||||
; |
||||
|
||||
// API
|
||||
module.exports = terminator; |
||||
|
||||
/** |
||||
* Terminates jobs in the attached state context |
||||
* |
||||
* @this AsyncKitState# |
||||
* @param {function} callback - final callback to invoke after termination |
||||
*/ |
||||
function terminator(callback) |
||||
{ |
||||
if (!Object.keys(this.jobs).length) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
// fast forward iteration index
|
||||
this.index = this.size; |
||||
|
||||
// abort jobs
|
||||
abort(this); |
||||
|
||||
// send back results we have so far
|
||||
async(callback)(null, this.results); |
||||
} |
@ -1,91 +0,0 @@ |
||||
{ |
||||
"_from": "asynckit@^0.4.0", |
||||
"_id": "asynckit@0.4.0", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", |
||||
"_location": "/asynckit", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "asynckit@^0.4.0", |
||||
"name": "asynckit", |
||||
"escapedName": "asynckit", |
||||
"rawSpec": "^0.4.0", |
||||
"saveSpec": null, |
||||
"fetchSpec": "^0.4.0" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/form-data" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", |
||||
"_shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79", |
||||
"_spec": "asynckit@^0.4.0", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/form-data", |
||||
"author": { |
||||
"name": "Alex Indigo", |
||||
"email": "iam@alexindigo.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/alexindigo/asynckit/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"dependencies": {}, |
||||
"deprecated": false, |
||||
"description": "Minimal async jobs utility library, with streams support", |
||||
"devDependencies": { |
||||
"browserify": "^13.0.0", |
||||
"browserify-istanbul": "^2.0.0", |
||||
"coveralls": "^2.11.9", |
||||
"eslint": "^2.9.0", |
||||
"istanbul": "^0.4.3", |
||||
"obake": "^0.1.2", |
||||
"phantomjs-prebuilt": "^2.1.7", |
||||
"pre-commit": "^1.1.3", |
||||
"reamde": "^1.1.0", |
||||
"rimraf": "^2.5.2", |
||||
"size-table": "^0.2.0", |
||||
"tap-spec": "^4.1.1", |
||||
"tape": "^4.5.1" |
||||
}, |
||||
"homepage": "https://github.com/alexindigo/asynckit#readme", |
||||
"keywords": [ |
||||
"async", |
||||
"jobs", |
||||
"parallel", |
||||
"serial", |
||||
"iterator", |
||||
"array", |
||||
"object", |
||||
"stream", |
||||
"destroy", |
||||
"terminate", |
||||
"abort" |
||||
], |
||||
"license": "MIT", |
||||
"main": "index.js", |
||||
"name": "asynckit", |
||||
"pre-commit": [ |
||||
"clean", |
||||
"lint", |
||||
"test", |
||||
"browser", |
||||
"report", |
||||
"size" |
||||
], |
||||
"repository": { |
||||
"type": "git", |
||||
"url": "git+https://github.com/alexindigo/asynckit.git" |
||||
}, |
||||
"scripts": { |
||||
"browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", |
||||
"clean": "rimraf coverage", |
||||
"debug": "tape test/test-*.js", |
||||
"lint": "eslint *.js lib/*.js test/*.js", |
||||
"report": "istanbul report", |
||||
"size": "browserify index.js | size-table asynckit", |
||||
"test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", |
||||
"win-test": "tape test/test-*.js" |
||||
}, |
||||
"version": "0.4.0" |
||||
} |
@ -1,43 +0,0 @@ |
||||
var iterate = require('./lib/iterate.js') |
||||
, initState = require('./lib/state.js') |
||||
, terminator = require('./lib/terminator.js') |
||||
; |
||||
|
||||
// Public API
|
||||
module.exports = parallel; |
||||
|
||||
/** |
||||
* Runs iterator over provided array elements in parallel |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {function} - jobs terminator |
||||
*/ |
||||
function parallel(list, iterator, callback) |
||||
{ |
||||
var state = initState(list); |
||||
|
||||
while (state.index < (state['keyedList'] || list).length) |
||||
{ |
||||
iterate(list, iterator, state, function(error, result) |
||||
{ |
||||
if (error) |
||||
{ |
||||
callback(error, result); |
||||
return; |
||||
} |
||||
|
||||
// looks like it's the last one
|
||||
if (Object.keys(state.jobs).length === 0) |
||||
{ |
||||
callback(null, state.results); |
||||
return; |
||||
} |
||||
}); |
||||
|
||||
state.index++; |
||||
} |
||||
|
||||
return terminator.bind(state, callback); |
||||
} |
@ -1,17 +0,0 @@ |
||||
var serialOrdered = require('./serialOrdered.js'); |
||||
|
||||
// Public API
|
||||
module.exports = serial; |
||||
|
||||
/** |
||||
* Runs iterator over provided array elements in series |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {function} - jobs terminator |
||||
*/ |
||||
function serial(list, iterator, callback) |
||||
{ |
||||
return serialOrdered(list, iterator, null, callback); |
||||
} |
@ -1,75 +0,0 @@ |
||||
var iterate = require('./lib/iterate.js') |
||||
, initState = require('./lib/state.js') |
||||
, terminator = require('./lib/terminator.js') |
||||
; |
||||
|
||||
// Public API
|
||||
module.exports = serialOrdered; |
||||
// sorting helpers
|
||||
module.exports.ascending = ascending; |
||||
module.exports.descending = descending; |
||||
|
||||
/** |
||||
* Runs iterator over provided sorted array elements in series |
||||
* |
||||
* @param {array|object} list - array or object (named list) to iterate over |
||||
* @param {function} iterator - iterator to run |
||||
* @param {function} sortMethod - custom sort function |
||||
* @param {function} callback - invoked when all elements processed |
||||
* @returns {function} - jobs terminator |
||||
*/ |
||||
function serialOrdered(list, iterator, sortMethod, callback) |
||||
{ |
||||
var state = initState(list, sortMethod); |
||||
|
||||
iterate(list, iterator, state, function iteratorHandler(error, result) |
||||
{ |
||||
if (error) |
||||
{ |
||||
callback(error, result); |
||||
return; |
||||
} |
||||
|
||||
state.index++; |
||||
|
||||
// are we there yet?
|
||||
if (state.index < (state['keyedList'] || list).length) |
||||
{ |
||||
iterate(list, iterator, state, iteratorHandler); |
||||
return; |
||||
} |
||||
|
||||
// done here
|
||||
callback(null, state.results); |
||||
}); |
||||
|
||||
return terminator.bind(state, callback); |
||||
} |
||||
|
||||
/* |
||||
* -- Sort methods |
||||
*/ |
||||
|
||||
/** |
||||
* sort helper to sort array elements in ascending order |
||||
* |
||||
* @param {mixed} a - an item to compare |
||||
* @param {mixed} b - an item to compare |
||||
* @returns {number} - comparison result |
||||
*/ |
||||
function ascending(a, b) |
||||
{ |
||||
return a < b ? -1 : a > b ? 1 : 0; |
||||
} |
||||
|
||||
/** |
||||
* sort helper to sort array elements in descending order |
||||
* |
||||
* @param {mixed} a - an item to compare |
||||
* @param {mixed} b - an item to compare |
||||
* @returns {number} - comparison result |
||||
*/ |
||||
function descending(a, b) |
||||
{ |
||||
return -1 * ascending(a, b); |
||||
} |
@ -1,21 +0,0 @@ |
||||
var inherits = require('util').inherits |
||||
, Readable = require('stream').Readable |
||||
, ReadableAsyncKit = require('./lib/readable_asynckit.js') |
||||
, ReadableParallel = require('./lib/readable_parallel.js') |
||||
, ReadableSerial = require('./lib/readable_serial.js') |
||||
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') |
||||
; |
||||
|
||||
// API
|
||||
module.exports = |
||||
{ |
||||
parallel : ReadableParallel, |
||||
serial : ReadableSerial, |
||||
serialOrdered : ReadableSerialOrdered,
|
||||
}; |
||||
|
||||
inherits(ReadableAsyncKit, Readable); |
||||
|
||||
inherits(ReadableParallel, ReadableAsyncKit); |
||||
inherits(ReadableSerial, ReadableAsyncKit); |
||||
inherits(ReadableSerialOrdered, ReadableAsyncKit); |
@ -1,55 +0,0 @@ |
||||
Apache License |
||||
|
||||
Version 2.0, January 2004 |
||||
|
||||
http://www.apache.org/licenses/ |
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
||||
|
||||
1. Definitions. |
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. |
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. |
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. |
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. |
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. |
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. |
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). |
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. |
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." |
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. |
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. |
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. |
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: |
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of this License; and |
||||
|
||||
You must cause any modified files to carry prominent notices stating that You changed the files; and |
||||
|
||||
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and |
||||
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. |
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. |
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. |
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. |
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. |
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. |
||||
|
||||
END OF TERMS AND CONDITIONS |
@ -1,4 +0,0 @@ |
||||
aws-sign |
||||
======== |
||||
|
||||
AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. |
@ -1,212 +0,0 @@ |
||||
|
||||
/*! |
||||
* Copyright 2010 LearnBoost <dev@learnboost.com> |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
*/ |
||||
|
||||
/** |
||||
* Module dependencies. |
||||
*/ |
||||
|
||||
var crypto = require('crypto') |
||||
, parse = require('url').parse |
||||
; |
||||
|
||||
/** |
||||
* Valid keys. |
||||
*/ |
||||
|
||||
var keys =
|
||||
[ 'acl' |
||||
, 'location' |
||||
, 'logging' |
||||
, 'notification' |
||||
, 'partNumber' |
||||
, 'policy' |
||||
, 'requestPayment' |
||||
, 'torrent' |
||||
, 'uploadId' |
||||
, 'uploads' |
||||
, 'versionId' |
||||
, 'versioning' |
||||
, 'versions' |
||||
, 'website' |
||||
] |
||||
|
||||
/** |
||||
* Return an "Authorization" header value with the given `options` |
||||
* in the form of "AWS <key>:<signature>" |
||||
* |
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function authorization (options) { |
||||
return 'AWS ' + options.key + ':' + sign(options) |
||||
} |
||||
|
||||
module.exports = authorization |
||||
module.exports.authorization = authorization |
||||
|
||||
/** |
||||
* Simple HMAC-SHA1 Wrapper |
||||
* |
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function hmacSha1 (options) { |
||||
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') |
||||
} |
||||
|
||||
module.exports.hmacSha1 = hmacSha1 |
||||
|
||||
/** |
||||
* Create a base64 sha1 HMAC for `options`.
|
||||
*
|
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function sign (options) { |
||||
options.message = stringToSign(options) |
||||
return hmacSha1(options) |
||||
} |
||||
module.exports.sign = sign |
||||
|
||||
/** |
||||
* Create a base64 sha1 HMAC for `options`.
|
||||
* |
||||
* Specifically to be used with S3 presigned URLs |
||||
*
|
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function signQuery (options) { |
||||
options.message = queryStringToSign(options) |
||||
return hmacSha1(options) |
||||
} |
||||
module.exports.signQuery= signQuery |
||||
|
||||
/** |
||||
* Return a string for sign() with the given `options`. |
||||
* |
||||
* Spec: |
||||
*
|
||||
* <verb>\n |
||||
* <md5>\n |
||||
* <content-type>\n |
||||
* <date>\n |
||||
* [headers\n] |
||||
* <resource> |
||||
* |
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function stringToSign (options) { |
||||
var headers = options.amazonHeaders || '' |
||||
if (headers) headers += '\n' |
||||
var r =
|
||||
[ options.verb |
||||
, options.md5 |
||||
, options.contentType |
||||
, options.date ? options.date.toUTCString() : '' |
||||
, headers + options.resource |
||||
] |
||||
return r.join('\n') |
||||
} |
||||
module.exports.queryStringToSign = stringToSign |
||||
|
||||
/** |
||||
* Return a string for sign() with the given `options`, but is meant exclusively |
||||
* for S3 presigned URLs |
||||
* |
||||
* Spec: |
||||
*
|
||||
* <date>\n |
||||
* <resource> |
||||
* |
||||
* @param {Object} options |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function queryStringToSign (options){ |
||||
return 'GET\n\n\n' + options.date + '\n' + options.resource |
||||
} |
||||
module.exports.queryStringToSign = queryStringToSign |
||||
|
||||
/** |
||||
* Perform the following: |
||||
* |
||||
* - ignore non-amazon headers |
||||
* - lowercase fields |
||||
* - sort lexicographically |
||||
* - trim whitespace between ":" |
||||
* - join with newline |
||||
* |
||||
* @param {Object} headers |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function canonicalizeHeaders (headers) { |
||||
var buf = [] |
||||
, fields = Object.keys(headers) |
||||
; |
||||
for (var i = 0, len = fields.length; i < len; ++i) { |
||||
var field = fields[i] |
||||
, val = headers[field] |
||||
, field = field.toLowerCase() |
||||
; |
||||
if (0 !== field.indexOf('x-amz')) continue |
||||
buf.push(field + ':' + val) |
||||
} |
||||
return buf.sort().join('\n') |
||||
} |
||||
module.exports.canonicalizeHeaders = canonicalizeHeaders |
||||
|
||||
/** |
||||
* Perform the following: |
||||
* |
||||
* - ignore non sub-resources |
||||
* - sort lexicographically |
||||
* |
||||
* @param {String} resource |
||||
* @return {String} |
||||
* @api private |
||||
*/ |
||||
|
||||
function canonicalizeResource (resource) { |
||||
var url = parse(resource, true) |
||||
, path = url.pathname |
||||
, buf = [] |
||||
; |
||||
|
||||
Object.keys(url.query).forEach(function(key){ |
||||
if (!~keys.indexOf(key)) return |
||||
var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) |
||||
buf.push(key + val) |
||||
}) |
||||
|
||||
return path + (buf.length ? '?' + buf.sort().join('&') : '') |
||||
} |
||||
module.exports.canonicalizeResource = canonicalizeResource |
@ -1,50 +0,0 @@ |
||||
{ |
||||
"_from": "aws-sign2@~0.6.0", |
||||
"_id": "aws-sign2@0.6.0", |
||||
"_inBundle": false, |
||||
"_integrity": "sha1-FDQt0428yU0OW4fXY81jYSwOeU8=", |
||||
"_location": "/aws-sign2", |
||||
"_phantomChildren": {}, |
||||
"_requested": { |
||||
"type": "range", |
||||
"registry": true, |
||||
"raw": "aws-sign2@~0.6.0", |
||||
"name": "aws-sign2", |
||||
"escapedName": "aws-sign2", |
||||
"rawSpec": "~0.6.0", |
||||
"saveSpec": null, |
||||
"fetchSpec": "~0.6.0" |
||||
}, |
||||
"_requiredBy": [ |
||||
"/request" |
||||
], |
||||
"_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz", |
||||
"_shasum": "14342dd38dbcc94d0e5b87d763cd63612c0e794f", |
||||
"_spec": "aws-sign2@~0.6.0", |
||||
"_where": "/home/orionstark/Documents/astronomy-algorithm/node_modules/request", |
||||
"author": { |
||||
"name": "Mikeal Rogers", |
||||
"email": "mikeal.rogers@gmail.com", |
||||
"url": "http://www.futurealoof.com" |
||||
}, |
||||
"bugs": { |
||||
"url": "https://github.com/mikeal/aws-sign/issues" |
||||
}, |
||||
"bundleDependencies": false, |
||||
"dependencies": {}, |
||||
"deprecated": false, |
||||
"description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.", |
||||
"devDependencies": {}, |
||||
"engines": { |
||||
"node": "*" |
||||
}, |
||||
"homepage": "https://github.com/mikeal/aws-sign#readme", |
||||
"license": "Apache-2.0", |
||||
"main": "index.js", |
||||
"name": "aws-sign2", |
||||
"optionalDependencies": {}, |
||||
"repository": { |
||||
"url": "git+https://github.com/mikeal/aws-sign.git" |
||||
}, |
||||
"version": "0.6.0" |
||||
} |
@ -1,4 +0,0 @@ |
||||
test |
||||
examples |
||||
example.js |
||||
browser |
@ -1 +0,0 @@ |
||||
62638 |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue