-
Notifications
You must be signed in to change notification settings - Fork 116
feat(eslint-plugin): add rule for restricting asset imports #3989
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tido64
wants to merge
2
commits into
main
Choose a base branch
from
tido/eslint/restricted-imports
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@rnx-kit/eslint-plugin": patch | ||
| --- | ||
|
|
||
| Added a rule for restricting asset imports |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import * as nodefs from "node:fs"; | ||
| import * as path from "node:path"; | ||
|
|
||
| /** | ||
| * Returns the name of a file as stored on disk. | ||
| * @param {string} p The path to the file. | ||
| * @param {string} relativeTo The file to resolve from. | ||
| * @returns {string | undefined} | ||
| */ | ||
| export function realname(p, relativeTo, /** @internal */ fs = nodefs) { | ||
| const base = path.dirname(relativeTo); | ||
| const fullPath = path.resolve(base, p); | ||
| if (!fs.existsSync(fullPath)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // This is currently the only way to get the actual file name on disk, which | ||
| // is needed to check for case sensitivity. | ||
| // Note: We cannot use `fs.realpath.native()` because it resolves symbolic | ||
| // links while we want the actual file itself, symbolic link or not. | ||
| const needle = path.basename(p).toLowerCase(); | ||
| const matches = fs | ||
| .readdirSync(path.dirname(fullPath)) | ||
| .filter((file) => file.toLowerCase() === needle); | ||
|
|
||
| const numMatches = matches.length; | ||
| if (numMatches === 0) { | ||
| // This can only happen if the file was deleted between `existsSync()` and | ||
| // the `readdirSync()` call, but we should still handle it gracefully. | ||
| return undefined; | ||
| } | ||
|
|
||
| if (numMatches > 1) { | ||
| // Only case-sensitive file systems can return multiple matches, so we can | ||
| // be confident that the file name on disk is exact if it exists. | ||
| return p; | ||
| } | ||
|
|
||
| // Ensure that the path string keeps the same prefix (e.g., "./") as the | ||
| // original value. | ||
| const filename = matches[0]; | ||
| const targetDir = path.dirname(p); | ||
| return targetDir === "." ? `./${filename}` : `${targetDir}/${filename}`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
118 changes: 118 additions & 0 deletions
118
packages/eslint-plugin/src/rules/restricted-asset-imports.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| // @ts-check | ||
| "use strict"; | ||
|
|
||
| /** @import { Rule } from "eslint"; */ | ||
| const { realname } = require("../helpers/path.js"); | ||
| const path = require("node:path"); | ||
|
|
||
| const SOURCE_FILES = [ | ||
| ".cjs", | ||
| ".cts", | ||
| ".js", | ||
| ".jsx", | ||
| ".mjs", | ||
| ".mts", | ||
| ".ts", | ||
| ".tsx", | ||
| ]; | ||
|
|
||
| /** | ||
| * Returns whether the specified node is an import or require statement. | ||
| * @param {Rule.Node} node | ||
| * @returns {boolean} | ||
| */ | ||
| function isImportOrRequire(node) { | ||
| switch (node.type) { | ||
| case "CallExpression": { | ||
| // const m = require(...); | ||
| const callee = node.callee; | ||
| return callee.type === "Identifier" && callee.name === "require"; | ||
| } | ||
| case "ImportDeclaration": // import m from "..."; | ||
| case "ImportExpression": // const m = import(...); | ||
| return true; | ||
| default: | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param {string} value | ||
| * @returns {boolean} | ||
| */ | ||
| function isSourceFile(value) { | ||
| const ext = path.extname(value); | ||
| return !ext || SOURCE_FILES.includes(ext); | ||
| } | ||
|
|
||
| /** @type {Rule.RuleModule} */ | ||
| module.exports = { | ||
| meta: { | ||
| type: "problem", | ||
| docs: { | ||
| description: "asset imports must follow a set of rules", | ||
| category: "Possible Errors", | ||
| recommended: true, | ||
| url: require("../../package.json").homepage, | ||
| }, | ||
| messages: { | ||
| lowercase: "File name must be lowercase", | ||
| lowercaseDisk: "File name must be lowercase on disk", | ||
| mismatch: "File name does not match the file on disk", | ||
| noSuchFile: "No such file exists", | ||
| }, | ||
| schema: [ | ||
| { | ||
| type: "object", | ||
| properties: { | ||
| extensions: { type: "array", items: { type: "string" } }, | ||
| exists: { type: "boolean" }, | ||
| lowercase: { type: "boolean" }, | ||
| }, | ||
| additionalProperties: false, | ||
| }, | ||
| ], | ||
| }, | ||
| create: (context) => { | ||
| const { extensions, exists, lowercase } = context.options[0] || {}; | ||
|
|
||
| /** @type {Rule.NodeListener} */ | ||
| return { | ||
| Literal: (node) => { | ||
| const { value, parent } = node; | ||
| if ( | ||
| typeof value !== "string" || | ||
| !value.startsWith("./") || | ||
| !isImportOrRequire(parent) | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| if (Array.isArray(extensions)) { | ||
| if (!extensions.includes(path.extname(value))) { | ||
| return; | ||
| } | ||
| } else if (isSourceFile(value)) { | ||
| return; | ||
| } | ||
|
|
||
| if (lowercase !== false && value.toLowerCase() !== value) { | ||
| context.report({ node, messageId: "lowercase" }); | ||
| } | ||
|
|
||
| if (exists !== false) { | ||
| const p = realname(value, context.filename); | ||
| if (!p) { | ||
| context.report({ node, messageId: "noSuchFile" }); | ||
| } else if (lowercase !== false) { | ||
| if (p.toLowerCase() !== p) { | ||
| context.report({ node, messageId: "lowercaseDisk" }); | ||
| } | ||
| } else if (p !== value) { | ||
| context.report({ node, messageId: "mismatch" }); | ||
| } | ||
| } | ||
| }, | ||
| }; | ||
| }, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import * as fs from "node:fs"; | ||
| import { realname } from "../../src/helpers/path.js"; | ||
|
|
||
| describe("realname()", () => { | ||
| const thisFile = __filename; | ||
|
|
||
| it("returns the file name on disk", () => { | ||
| const cases = [ | ||
| "../../README.md", | ||
| "../../package.json", | ||
| "../../../../README.md", | ||
| "../../../../package.json", | ||
| ]; | ||
| for (const c of cases) { | ||
| expect(realname(c, thisFile)).toEqual(c); | ||
| } | ||
| }); | ||
|
|
||
| // The following tests only work on case-sensitive file systems | ||
| const isCaseSensitive = !fs.existsSync(thisFile.toUpperCase()); | ||
| const iit = isCaseSensitive ? it.skip : it; | ||
|
|
||
| iit("returns the file name on disk (case-insensitive)", () => { | ||
| const cases = [ | ||
| ["../../rEaDmE.md", "../../README.md"], | ||
| ["../../PaCkAgE.json", "../../package.json"], | ||
| ["../../../../PaCkAgE.json", "../../../../package.json"], | ||
| ] as const; | ||
| for (const [input, expected] of cases) { | ||
| expect(realname(input, thisFile)).toEqual(expected); | ||
| } | ||
| }); | ||
| }); |
136 changes: 136 additions & 0 deletions
136
packages/eslint-plugin/test/restricted-asset-imports.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import * as fs from "node:fs"; | ||
| import rule from "../src/rules/restricted-asset-imports.js"; | ||
| import { makeRuleTester } from "./RuleTester.ts"; | ||
|
|
||
| describe("asset imports must follow a set of rules", () => { | ||
| const E_LOWERCASE = { messageId: "lowercase" }; | ||
| const E_LOWERCASEDISK = { messageId: "lowercaseDisk" }; | ||
| const E_MISMATCH = { messageId: "mismatch" }; | ||
| const E_NOSUCHFILE = { messageId: "noSuchFile" }; | ||
|
|
||
| const ruleTester = makeRuleTester(); | ||
|
|
||
| ruleTester.run("restricted-asset-imports", rule, { | ||
| valid: [ | ||
| '"./assets/Image.png";', | ||
| 'import t from "module.png";', | ||
| 'import t from "./types";', | ||
| 'import t from "./types.cjs";', | ||
| 'import t from "./types.cts";', | ||
| 'import t from "./types.js";', | ||
| 'import t from "./types.jsx";', | ||
| 'import t from "./types.mjs";', | ||
| 'import t from "./types.mts";', | ||
| 'import t from "./types.ts";', | ||
| 'import t from "./types.tsx";', | ||
| { | ||
| code: 'import i from "./assets/image.png";', | ||
| options: [{ exists: false }], | ||
| }, | ||
| { | ||
| code: 'import i from "./assets/Image.png";', | ||
| options: [{ extensions: [".jpg"], exists: false }], | ||
| }, | ||
| { | ||
| code: 'import i from "./assets/Image.png";', | ||
| options: [{ lowercase: false, exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/image.png");', | ||
| options: [{ exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/Image.png");', | ||
| options: [{ extensions: [".jpg"], exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/Image.png");', | ||
| options: [{ lowercase: false, exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/image.png");', | ||
| options: [{ exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/Image.png");', | ||
| options: [{ extensions: [".jpg"], exists: false }], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/Image.png");', | ||
| options: [{ lowercase: false, exists: false }], | ||
| }, | ||
| ], | ||
| invalid: [ | ||
| { | ||
| code: 'import i from "./assets/Image.png";', | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'import i from "./assets/Image.png";', | ||
| options: [{ extensions: [".png"] }], | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'import i from "./assets/Image.png";', | ||
| options: [{ extensions: [".png"], exists: false }], | ||
| errors: [E_LOWERCASE], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/Image.png");', | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/Image.png");', | ||
| options: [{ extensions: [".png"] }], | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'const i = import("./assets/Image.png");', | ||
| options: [{ extensions: [".png"], exists: false }], | ||
| errors: [E_LOWERCASE], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/Image.png");', | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/Image.png");', | ||
| options: [{ extensions: [".png"] }], | ||
| errors: [E_LOWERCASE, E_NOSUCHFILE], | ||
| }, | ||
| { | ||
| code: 'const i = require("./assets/Image.png");', | ||
| options: [{ extensions: [".png"], exists: false }], | ||
| errors: [E_LOWERCASE], | ||
| }, | ||
| ], | ||
| }); | ||
|
|
||
| // These tests only work on case-sensitive file systems | ||
| const thisFile = __filename; | ||
| if (fs.existsSync(thisFile.toUpperCase())) { | ||
| ruleTester.run("restricted-asset-imports (case-insensitive)", rule, { | ||
| valid: [ | ||
| { | ||
| code: 'import m from "./README.md";', | ||
| options: [{ lowercase: false }], | ||
| }, | ||
| ], | ||
| invalid: [ | ||
| { | ||
| code: 'import m from "./readme.md";', | ||
| errors: [E_LOWERCASEDISK], | ||
| }, | ||
| { | ||
| code: 'import m from "./ReadMe.md";', | ||
| errors: [E_LOWERCASE, E_LOWERCASEDISK], | ||
| }, | ||
| { | ||
| code: 'import m from "./ReadMe.md";', | ||
| options: [{ lowercase: false }], | ||
| errors: [E_MISMATCH], | ||
| }, | ||
| ], | ||
| }); | ||
| } | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Curious, can these be esm?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We wrote these in CJS to be backwards compatible. Changing them to ESM now would require a major release and doesn't really give us anything right now.