This repository was archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 653
feat(rome_js_analyze): new lint rule: useImportRestrictions
#4700
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
eec5c57
New lint rule: useImportRestrictions
arendjr c31d42d
Merge remote-tracking branch 'upstream/main'
arendjr b0469f9
Preserve index filenames in reported paths and suggestions
arendjr 20f3552
Force forward slashes on Windows
arendjr cdb81f7
Merge remote-tracking branch 'upstream/main'
arendjr f60d42d
PR feedback
arendjr 241158d
PR feedback
arendjr ba73304
Merge branch 'main' of github.com:arendjr/rome-tools
arendjr 4b62c7b
PR feedback
arendjr 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
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
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
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 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,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"]; | ||
ematipico marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we consider There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think it makes sense to be honest, since you can't |
||
|
||
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 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,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"; |
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.
Uh oh!
There was an error while loading. Please reload this page.