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.

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