legacy.js 17 KB

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