63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import type { Rule } from "eslint"
|
|
|
|
interface RuleOptions {
|
|
/**
|
|
* The maximum number of times a relative path import can go to the parent directory.
|
|
*/
|
|
maxDepth?: number
|
|
}
|
|
|
|
const rule: Rule.RuleModule = {
|
|
meta: {
|
|
type: "suggestion",
|
|
docs: {
|
|
description:
|
|
"Bans relative path imports that go to the parent directory too many times",
|
|
category: "Best Practices",
|
|
recommended: true,
|
|
},
|
|
fixable: "code",
|
|
schema: [
|
|
{
|
|
type: "object",
|
|
properties: {
|
|
maxDepth: {
|
|
type: "integer",
|
|
minimum: 1,
|
|
},
|
|
},
|
|
additionalProperties: false,
|
|
},
|
|
],
|
|
},
|
|
create(context) {
|
|
const { maxDepth = 3 } = (context.options[0] || {}) as RuleOptions
|
|
const errorMessage = `Relative path imports cannot go to the parent directory more than ${maxDepth} levels`
|
|
|
|
return {
|
|
ImportDeclaration(node) {
|
|
const { source } = node
|
|
if (
|
|
source.type === "Literal" &&
|
|
typeof source.value === "string" &&
|
|
source.value.startsWith("..")
|
|
) {
|
|
const depth = source.value.match(/\.\.\//g)?.length ?? 0
|
|
if (depth > maxDepth) {
|
|
context.report({
|
|
node: source,
|
|
message: errorMessage,
|
|
fix(fixer) {
|
|
const newValue = (source.value as string)!.replace(/\.\.\//g, "")
|
|
return fixer.replaceText(source, `'${newValue}'`)
|
|
},
|
|
})
|
|
}
|
|
}
|
|
},
|
|
}
|
|
},
|
|
}
|
|
|
|
export default rule
|