index.js 15 KB

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