Skip to content
This repository has been archived by the owner on Aug 31, 2023. It is now read-only.

Commit

Permalink
feat(rome_js_analyze): new lint rule: useImportRestrictions (#4700)
Browse files Browse the repository at this point in the history
  • Loading branch information
arendjr authored Jul 21, 2023
1 parent a65c626 commit d496da0
Show file tree
Hide file tree
Showing 16 changed files with 517 additions and 56 deletions.
39 changes: 0 additions & 39 deletions crates/rome_analyze/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,45 +343,6 @@ This allows the rule to be configured inside `rome.json` file like:
}
```

In this specific case, we don't want the configuration to replace all the standard React hooks configuration,
so to have more control on the deserialization of options, we can implement the trait `DeserializableRuleOptions`.
In the example below we also deserialize to a struct with a more user-friendly schema.
This code run only once when the analyzer is first called.
```rust,ignore
impl DeserializableRuleOptions for ReactExtensiveDependenciesOptions {
fn try_from(value: serde_json::Value) -> Result<Self, serde_json::Error> {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Options {
#[serde(default)]
hooks: Vec<(String, usize, usize)>,
#[serde(default)]
stables: HashSet<StableReactHookConfiguration>,
}
let options: Options = serde_json::from_value(value)?;
let mut default = ReactExtensiveDependenciesOptions::default();
for (k, closure_index, dependencies_index) in options.hooks.into_iter() {
default.hooks_config.insert(
k,
ReactHookConfiguration {
closure_index,
dependencies_index,
},
);
}
default.stable_config.extend(options.stables.into_iter());
Ok(default)
}
}
```
A rule can retrieve its option with:

```rust,ignore
Expand Down
1 change: 1 addition & 0 deletions crates/rome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ define_categories! {
"lint/nursery/useGroupedTypeImport": "https://docs.rome.tools/lint/rules/useGroupedTypeImport",
"lint/nursery/useHeadingContent": "https://docs.rome.tools/lint/rules/useHeadingContent",
"lint/nursery/useHookAtTopLevel": "https://docs.rome.tools/lint/rules/useHookAtTopLevel",
"lint/nursery/useImportRestrictions": "https://docs.rome.tools/lint/rules/useImportRestrictions",
"lint/nursery/useIsArray": "https://docs.rome.tools/lint/rules/useIsArray",
"lint/nursery/useIsNan": "https://docs.rome.tools/lint/rules/useIsNan",
"lint/nursery/useLiteralEnumMembers": "https://docs.rome.tools/lint/rules/useLiteralEnumMembers",
Expand Down
2 changes: 2 additions & 0 deletions crates/rome_js_analyze/src/analyzers/nursery.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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,
})
}
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";
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).
```


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";
Loading

0 comments on commit d496da0

Please sign in to comment.