-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathignored-paths.ts
404 lines (354 loc) · 11.3 KB
/
ignored-paths.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/**
* @fileoverview Responsible for loading ignore config files and managing ignore patterns
* Borrow from GitHub `eslint/eslint` repo
* @see https://github.com/eslint/eslint/blob/v5.2.0/lib/ignored-paths.js
* @author kazuya kawaguchi (a.k.a. kazupon)
*/
import { existsSync, statSync, readFileSync } from 'fs'
import { resolve, dirname, relative, sep } from 'path'
import { getRelativePath } from './path-utils'
import type { Ignore } from 'ignore'
import ignore from 'ignore'
import debugBuilder from 'debug'
const debug = debugBuilder('eslint-plugin-vue-i18n:ignored-paths')
const ESLINT_IGNORE_FILENAME = '.eslintignore'
/**
* Adds `"*"` at the end of `"node_modules/"`,
* so that subtle directories could be re-included by .gitignore patterns
* such as `"!node_modules/should_not_ignored"`
*/
const DEFAULT_IGNORE_DIRS = ['/node_modules/*', '/bower_components/*']
const DEFAULT_OPTIONS = {
dotfiles: false
}
/**
* Find a file in the current directory.
*/
function findFile(cwd: string, name: string) {
const ignoreFilePath = resolve(cwd, name)
return existsSync(ignoreFilePath) && statSync(ignoreFilePath).isFile()
? ignoreFilePath
: ''
}
/**
* Find an ignore file in the current directory.
*/
function findIgnoreFile(cwd: string) {
return findFile(cwd, ESLINT_IGNORE_FILENAME)
}
/**
* Find an package.json file in the current directory.
*/
function findPackageJSONFile(cwd: string) {
return findFile(cwd, 'package.json')
}
/**
* Merge options with defaults
*/
function mergeDefaultOptions<O>(
options: { dotfiles?: boolean; cwd?: string } & O
): O & { cwd: string; dotfiles: boolean } {
const mergedOptions = Object.assign({}, DEFAULT_OPTIONS, options)
if (!mergedOptions.cwd) {
mergedOptions.cwd = process.cwd()
}
debug('mergeDefaultOptions: mergedOptions = %j', mergedOptions)
return mergedOptions as never
}
/* eslint-disable valid-jsdoc */
/**
* Normalize the path separators in a given string.
* On Windows environment, this replaces `\` by `/`.
* Otherwrise, this does nothing.
*/
const normalizePathSeps =
sep === '/'
? (str: string) => str
: ((seps: RegExp, str: string) => str.replace(seps, '/')).bind(
null,
new RegExp(`\\${sep}`, 'g')
)
/* eslint-enable valid-jsdoc */
/**
* Converts a glob pattern to a new glob pattern relative to a different directory
*/
function relativize(globPattern: string, relativePathToOldBaseDir: string) {
if (relativePathToOldBaseDir === '') {
return globPattern
}
const prefix = globPattern.startsWith('!') ? '!' : ''
const globWithoutPrefix = globPattern.replace(/^!/, '')
if (globWithoutPrefix.startsWith('/')) {
return `${prefix}/${normalizePathSeps(
relativePathToOldBaseDir
)}${globWithoutPrefix}`
}
return globPattern
}
/**
* IgnoredPaths class
*/
export class IgnoredPaths {
cache: {
[key: string]: string[] | undefined
}
defaultPatterns: string[]
ignoreFileDir: string
options: {
dotfiles: boolean
cwd: string
patterns?: string[]
ignore?: boolean
ignorePath?: string
ignorePattern?: string
}
private _baseDir: string | null
ig: {
custom: Ignore & { ignoreFiles: string[] }
default: Ignore & { ignoreFiles: string[] }
}
constructor(providedOptions: {
dotfiles?: boolean | undefined
cwd?: string | undefined
patterns?: string[]
ignore?: boolean
ignorePath?: string
ignorePattern?: string
}) {
const options = mergeDefaultOptions(providedOptions)
this.cache = {}
this.defaultPatterns = ([] as string[]).concat(
DEFAULT_IGNORE_DIRS,
options.patterns || []
)
this.ignoreFileDir =
options.ignore !== false && options.ignorePath
? dirname(resolve(options.cwd, options.ignorePath))
: options.cwd
this.options = options
this._baseDir = null
this.ig = {
custom: ignore() as never,
default: ignore() as never
}
this.defaultPatterns.forEach(pattern =>
this.addPatternRelativeToCwd(this.ig.default, pattern)
)
if (options.dotfiles !== true) {
/*
* ignore files beginning with a dot, but not files in a parent or
* ancestor directory (which in relative format will begin with `../`).
*/
this.addPatternRelativeToCwd(this.ig.default, '.*')
this.addPatternRelativeToCwd(this.ig.default, '!../')
}
/*
* Add a way to keep track of ignored files. This was present in node-ignore
* 2.x, but dropped for now as of 3.0.10.
*/
this.ig.custom.ignoreFiles = []
this.ig.default.ignoreFiles = []
if (options.ignore !== false) {
let ignorePath
if (options.ignorePath) {
debug('Using specific ignore file')
try {
statSync(options.ignorePath)
ignorePath = options.ignorePath
} catch (
// eslint-disable-next-line @typescript-eslint/no-explicit-any, prettier/prettier
e: any
) {
e.message = `Cannot read ignore file: ${options.ignorePath}\nError: ${e.message}`
throw e
}
} else {
debug(`Looking for ignore file in ${options.cwd}`)
ignorePath = findIgnoreFile(options.cwd)
try {
statSync(ignorePath)
debug(`Loaded ignore file ${ignorePath}`)
} catch (e) {
debug('Could not find ignore file in cwd')
}
}
if (ignorePath) {
debug(`Adding ${ignorePath}`)
this.addIgnoreFile(this.ig.custom, ignorePath)
this.addIgnoreFile(this.ig.default, ignorePath)
} else {
try {
// if the ignoreFile does not exist, check package.json for eslintIgnore
const packageJSONPath = findPackageJSONFile(options.cwd)
if (packageJSONPath) {
let packageJSONOptions: { eslintIgnore: string[] }
try {
packageJSONOptions = JSON.parse(
readFileSync(packageJSONPath, 'utf8')
)
} catch (
// eslint-disable-next-line @typescript-eslint/no-explicit-any, prettier/prettier
e: any
) {
debug(
'Could not read package.json file to check eslintIgnore property'
)
e.messageTemplate = 'failed-to-read-json'
e.messageData = {
path: packageJSONPath,
message: e.message
}
throw e
}
if (packageJSONOptions.eslintIgnore) {
if (Array.isArray(packageJSONOptions.eslintIgnore)) {
packageJSONOptions.eslintIgnore.forEach(pattern => {
this.addPatternRelativeToIgnoreFile(this.ig.custom, pattern)
this.addPatternRelativeToIgnoreFile(this.ig.default, pattern)
})
} else {
throw new TypeError(
'Package.json eslintIgnore property requires an array of paths'
)
}
}
}
} catch (e) {
debug('Could not find package.json to check eslintIgnore property')
throw e
}
}
if (options.ignorePattern) {
this.addPatternRelativeToCwd(this.ig.custom, options.ignorePattern)
this.addPatternRelativeToCwd(this.ig.default, options.ignorePattern)
}
}
}
/*
* If `ignoreFileDir` is a subdirectory of `cwd`, all paths will be normalized to be relative to `cwd`.
* Otherwise, all paths will be normalized to be relative to `ignoreFileDir`.
* This ensures that the final normalized ignore rule will not contain `..`, which is forbidden in
* ignore rules.
*/
addPatternRelativeToCwd(ig: Ignore, pattern: string): void {
const baseDir = this.getBaseDir()
const cookedPattern =
baseDir === this.options.cwd
? pattern
: relativize(pattern, relative(baseDir, this.options.cwd))
ig.add(cookedPattern)
debug(
'addPatternRelativeToCwd:\n original = %j\n cooked = %j',
pattern,
cookedPattern
)
}
addPatternRelativeToIgnoreFile(ig: Ignore, pattern: string): void {
const baseDir = this.getBaseDir()
const cookedPattern =
baseDir === this.ignoreFileDir
? pattern
: relativize(pattern, relative(baseDir, this.ignoreFileDir))
ig.add(cookedPattern)
debug(
'addPatternRelativeToIgnoreFile:\n original = %j\n cooked = %j',
pattern,
cookedPattern
)
}
// Detect the common ancestor
getBaseDir(): string {
if (!this._baseDir) {
const a = resolve(this.options.cwd)
const b = resolve(this.ignoreFileDir)
let lastSepPos = 0
// Set the shorter one (it's the common ancestor if one includes the other).
this._baseDir = a.length < b.length ? a : b
// Set the common ancestor.
for (let i = 0; i < a.length && i < b.length; ++i) {
if (a[i] !== b[i]) {
this._baseDir = a.slice(0, lastSepPos)
break
}
if (a[i] === sep) {
lastSepPos = i
}
}
// If it's only Windows drive letter, it needs \
if (/^[A-Z]:$/.test(this._baseDir)) {
this._baseDir += '\\'
}
debug('set baseDir = %j', this._baseDir)
} else {
debug('alredy set baseDir = %j', this._baseDir)
}
return this._baseDir
}
/**
* read ignore filepath
*/
readIgnoreFile(filePath: string): string[] {
if (typeof this.cache[filePath] === 'undefined') {
this.cache[filePath] = readFileSync(filePath, 'utf8')
.split(/\r?\n/g)
.filter(Boolean)
}
return this.cache[filePath]!
}
/**
* add ignore file to node-ignore instance
*/
addIgnoreFile(
ig: Ignore & { ignoreFiles: string[] },
filePath: string
): void {
ig.ignoreFiles.push(filePath)
this.readIgnoreFile(filePath).forEach(ignoreRule =>
this.addPatternRelativeToIgnoreFile(ig, ignoreRule)
)
}
/**
* Determine whether a file path is included in the default or custom ignore patterns
*/
contains(filepath: string, category?: 'custom' | 'default'): boolean {
let result = false
const absolutePath = resolve(this.options.cwd, filepath)
const relativePath = getRelativePath(absolutePath, this.getBaseDir())
if (typeof category === 'undefined') {
result =
this.ig.default.filter([relativePath]).length === 0 ||
this.ig.custom.filter([relativePath]).length === 0
} else {
result = this.ig[category].filter([relativePath]).length === 0
}
debug('contains:')
debug(' target = %j', filepath)
debug(' result = %j', result)
return result
}
/**
* Returns a list of dir patterns for glob to ignore
*/
getIgnoredFoldersGlobChecker(): (absolutePath: string) => boolean {
const baseDir = this.getBaseDir()
const ig = ignore()
DEFAULT_IGNORE_DIRS.forEach(ignoreDir =>
this.addPatternRelativeToCwd(ig, ignoreDir)
)
if (this.options.dotfiles !== true) {
// Ignore hidden folders. (This cannot be ".*", or else it's not possible to unignore hidden files)
ig.add(['.*/*', '!../*'])
}
if (this.options.ignore) {
ig.add(this.ig.custom)
}
const filter = ig.createFilter()
return function (absolutePath: string): boolean {
const relative = getRelativePath(absolutePath, baseDir)
if (!relative) {
return false
}
return !filter(relative)
}
}
}