legacy.js 18 KB

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