You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

466 lines
13 KiB

4 years ago
  1. 'use strict';
  2. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4. // A simple implementation of make-array
  5. function make_array(subject) {
  6. return Array.isArray(subject) ? subject : [subject];
  7. }
  8. var REGEX_BLANK_LINE = /^\s+$/;
  9. var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
  10. var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
  11. var SLASH = '/';
  12. var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
  13. /* istanbul ignore next */
  14. : 'node-ignore';
  15. var define = function define(object, key, value) {
  16. return Object.defineProperty(object, key, { value });
  17. };
  18. var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
  19. // Sanitize the range of a regular expression
  20. // The cases are complicated, see test cases for details
  21. var sanitizeRange = function sanitizeRange(range) {
  22. return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
  23. return from.charCodeAt(0) <= to.charCodeAt(0) ? match
  24. // Invalid range (out of order) which is ok for gitignore rules but
  25. // fatal for JavaScript regular expression, so eliminate it.
  26. : '';
  27. });
  28. };
  29. // > If the pattern ends with a slash,
  30. // > it is removed for the purpose of the following description,
  31. // > but it would only find a match with a directory.
  32. // > In other words, foo/ will match a directory foo and paths underneath it,
  33. // > but will not match a regular file or a symbolic link foo
  34. // > (this is consistent with the way how pathspec works in general in Git).
  35. // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
  36. // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
  37. // you could use option `mark: true` with `glob`
  38. // '`foo/`' should not continue with the '`..`'
  39. var DEFAULT_REPLACER_PREFIX = [
  40. // > Trailing spaces are ignored unless they are quoted with backslash ("\")
  41. [
  42. // (a\ ) -> (a )
  43. // (a ) -> (a)
  44. // (a \ ) -> (a )
  45. /\\?\s+$/, function (match) {
  46. return match.indexOf('\\') === 0 ? ' ' : '';
  47. }],
  48. // replace (\ ) with ' '
  49. [/\\\s/g, function () {
  50. return ' ';
  51. }],
  52. // Escape metacharacters
  53. // which is written down by users but means special for regular expressions.
  54. // > There are 12 characters with special meanings:
  55. // > - the backslash \,
  56. // > - the caret ^,
  57. // > - the dollar sign $,
  58. // > - the period or dot .,
  59. // > - the vertical bar or pipe symbol |,
  60. // > - the question mark ?,
  61. // > - the asterisk or star *,
  62. // > - the plus sign +,
  63. // > - the opening parenthesis (,
  64. // > - the closing parenthesis ),
  65. // > - and the opening square bracket [,
  66. // > - the opening curly brace {,
  67. // > These special characters are often called "metacharacters".
  68. [/[\\^$.|*+(){]/g, function (match) {
  69. return `\\${match}`;
  70. }], [
  71. // > [abc] matches any character inside the brackets
  72. // > (in this case a, b, or c);
  73. /\[([^\]/]*)($|\])/g, function (match, p1, p2) {
  74. return p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`;
  75. }], [
  76. // > a question mark (?) matches a single character
  77. /(?!\\)\?/g, function () {
  78. return '[^/]';
  79. }],
  80. // leading slash
  81. [
  82. // > A leading slash matches the beginning of the pathname.
  83. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
  84. // A leading slash matches the beginning of the pathname
  85. /^\//, function () {
  86. return '^';
  87. }],
  88. // replace special metacharacter slash after the leading slash
  89. [/\//g, function () {
  90. return '\\/';
  91. }], [
  92. // > A leading "**" followed by a slash means match in all directories.
  93. // > For example, "**/foo" matches file or directory "foo" anywhere,
  94. // > the same as pattern "foo".
  95. // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
  96. // > under directory "foo".
  97. // Notice that the '*'s have been replaced as '\\*'
  98. /^\^*\\\*\\\*\\\//,
  99. // '**/foo' <-> 'foo'
  100. function () {
  101. return '^(?:.*\\/)?';
  102. }]];
  103. var DEFAULT_REPLACER_SUFFIX = [
  104. // starting
  105. [
  106. // there will be no leading '/'
  107. // (which has been replaced by section "leading slash")
  108. // If starts with '**', adding a '^' to the regular expression also works
  109. /^(?=[^^])/, function startingReplacer() {
  110. return !/\/(?!$)/.test(this)
  111. // > If the pattern does not contain a slash /,
  112. // > Git treats it as a shell glob pattern
  113. // Actually, if there is only a trailing slash,
  114. // git also treats it as a shell glob pattern
  115. ? '(?:^|\\/)'
  116. // > Otherwise, Git treats the pattern as a shell glob suitable for
  117. // > consumption by fnmatch(3)
  118. : '^';
  119. }],
  120. // two globstars
  121. [
  122. // Use lookahead assertions so that we could match more than one `'/**'`
  123. /\\\/\\\*\\\*(?=\\\/|$)/g,
  124. // Zero, one or several directories
  125. // should not use '*', or it will be replaced by the next replacer
  126. // Check if it is not the last `'/**'`
  127. function (match, index, str) {
  128. return index + 6 < str.length
  129. // case: /**/
  130. // > A slash followed by two consecutive asterisks then a slash matches
  131. // > zero or more directories.
  132. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
  133. // '/**/'
  134. ? '(?:\\/[^\\/]+)*'
  135. // case: /**
  136. // > A trailing `"/**"` matches everything inside.
  137. // #21: everything inside but it should not include the current folder
  138. : '\\/.+';
  139. }],
  140. // intermediate wildcards
  141. [
  142. // Never replace escaped '*'
  143. // ignore rule '\*' will match the path '*'
  144. // 'abc.*/' -> go
  145. // 'abc.*' -> skip this rule
  146. /(^|[^\\]+)\\\*(?=.+)/g,
  147. // '*.js' matches '.js'
  148. // '*.js' doesn't match 'abc'
  149. function (match, p1) {
  150. return `${p1}[^\\/]*`;
  151. }],
  152. // trailing wildcard
  153. [/(\^|\\\/)?\\\*$/, function (match, p1) {
  154. var prefix = p1
  155. // '\^':
  156. // '/*' does not match ''
  157. // '/*' does not match everything
  158. // '\\\/':
  159. // 'abc/*' does not match 'abc/'
  160. ? `${p1}[^/]+`
  161. // 'a*' matches 'a'
  162. // 'a*' matches 'aa'
  163. : '[^/]*';
  164. return `${prefix}(?=$|\\/$)`;
  165. }], [
  166. // unescape
  167. /\\\\\\/g, function () {
  168. return '\\';
  169. }]];
  170. var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
  171. // 'f'
  172. // matches
  173. // - /f(end)
  174. // - /f/
  175. // - (start)f(end)
  176. // - (start)f/
  177. // doesn't match
  178. // - oof
  179. // - foo
  180. // pseudo:
  181. // -> (^|/)f(/|$)
  182. // ending
  183. [
  184. // 'js' will not match 'js.'
  185. // 'ab' will not match 'abc'
  186. /(?:[^*/])$/,
  187. // 'js*' will not match 'a.js'
  188. // 'js/' will not match 'a.js'
  189. // 'js' will match 'a.js' and 'a.js/'
  190. function (match) {
  191. return `${match}(?=$|\\/)`;
  192. }]], DEFAULT_REPLACER_SUFFIX);
  193. var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
  194. // #24, #38
  195. // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
  196. // A negative pattern without a trailing wildcard should not
  197. // re-include the things inside that directory.
  198. // eg:
  199. // ['node_modules/*', '!node_modules']
  200. // should ignore `node_modules/a.js`
  201. [/(?:[^*])$/, function (match) {
  202. return `${match}(?=$|\\/$)`;
  203. }]], DEFAULT_REPLACER_SUFFIX);
  204. // A simple cache, because an ignore rule only has only one certain meaning
  205. var cache = Object.create(null);
  206. // @param {pattern}
  207. var make_regex = function make_regex(pattern, negative, ignorecase) {
  208. var r = cache[pattern];
  209. if (r) {
  210. return r;
  211. }
  212. var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
  213. var source = replacers.reduce(function (prev, current) {
  214. return prev.replace(current[0], current[1].bind(pattern));
  215. }, pattern);
  216. return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
  217. };
  218. // > A blank line matches no files, so it can serve as a separator for readability.
  219. var checkPattern = function checkPattern(pattern) {
  220. return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern)
  221. // > A line starting with # serves as a comment.
  222. && pattern.indexOf('#') !== 0;
  223. };
  224. var createRule = function createRule(pattern, ignorecase) {
  225. var origin = pattern;
  226. var negative = false;
  227. // > An optional prefix "!" which negates the pattern;
  228. if (pattern.indexOf('!') === 0) {
  229. negative = true;
  230. pattern = pattern.substr(1);
  231. }
  232. pattern = pattern
  233. // > Put a backslash ("\") in front of the first "!" for patterns that
  234. // > begin with a literal "!", for example, `"\!important!.txt"`.
  235. .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!')
  236. // > Put a backslash ("\") in front of the first hash for patterns that
  237. // > begin with a hash.
  238. .replace(REGEX_LEADING_EXCAPED_HASH, '#');
  239. var regex = make_regex(pattern, negative, ignorecase);
  240. return {
  241. origin,
  242. pattern,
  243. negative,
  244. regex
  245. };
  246. };
  247. var IgnoreBase = function () {
  248. function IgnoreBase() {
  249. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  250. _ref$ignorecase = _ref.ignorecase,
  251. ignorecase = _ref$ignorecase === undefined ? true : _ref$ignorecase;
  252. _classCallCheck(this, IgnoreBase);
  253. this._rules = [];
  254. this._ignorecase = ignorecase;
  255. define(this, KEY_IGNORE, true);
  256. this._initCache();
  257. }
  258. _createClass(IgnoreBase, [{
  259. key: '_initCache',
  260. value: function _initCache() {
  261. this._cache = Object.create(null);
  262. }
  263. // @param {Array.<string>|string|Ignore} pattern
  264. }, {
  265. key: 'add',
  266. value: function add(pattern) {
  267. this._added = false;
  268. if (typeof pattern === 'string') {
  269. pattern = pattern.split(/\r?\n/g);
  270. }
  271. make_array(pattern).forEach(this._addPattern, this);
  272. // Some rules have just added to the ignore,
  273. // making the behavior changed.
  274. if (this._added) {
  275. this._initCache();
  276. }
  277. return this;
  278. }
  279. // legacy
  280. }, {
  281. key: 'addPattern',
  282. value: function addPattern(pattern) {
  283. return this.add(pattern);
  284. }
  285. }, {
  286. key: '_addPattern',
  287. value: function _addPattern(pattern) {
  288. // #32
  289. if (pattern && pattern[KEY_IGNORE]) {
  290. this._rules = this._rules.concat(pattern._rules);
  291. this._added = true;
  292. return;
  293. }
  294. if (checkPattern(pattern)) {
  295. var rule = createRule(pattern, this._ignorecase);
  296. this._added = true;
  297. this._rules.push(rule);
  298. }
  299. }
  300. }, {
  301. key: 'filter',
  302. value: function filter(paths) {
  303. var _this = this;
  304. return make_array(paths).filter(function (path) {
  305. return _this._filter(path);
  306. });
  307. }
  308. }, {
  309. key: 'createFilter',
  310. value: function createFilter() {
  311. var _this2 = this;
  312. return function (path) {
  313. return _this2._filter(path);
  314. };
  315. }
  316. }, {
  317. key: 'ignores',
  318. value: function ignores(path) {
  319. return !this._filter(path);
  320. }
  321. // @returns `Boolean` true if the `path` is NOT ignored
  322. }, {
  323. key: '_filter',
  324. value: function _filter(path, slices) {
  325. if (!path) {
  326. return false;
  327. }
  328. if (path in this._cache) {
  329. return this._cache[path];
  330. }
  331. if (!slices) {
  332. // path/to/a.js
  333. // ['path', 'to', 'a.js']
  334. slices = path.split(SLASH);
  335. }
  336. slices.pop();
  337. return this._cache[path] = slices.length
  338. // > It is not possible to re-include a file if a parent directory of
  339. // > that file is excluded.
  340. // If the path contains a parent directory, check the parent first
  341. ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path)
  342. // Or only test the path
  343. : this._test(path);
  344. }
  345. // @returns {Boolean} true if a file is NOT ignored
  346. }, {
  347. key: '_test',
  348. value: function _test(path) {
  349. // Explicitly define variable type by setting matched to `0`
  350. var matched = 0;
  351. this._rules.forEach(function (rule) {
  352. // if matched = true, then we only test negative rules
  353. // if matched = false, then we test non-negative rules
  354. if (!(matched ^ rule.negative)) {
  355. matched = rule.negative ^ rule.regex.test(path);
  356. }
  357. });
  358. return !matched;
  359. }
  360. }]);
  361. return IgnoreBase;
  362. }();
  363. // Windows
  364. // --------------------------------------------------------------
  365. /* istanbul ignore if */
  366. if (
  367. // Detect `process` so that it can run in browsers.
  368. typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
  369. var filter = IgnoreBase.prototype._filter;
  370. /* eslint no-control-regex: "off" */
  371. var make_posix = function make_posix(str) {
  372. return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/')
  373. );
  374. };
  375. IgnoreBase.prototype._filter = function filterWin32(path, slices) {
  376. path = make_posix(path);
  377. return filter.call(this, path, slices);
  378. };
  379. }
  380. module.exports = function (options) {
  381. return new IgnoreBase(options);
  382. };