legacy.js 17 KB

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