This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 659
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rome_js_analyze): new lint rule:
useImportRestrictions
(#4700)
- Loading branch information
Showing
16 changed files
with
517 additions
and
56 deletions.
There are no files selected for viewing
This file contains 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 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
182 changes: 182 additions & 0 deletions
182
crates/rome_js_analyze/src/analyzers/nursery/use_import_restrictions.rs
This file contains 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,182 @@ | ||
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic}; | ||
use rome_console::markup; | ||
use rome_js_syntax::JsModuleSource; | ||
use rome_rowan::{AstNode, SyntaxTokenText}; | ||
|
||
const INDEX_BASENAMES: &[&str] = &["index", "mod"]; | ||
|
||
const SOURCE_EXTENSIONS: &[&str] = &["js", "ts", "cjs", "cts", "mjs", "mts", "jsx", "tsx"]; | ||
|
||
declare_rule! { | ||
/// Disallows package private imports. | ||
/// | ||
/// This rules enforces the following restrictions: | ||
/// | ||
/// ## Package private visibility | ||
/// | ||
/// All exported symbols, such as types, functions or other things that may be exported, are | ||
/// considered to be "package private". This means that modules that reside in the same | ||
/// directory, as well as submodules of those "sibling" modules, are allowed to import them, | ||
/// while any other modules that are further away in the file system are restricted from | ||
/// importing them. A symbol's visibility may be extended by re-exporting from an index file. | ||
/// | ||
/// Notes: | ||
/// | ||
/// * This rule only applies to relative imports. External dependencies are exempted. | ||
/// * This rule only applies to imports for JavaScript and TypeScript files. Imports for | ||
/// resources such as images or CSS files are exempted. | ||
/// | ||
/// Source: https://github.com/uhyo/eslint-plugin-import-access | ||
/// | ||
/// ## Examples | ||
/// | ||
/// ### Invalid | ||
/// | ||
/// ```js,expect_diagnostic | ||
/// // Attempt to import from `foo.js` from outside its `sub` module. | ||
/// import { fooPackageVariable } from "./sub/foo.js"; | ||
/// | ||
/// // Attempt to import from `bar.ts` from outside its `aunt` module. | ||
/// import { barPackageVariable } from "../aunt/bar.ts"; | ||
/// | ||
/// // Assumed to resolve to a JS/TS file. | ||
/// import { fooPackageVariable } from "./sub/foo"; | ||
/// | ||
/// // If the `sub/foo` module is inaccessible, so is its index file. | ||
/// import { fooPackageVariable } from "./sub/foo/index.js"; | ||
/// ``` | ||
/// | ||
/// ### Valid | ||
/// | ||
/// ```js | ||
/// // Imports within the same module are always allowed. | ||
/// import { fooPackageVariable } from "./foo.js"; | ||
/// | ||
/// // Resources (anything other than JS/TS files) are exempt. | ||
/// import { barResource } from "../aunt/bar.png"; | ||
/// | ||
/// // A parent index file is accessible like other modules. | ||
/// import { internal } from "../../index.js"; | ||
/// | ||
/// // If the `sub` module is accessible, so is its index file. | ||
/// import { subPackageVariable } from "./sub/index.js"; | ||
/// | ||
/// // Library imports are exempt. | ||
/// import useAsync from "react-use/lib/useAsync"; | ||
/// ``` | ||
/// | ||
pub(crate) UseImportRestrictions { | ||
version: "next", | ||
name: "useImportRestrictions", | ||
recommended: false, | ||
} | ||
} | ||
|
||
impl Rule for UseImportRestrictions { | ||
type Query = Ast<JsModuleSource>; | ||
type State = ImportRestrictionsState; | ||
type Signals = Option<Self::State>; | ||
type Options = (); | ||
|
||
fn run(ctx: &RuleContext<Self>) -> Self::Signals { | ||
let binding = ctx.query(); | ||
let Ok(path) = binding.inner_string_text() else { | ||
return None; | ||
}; | ||
|
||
get_restricted_import(&path) | ||
} | ||
|
||
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { | ||
let ImportRestrictionsState { path, suggestion } = state; | ||
|
||
let diagnostic = RuleDiagnostic::new( | ||
rule_category!(), | ||
ctx.query().range(), | ||
markup! { | ||
"Importing package private symbols is prohibited from outside the module directory." | ||
}, | ||
) | ||
.note(markup! { | ||
"Please import from "<Emphasis>{suggestion}</Emphasis>" instead " | ||
"(you may need to re-export the symbol(s) from "<Emphasis>{path}</Emphasis>")." | ||
}); | ||
|
||
Some(diagnostic) | ||
} | ||
} | ||
|
||
pub(crate) struct ImportRestrictionsState { | ||
/// The path that is being restricted. | ||
path: String, | ||
|
||
/// Suggestion from which to import instead. | ||
suggestion: String, | ||
} | ||
|
||
fn get_restricted_import(module_path: &SyntaxTokenText) -> Option<ImportRestrictionsState> { | ||
if !module_path.starts_with('.') { | ||
return None; | ||
} | ||
|
||
let mut path_parts: Vec<_> = module_path.text().split('/').collect(); | ||
let mut index_filename = None; | ||
|
||
if let Some(extension) = get_extension(&path_parts) { | ||
if !SOURCE_EXTENSIONS.contains(&extension) { | ||
return None; // Resource files are exempt. | ||
} | ||
|
||
if let Some(basename) = get_basename(&path_parts) { | ||
if INDEX_BASENAMES.contains(&basename) { | ||
// We pop the index file because it shouldn't count as a path, | ||
// component, but we store the file name so we can add it to | ||
// both the reported path and the suggestion. | ||
index_filename = path_parts.last().cloned(); | ||
path_parts.pop(); | ||
} | ||
} | ||
} | ||
|
||
let is_restricted = path_parts | ||
.iter() | ||
.filter(|&&part| part != "." && part != "..") | ||
.count() | ||
> 1; | ||
if !is_restricted { | ||
return None; | ||
} | ||
|
||
let mut suggestion_parts = path_parts[..path_parts.len() - 1].to_vec(); | ||
|
||
// Push the index file if it exists. This makes sure the reported path | ||
// matches the import path exactly. | ||
if let Some(index_filename) = index_filename { | ||
path_parts.push(index_filename); | ||
|
||
// Assumes the user probably wants to use an index file that has the | ||
// same name as the original. | ||
suggestion_parts.push(index_filename); | ||
} | ||
|
||
Some(ImportRestrictionsState { | ||
path: path_parts.join("/"), | ||
suggestion: suggestion_parts.join("/"), | ||
}) | ||
} | ||
|
||
fn get_basename<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> { | ||
path_parts.last().map(|&part| match part.find('.') { | ||
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => &part[..dot_index], | ||
_ => part, | ||
}) | ||
} | ||
|
||
fn get_extension<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> { | ||
path_parts.last().and_then(|part| match part.find('.') { | ||
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => { | ||
Some(&part[dot_index + 1..]) | ||
} | ||
_ => None, | ||
}) | ||
} |
11 changes: 11 additions & 0 deletions
11
...rome_js_analyze/tests/specs/nursery/useImportRestrictions/invalidPackagePrivateImports.js
This file contains 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,11 @@ | ||
// Attempt to import from `foo.js` from outside its `sub` module. | ||
import { fooPackageVariable } from "./sub/foo.js"; | ||
|
||
// Attempt to import from `bar.ts` from outside its `aunt` module. | ||
import { barPackageVariable } from "../aunt/bar.ts"; | ||
|
||
// Assumed to resolve to a JS/TS file. | ||
import { fooPackageVariable } from "./sub/foo"; | ||
|
||
// If the `sub/foo` module is inaccessible, so is its index file. | ||
import { fooPackageVariable } from "./sub/foo/index.js"; |
85 changes: 85 additions & 0 deletions
85
...js_analyze/tests/specs/nursery/useImportRestrictions/invalidPackagePrivateImports.js.snap
This file contains 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,85 @@ | ||
--- | ||
source: crates/rome_js_analyze/tests/spec_tests.rs | ||
expression: invalidPackagePrivateImports.js | ||
--- | ||
# Input | ||
```js | ||
// Attempt to import from `foo.js` from outside its `sub` module. | ||
import { fooPackageVariable } from "./sub/foo.js"; | ||
|
||
// Attempt to import from `bar.ts` from outside its `aunt` module. | ||
import { barPackageVariable } from "../aunt/bar.ts"; | ||
|
||
// Assumed to resolve to a JS/TS file. | ||
import { fooPackageVariable } from "./sub/foo"; | ||
|
||
// If the `sub/foo` module is inaccessible, so is its index file. | ||
import { fooPackageVariable } from "./sub/foo/index.js"; | ||
|
||
``` | ||
|
||
# Diagnostics | ||
``` | ||
invalidPackagePrivateImports.js:2:36 lint/nursery/useImportRestrictions ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ | ||
! Importing package private symbols is prohibited from outside the module directory. | ||
1 │ // Attempt to import from `foo.js` from outside its `sub` module. | ||
> 2 │ import { fooPackageVariable } from "./sub/foo.js"; | ||
│ ^^^^^^^^^^^^^^ | ||
3 │ | ||
4 │ // Attempt to import from `bar.ts` from outside its `aunt` module. | ||
i Please import from ./sub instead (you may need to re-export the symbol(s) from ./sub/foo.js). | ||
``` | ||
|
||
``` | ||
invalidPackagePrivateImports.js:5:36 lint/nursery/useImportRestrictions ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ | ||
! Importing package private symbols is prohibited from outside the module directory. | ||
4 │ // Attempt to import from `bar.ts` from outside its `aunt` module. | ||
> 5 │ import { barPackageVariable } from "../aunt/bar.ts"; | ||
│ ^^^^^^^^^^^^^^^^ | ||
6 │ | ||
7 │ // Assumed to resolve to a JS/TS file. | ||
i Please import from ../aunt instead (you may need to re-export the symbol(s) from ../aunt/bar.ts). | ||
``` | ||
|
||
``` | ||
invalidPackagePrivateImports.js:8:36 lint/nursery/useImportRestrictions ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ | ||
! Importing package private symbols is prohibited from outside the module directory. | ||
7 │ // Assumed to resolve to a JS/TS file. | ||
> 8 │ import { fooPackageVariable } from "./sub/foo"; | ||
│ ^^^^^^^^^^^ | ||
9 │ | ||
10 │ // If the `sub/foo` module is inaccessible, so is its index file. | ||
i Please import from ./sub instead (you may need to re-export the symbol(s) from ./sub/foo). | ||
``` | ||
|
||
``` | ||
invalidPackagePrivateImports.js:11:36 lint/nursery/useImportRestrictions ━━━━━━━━━━━━━━━━━━━━━━━━━━━ | ||
! Importing package private symbols is prohibited from outside the module directory. | ||
10 │ // If the `sub/foo` module is inaccessible, so is its index file. | ||
> 11 │ import { fooPackageVariable } from "./sub/foo/index.js"; | ||
│ ^^^^^^^^^^^^^^^^^^^^ | ||
12 │ | ||
i Please import from ./sub/index.js instead (you may need to re-export the symbol(s) from ./sub/foo/index.js). | ||
``` | ||
|
||
|
22 changes: 22 additions & 0 deletions
22
...s/rome_js_analyze/tests/specs/nursery/useImportRestrictions/validPackagePrivateImports.js
This file contains 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,22 @@ | ||
/* should not generate diagnostics */ | ||
|
||
// Imports within the same module are always allowed. | ||
import { fooPackageVariable } from "./foo.js"; | ||
|
||
// Resources (anything other than JS/TS files) are exempt. | ||
import { barResource } from "../aunt/bar.png"; | ||
|
||
// A parent index file is accessible like other modules. | ||
import { internal } from "../../index.js"; | ||
|
||
// If the `sub` module is accessible, so is its index file. | ||
import { subPackageVariable } from "./sub/index.js"; | ||
|
||
// Library imports are exempt. | ||
import useAsync from "react-use/lib/useAsync"; | ||
|
||
// Including library imports with an extension. | ||
import map from "lodash/map.js"; | ||
|
||
// Scoped packages work too. | ||
import netlify from "@astrojs/netlify/functions.js"; |
Oops, something went wrong.