legacy.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. "use strict";
  2. var _TRAILING_WILD_CARD_R;
  3. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  4. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5. 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, _toPropertyKey(descriptor.key), descriptor); } }
  6. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  7. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  8. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  9. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  10. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  11. function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
  12. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  13. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
  15. function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  16. // A simple implementation of make-array
  17. function makeArray(subject) {
  18. return Array.isArray(subject) ? subject : [subject];
  19. }
  20. var UNDEFINED = undefined;
  21. var EMPTY = '';
  22. var SPACE = ' ';
  23. var ESCAPE = '\\';
  24. var REGEX_TEST_BLANK_LINE = /^\s+$/;
  25. var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
  26. var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
  27. var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
  28. var REGEX_SPLITALL_CRLF = /\r?\n/g;
  29. // Invalid:
  30. // - /foo,
  31. // - ./foo,
  32. // - ../foo,
  33. // - .
  34. // - ..
  35. // Valid:
  36. // - .foo
  37. var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
  38. var REGEX_TEST_TRAILING_SLASH = /\/$/;
  39. var SLASH = '/';
  40. // Do not use ternary expression here, since "istanbul ignore next" is buggy
  41. var TMP_KEY_IGNORE = 'node-ignore';
  42. /* istanbul ignore else */
  43. if (typeof Symbol !== 'undefined') {
  44. TMP_KEY_IGNORE = Symbol["for"]('node-ignore');
  45. }
  46. var KEY_IGNORE = TMP_KEY_IGNORE;
  47. var define = function define(object, key, value) {
  48. Object.defineProperty(object, key, {
  49. value: value
  50. });
  51. return value;
  52. };
  53. var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
  54. var RETURN_FALSE = function RETURN_FALSE() {
  55. return false;
  56. };
  57. // Sanitize the range of a regular expression
  58. // The cases are complicated, see test cases for details
  59. var sanitizeRange = function sanitizeRange(range) {
  60. return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
  61. return from.charCodeAt(0) <= to.charCodeAt(0) ? match
  62. // Invalid range (out of order) which is ok for gitignore rules but
  63. // fatal for JavaScript regular expression, so eliminate it.
  64. : EMPTY;
  65. });
  66. };
  67. // See fixtures #59
  68. var cleanRangeBackSlash = function cleanRangeBackSlash(slashes) {
  69. var length = slashes.length;
  70. return slashes.slice(0, length - length % 2);
  71. };
  72. // > If the pattern ends with a slash,
  73. // > it is removed for the purpose of the following description,
  74. // > but it would only find a match with a directory.
  75. // > In other words, foo/ will match a directory foo and paths underneath it,
  76. // > but will not match a regular file or a symbolic link foo
  77. // > (this is consistent with the way how pathspec works in general in Git).
  78. // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
  79. // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
  80. // you could use option `mark: true` with `glob`
  81. // '`foo/`' should not continue with the '`..`'
  82. var REPLACERS = [[
  83. // Remove BOM
  84. // TODO:
  85. // Other similar zero-width characters?
  86. /^\uFEFF/, function () {
  87. return EMPTY;
  88. }],
  89. // > Trailing spaces are ignored unless they are quoted with backslash ("\")
  90. [
  91. // (a\ ) -> (a )
  92. // (a ) -> (a)
  93. // (a ) -> (a)
  94. // (a \ ) -> (a )
  95. /((?:\\\\)*?)(\\?\s+)$/, function (_, m1, m2) {
  96. return m1 + (m2.indexOf('\\') === 0 ? SPACE : EMPTY);
  97. }],
  98. // Replace (\ ) with ' '
  99. // (\ ) -> ' '
  100. // (\\ ) -> '\\ '
  101. // (\\\ ) -> '\\ '
  102. [/(\\+?)\s/g, function (_, m1) {
  103. var length = m1.length;
  104. return m1.slice(0, length - length % 2) + SPACE;
  105. }],
  106. // Escape metacharacters
  107. // which is written down by users but means special for regular expressions.
  108. // > There are 12 characters with special meanings:
  109. // > - the backslash \,
  110. // > - the caret ^,
  111. // > - the dollar sign $,
  112. // > - the period or dot .,
  113. // > - the vertical bar or pipe symbol |,
  114. // > - the question mark ?,
  115. // > - the asterisk or star *,
  116. // > - the plus sign +,
  117. // > - the opening parenthesis (,
  118. // > - the closing parenthesis ),
  119. // > - and the opening square bracket [,
  120. // > - the opening curly brace {,
  121. // > These special characters are often called "metacharacters".
  122. [/[\\$.|*+(){^]/g, function (match) {
  123. return "\\".concat(match);
  124. }], [
  125. // > a question mark (?) matches a single character
  126. /(?!\\)\?/g, function () {
  127. return '[^/]';
  128. }],
  129. // leading slash
  130. [
  131. // > A leading slash matches the beginning of the pathname.
  132. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
  133. // A leading slash matches the beginning of the pathname
  134. /^\//, function () {
  135. return '^';
  136. }],
  137. // replace special metacharacter slash after the leading slash
  138. [/\//g, function () {
  139. return '\\/';
  140. }], [
  141. // > A leading "**" followed by a slash means match in all directories.
  142. // > For example, "**/foo" matches file or directory "foo" anywhere,
  143. // > the same as pattern "foo".
  144. // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
  145. // > under directory "foo".
  146. // Notice that the '*'s have been replaced as '\\*'
  147. /^\^*\\\*\\\*\\\//,
  148. // '**/foo' <-> 'foo'
  149. function () {
  150. return '^(?:.*\\/)?';
  151. }],
  152. // starting
  153. [
  154. // there will be no leading '/'
  155. // (which has been replaced by section "leading slash")
  156. // If starts with '**', adding a '^' to the regular expression also works
  157. /^(?=[^^])/, function startingReplacer() {
  158. // If has a slash `/` at the beginning or middle
  159. return !/\/(?!$)/.test(this)
  160. // > Prior to 2.22.1
  161. // > If the pattern does not contain a slash /,
  162. // > Git treats it as a shell glob pattern
  163. // Actually, if there is only a trailing slash,
  164. // git also treats it as a shell glob pattern
  165. // After 2.22.1 (compatible but clearer)
  166. // > If there is a separator at the beginning or middle (or both)
  167. // > of the pattern, then the pattern is relative to the directory
  168. // > level of the particular .gitignore file itself.
  169. // > Otherwise the pattern may also match at any level below
  170. // > the .gitignore level.
  171. ? '(?:^|\\/)'
  172. // > Otherwise, Git treats the pattern as a shell glob suitable for
  173. // > consumption by fnmatch(3)
  174. : '^';
  175. }],
  176. // two globstars
  177. [
  178. // Use lookahead assertions so that we could match more than one `'/**'`
  179. /\\\/\\\*\\\*(?=\\\/|$)/g,
  180. // Zero, one or several directories
  181. // should not use '*', or it will be replaced by the next replacer
  182. // Check if it is not the last `'/**'`
  183. function (_, index, str) {
  184. return index + 6 < str.length
  185. // case: /**/
  186. // > A slash followed by two consecutive asterisks then a slash matches
  187. // > zero or more directories.
  188. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
  189. // '/**/'
  190. ? '(?:\\/[^\\/]+)*'
  191. // case: /**
  192. // > A trailing `"/**"` matches everything inside.
  193. // #21: everything inside but it should not include the current folder
  194. : '\\/.+';
  195. }],
  196. // normal intermediate wildcards
  197. [
  198. // Never replace escaped '*'
  199. // ignore rule '\*' will match the path '*'
  200. // 'abc.*/' -> go
  201. // 'abc.*' -> skip this rule,
  202. // coz trailing single wildcard will be handed by [trailing wildcard]
  203. /(^|[^\\]+)(\\\*)+(?=.+)/g,
  204. // '*.js' matches '.js'
  205. // '*.js' doesn't match 'abc'
  206. function (_, p1, p2) {
  207. // 1.
  208. // > An asterisk "*" matches anything except a slash.
  209. // 2.
  210. // > Other consecutive asterisks are considered regular asterisks
  211. // > and will match according to the previous rules.
  212. var unescaped = p2.replace(/\\\*/g, '[^\\/]*');
  213. return p1 + unescaped;
  214. }], [
  215. // unescape, revert step 3 except for back slash
  216. // For example, if a user escape a '\\*',
  217. // after step 3, the result will be '\\\\\\*'
  218. /\\\\\\(?=[$.|*+(){^])/g, function () {
  219. return ESCAPE;
  220. }], [
  221. // '\\\\' -> '\\'
  222. /\\\\/g, function () {
  223. return ESCAPE;
  224. }], [
  225. // > The range notation, e.g. [a-zA-Z],
  226. // > can be used to match one of the characters in a range.
  227. // `\` is escaped by step 3
  228. /(\\)?\[([^\]/]*?)(\\*)($|\])/g, function (match, leadEscape, range, endEscape, close) {
  229. return leadEscape === ESCAPE
  230. // '\\[bar]' -> '\\\\[bar\\]'
  231. ? "\\[".concat(range).concat(cleanRangeBackSlash(endEscape)).concat(close) : close === ']' ? endEscape.length % 2 === 0
  232. // A normal case, and it is a range notation
  233. // '[bar]'
  234. // '[bar\\\\]'
  235. ? "[".concat(sanitizeRange(range)).concat(endEscape, "]") // Invalid range notaton
  236. // '[bar\\]' -> '[bar\\\\]'
  237. : '[]' : '[]';
  238. }],
  239. // ending
  240. [
  241. // 'js' will not match 'js.'
  242. // 'ab' will not match 'abc'
  243. /(?:[^*])$/,
  244. // WTF!
  245. // https://git-scm.com/docs/gitignore
  246. // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
  247. // which re-fixes #24, #38
  248. // > If there is a separator at the end of the pattern then the pattern
  249. // > will only match directories, otherwise the pattern can match both
  250. // > files and directories.
  251. // 'js*' will not match 'a.js'
  252. // 'js/' will not match 'a.js'
  253. // 'js' will match 'a.js' and 'a.js/'
  254. function (match) {
  255. return /\/$/.test(match)
  256. // foo/ will not match 'foo'
  257. ? "".concat(match, "$") // foo matches 'foo' and 'foo/'
  258. : "".concat(match, "(?=$|\\/$)");
  259. }]];
  260. var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
  261. var MODE_IGNORE = 'regex';
  262. var MODE_CHECK_IGNORE = 'checkRegex';
  263. var UNDERSCORE = '_';
  264. var TRAILING_WILD_CARD_REPLACERS = (_TRAILING_WILD_CARD_R = {}, _defineProperty(_TRAILING_WILD_CARD_R, MODE_IGNORE, function (_, p1) {
  265. var prefix = p1
  266. // '\^':
  267. // '/*' does not match EMPTY
  268. // '/*' does not match everything
  269. // '\\\/':
  270. // 'abc/*' does not match 'abc/'
  271. ? "".concat(p1, "[^/]+") // 'a*' matches 'a'
  272. // 'a*' matches 'aa'
  273. : '[^/]*';
  274. return "".concat(prefix, "(?=$|\\/$)");
  275. }), _defineProperty(_TRAILING_WILD_CARD_R, MODE_CHECK_IGNORE, function (_, p1) {
  276. // When doing `git check-ignore`
  277. var prefix = p1
  278. // '\\\/':
  279. // 'abc/*' DOES match 'abc/' !
  280. ? "".concat(p1, "[^/]*") // 'a*' matches 'a'
  281. // 'a*' matches 'aa'
  282. : '[^/]*';
  283. return "".concat(prefix, "(?=$|\\/$)");
  284. }), _TRAILING_WILD_CARD_R);
  285. // @param {pattern}
  286. var makeRegexPrefix = function makeRegexPrefix(pattern) {
  287. return REPLACERS.reduce(function (prev, _ref) {
  288. var _ref2 = _slicedToArray(_ref, 2),
  289. matcher = _ref2[0],
  290. replacer = _ref2[1];
  291. return prev.replace(matcher, replacer.bind(pattern));
  292. }, pattern);
  293. };
  294. var isString = function isString(subject) {
  295. return typeof subject === 'string';
  296. };
  297. // > A blank line matches no files, so it can serve as a separator for readability.
  298. var checkPattern = function checkPattern(pattern) {
  299. return pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)
  300. // > A line starting with # serves as a comment.
  301. && pattern.indexOf('#') !== 0;
  302. };
  303. var splitPattern = function splitPattern(pattern) {
  304. return pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
  305. };
  306. var IgnoreRule = /*#__PURE__*/function () {
  307. function IgnoreRule(pattern, mark, body, ignoreCase, negative, prefix) {
  308. _classCallCheck(this, IgnoreRule);
  309. this.pattern = pattern;
  310. this.mark = mark;
  311. this.negative = negative;
  312. define(this, 'body', body);
  313. define(this, 'ignoreCase', ignoreCase);
  314. define(this, 'regexPrefix', prefix);
  315. }
  316. _createClass(IgnoreRule, [{
  317. key: "regex",
  318. get: function get() {
  319. var key = UNDERSCORE + MODE_IGNORE;
  320. if (this[key]) {
  321. return this[key];
  322. }
  323. return this._make(MODE_IGNORE, key);
  324. }
  325. }, {
  326. key: "checkRegex",
  327. get: function get() {
  328. var key = UNDERSCORE + MODE_CHECK_IGNORE;
  329. if (this[key]) {
  330. return this[key];
  331. }
  332. return this._make(MODE_CHECK_IGNORE, key);
  333. }
  334. }, {
  335. key: "_make",
  336. value: function _make(mode, key) {
  337. var str = this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,
  338. // It does not need to bind pattern
  339. TRAILING_WILD_CARD_REPLACERS[mode]);
  340. var regex = this.ignoreCase ? new RegExp(str, 'i') : new RegExp(str);
  341. return define(this, key, regex);
  342. }
  343. }]);
  344. return IgnoreRule;
  345. }();
  346. var createRule = function createRule(_ref3, ignoreCase) {
  347. var pattern = _ref3.pattern,
  348. mark = _ref3.mark;
  349. var negative = false;
  350. var body = pattern;
  351. // > An optional prefix "!" which negates the pattern;
  352. if (body.indexOf('!') === 0) {
  353. negative = true;
  354. body = body.substr(1);
  355. }
  356. body = body
  357. // > Put a backslash ("\") in front of the first "!" for patterns that
  358. // > begin with a literal "!", for example, `"\!important!.txt"`.
  359. .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
  360. // > Put a backslash ("\") in front of the first hash for patterns that
  361. // > begin with a hash.
  362. .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
  363. var regexPrefix = makeRegexPrefix(body);
  364. return new IgnoreRule(pattern, mark, body, ignoreCase, negative, regexPrefix);
  365. };
  366. var RuleManager = /*#__PURE__*/function () {
  367. function RuleManager(ignoreCase) {
  368. _classCallCheck(this, RuleManager);
  369. this._ignoreCase = ignoreCase;
  370. this._rules = [];
  371. }
  372. _createClass(RuleManager, [{
  373. key: "_add",
  374. value: function _add(pattern) {
  375. // #32
  376. if (pattern && pattern[KEY_IGNORE]) {
  377. this._rules = this._rules.concat(pattern._rules._rules);
  378. this._added = true;
  379. return;
  380. }
  381. if (isString(pattern)) {
  382. pattern = {
  383. pattern: pattern
  384. };
  385. }
  386. if (checkPattern(pattern.pattern)) {
  387. var rule = createRule(pattern, this._ignoreCase);
  388. this._added = true;
  389. this._rules.push(rule);
  390. }
  391. }
  392. // @param {Array<string> | string | Ignore} pattern
  393. }, {
  394. key: "add",
  395. value: function add(pattern) {
  396. this._added = false;
  397. makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._add, this);
  398. return this._added;
  399. }
  400. // Test one single path without recursively checking parent directories
  401. //
  402. // - checkUnignored `boolean` whether should check if the path is unignored,
  403. // setting `checkUnignored` to `false` could reduce additional
  404. // path matching.
  405. // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
  406. // @returns {TestResult} true if a file is ignored
  407. }, {
  408. key: "test",
  409. value: function test(path, checkUnignored, mode) {
  410. var ignored = false;
  411. var unignored = false;
  412. var matchedRule;
  413. this._rules.forEach(function (rule) {
  414. var negative = rule.negative;
  415. // | ignored : unignored
  416. // -------- | ---------------------------------------
  417. // negative | 0:0 | 0:1 | 1:0 | 1:1
  418. // -------- | ------- | ------- | ------- | --------
  419. // 0 | TEST | TEST | SKIP | X
  420. // 1 | TESTIF | SKIP | TEST | X
  421. // - SKIP: always skip
  422. // - TEST: always test
  423. // - TESTIF: only test if checkUnignored
  424. // - X: that never happen
  425. if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
  426. return;
  427. }
  428. var matched = rule[mode].test(path);
  429. if (!matched) {
  430. return;
  431. }
  432. ignored = !negative;
  433. unignored = negative;
  434. matchedRule = negative ? UNDEFINED : rule;
  435. });
  436. var ret = {
  437. ignored: ignored,
  438. unignored: unignored
  439. };
  440. if (matchedRule) {
  441. ret.rule = matchedRule;
  442. }
  443. return ret;
  444. }
  445. }]);
  446. return RuleManager;
  447. }();
  448. var throwError = function throwError(message, Ctor) {
  449. throw new Ctor(message);
  450. };
  451. var checkPath = function checkPath(path, originalPath, doThrow) {
  452. if (!isString(path)) {
  453. return doThrow("path must be a string, but got `".concat(originalPath, "`"), TypeError);
  454. }
  455. // We don't know if we should ignore EMPTY, so throw
  456. if (!path) {
  457. return doThrow("path must not be empty", TypeError);
  458. }
  459. // Check if it is a relative path
  460. if (checkPath.isNotRelative(path)) {
  461. var r = '`path.relative()`d';
  462. return doThrow("path should be a ".concat(r, " string, but got \"").concat(originalPath, "\""), RangeError);
  463. }
  464. return true;
  465. };
  466. var isNotRelative = function isNotRelative(path) {
  467. return REGEX_TEST_INVALID_PATH.test(path);
  468. };
  469. checkPath.isNotRelative = isNotRelative;
  470. // On windows, the following function will be replaced
  471. /* istanbul ignore next */
  472. checkPath.convert = function (p) {
  473. return p;
  474. };
  475. var Ignore = /*#__PURE__*/function () {
  476. function Ignore() {
  477. var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  478. _ref4$ignorecase = _ref4.ignorecase,
  479. ignorecase = _ref4$ignorecase === void 0 ? true : _ref4$ignorecase,
  480. _ref4$ignoreCase = _ref4.ignoreCase,
  481. ignoreCase = _ref4$ignoreCase === void 0 ? ignorecase : _ref4$ignoreCase,
  482. _ref4$allowRelativePa = _ref4.allowRelativePaths,
  483. allowRelativePaths = _ref4$allowRelativePa === void 0 ? false : _ref4$allowRelativePa;
  484. _classCallCheck(this, Ignore);
  485. define(this, KEY_IGNORE, true);
  486. this._rules = new RuleManager(ignoreCase);
  487. this._strictPathCheck = !allowRelativePaths;
  488. this._initCache();
  489. }
  490. _createClass(Ignore, [{
  491. key: "_initCache",
  492. value: function _initCache() {
  493. // A cache for the result of `.ignores()`
  494. this._ignoreCache = Object.create(null);
  495. // A cache for the result of `.test()`
  496. this._testCache = Object.create(null);
  497. }
  498. }, {
  499. key: "add",
  500. value: function add(pattern) {
  501. if (this._rules.add(pattern)) {
  502. // Some rules have just added to the ignore,
  503. // making the behavior changed,
  504. // so we need to re-initialize the result cache
  505. this._initCache();
  506. }
  507. return this;
  508. }
  509. // legacy
  510. }, {
  511. key: "addPattern",
  512. value: function addPattern(pattern) {
  513. return this.add(pattern);
  514. }
  515. // @returns {TestResult}
  516. }, {
  517. key: "_test",
  518. value: function _test(originalPath, cache, checkUnignored, slices) {
  519. var path = originalPath
  520. // Supports nullable path
  521. && checkPath.convert(originalPath);
  522. checkPath(path, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE);
  523. return this._t(path, cache, checkUnignored, slices);
  524. }
  525. }, {
  526. key: "checkIgnore",
  527. value: function checkIgnore(path) {
  528. // If the path doest not end with a slash, `.ignores()` is much equivalent
  529. // to `git check-ignore`
  530. if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
  531. return this.test(path);
  532. }
  533. var slices = path.split(SLASH).filter(Boolean);
  534. slices.pop();
  535. if (slices.length) {
  536. var parent = this._t(slices.join(SLASH) + SLASH, this._testCache, true, slices);
  537. if (parent.ignored) {
  538. return parent;
  539. }
  540. }
  541. return this._rules.test(path, false, MODE_CHECK_IGNORE);
  542. }
  543. }, {
  544. key: "_t",
  545. value: function _t(
  546. // The path to be tested
  547. path,
  548. // The cache for the result of a certain checking
  549. cache,
  550. // Whether should check if the path is unignored
  551. checkUnignored,
  552. // The path slices
  553. slices) {
  554. if (path in cache) {
  555. return cache[path];
  556. }
  557. if (!slices) {
  558. // path/to/a.js
  559. // ['path', 'to', 'a.js']
  560. slices = path.split(SLASH).filter(Boolean);
  561. }
  562. slices.pop();
  563. // If the path has no parent directory, just test it
  564. if (!slices.length) {
  565. return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
  566. }
  567. var parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
  568. // If the path contains a parent directory, check the parent first
  569. return cache[path] = parent.ignored
  570. // > It is not possible to re-include a file if a parent directory of
  571. // > that file is excluded.
  572. ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
  573. }
  574. }, {
  575. key: "ignores",
  576. value: function ignores(path) {
  577. return this._test(path, this._ignoreCache, false).ignored;
  578. }
  579. }, {
  580. key: "createFilter",
  581. value: function createFilter() {
  582. var _this = this;
  583. return function (path) {
  584. return !_this.ignores(path);
  585. };
  586. }
  587. }, {
  588. key: "filter",
  589. value: function filter(paths) {
  590. return makeArray(paths).filter(this.createFilter());
  591. }
  592. // @returns {TestResult}
  593. }, {
  594. key: "test",
  595. value: function test(path) {
  596. return this._test(path, this._testCache, true);
  597. }
  598. }]);
  599. return Ignore;
  600. }();
  601. var factory = function factory(options) {
  602. return new Ignore(options);
  603. };
  604. var isPathValid = function isPathValid(path) {
  605. return checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
  606. };
  607. // Windows
  608. // --------------------------------------------------------------
  609. /* istanbul ignore next */
  610. if (
  611. // Detect `process` so that it can run in browsers.
  612. typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
  613. /* eslint no-control-regex: "off" */
  614. var makePosix = function makePosix(str) {
  615. return /^\\\\\?\\/.test(str) || /[\0-\x1F"<>\|]+/.test(str) ? str : str.replace(/\\/g, '/');
  616. };
  617. checkPath.convert = makePosix;
  618. // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
  619. // 'd:\\foo'
  620. var REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
  621. checkPath.isNotRelative = function (path) {
  622. return REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
  623. };
  624. }
  625. // COMMONJS_EXPORTS ////////////////////////////////////////////////////////////
  626. module.exports = factory;
  627. // Although it is an anti-pattern,
  628. // it is still widely misused by a lot of libraries in github
  629. // Ref: https://github.com/search?q=ignore.default%28%29&type=code
  630. factory["default"] = factory;
  631. module.exports.isPathValid = isPathValid;