index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. 'use strict';
  2. /**
  3. * Module dependencies
  4. */
  5. var toRegex = require('to-regex');
  6. var unique = require('array-unique');
  7. var extend = require('extend-shallow');
  8. var define = require('define-property');
  9. /**
  10. * Local dependencies
  11. */
  12. var compilers = require('./lib/compilers');
  13. var parsers = require('./lib/parsers');
  14. var Braces = require('./lib/braces');
  15. var utils = require('./lib/utils');
  16. var MAX_LENGTH = 1024 * 64;
  17. var cache = {};
  18. /**
  19. * 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)).
  20. *
  21. * ```js
  22. * var braces = require('braces');
  23. * console.log(braces('{a,b,c}'));
  24. * //=> ['(a|b|c)']
  25. *
  26. * console.log(braces('{a,b,c}', {expand: true}));
  27. * //=> ['a', 'b', 'c']
  28. * ```
  29. * @param {String} `str`
  30. * @param {Object} `options`
  31. * @return {String}
  32. * @api public
  33. */
  34. function braces(pattern, options) {
  35. var key = utils.createKey(String(pattern), options);
  36. var arr = [];
  37. var disabled = options && options.cache === false;
  38. if (!disabled && cache.hasOwnProperty(key)) {
  39. return cache[key];
  40. }
  41. if (Array.isArray(pattern)) {
  42. for (var i = 0; i < pattern.length; i++) {
  43. arr.push.apply(arr, braces.create(pattern[i], options));
  44. }
  45. } else {
  46. arr = braces.create(pattern, options);
  47. }
  48. if (options && options.nodupes === true) {
  49. arr = unique(arr);
  50. }
  51. if (!disabled) {
  52. cache[key] = arr;
  53. }
  54. return arr;
  55. }
  56. /**
  57. * 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.
  58. *
  59. * ```js
  60. * var braces = require('braces');
  61. * console.log(braces.expand('a/{b,c}/d'));
  62. * //=> ['a/b/d', 'a/c/d'];
  63. * ```
  64. * @param {String} `pattern` Brace pattern
  65. * @param {Object} `options`
  66. * @return {Array} Returns an array of expanded values.
  67. * @api public
  68. */
  69. braces.expand = function(pattern, options) {
  70. return braces.create(pattern, extend({}, options, {expand: true}));
  71. };
  72. /**
  73. * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
  74. *
  75. * ```js
  76. * var braces = require('braces');
  77. * console.log(braces.expand('a/{b,c}/d'));
  78. * //=> ['a/(b|c)/d']
  79. * ```
  80. * @param {String} `pattern` Brace pattern
  81. * @param {Object} `options`
  82. * @return {Array} Returns an array of expanded values.
  83. * @api public
  84. */
  85. braces.optimize = function(pattern, options) {
  86. return braces.create(pattern, options);
  87. };
  88. /**
  89. * 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.
  90. *
  91. * ```js
  92. * var braces = require('braces');
  93. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  94. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  95. * ```
  96. * @param {String} `pattern` Brace pattern
  97. * @param {Object} `options`
  98. * @return {Array} Returns an array of expanded values.
  99. * @api public
  100. */
  101. braces.create = function(pattern, options) {
  102. if (typeof pattern !== 'string') {
  103. throw new TypeError('expected a string');
  104. }
  105. var maxLength = (options && options.maxLength) || MAX_LENGTH;
  106. if (pattern.length >= maxLength) {
  107. throw new Error('expected pattern to be less than ' + maxLength + ' characters');
  108. }
  109. function create() {
  110. if (pattern === '' || pattern.length < 3) {
  111. return [pattern];
  112. }
  113. if (utils.isEmptySets(pattern)) {
  114. return [];
  115. }
  116. if (utils.isQuotedString(pattern)) {
  117. return [pattern.slice(1, -1)];
  118. }
  119. var proto = new Braces(options);
  120. var result = !options || options.expand !== true
  121. ? proto.optimize(pattern, options)
  122. : proto.expand(pattern, options);
  123. // get the generated pattern(s)
  124. var arr = result.output;
  125. // filter out empty strings if specified
  126. if (options && options.noempty === true) {
  127. arr = arr.filter(Boolean);
  128. }
  129. // filter out duplicates if specified
  130. if (options && options.nodupes === true) {
  131. arr = unique(arr);
  132. }
  133. define(arr, 'result', result);
  134. return arr;
  135. }
  136. return memoize('create', pattern, options, create);
  137. };
  138. /**
  139. * Create a regular expression from the given string `pattern`.
  140. *
  141. * ```js
  142. * var braces = require('braces');
  143. *
  144. * console.log(braces.makeRe('id-{200..300}'));
  145. * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
  146. * ```
  147. * @param {String} `pattern` The pattern to convert to regex.
  148. * @param {Object} `options`
  149. * @return {RegExp}
  150. * @api public
  151. */
  152. braces.makeRe = function(pattern, options) {
  153. if (typeof pattern !== 'string') {
  154. throw new TypeError('expected a string');
  155. }
  156. var maxLength = (options && options.maxLength) || MAX_LENGTH;
  157. if (pattern.length >= maxLength) {
  158. throw new Error('expected pattern to be less than ' + maxLength + ' characters');
  159. }
  160. function makeRe() {
  161. var arr = braces(pattern, options);
  162. var opts = extend({strictErrors: false}, options);
  163. return toRegex(arr, opts);
  164. }
  165. return memoize('makeRe', pattern, options, makeRe);
  166. };
  167. /**
  168. * Parse the given `str` with the given `options`.
  169. *
  170. * ```js
  171. * var braces = require('braces');
  172. * var ast = braces.parse('a/{b,c}/d');
  173. * console.log(ast);
  174. * // { type: 'root',
  175. * // errors: [],
  176. * // input: 'a/{b,c}/d',
  177. * // nodes:
  178. * // [ { type: 'bos', val: '' },
  179. * // { type: 'text', val: 'a/' },
  180. * // { type: 'brace',
  181. * // nodes:
  182. * // [ { type: 'brace.open', val: '{' },
  183. * // { type: 'text', val: 'b,c' },
  184. * // { type: 'brace.close', val: '}' } ] },
  185. * // { type: 'text', val: '/d' },
  186. * // { type: 'eos', val: '' } ] }
  187. * ```
  188. * @param {String} `pattern` Brace pattern to parse
  189. * @param {Object} `options`
  190. * @return {Object} Returns an AST
  191. * @api public
  192. */
  193. braces.parse = function(pattern, options) {
  194. var proto = new Braces(options);
  195. return proto.parse(pattern, options);
  196. };
  197. /**
  198. * Compile the given `ast` or string with the given `options`.
  199. *
  200. * ```js
  201. * var braces = require('braces');
  202. * var ast = braces.parse('a/{b,c}/d');
  203. * console.log(braces.compile(ast));
  204. * // { options: { source: 'string' },
  205. * // state: {},
  206. * // compilers:
  207. * // { eos: [Function],
  208. * // noop: [Function],
  209. * // bos: [Function],
  210. * // brace: [Function],
  211. * // 'brace.open': [Function],
  212. * // text: [Function],
  213. * // 'brace.close': [Function] },
  214. * // output: [ 'a/(b|c)/d' ],
  215. * // ast:
  216. * // { ... },
  217. * // parsingErrors: [] }
  218. * ```
  219. * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
  220. * @param {Object} `options`
  221. * @return {Object} Returns an object that has an `output` property with the compiled string.
  222. * @api public
  223. */
  224. braces.compile = function(ast, options) {
  225. var proto = new Braces(options);
  226. return proto.compile(ast, options);
  227. };
  228. /**
  229. * Clear the regex cache.
  230. *
  231. * ```js
  232. * braces.clearCache();
  233. * ```
  234. * @api public
  235. */
  236. braces.clearCache = function() {
  237. cache = braces.cache = {};
  238. };
  239. /**
  240. * Memoize a generated regex or function. A unique key is generated
  241. * from the method name, pattern, and user-defined options. Set
  242. * options.memoize to false to disable.
  243. */
  244. function memoize(type, pattern, options, fn) {
  245. var key = utils.createKey(type + ':' + pattern, options);
  246. var disabled = options && options.cache === false;
  247. if (disabled) {
  248. braces.clearCache();
  249. return fn(pattern, options);
  250. }
  251. if (cache.hasOwnProperty(key)) {
  252. return cache[key];
  253. }
  254. var res = fn(pattern, options);
  255. cache[key] = res;
  256. return res;
  257. }
  258. /**
  259. * Expose `Braces` constructor and methods
  260. * @type {Function}
  261. */
  262. braces.Braces = Braces;
  263. braces.compilers = compilers;
  264. braces.parsers = parsers;
  265. braces.cache = cache;
  266. /**
  267. * Expose `braces`
  268. * @type {Function}
  269. */
  270. module.exports = braces;