Commit f064c792 authored by Muddsair Sharif's avatar Muddsair Sharif
Browse files

Initial commit

parents
Pipeline #8 canceled with stages
# braces [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/braces.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/braces)
> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save braces
```
## Why use braces?
Brace patterns are great for matching ranges. Users (and implementors) shouldn't have to think about whether or not they will break their application (or yours) from accidentally defining an aggressive brace pattern. _Braces is the only library that offers a [solution to this problem](#performance)_.
* **Safe(r)**: Braces isn't vulnerable to DoS attacks like [brace-expansion](https://github.com/juliangruber/brace-expansion), [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) (a different bug than the [other regex DoS bug](https://medium.com/node-security/minimatch-redos-vulnerability-590da24e6d3c#.jew0b6mpc)).
* **Accurate**: complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests)
* **[fast and performant](#benchmarks)**: Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity.
* **Organized code base**: with parser and compiler that are eas(y|ier) to maintain and update when edge cases crop up.
* **Well-tested**: thousands of test assertions. Passes 100% of the [minimatch](https://github.com/isaacs/minimatch) and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests as well (as of the writing of this).
## Usage
The main export is a function that takes one or more brace `patterns` and `options`.
```js
var braces = require('braces');
braces(pattern[, options]);
```
By default, braces returns an optimized regex-source string. To get an array of brace patterns, use `brace.expand()`.
The following section explains the difference in more detail. _(If you're curious about "why" braces does this by default, see [brace matching pitfalls](#brace-matching-pitfalls)_.
### Optimized vs. expanded braces
**Optimized**
By default, patterns are optimized for regex and matching:
```js
console.log(braces('a/{x,y,z}/b'));
//=> ['a/(x|y|z)/b']
```
**Expanded**
To expand patterns the same way as Bash or [minimatch](https://github.com/isaacs/minimatch), use the [.expand](#expand) method:
```js
console.log(braces.expand('a/{x,y,z}/b'));
//=> ['a/x/b', 'a/y/b', 'a/z/b']
```
Or use [options.expand](#optionsexpand):
```js
console.log(braces('a/{x,y,z}/b', {expand: true}));
//=> ['a/x/b', 'a/y/b', 'a/z/b']
```
## Features
* [lists](#lists): Supports "lists": `a/{b,c}/d` => `['a/b/d', 'a/c/d']`
* [sequences](#sequences): Supports alphabetical or numerical "sequences" (ranges): `{1..3}` => `['1', '2', '3']`
* [steps](#steps): Supports "steps" or increments: `{2..10..2}` => `['2', '4', '6', '8', '10']`
* [escaping](#escaping)
* [options](#options)
### Lists
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric lists:
```js
console.log(braces('a/{foo,bar,baz}/*.js'));
//=> ['a/(foo|bar|baz)/*.js']
console.log(braces.expand('a/{foo,bar,baz}/*.js'));
//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js']
```
### Sequences
Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric ranges (bash "sequences"):
```js
console.log(braces.expand('{1..3}')); // ['1', '2', '3']
console.log(braces.expand('a{01..03}b')); // ['a01b', 'a02b', 'a03b']
console.log(braces.expand('a{1..3}b')); // ['a1b', 'a2b', 'a3b']
console.log(braces.expand('{a..c}')); // ['a', 'b', 'c']
console.log(braces.expand('foo/{a..c}')); // ['foo/a', 'foo/b', 'foo/c']
// supports padded ranges
console.log(braces('a{01..03}b')); //=> [ 'a(0[1-3])b' ]
console.log(braces('a{001..300}b')); //=> [ 'a(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)b' ]
```
### Steps
Steps, or increments, may be used with ranges:
```js
console.log(braces.expand('{2..10..2}'));
//=> ['2', '4', '6', '8', '10']
console.log(braces('{2..10..2}'));
//=> ['(2|4|6|8|10)']
```
When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion.
### Nesting
Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved.
**"Expanded" braces**
```js
console.log(braces.expand('a{b,c,/{x,y}}/e'));
//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e']
console.log(braces.expand('a/{x,{1..5},y}/c'));
//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c']
```
**"Optimized" braces**
```js
console.log(braces('a{b,c,/{x,y}}/e'));
//=> ['a(b|c|/(x|y))/e']
console.log(braces('a/{x,{1..5},y}/c'));
//=> ['a/(x|([1-5])|y)/c']
```
### Escaping
**Escaping braces**
A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_:
```js
console.log(braces.expand('a\\{d,c,b}e'));
//=> ['a{d,c,b}e']
console.log(braces.expand('a{d,c,b\\}e'));
//=> ['a{d,c,b}e']
```
**Escaping commas**
Commas inside braces may also be escaped:
```js
console.log(braces.expand('a{b\\,c}d'));
//=> ['a{b,c}d']
console.log(braces.expand('a{d\\,c,b}e'));
//=> ['ad,ce', 'abe']
```
**Single items**
Following bash conventions, a brace pattern is also not expanded when it contains a single character:
```js
console.log(braces.expand('a{b}c'));
//=> ['a{b}c']
```
## Options
### options.maxLength
**Type**: `Number`
**Default**: `65,536`
**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera.
```js
console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error
```
### options.expand
**Type**: `Boolean`
**Default**: `undefined`
**Description**: Generate an "expanded" brace pattern (this option is unncessary with the `.expand` method, which does the same thing).
```js
console.log(braces('a/{b,c}/d', {expand: true}));
//=> [ 'a/b/d', 'a/c/d' ]
```
### options.optimize
**Type**: `Boolean`
**Default**: `true`
**Description**: Enabled by default.
```js
console.log(braces('a/{b,c}/d'));
//=> [ 'a/(b|c)/d' ]
```
### options.nodupes
**Type**: `Boolean`
**Default**: `true`
**Description**: Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options
### options.rangeLimit
**Type**: `Number`
**Default**: `250`
**Description**: When `braces.expand()` is used, or `options.expand` is true, brace patterns will automatically be [optimized](#optionsoptimize) when the difference between the range minimum and range maximum exceeds the `rangeLimit`. This is to prevent huge ranges from freezing your application.
You can set this to any number, or change `options.rangeLimit` to `Inifinity` to disable this altogether.
**Examples**
```js
// pattern exceeds the "rangeLimit", so it's optimized automatically
console.log(braces.expand('{1..1000}'));
//=> ['([1-9]|[1-9][0-9]{1,2}|1000)']
// pattern does not exceed "rangeLimit", so it's NOT optimized
console.log(braces.expand('{1..100}'));
//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
```
### options.transform
**Type**: `Function`
**Default**: `undefined`
**Description**: Customize range expansion.
```js
var range = braces.expand('x{a..e}y', {
transform: function(str) {
return 'foo' + str;
}
});
console.log(range);
//=> [ 'xfooay', 'xfooby', 'xfoocy', 'xfoody', 'xfooey' ]
```
### options.quantifiers
**Type**: `Boolean`
**Default**: `undefined`
**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times.
Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists)
The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists.
**Examples**
```js
var braces = require('braces');
console.log(braces('a/b{1,3}/{x,y,z}'));
//=> [ 'a/b(1|3)/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true}));
//=> [ 'a/b{1,3}/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true}));
//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ]
```
### options.unescape
**Type**: `Boolean`
**Default**: `undefined`
**Description**: Strip backslashes that were used for escaping from the result.
## What is "brace expansion"?
Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs).
In addition to "expansion", braces are also used for matching. In other words:
* [brace expansion](#brace-expansion) is for generating new lists
* [brace matching](#brace-matching) is for filtering existing lists
<details>
<summary><strong>More about brace expansion</strong> (click to expand)</summary>
There are two main types of brace expansion:
1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}`
2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges".
Here are some example brace patterns to illustrate how they work:
**Sets**
```
{a,b,c} => a b c
{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2
```
**Sequences**
```
{1..9} => 1 2 3 4 5 6 7 8 9
{4..-4} => 4 3 2 1 0 -1 -2 -3 -4
{1..20..3} => 1 4 7 10 13 16 19
{a..j} => a b c d e f g h i j
{j..a} => j i h g f e d c b a
{a..z..3} => a d g j m p s v y
```
**Combination**
Sets and sequences can be mixed together or used along with any other strings.
```
{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3
foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar
```
The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases.
## Brace matching
In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching.
For example, the pattern `foo/{1..3}/bar` would match any of following strings:
```
foo/1/bar
foo/2/bar
foo/3/bar
```
But not:
```
baz/1/qux
baz/2/qux
baz/3/qux
```
Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings:
```
foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux
```
## Brace matching pitfalls
Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of.
### tldr
**"brace bombs"**
* brace expansion can eat up a huge amount of processing resources
* as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially
* users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!)
For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section.
### The solution
Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries.
### Geometric complexity
At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`.
For example, the following sets demonstrate quadratic (`O(n^2)`) complexity:
```
{1,2}{3,4} => (2X2) => 13 14 23 24
{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246
```
But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity:
```
{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248
249 257 258 259 267 268 269 347 348 349 357
358 359 367 368 369
```
Now, imagine how this complexity grows given that each element is a n-tuple:
```
{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB)
{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB)
```
Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control.
**More information**
Interested in learning more about brace expansion?
* [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion)
* [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion)
* [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)
</details>
## Performance
Braces is not only screaming fast, it's also more accurate the other brace expansion libraries.
### Better algorithms
Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_.
Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently.
**The proof is in the numbers**
Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively.
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
| --- | --- | --- |
| `{1..9007199254740991}`<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> | `298 B` (5ms 459μs) | N/A (freezes) |
| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) |
| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) |
| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) |
| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) |
| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) |
| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) |
| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) |
| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) |
| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) |
| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) |
| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) |
| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) |
| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) |
| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) |
| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) |
| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) |
### Faster algorithms
When you need expansion, braces is still much faster.
_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_
| **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** |
| --- | --- | --- |
| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) |
| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) |
| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) |
| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) |
| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) |
| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) |
| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) |
| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) |
If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js).
## Benchmarks
### Running benchmarks
Install dev dependencies:
```bash
npm i -d && npm benchmark
```
### Latest results
```bash
Benchmarking: (8 of 8)
· combination-nested
· combination
· escaped
· list-basic
· list-multiple
· no-braces
· sequence-basic
· sequence-multiple
# benchmark/fixtures/combination-nested.js (52 bytes)
brace-expansion x 4,756 ops/sec ±1.09% (86 runs sampled)
braces x 11,202,303 ops/sec ±1.06% (88 runs sampled)
minimatch x 4,816 ops/sec ±0.99% (87 runs sampled)
fastest is braces
# benchmark/fixtures/combination.js (51 bytes)
brace-expansion x 625 ops/sec ±0.87% (87 runs sampled)
braces x 11,031,884 ops/sec ±0.72% (90 runs sampled)
minimatch x 637 ops/sec ±0.84% (88 runs sampled)
fastest is braces
# benchmark/fixtures/escaped.js (44 bytes)
brace-expansion x 163,325 ops/sec ±1.05% (87 runs sampled)
braces x 10,655,071 ops/sec ±1.22% (88 runs sampled)
minimatch x 147,495 ops/sec ±0.96% (88 runs sampled)
fastest is braces
# benchmark/fixtures/list-basic.js (40 bytes)
brace-expansion x 99,726 ops/sec ±1.07% (83 runs sampled)
braces x 10,596,584 ops/sec ±0.98% (88 runs sampled)
minimatch x 100,069 ops/sec ±1.17% (86 runs sampled)
fastest is braces
# benchmark/fixtures/list-multiple.js (52 bytes)
brace-expansion x 34,348 ops/sec ±1.08% (88 runs sampled)
braces x 9,264,131 ops/sec ±1.12% (88 runs sampled)
minimatch x 34,893 ops/sec ±0.87% (87 runs sampled)
fastest is braces
# benchmark/fixtures/no-braces.js (48 bytes)
brace-expansion x 275,368 ops/sec ±1.18% (89 runs sampled)
braces x 9,134,677 ops/sec ±0.95% (88 runs sampled)
minimatch x 3,755,954 ops/sec ±1.13% (89 runs sampled)
fastest is braces
# benchmark/fixtures/sequence-basic.js (41 bytes)
brace-expansion x 5,492 ops/sec ±1.35% (87 runs sampled)
braces x 8,485,034 ops/sec ±1.28% (89 runs sampled)
minimatch x 5,341 ops/sec ±1.17% (87 runs sampled)
fastest is braces
# benchmark/fixtures/sequence-multiple.js (51 bytes)
brace-expansion x 116 ops/sec ±0.77% (77 runs sampled)
braces x 9,445,118 ops/sec ±1.32% (84 runs sampled)
minimatch x 109 ops/sec ±1.16% (76 runs sampled)
fastest is braces
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.")
* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.")
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 188 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [es128](https://github.com/es128) |
| 1 | [eush77](https://github.com/eush77) |
| 1 | [hemanth](https://github.com/hemanth) |
### Author
**Jon Schlinkert**
* [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert)
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 17, 2018._
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item">this is the largest safe integer allowed in JavaScript. <a href="#fnref1" class="footnote-backref"></a>
</li>
</ol>
</section>
\ No newline at end of file
'use strict';
/**
* Module dependencies
*/
var toRegex = require('to-regex');
var unique = require('array-unique');
var extend = require('extend-shallow');
/**
* Local dependencies
*/
var compilers = require('./lib/compilers');
var parsers = require('./lib/parsers');
var Braces = require('./lib/braces');
var utils = require('./lib/utils');
var MAX_LENGTH = 1024 * 64;
var cache = {};
/**
* Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).
*
* ```js
* var braces = require('braces');
* console.log(braces('{a,b,c}'));
* //=> ['(a|b|c)']
*
* console.log(braces('{a,b,c}', {expand: true}));
* //=> ['a', 'b', 'c']
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {String}
* @api public
*/
function braces(pattern, options) {
var key = utils.createKey(String(pattern), options);
var arr = [];
var disabled = options && options.cache === false;
if (!disabled && cache.hasOwnProperty(key)) {
return cache[key];
}
if (Array.isArray(pattern)) {
for (var i = 0; i < pattern.length; i++) {
arr.push.apply(arr, braces.create(pattern[i], options));
}
} else {
arr = braces.create(pattern, options);
}
if (options && options.nodupes === true) {
arr = unique(arr);
}
if (!disabled) {
cache[key] = arr;
}
return arr;
}
/**
* Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.
*
* ```js
* var braces = require('braces');
* console.log(braces.expand('a/{b,c}/d'));
* //=> ['a/b/d', 'a/c/d'];
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.expand = function(pattern, options) {
return braces.create(pattern, extend({}, options, {expand: true}));
};
/**
* Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
*
* ```js
* var braces = require('braces');
* console.log(braces.expand('a/{b,c}/d'));
* //=> ['a/(b|c)/d']
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.optimize = function(pattern, options) {
return braces.create(pattern, options);
};
/**
* Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.
*
* ```js
* var braces = require('braces');
* console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
* //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
* ```
* @param {String} `pattern` Brace pattern
* @param {Object} `options`
* @return {Array} Returns an array of expanded values.
* @api public
*/
braces.create = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
var maxLength = (options && options.maxLength) || MAX_LENGTH;
if (pattern.length >= maxLength) {
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
}
function create() {
if (pattern === '' || pattern.length < 3) {
return [pattern];
}
if (utils.isEmptySets(pattern)) {
return [];
}
if (utils.isQuotedString(pattern)) {
return [pattern.slice(1, -1)];
}
var proto = new Braces(options);
var result = !options || options.expand !== true
? proto.optimize(pattern, options)
: proto.expand(pattern, options);
// get the generated pattern(s)
var arr = result.output;
// filter out empty strings if specified
if (options && options.noempty === true) {
arr = arr.filter(Boolean);
}
// filter out duplicates if specified
if (options && options.nodupes === true) {
arr = unique(arr);
}
Object.defineProperty(arr, 'result', {
enumerable: false,
value: result
});
return arr;
}
return memoize('create', pattern, options, create);
};
/**
* Create a regular expression from the given string `pattern`.
*
* ```js
* var braces = require('braces');
*
* console.log(braces.makeRe('id-{200..300}'));
* //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
* ```
* @param {String} `pattern` The pattern to convert to regex.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
braces.makeRe = function(pattern, options) {
if (typeof pattern !== 'string') {
throw new TypeError('expected a string');
}
var maxLength = (options && options.maxLength) || MAX_LENGTH;
if (pattern.length >= maxLength) {
throw new Error('expected pattern to be less than ' + maxLength + ' characters');
}
function makeRe() {
var arr = braces(pattern, options);
var opts = extend({strictErrors: false}, options);
return toRegex(arr, opts);
}
return memoize('makeRe', pattern, options, makeRe);
};
/**
* Parse the given `str` with the given `options`.
*
* ```js
* var braces = require('braces');
* var ast = braces.parse('a/{b,c}/d');
* console.log(ast);
* // { type: 'root',
* // errors: [],
* // input: 'a/{b,c}/d',
* // nodes:
* // [ { type: 'bos', val: '' },
* // { type: 'text', val: 'a/' },
* // { type: 'brace',
* // nodes:
* // [ { type: 'brace.open', val: '{' },
* // { type: 'text', val: 'b,c' },
* // { type: 'brace.close', val: '}' } ] },
* // { type: 'text', val: '/d' },
* // { type: 'eos', val: '' } ] }
* ```
* @param {String} `pattern` Brace pattern to parse
* @param {Object} `options`
* @return {Object} Returns an AST
* @api public
*/
braces.parse = function(pattern, options) {
var proto = new Braces(options);
return proto.parse(pattern, options);
};
/**
* Compile the given `ast` or string with the given `options`.
*
* ```js
* var braces = require('braces');
* var ast = braces.parse('a/{b,c}/d');
* console.log(braces.compile(ast));
* // { options: { source: 'string' },
* // state: {},
* // compilers:
* // { eos: [Function],
* // noop: [Function],
* // bos: [Function],
* // brace: [Function],
* // 'brace.open': [Function],
* // text: [Function],
* // 'brace.close': [Function] },
* // output: [ 'a/(b|c)/d' ],
* // ast:
* // { ... },
* // parsingErrors: [] }
* ```
* @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
* @param {Object} `options`
* @return {Object} Returns an object that has an `output` property with the compiled string.
* @api public
*/
braces.compile = function(ast, options) {
var proto = new Braces(options);
return proto.compile(ast, options);
};
/**
* Clear the regex cache.
*
* ```js
* braces.clearCache();
* ```
* @api public
*/
braces.clearCache = function() {
cache = braces.cache = {};
};
/**
* Memoize a generated regex or function. A unique key is generated
* from the method name, pattern, and user-defined options. Set
* options.memoize to false to disable.
*/
function memoize(type, pattern, options, fn) {
var key = utils.createKey(type + ':' + pattern, options);
var disabled = options && options.cache === false;
if (disabled) {
braces.clearCache();
return fn(pattern, options);
}
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var res = fn(pattern, options);
cache[key] = res;
return res;
}
/**
* Expose `Braces` constructor and methods
* @type {Function}
*/
braces.Braces = Braces;
braces.compilers = compilers;
braces.parsers = parsers;
braces.cache = cache;
/**
* Expose `braces`
* @type {Function}
*/
module.exports = braces;
'use strict';
var extend = require('extend-shallow');
var Snapdragon = require('snapdragon');
var compilers = require('./compilers');
var parsers = require('./parsers');
var utils = require('./utils');
/**
* Customize Snapdragon parser and renderer
*/
function Braces(options) {
this.options = extend({}, options);
}
/**
* Initialize braces
*/
Braces.prototype.init = function(options) {
if (this.isInitialized) return;
this.isInitialized = true;
var opts = utils.createOptions({}, this.options, options);
this.snapdragon = this.options.snapdragon || new Snapdragon(opts);
this.compiler = this.snapdragon.compiler;
this.parser = this.snapdragon.parser;
compilers(this.snapdragon, opts);
parsers(this.snapdragon, opts);
/**
* Call Snapdragon `.parse` method. When AST is returned, we check to
* see if any unclosed braces are left on the stack and, if so, we iterate
* over the stack and correct the AST so that compilers are called in the correct
* order and unbalance braces are properly escaped.
*/
utils.define(this.snapdragon, 'parse', function(pattern, options) {
var parsed = Snapdragon.prototype.parse.apply(this, arguments);
this.parser.ast.input = pattern;
var stack = this.parser.stack;
while (stack.length) {
addParent({type: 'brace.close', val: ''}, stack.pop());
}
function addParent(node, parent) {
utils.define(node, 'parent', parent);
parent.nodes.push(node);
}
// add non-enumerable parser reference
utils.define(parsed, 'parser', this.parser);
return parsed;
});
};
/**
* Decorate `.parse` method
*/
Braces.prototype.parse = function(ast, options) {
if (ast && typeof ast === 'object' && ast.nodes) return ast;
this.init(options);
return this.snapdragon.parse(ast, options);
};
/**
* Decorate `.compile` method
*/
Braces.prototype.compile = function(ast, options) {
if (typeof ast === 'string') {
ast = this.parse(ast, options);
} else {
this.init(options);
}
return this.snapdragon.compile(ast, options);
};
/**
* Expand
*/
Braces.prototype.expand = function(pattern) {
var ast = this.parse(pattern, {expand: true});
return this.compile(ast, {expand: true});
};
/**
* Optimize
*/
Braces.prototype.optimize = function(pattern) {
var ast = this.parse(pattern, {optimize: true});
return this.compile(ast, {optimize: true});
};
/**
* Expose `Braces`
*/
module.exports = Braces;
'use strict';
var utils = require('./utils');
module.exports = function(braces, options) {
braces.compiler
/**
* bos
*/
.set('bos', function() {
if (this.output) return;
this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
this.ast.count = 1;
})
/**
* Square brackets
*/
.set('bracket', function(node) {
var close = node.close;
var open = !node.escaped ? '[' : '\\[';
var negated = node.negated;
var inner = node.inner;
inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
if (inner === ']-') {
inner = '\\]\\-';
}
if (negated && inner.indexOf('.') === -1) {
inner += '.';
}
if (negated && inner.indexOf('/') === -1) {
inner += '/';
}
var val = open + negated + inner + close;
var queue = node.parent.queue;
var last = utils.arrayify(queue.pop());
queue.push(utils.join(last, val));
queue.push.apply(queue, []);
})
/**
* Brace
*/
.set('brace', function(node) {
node.queue = isEscaped(node) ? [node.val] : [];
node.count = 1;
return this.mapVisit(node.nodes);
})
/**
* Open
*/
.set('brace.open', function(node) {
node.parent.open = node.val;
})
/**
* Inner
*/
.set('text', function(node) {
var queue = node.parent.queue;
var escaped = node.escaped;
var segs = [node.val];
if (node.optimize === false) {
options = utils.extend({}, options, {optimize: false});
}
if (node.multiplier > 1) {
node.parent.count *= node.multiplier;
}
if (options.quantifiers === true && utils.isQuantifier(node.val)) {
escaped = true;
} else if (node.val.length > 1) {
if (isType(node.parent, 'brace') && !isEscaped(node)) {
var expanded = utils.expand(node.val, options);
segs = expanded.segs;
if (expanded.isOptimized) {
node.parent.isOptimized = true;
}
// if nothing was expanded, we probably have a literal brace
if (!segs.length) {
var val = (expanded.val || node.val);
if (options.unescape !== false) {
// unescape unexpanded brace sequence/set separators
val = val.replace(/\\([,.])/g, '$1');
// strip quotes
val = val.replace(/["'`]/g, '');
}
segs = [val];
escaped = true;
}
}
} else if (node.val === ',') {
if (options.expand) {
node.parent.queue.push(['']);
segs = [''];
} else {
segs = ['|'];
}
} else {
escaped = true;
}
if (escaped && isType(node.parent, 'brace')) {
if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
node.parent.escaped = true;
} else if (node.parent.length <= 3) {
node.parent.escaped = true;
}
}
if (!hasQueue(node.parent)) {
node.parent.queue = segs;
return;
}
var last = utils.arrayify(queue.pop());
if (node.parent.count > 1 && options.expand) {
last = multiply(last, node.parent.count);
node.parent.count = 1;
}
queue.push(utils.join(utils.flatten(last), segs.shift()));
queue.push.apply(queue, segs);
})
/**
* Close
*/
.set('brace.close', function(node) {
var queue = node.parent.queue;
var prev = node.parent.parent;
var last = prev.queue.pop();
var open = node.parent.open;
var close = node.val;
if (open && close && isOptimized(node, options)) {
open = '(';
close = ')';
}
// if a close brace exists, and the previous segment is one character
// don't wrap the result in braces or parens
var ele = utils.last(queue);
if (node.parent.count > 1 && options.expand) {
ele = multiply(queue.pop(), node.parent.count);
node.parent.count = 1;
queue.push(ele);
}
if (close && typeof ele === 'string' && ele.length === 1) {
open = '';
close = '';
}
if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
queue.push(utils.join(open, queue.pop() || ''));
queue = utils.flatten(utils.join(queue, close));
}
if (typeof last === 'undefined') {
prev.queue = [queue];
} else {
prev.queue.push(utils.flatten(utils.join(last, queue)));
}
})
/**
* eos
*/
.set('eos', function(node) {
if (this.input) return;
if (options.optimize !== false) {
this.output = utils.last(utils.flatten(this.ast.queue));
} else if (Array.isArray(utils.last(this.ast.queue))) {
this.output = utils.flatten(this.ast.queue.pop());
} else {
this.output = utils.flatten(this.ast.queue);
}
if (node.parent.count > 1 && options.expand) {
this.output = multiply(this.output, node.parent.count);
}
this.output = utils.arrayify(this.output);
this.ast.queue = [];
});
};
/**
* Multiply the segments in the current brace level
*/
function multiply(queue, n, options) {
return utils.flatten(utils.repeat(utils.arrayify(queue), n));
}
/**
* Return true if `node` is escaped
*/
function isEscaped(node) {
return node.escaped === true;
}
/**
* Returns true if regex parens should be used for sets. If the parent `type`
* is not `brace`, then we're on a root node, which means we should never
* expand segments and open/close braces should be `{}` (since this indicates
* a brace is missing from the set)
*/
function isOptimized(node, options) {
if (node.parent.isOptimized) return true;
return isType(node.parent, 'brace')
&& !isEscaped(node.parent)
&& options.expand !== true;
}
/**
* Returns true if the value in `node` should be wrapped in a literal brace.
* @return {Boolean}
*/
function isLiteralBrace(node, options) {
return isEscaped(node.parent) || options.optimize !== false;
}
/**
* Returns true if the given `node` does not have an inner value.
* @return {Boolean}
*/
function noInner(node, type) {
if (node.parent.queue.length === 1) {
return true;
}
var nodes = node.parent.nodes;
return nodes.length === 3
&& isType(nodes[0], 'brace.open')
&& !isType(nodes[1], 'text')
&& isType(nodes[2], 'brace.close');
}
/**
* Returns true if the given `node` is the given `type`
* @return {Boolean}
*/
function isType(node, type) {
return typeof node !== 'undefined' && node.type === type;
}
/**
* Returns true if the given `node` has a non-empty queue.
* @return {Boolean}
*/
function hasQueue(node) {
return Array.isArray(node.queue) && node.queue.length;
}
'use strict';
var Node = require('snapdragon-node');
var utils = require('./utils');
/**
* Braces parsers
*/
module.exports = function(braces, options) {
braces.parser
.set('bos', function() {
if (!this.parsed) {
this.ast = this.nodes[0] = new Node(this.ast);
}
})
/**
* Character parsers
*/
.set('escape', function() {
var pos = this.position();
var m = this.match(/^(?:\\(.)|\$\{)/);
if (!m) return;
var prev = this.prev();
var last = utils.last(prev.nodes);
var node = pos(new Node({
type: 'text',
multiplier: 1,
val: m[0]
}));
if (node.val === '\\\\') {
return node;
}
if (node.val === '${') {
var str = this.input;
var idx = -1;
var ch;
while ((ch = str[++idx])) {
this.consume(1);
node.val += ch;
if (ch === '\\') {
node.val += str[++idx];
continue;
}
if (ch === '}') {
break;
}
}
}
if (this.options.unescape !== false) {
node.val = node.val.replace(/\\([{}])/g, '$1');
}
if (last.val === '"' && this.input.charAt(0) === '"') {
last.val = node.val;
this.consume(1);
return;
}
return concatNodes.call(this, pos, node, prev, options);
})
/**
* Brackets: "[...]" (basic, this is overridden by
* other parsers in more advanced implementations)
*/
.set('bracket', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
if (!m) return;
var prev = this.prev();
var val = m[0];
var negated = m[1] ? '^' : '';
var inner = m[2] || '';
var close = m[3] || '';
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var esc = this.input.slice(0, 2);
if (inner === '' && esc === '\\]') {
inner += esc;
this.consume(2);
var str = this.input;
var idx = -1;
var ch;
while ((ch = str[++idx])) {
this.consume(1);
if (ch === ']') {
close = ch;
break;
}
inner += ch;
}
}
return pos(new Node({
type: 'bracket',
val: val,
escaped: close !== ']',
negated: negated,
inner: inner,
close: close
}));
})
/**
* Empty braces (we capture these early to
* speed up processing in the compiler)
*/
.set('multiplier', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^\{((?:,|\{,+\})+)\}/);
if (!m) return;
this.multiplier = true;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var node = pos(new Node({
type: 'text',
multiplier: 1,
match: m,
val: val
}));
return concatNodes.call(this, pos, node, prev, options);
})
/**
* Open
*/
.set('brace.open', function() {
var pos = this.position();
var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
if (!m) return;
var prev = this.prev();
var last = utils.last(prev.nodes);
// if the last parsed character was an extglob character
// we need to _not optimize_ the brace pattern because
// it might be mistaken for an extglob by a downstream parser
if (last && last.val && isExtglobChar(last.val.slice(-1))) {
last.optimize = false;
}
var open = pos(new Node({
type: 'brace.open',
val: m[0]
}));
var node = pos(new Node({
type: 'brace',
nodes: []
}));
node.push(open);
prev.push(node);
this.push('brace', node);
})
/**
* Close
*/
.set('brace.close', function() {
var pos = this.position();
var m = this.match(/^\}/);
if (!m || !m[0]) return;
var brace = this.pop('brace');
var node = pos(new Node({
type: 'brace.close',
val: m[0]
}));
if (!this.isType(brace, 'brace')) {
if (this.options.strict) {
throw new Error('missing opening "{"');
}
node.type = 'text';
node.multiplier = 0;
node.escaped = true;
return node;
}
var prev = this.prev();
var last = utils.last(prev.nodes);
if (last.text) {
var lastNode = utils.last(last.nodes);
if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
var open = last.nodes[0];
var text = last.nodes[1];
if (open.type === 'brace.open' && text && text.type === 'text') {
text.optimize = false;
}
}
}
if (brace.nodes.length > 2) {
var first = brace.nodes[1];
if (first.type === 'text' && first.val === ',') {
brace.nodes.splice(1, 1);
brace.nodes.push(first);
}
}
brace.push(node);
})
/**
* Capture boundary characters
*/
.set('boundary', function() {
var pos = this.position();
var m = this.match(/^[$^](?!\{)/);
if (!m) return;
return pos(new Node({
type: 'text',
val: m[0]
}));
})
/**
* One or zero, non-comma characters wrapped in braces
*/
.set('nobrace', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^\{[^,]?\}/);
if (!m) return;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
return pos(new Node({
type: 'text',
multiplier: 0,
val: val
}));
})
/**
* Text
*/
.set('text', function() {
var isInside = this.isInside('brace');
var pos = this.position();
var m = this.match(/^((?!\\)[^${}[\]])+/);
if (!m) return;
var prev = this.prev();
var val = m[0];
if (isInside && prev.type === 'brace') {
prev.text = prev.text || '';
prev.text += val;
}
var node = pos(new Node({
type: 'text',
multiplier: 1,
val: val
}));
return concatNodes.call(this, pos, node, prev, options);
});
};
/**
* Returns true if the character is an extglob character.
*/
function isExtglobChar(ch) {
return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
}
/**
* Combine text nodes, and calculate empty sets (`{,,}`)
* @param {Function} `pos` Function to calculate node position
* @param {Object} `node` AST node
* @return {Object}
*/
function concatNodes(pos, node, parent, options) {
node.orig = node.val;
var prev = this.prev();
var last = utils.last(prev.nodes);
var isEscaped = false;
if (node.val.length > 1) {
var a = node.val.charAt(0);
var b = node.val.slice(-1);
isEscaped = (a === '"' && b === '"')
|| (a === "'" && b === "'")
|| (a === '`' && b === '`');
}
if (isEscaped && options.unescape !== false) {
node.val = node.val.slice(1, node.val.length - 1);
node.escaped = true;
}
if (node.match) {
var match = node.match[1];
if (!match || match.indexOf('}') === -1) {
match = node.match[0];
}
// replace each set with a single ","
var val = match.replace(/\{/g, ',').replace(/\}/g, '');
node.multiplier *= val.length;
node.val = '';
}
var simpleText = last.type === 'text'
&& last.multiplier === 1
&& node.multiplier === 1
&& node.val;
if (simpleText) {
last.val += node.val;
return;
}
prev.push(node);
}
'use strict';
var splitString = require('split-string');
var utils = module.exports;
/**
* Module dependencies
*/
utils.extend = require('extend-shallow');
utils.flatten = require('arr-flatten');
utils.isObject = require('isobject');
utils.fillRange = require('fill-range');
utils.repeat = require('repeat-element');
utils.unique = require('array-unique');
utils.define = function(obj, key, val) {
Object.defineProperty(obj, key, {
writable: true,
configurable: true,
enumerable: false,
value: val
});
};
/**
* Returns true if the given string contains only empty brace sets.
*/
utils.isEmptySets = function(str) {
return /^(?:\{,\})+$/.test(str);
};
/**
* Returns true if the given string contains only empty brace sets.
*/
utils.isQuotedString = function(str) {
var open = str.charAt(0);
if (open === '\'' || open === '"' || open === '`') {
return str.slice(-1) === open;
}
return false;
};
/**
* Create the key to use for memoization. The unique key is generated
* by iterating over the options and concatenating key-value pairs
* to the pattern string.
*/
utils.createKey = function(pattern, options) {
var id = pattern;
if (typeof options === 'undefined') {
return id;
}
var keys = Object.keys(options);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
id += ';' + key + '=' + String(options[key]);
}
return id;
};
/**
* Normalize options
*/
utils.createOptions = function(options) {
var opts = utils.extend.apply(null, arguments);
if (typeof opts.expand === 'boolean') {
opts.optimize = !opts.expand;
}
if (typeof opts.optimize === 'boolean') {
opts.expand = !opts.optimize;
}
if (opts.optimize === true) {
opts.makeRe = true;
}
return opts;
};
/**
* Join patterns in `a` to patterns in `b`
*/
utils.join = function(a, b, options) {
options = options || {};
a = utils.arrayify(a);
b = utils.arrayify(b);
if (!a.length) return b;
if (!b.length) return a;
var len = a.length;
var idx = -1;
var arr = [];
while (++idx < len) {
var val = a[idx];
if (Array.isArray(val)) {
for (var i = 0; i < val.length; i++) {
val[i] = utils.join(val[i], b, options);
}
arr.push(val);
continue;
}
for (var j = 0; j < b.length; j++) {
var bval = b[j];
if (Array.isArray(bval)) {
arr.push(utils.join(val, bval, options));
} else {
arr.push(val + bval);
}
}
}
return arr;
};
/**
* Split the given string on `,` if not escaped.
*/
utils.split = function(str, options) {
var opts = utils.extend({sep: ','}, options);
if (typeof opts.keepQuotes !== 'boolean') {
opts.keepQuotes = true;
}
if (opts.unescape === false) {
opts.keepEscaping = true;
}
return splitString(str, opts, utils.escapeBrackets(opts));
};
/**
* Expand ranges or sets in the given `pattern`.
*
* @param {String} `str`
* @param {Object} `options`
* @return {Object}
*/
utils.expand = function(str, options) {
var opts = utils.extend({rangeLimit: 10000}, options);
var segs = utils.split(str, opts);
var tok = { segs: segs };
if (utils.isQuotedString(str)) {
return tok;
}
if (opts.rangeLimit === true) {
opts.rangeLimit = 10000;
}
if (segs.length > 1) {
if (opts.optimize === false) {
tok.val = segs[0];
return tok;
}
tok.segs = utils.stringifyArray(tok.segs);
} else if (segs.length === 1) {
var arr = str.split('..');
if (arr.length === 1) {
tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
tok.segs = [];
return tok;
}
if (arr.length === 2 && arr[0] === arr[1]) {
tok.escaped = true;
tok.val = arr[0];
tok.segs = [];
return tok;
}
if (arr.length > 1) {
if (opts.optimize !== false) {
opts.optimize = true;
delete opts.expand;
}
if (opts.optimize !== true) {
var min = Math.min(arr[0], arr[1]);
var max = Math.max(arr[0], arr[1]);
var step = arr[2] || 1;
if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
}
}
arr.push(opts);
tok.segs = utils.fillRange.apply(null, arr);
if (!tok.segs.length) {
tok.escaped = true;
tok.val = str;
return tok;
}
if (opts.optimize === true) {
tok.segs = utils.stringifyArray(tok.segs);
}
if (tok.segs === '') {
tok.val = str;
} else {
tok.val = tok.segs[0];
}
return tok;
}
} else {
tok.val = str;
}
return tok;
};
/**
* Ensure commas inside brackets and parens are not split.
* @param {Object} `tok` Token from the `split-string` module
* @return {undefined}
*/
utils.escapeBrackets = function(options) {
return function(tok) {
if (tok.escaped && tok.val === 'b') {
tok.val = '\\b';
return;
}
if (tok.val !== '(' && tok.val !== '[') return;
var opts = utils.extend({}, options);
var brackets = [];
var parens = [];
var stack = [];
var val = tok.val;
var str = tok.str;
var i = tok.idx - 1;
while (++i < str.length) {
var ch = str[i];
if (ch === '\\') {
val += (opts.keepEscaping === false ? '' : ch) + str[++i];
continue;
}
if (ch === '(') {
parens.push(ch);
stack.push(ch);
}
if (ch === '[') {
brackets.push(ch);
stack.push(ch);
}
if (ch === ')') {
parens.pop();
stack.pop();
if (!stack.length) {
val += ch;
break;
}
}
if (ch === ']') {
brackets.pop();
stack.pop();
if (!stack.length) {
val += ch;
break;
}
}
val += ch;
}
tok.split = false;
tok.val = val.slice(1);
tok.idx = i;
};
};
/**
* Returns true if the given string looks like a regex quantifier
* @return {Boolean}
*/
utils.isQuantifier = function(str) {
return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
};
/**
* Cast `val` to an array.
* @param {*} `val`
*/
utils.stringifyArray = function(arr) {
return [utils.arrayify(arr).join('|')];
};
/**
* Cast `val` to an array.
* @param {*} `val`
*/
utils.arrayify = function(arr) {
if (typeof arr === 'undefined') {
return [];
}
if (typeof arr === 'string') {
return [arr];
}
return arr;
};
/**
* Returns true if the given `str` is a non-empty string
* @return {Boolean}
*/
utils.isString = function(str) {
return str != null && typeof str === 'string';
};
/**
* Get the last element from `array`
* @param {Array} `array`
* @return {*}
*/
utils.last = function(arr, n) {
return arr[arr.length - (n || 1)];
};
utils.escapeRegex = function(str) {
return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
};
The MIT License (MIT)
Copyright (c) 2014-2015, Jon Schlinkert.
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.
# extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow)
> Extend an object with the properties of additional objects. node.js/javascript util.
## Install
Install with [npm](https://www.npmjs.com/)
```sh
$ npm i extend-shallow --save
```
## Usage
```js
var extend = require('extend-shallow');
extend({a: 'b'}, {c: 'd'})
//=> {a: 'b', c: 'd'}
```
Pass an empty object to shallow clone:
```js
var obj = {};
extend(obj, {a: 'b'}, {c: 'd'})
//=> {a: 'b', c: 'd'}
```
## Related
* [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util.
* [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own)
* [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in)
* [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor.
* [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null.
* [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value.
## Running tests
Install dev dependencies:
```sh
$ npm i -d && npm test
```
## Author
**Jon Schlinkert**
+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
## License
Copyright © 2015 Jon Schlinkert
Released under the MIT license.
***
_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._
\ No newline at end of file
'use strict';
var isObject = require('is-extendable');
module.exports = function extend(o/*, objects*/) {
if (!isObject(o)) { o = {}; }
var len = arguments.length;
for (var i = 1; i < len; i++) {
var obj = arguments[i];
if (isObject(obj)) {
assign(o, obj);
}
}
return o;
};
function assign(a, b) {
for (var key in b) {
if (hasOwn(b, key)) {
a[key] = b[key];
}
}
}
/**
* Returns true if the given `key` is an own property of `obj`.
*/
function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
{
"_from": "extend-shallow@^2.0.1",
"_id": "extend-shallow@2.0.1",
"_inBundle": false,
"_integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
"_location": "/braces/extend-shallow",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "extend-shallow@^2.0.1",
"name": "extend-shallow",
"escapedName": "extend-shallow",
"rawSpec": "^2.0.1",
"saveSpec": null,
"fetchSpec": "^2.0.1"
},
"_requiredBy": [
"/braces"
],
"_resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
"_shasum": "51af7d614ad9a9f610ea1bafbb989d6b1c56890f",
"_spec": "extend-shallow@^2.0.1",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/braces",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/extend-shallow/issues"
},
"bundleDependencies": false,
"dependencies": {
"is-extendable": "^0.1.0"
},
"deprecated": false,
"description": "Extend an object with the properties of additional objects. node.js/javascript util.",
"devDependencies": {
"array-slice": "^0.2.3",
"benchmarked": "^0.1.4",
"chalk": "^1.0.0",
"for-own": "^0.1.3",
"glob": "^5.0.12",
"is-plain-object": "^2.0.1",
"kind-of": "^2.0.0",
"minimist": "^1.1.1",
"mocha": "^2.2.5",
"should": "^7.0.1"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/extend-shallow",
"keywords": [
"assign",
"extend",
"javascript",
"js",
"keys",
"merge",
"obj",
"object",
"prop",
"properties",
"property",
"props",
"shallow",
"util",
"utility",
"utils",
"value"
],
"license": "MIT",
"main": "index.js",
"name": "extend-shallow",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/extend-shallow.git"
},
"scripts": {
"test": "mocha"
},
"version": "2.0.1"
}
{
"_from": "braces@^2.3.0",
"_id": "braces@2.3.2",
"_inBundle": false,
"_integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
"_location": "/braces",
"_phantomChildren": {
"is-extendable": "0.1.1"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "braces@^2.3.0",
"name": "braces",
"escapedName": "braces",
"rawSpec": "^2.3.0",
"saveSpec": null,
"fetchSpec": "^2.3.0"
},
"_requiredBy": [
"/chokidar",
"/micromatch"
],
"_resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
"_shasum": "5979fd3f14cd531565e5fa2df1abfff1dfaee729",
"_spec": "braces@^2.3.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/chokidar",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/micromatch/braces/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Brian Woodward",
"url": "https://twitter.com/doowb"
},
{
"name": "Elan Shanker",
"url": "https://github.com/es128"
},
{
"name": "Eugene Sharygin",
"url": "https://github.com/eush77"
},
{
"name": "hemanth.hm",
"url": "http://h3manth.com"
},
{
"name": "Jon Schlinkert",
"url": "http://twitter.com/jonschlinkert"
}
],
"dependencies": {
"arr-flatten": "^1.1.0",
"array-unique": "^0.3.2",
"extend-shallow": "^2.0.1",
"fill-range": "^4.0.0",
"isobject": "^3.0.1",
"repeat-element": "^1.1.2",
"snapdragon": "^0.8.1",
"snapdragon-node": "^2.0.1",
"split-string": "^3.0.2",
"to-regex": "^3.0.1"
},
"deprecated": false,
"description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.",
"devDependencies": {
"ansi-cyan": "^0.1.1",
"benchmarked": "^2.0.0",
"brace-expansion": "^1.1.8",
"cross-spawn": "^5.1.0",
"gulp": "^3.9.1",
"gulp-eslint": "^4.0.0",
"gulp-format-md": "^1.0.0",
"gulp-istanbul": "^1.1.2",
"gulp-mocha": "^3.0.1",
"gulp-unused": "^0.2.1",
"is-windows": "^1.0.1",
"minimatch": "^3.0.4",
"mocha": "^3.2.0",
"noncharacters": "^1.1.0",
"text-table": "^0.2.0",
"time-diff": "^0.3.1",
"yargs-parser": "^8.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js",
"lib"
],
"homepage": "https://github.com/micromatch/braces",
"keywords": [
"alpha",
"alphabetical",
"bash",
"brace",
"braces",
"expand",
"expansion",
"filepath",
"fill",
"fs",
"glob",
"globbing",
"letter",
"match",
"matches",
"matching",
"number",
"numerical",
"path",
"range",
"ranges",
"sh"
],
"license": "MIT",
"main": "index.js",
"name": "braces",
"repository": {
"type": "git",
"url": "git+https://github.com/micromatch/braces.git"
},
"scripts": {
"benchmark": "node benchmark",
"test": "mocha"
},
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"lint": {
"reflinks": true
},
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"expand-brackets",
"extglob",
"fill-range",
"micromatch",
"nanomatch"
]
}
},
"version": "2.3.2"
}
benchmark/versions/
node_modules
language: node_js
node_js:
- 0.8
- 0.9
The MIT License (MIT)
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.
# buffer-writer
[![Build Status](https://secure.travis-ci.org/brianc/node-buffer-writer.png?branch=master)](http://travis-ci.org/brianc/node-buffer-writer)
Fast & efficient buffer writer used to keep memory usage low by internally recycling a single large buffer.
Used as the binary protocol writer in [node-postgres](https://github.com/brianc/node-postgres)
Since postgres requires big endian encoding, this only writes big endian numbers for now, but can & probably will easily be extended to write little endian as well.
I'll admit this has a few postgres specific things I might need to take out in the future, such as `addHeader`
## api
`var writer = new (require('buffer-writer')());`
### writer.addInt32(num)
Writes a 4-byte big endian binary encoded number to the end of the buffer.
### writer.addInt16(num)
Writes a 2-byte big endian binary encoded number to the end of the buffer.
### writer.addCString(string)
Writes a string to the buffer `utf8` encoded and adds a null character (`\0`) at the end.
### var buffer = writer.addHeader(char)
Writes the 5 byte PostgreSQL required header to the beginning of the buffer. (1 byte for character, 1 BE Int32 for length of the buffer)
### var buffer = writer.join()
Collects all data in the writer and joins it into a single, new buffer.
### var buffer = writer.flush(char)
Writes the 5 byte postgres required message header, collects all data in the writer and joins it into a single, new buffer, and then resets the writer.
## thoughts
This is kind of node-postgres specific. If you're interested in using this for a more general purpose thing, lemme know.
I would love to work with you on getting this more reusable for your needs.
## license
MIT
var fs = require('fs');
var path = require('path');
var bench = require('bench');
var async = require('async');
var rmdir = require('rmdir');
var ok = require('okay');
var cloned = require('cloned');
cloned.workingDir = __dirname + '/versions';
exports.compare = {
'math': function() {
var two = 1 + 1;
},
'another': function() {
var yay = 2 + 2;
}
};
var clone = function(rev, cb) {
var outputDir = path.join(cloned.workingDir, rev);
console.log(outputDir)
if(fs.existsSync(outputDir)) {
return cb(null, {
rev: rev,
dir: outputDir
});
}
console.log('cloning version ' + rev);
cloned(rev, ok(cb, function(dir) {
console.log('cloned version ' + rev + ' to ' + dir);
cb(null, {
rev: rev,
dir: dir
});
}));
};
var versions = [
'ef599d3'
];
var scripts = fs.readdirSync(__dirname).filter(function(x) {
return x.indexOf('benchmark') > 0;
});
if(process.argv[2]) {
scripts = [process.argv[2]]
}
var run = function() {
async.map(versions, clone, function(err, results) {
if(err) throw err;
exports.compare = { };
var suites = [];
scripts.forEach(function(script) {
for(var i = 0; i < results.length; i++) {
var result = results[i];
var benchPath = path.join(result.dir, 'benchmark', script);
var suite = {};
suites.push(suite);
if(fs.existsSync(benchPath)) {
var bench = require(benchPath);
suite[script + '@' + result.rev] = bench;
} else {
console.log('%s missing at revision %s', benchPath, result.rev);
}
}
suite[script + '@HEAD'] = require(__dirname + '/' + script);
});
var compare = function(suite, cb) {
console.log('running...')
bench.compare(suite, null, null, null, function(err, data) {
if(err) return cb(err);
bench.show(data);
cb(null);
});
}
async.eachSeries(suites, compare, function(err, res) {
console.log('all suites done')
})
});
};
run();
var Writer = require(__dirname + '/../');
module.exports = function() {
var writer = new Writer();
writer.addInt16(-100000000);
writer.addInt16(-1000);
writer.addInt16(-1);
writer.addInt16(0);
writer.addInt16(1);
writer.addInt16(1000);
writer.addInt16(1000000000);
writer.addInt16(-100000000);
writer.addInt16(-100000000);
writer.addInt16(-1000);
writer.addInt16(-1);
writer.addInt16(0);
writer.addInt16(1);
writer.addInt16(1000);
writer.addInt16(1000000000);
writer.addInt16(-1000);
writer.addInt16(-1);
writer.addInt16(0);
writer.addInt16(1);
writer.addInt16(1000);
writer.addInt16(1000000000);
};
if(!module.parent) {
module.exports();
console.log('benchmark ok');
}
var Writer = require(__dirname + '/../');
module.exports = function() {
var writer = new Writer();
writer.addInt32(-10000000000000);
writer.addInt32(-1000);
writer.addInt32(-1);
writer.addInt32(0);
writer.addInt32(1);
writer.addInt32(1000);
writer.addInt32(10000000000000);
};
if(!module.parent) {
module.exports();
console.log('benchmark ok');
}
var Writer = require(__dirname + '/../');
var writer = new Writer();
writer.addCString('hello');
writer.addCString('something else, really');
writer.addInt32(38013);
writer.addCString('and that\'s all she wrote, folks\n...\n...not really');
module.exports = function() {
writer.join(0x50);
};
if(!module.parent) {
module.exports();
console.log('benchmark ok');
}
var Writer = require(__dirname + '/../');
var string = "";
for(var i = 0; i < 10; i++) {
string += 'Once upon a time long ago there lived a little programming language named JavaScript';
}
module.exports = function() {
var writer = new Writer(4);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
writer.addCString(string);
};
if(!module.parent) {
module.exports();
console.log('benchmark ok');
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment