Dataset Viewer
Auto-converted to Parquet Duplicate
repo
string
pull_number
int64
instance_id
string
issue_numbers
sequence
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
string
version
string
updated_at
string
environment_setup_commit
string
FAIL_TO_PASS
sequence
PASS_TO_PASS
sequence
FAIL_TO_FAIL
sequence
PASS_TO_FAIL
sequence
source_dir
string
biomejs/biome
2,324
biomejs__biome-2324
[ "2303" ]
75af8016b50476ae32193ec87c475e182925e9e0
diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -273,6 +273,8 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b - Implement [#2043](https://github.com/biomejs/biome/issues/2043): The React rule [`useExhaustiveDependencies`](https://biomejs.dev/linter/rules/use-exhaustive-dependencies/) is now also compatible with Preact hooks imported from `preact/hooks` or `preact/compat`. Contributed by @arendjr +- Add rule [noFlatMapIdentity](https://biomejs.dev/linter/rules/no-flat-map-identity) to disallow unnecessary callback use on `flatMap`. Contributed by @isnakode + - Add rule [noConstantMathMinMaxClamp](https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp), which disallows using `Math.min` and `Math.max` to clamp a value where the result itself is constant. Contributed by @mgomulak #### Enhancements diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2679,7 +2682,7 @@ impl DeserializableValidator for Nursery { } impl Nursery { const GROUP_NAME: &'static str = "nursery"; - pub(crate) const GROUP_RULES: [&'static str; 26] = [ + pub(crate) const GROUP_RULES: [&'static str; 27] = [ "noBarrelFile", "noColorInvalidHex", "noConsole", diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2692,6 +2695,7 @@ impl Nursery { "noEvolvingAny", "noExcessiveNestedTestSuites", "noExportsInTest", + "noFlatMapIdentity", "noFocusedTests", "noMisplacedAssertion", "noNamespaceImport", diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2707,7 +2711,7 @@ impl Nursery { "useNodeAssertStrict", "useSortedClasses", ]; - const RECOMMENDED_RULES: [&'static str; 11] = [ + const RECOMMENDED_RULES: [&'static str; 12] = [ "noDoneCallback", "noDuplicateElseIf", "noDuplicateFontNames", diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2716,11 +2720,12 @@ impl Nursery { "noEvolvingAny", "noExcessiveNestedTestSuites", "noExportsInTest", + "noFlatMapIdentity", "noFocusedTests", "noSuspiciousSemicolonInJsx", "noUselessTernary", ]; - const RECOMMENDED_RULES_AS_FILTERS: [RuleFilter<'static>; 11] = [ + const RECOMMENDED_RULES_AS_FILTERS: [RuleFilter<'static>; 12] = [ RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[4]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[5]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[6]), diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2730,10 +2735,11 @@ impl Nursery { RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[10]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12]), - RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19]), - RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21]), + RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[13]), + RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20]), + RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[22]), ]; - const ALL_RULES_AS_FILTERS: [RuleFilter<'static>; 26] = [ + const ALL_RULES_AS_FILTERS: [RuleFilter<'static>; 27] = [ RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[0]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[1]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[2]), diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2760,6 +2766,7 @@ impl Nursery { RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[23]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[24]), RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[25]), + RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[26]), ]; #[doc = r" Retrieves the recommended rules"] pub(crate) fn is_recommended_true(&self) -> bool { diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -3050,10 +3067,10 @@ impl Nursery { pub(crate) fn is_recommended_rule(rule_name: &str) -> bool { Self::RECOMMENDED_RULES.contains(&rule_name) } - pub(crate) fn recommended_rules_as_filters() -> [RuleFilter<'static>; 11] { + pub(crate) fn recommended_rules_as_filters() -> [RuleFilter<'static>; 12] { Self::RECOMMENDED_RULES_AS_FILTERS } - pub(crate) fn all_rules_as_filters() -> [RuleFilter<'static>; 26] { + pub(crate) fn all_rules_as_filters() -> [RuleFilter<'static>; 27] { Self::ALL_RULES_AS_FILTERS } #[doc = r" Select preset rules"] diff --git /dev/null b/crates/biome_js_analyze/src/lint/nursery/no_flat_map_identity.rs new file mode 100644 --- /dev/null +++ b/crates/biome_js_analyze/src/lint/nursery/no_flat_map_identity.rs @@ -0,0 +1,182 @@ +use biome_analyze::{ + context::RuleContext, declare_rule, ActionCategory, Ast, FixKind, Rule, RuleDiagnostic, + RuleSource, +}; +use biome_console::markup; +use biome_diagnostics::Applicability; +use biome_js_factory::make::{ident, js_call_argument_list, js_call_arguments, js_name, token}; +use biome_js_syntax::{ + AnyJsExpression, AnyJsFunctionBody, AnyJsMemberExpression, AnyJsName, AnyJsStatement, + JsCallExpression, JsSyntaxKind, +}; +use biome_rowan::{AstNode, AstSeparatedList, BatchMutationExt}; + +use crate::JsRuleAction; + +declare_rule! { + /// Disallow to use unnecessary callback on `flatMap`. + /// + /// To achieve the same result (flattening an array) more concisely and efficiently, you should use `flat` instead. + /// + /// ## Examples + /// + /// ### Invalid + /// + /// ```js,expect_diagnostic + /// array.flatMap((arr) => arr); + /// ``` + /// + /// ```js,expect_diagnostic + /// array.flatMap((arr) => {return arr}); + /// ``` + /// + /// ### Valid + /// + /// ```js + /// array.flatMap((arr) => arr * 2); + /// ``` + /// + pub NoFlatMapIdentity { + version: "next", + name: "noFlatMapIdentity", + recommended: true, + sources: &[RuleSource::Clippy("flat_map_identity")], + fix_kind: FixKind::Safe, + } +} + +impl Rule for NoFlatMapIdentity { + type Query = Ast<JsCallExpression>; + type State = (); + type Signals = Option<Self::State>; + type Options = (); + + fn run(ctx: &RuleContext<Self>) -> Self::Signals { + let flat_map_call = ctx.query(); + + let flat_map_expression = + AnyJsMemberExpression::cast_ref(flat_map_call.callee().ok()?.syntax())?; + + if flat_map_expression.object().is_err() { + return None; + } + + if flat_map_expression.member_name()?.text() != "flatMap" { + return None; + } + + let arguments = flat_map_call.arguments().ok()?.args(); + + if let Some(arg) = arguments.first() { + let arg = arg.ok()?; + let (function_param, function_body) = match arg.as_any_js_expression()? { + AnyJsExpression::JsArrowFunctionExpression(arg) => { + let parameter: String = match arg.parameters().ok()? { + biome_js_syntax::AnyJsArrowFunctionParameters::AnyJsBinding(p) => { + p.text().trim_matches(&['(', ')']).to_owned() + } + biome_js_syntax::AnyJsArrowFunctionParameters::JsParameters(p) => { + if p.items().len() == 1 { + if let Some(param) = p.items().into_iter().next() { + param.ok()?.text() + } else { + return None; + } + } else { + return None; + } + } + }; + + let function_body: String = match arg.body().ok()? { + AnyJsFunctionBody::AnyJsExpression(body) => body.omit_parentheses().text(), + AnyJsFunctionBody::JsFunctionBody(body) => { + let mut statement = body.statements().into_iter(); + match statement.next() { + Some(AnyJsStatement::JsReturnStatement(body)) => { + let Some(AnyJsExpression::JsIdentifierExpression( + return_statement, + )) = body.argument() + else { + return None; + }; + return_statement.name().ok()?.text() + } + _ => return None, + } + } + }; + (parameter, function_body) + } + AnyJsExpression::JsFunctionExpression(arg) => { + let function_parameter = arg.parameters().ok()?.text(); + let function_parameter = + function_parameter.trim_matches(&['(', ')']).to_owned(); + + let mut statement = arg.body().ok()?.statements().into_iter(); + if let Some(AnyJsStatement::JsReturnStatement(body)) = statement.next() { + let Some(AnyJsExpression::JsIdentifierExpression(return_statement)) = + body.argument() + else { + return None; + }; + (function_parameter, return_statement.name().ok()?.text()) + } else { + return None; + } + } + _ => return None, + }; + + if function_param == function_body { + return Some(()); + } + } + None + } + + fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { + let node = ctx.query(); + Some( + RuleDiagnostic::new( + rule_category!(), + node.range(), + markup! { + "Avoid unnecessary callback in "<Emphasis>"flatMap"</Emphasis>" call." + }, + ) + .note(markup! {"You can just use "<Emphasis>"flat"</Emphasis>" to flatten the array."}), + ) + } + fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> { + let node = ctx.query(); + let mut mutation = ctx.root().begin(); + + let empty_argument = js_call_arguments( + token(JsSyntaxKind::L_PAREN), + js_call_argument_list(vec![], vec![]), + token(JsSyntaxKind::R_PAREN), + ); + + let Ok(AnyJsExpression::JsStaticMemberExpression(flat_expression)) = node.callee() else { + return None; + }; + + let flat_member = js_name(ident("flat")); + let flat_call = flat_expression.with_member(AnyJsName::JsName(flat_member)); + + mutation.replace_node( + node.clone(), + node.clone() + .with_arguments(empty_argument) + .with_callee(AnyJsExpression::JsStaticMemberExpression(flat_call)), + ); + + Some(JsRuleAction { + mutation, + message: markup! {"Replace unnecessary "<Emphasis>"flatMap"</Emphasis>" call to "<Emphasis>"flat"</Emphasis>" instead."}.to_owned(), + category: ActionCategory::QuickFix, + applicability: Applicability::Always, + }) + } +} diff --git a/packages/@biomejs/backend-jsonrpc/src/workspace.ts b/packages/@biomejs/backend-jsonrpc/src/workspace.ts --- a/packages/@biomejs/backend-jsonrpc/src/workspace.ts +++ b/packages/@biomejs/backend-jsonrpc/src/workspace.ts @@ -1927,6 +1931,7 @@ export type Category = | "lint/nursery/noEvolvingAny" | "lint/nursery/noExcessiveNestedTestSuites" | "lint/nursery/noExportsInTest" + | "lint/nursery/noFlatMapIdentity" | "lint/nursery/noFocusedTests" | "lint/nursery/noDuplicateFontNames" | "lint/nursery/noMisplacedAssertion" diff --git a/website/src/components/generated/NumberOfRules.astro b/website/src/components/generated/NumberOfRules.astro --- a/website/src/components/generated/NumberOfRules.astro +++ b/website/src/components/generated/NumberOfRules.astro @@ -1,2 +1,2 @@ <!-- this file is auto generated, use `cargo lintdoc` to update it --> - <p>Biome's linter has a total of <strong><a href='/linter/rules'>215 rules</a></strong><p> \ No newline at end of file + <p>Biome's linter has a total of <strong><a href='/linter/rules'>216 rules</a></strong><p> \ No newline at end of file diff --git a/website/src/content/docs/internals/changelog.md b/website/src/content/docs/internals/changelog.md --- a/website/src/content/docs/internals/changelog.md +++ b/website/src/content/docs/internals/changelog.md @@ -279,6 +279,8 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b - Implement [#2043](https://github.com/biomejs/biome/issues/2043): The React rule [`useExhaustiveDependencies`](https://biomejs.dev/linter/rules/use-exhaustive-dependencies/) is now also compatible with Preact hooks imported from `preact/hooks` or `preact/compat`. Contributed by @arendjr +- Add rule [noFlatMapIdentity](https://biomejs.dev/linter/rules/no-flat-map-identity) to disallow unnecessary callback use on `flatMap`. Contributed by @isnakode + - Add rule [noConstantMathMinMaxClamp](https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp), which disallows using `Math.min` and `Math.max` to clamp a value where the result itself is constant. Contributed by @mgomulak #### Enhancements diff --git a/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md b/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md --- a/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md +++ b/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md @@ -24,7 +24,7 @@ Disallow the use of `Math.min` and `Math.max` to clamp a value where the result Math.min(0, Math.max(100, x)); ``` -<pre class="language-text"><code class="language-text">nursery/noConstantMathMinMaxClamp.js:1:1 <a href="https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp">lint/nursery/noConstantMathMinMaxClamp</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” +<pre class="language-text"><code class="language-text">nursery/noConstantMathMinMaxClamp.jsx:1:1 <a href="https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp">lint/nursery/noConstantMathMinMaxClamp</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” <strong><span style="color: Orange;"> </span></strong><strong><span style="color: Orange;">โš </span></strong> <span style="color: Orange;">This </span><span style="color: Orange;"><strong>Math.min/Math.max</strong></span><span style="color: Orange;"> combination leads to a constant result.</span> diff --git a/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md b/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md --- a/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md +++ b/website/src/content/docs/linter/rules/no-constant-math-min-max-clamp.md @@ -50,7 +50,7 @@ Math.min(0, Math.max(100, x)); Math.max(100, Math.min(0, x)); ``` -<pre class="language-text"><code class="language-text">nursery/noConstantMathMinMaxClamp.js:1:1 <a href="https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp">lint/nursery/noConstantMathMinMaxClamp</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” +<pre class="language-text"><code class="language-text">nursery/noConstantMathMinMaxClamp.jsx:1:1 <a href="https://biomejs.dev/linter/rules/no-constant-math-min-max-clamp">lint/nursery/noConstantMathMinMaxClamp</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” <strong><span style="color: Orange;"> </span></strong><strong><span style="color: Orange;">โš </span></strong> <span style="color: Orange;">This </span><span style="color: Orange;"><strong>Math.min/Math.max</strong></span><span style="color: Orange;"> combination leads to a constant result.</span> diff --git /dev/null b/website/src/content/docs/linter/rules/no-flat-map-identity.md new file mode 100644 --- /dev/null +++ b/website/src/content/docs/linter/rules/no-flat-map-identity.md @@ -0,0 +1,78 @@ +--- +title: noFlatMapIdentity (not released) +--- + +**Diagnostic Category: `lint/nursery/noFlatMapIdentity`** + +:::danger +This rule hasn't been released yet. +::: + +:::caution +This rule is part of the [nursery](/linter/rules/#nursery) group. +::: + +Source: <a href="https://rust-lang.github.io/rust-clippy/master/#/flat_map_identity" target="_blank"><code>flat_map_identity</code></a> + +Disallow to use unnecessary callback on `flatMap`. + +To achieve the same result (flattening an array) more concisely and efficiently, you should use `flat` instead. + +## Examples + +### Invalid + +```jsx +array.flatMap((arr) => arr); +``` + +<pre class="language-text"><code class="language-text">nursery/noFlatMapIdentity.jsx:1:1 <a href="https://biomejs.dev/linter/rules/no-flat-map-identity">lint/nursery/noFlatMapIdentity</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + +<strong><span style="color: Tomato;"> </span></strong><strong><span style="color: Tomato;">โœ–</span></strong> <span style="color: Tomato;">Avoid unnecessary callback in </span><span style="color: Tomato;"><strong>flatMap</strong></span><span style="color: Tomato;"> call.</span> + +<strong><span style="color: Tomato;"> </span></strong><strong><span style="color: Tomato;">&gt;</span></strong> <strong>1 โ”‚ </strong>array.flatMap((arr) =&gt; arr); + <strong> โ”‚ </strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong> + <strong>2 โ”‚ </strong> + +<strong><span style="color: lightgreen;"> </span></strong><strong><span style="color: lightgreen;">โ„น</span></strong> <span style="color: lightgreen;">You can just use </span><span style="color: lightgreen;"><strong>flat</strong></span><span style="color: lightgreen;"> to flatten the array.</span> + +<strong><span style="color: lightgreen;"> </span></strong><strong><span style="color: lightgreen;">โ„น</span></strong> <span style="color: lightgreen;">Safe fix</span><span style="color: lightgreen;">: </span><span style="color: lightgreen;">Replace unnecessary </span><span style="color: lightgreen;"><strong>flatMap</strong></span><span style="color: lightgreen;"> call to </span><span style="color: lightgreen;"><strong>flat</strong></span><span style="color: lightgreen;"> instead.</span> + + <strong>1</strong> <strong> โ”‚ </strong><span style="color: Tomato;">-</span> <span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>y</strong></span><span style="color: Tomato;"><strong>.</strong></span><span style="color: Tomato;"><strong>f</strong></span><span style="color: Tomato;"><strong>l</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>t</strong></span><span style="color: Tomato;"><strong>M</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>p</strong></span><span style="color: Tomato;"><strong>(</strong></span><span style="color: Tomato;">(</span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>)</strong></span><span style="color: Tomato;"><span style="opacity: 0.8;"><strong>ยท</strong></span></span><span style="color: Tomato;"><strong>=</strong></span><span style="color: Tomato;"><strong>&gt;</strong></span><span style="color: Tomato;"><span style="opacity: 0.8;"><strong>ยท</strong></span></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;">)</span><span style="color: Tomato;">;</span> + <strong>1</strong><strong> โ”‚ </strong><span style="color: MediumSeaGreen;">+</span> <span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>r</strong></span><span style="color: MediumSeaGreen;"><strong>r</strong></span><span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>y</strong></span><span style="color: MediumSeaGreen;"><strong>.</strong></span><span style="color: MediumSeaGreen;"><strong>f</strong></span><span style="color: MediumSeaGreen;"><strong>l</strong></span><span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>t</strong></span><span style="color: MediumSeaGreen;">(</span><span style="color: MediumSeaGreen;">)</span><span style="color: MediumSeaGreen;">;</span> + <strong>2</strong> <strong>2</strong><strong> โ”‚ </strong> + +</code></pre> + +```jsx +array.flatMap((arr) => {return arr}); +``` + +<pre class="language-text"><code class="language-text">nursery/noFlatMapIdentity.jsx:1:1 <a href="https://biomejs.dev/linter/rules/no-flat-map-identity">lint/nursery/noFlatMapIdentity</a> <span style="color: #000; background-color: #ddd;"> FIXABLE </span> โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + +<strong><span style="color: Tomato;"> </span></strong><strong><span style="color: Tomato;">โœ–</span></strong> <span style="color: Tomato;">Avoid unnecessary callback in </span><span style="color: Tomato;"><strong>flatMap</strong></span><span style="color: Tomato;"> call.</span> + +<strong><span style="color: Tomato;"> </span></strong><strong><span style="color: Tomato;">&gt;</span></strong> <strong>1 โ”‚ </strong>array.flatMap((arr) =&gt; {return arr}); + <strong> โ”‚ </strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong><strong><span style="color: Tomato;">^</span></strong> + <strong>2 โ”‚ </strong> + +<strong><span style="color: lightgreen;"> </span></strong><strong><span style="color: lightgreen;">โ„น</span></strong> <span style="color: lightgreen;">You can just use </span><span style="color: lightgreen;"><strong>flat</strong></span><span style="color: lightgreen;"> to flatten the array.</span> + +<strong><span style="color: lightgreen;"> </span></strong><strong><span style="color: lightgreen;">โ„น</span></strong> <span style="color: lightgreen;">Safe fix</span><span style="color: lightgreen;">: </span><span style="color: lightgreen;">Replace unnecessary </span><span style="color: lightgreen;"><strong>flatMap</strong></span><span style="color: lightgreen;"> call to </span><span style="color: lightgreen;"><strong>flat</strong></span><span style="color: lightgreen;"> instead.</span> + + <strong>1</strong> <strong> โ”‚ </strong><span style="color: Tomato;">-</span> <span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>y</strong></span><span style="color: Tomato;"><strong>.</strong></span><span style="color: Tomato;"><strong>f</strong></span><span style="color: Tomato;"><strong>l</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>t</strong></span><span style="color: Tomato;"><strong>M</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>p</strong></span><span style="color: Tomato;">(</span><span style="color: Tomato;"><strong>(</strong></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>)</strong></span><span style="color: Tomato;"><span style="opacity: 0.8;"><strong>ยท</strong></span></span><span style="color: Tomato;"><strong>=</strong></span><span style="color: Tomato;"><strong>&gt;</strong></span><span style="color: Tomato;"><span style="opacity: 0.8;"><strong>ยท</strong></span></span><span style="color: Tomato;"><strong>{</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>e</strong></span><span style="color: Tomato;"><strong>t</strong></span><span style="color: Tomato;"><strong>u</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>n</strong></span><span style="color: Tomato;"><span style="opacity: 0.8;"><strong>ยท</strong></span></span><span style="color: Tomato;"><strong>a</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>r</strong></span><span style="color: Tomato;"><strong>}</strong></span><span style="color: Tomato;">)</span><span style="color: Tomato;">;</span> + <strong>1</strong><strong> โ”‚ </strong><span style="color: MediumSeaGreen;">+</span> <span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>r</strong></span><span style="color: MediumSeaGreen;"><strong>r</strong></span><span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>y</strong></span><span style="color: MediumSeaGreen;"><strong>.</strong></span><span style="color: MediumSeaGreen;"><strong>f</strong></span><span style="color: MediumSeaGreen;"><strong>l</strong></span><span style="color: MediumSeaGreen;"><strong>a</strong></span><span style="color: MediumSeaGreen;"><strong>t</strong></span><span style="color: MediumSeaGreen;">(</span><span style="color: MediumSeaGreen;">)</span><span style="color: MediumSeaGreen;">;</span> + <strong>2</strong> <strong>2</strong><strong> โ”‚ </strong> + +</code></pre> + +### Valid + +```jsx +array.flatMap((arr) => arr * 2); +``` + +## Related links + +- [Disable a rule](/linter/#disable-a-lint-rule) +- [Rule options](/linter/#rule-options)
diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2620,6 +2620,9 @@ pub struct Nursery { #[doc = "Disallow using export or module.exports in files containing tests"] #[serde(skip_serializing_if = "Option::is_none")] pub no_exports_in_test: Option<RuleConfiguration<NoExportsInTest>>, + #[doc = "Disallow to use unnecessary callback on flatMap."] + #[serde(skip_serializing_if = "Option::is_none")] + pub no_flat_map_identity: Option<RuleConfiguration<NoFlatMapIdentity>>, #[doc = "Disallow focused tests."] #[serde(skip_serializing_if = "Option::is_none")] pub no_focused_tests: Option<RuleConfiguration<NoFocusedTests>>, diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2836,76 +2843,81 @@ impl Nursery { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11])); } } - if let Some(rule) = self.no_focused_tests.as_ref() { + if let Some(rule) = self.no_flat_map_identity.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12])); } } - if let Some(rule) = self.no_misplaced_assertion.as_ref() { + if let Some(rule) = self.no_focused_tests.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[13])); } } - if let Some(rule) = self.no_namespace_import.as_ref() { + if let Some(rule) = self.no_misplaced_assertion.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[14])); } } - if let Some(rule) = self.no_nodejs_modules.as_ref() { + if let Some(rule) = self.no_namespace_import.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[15])); } } - if let Some(rule) = self.no_re_export_all.as_ref() { + if let Some(rule) = self.no_nodejs_modules.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[16])); } } - if let Some(rule) = self.no_restricted_imports.as_ref() { + if let Some(rule) = self.no_re_export_all.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[17])); } } - if let Some(rule) = self.no_skipped_tests.as_ref() { + if let Some(rule) = self.no_restricted_imports.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[18])); } } - if let Some(rule) = self.no_suspicious_semicolon_in_jsx.as_ref() { + if let Some(rule) = self.no_skipped_tests.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19])); } } - if let Some(rule) = self.no_undeclared_dependencies.as_ref() { + if let Some(rule) = self.no_suspicious_semicolon_in_jsx.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20])); } } - if let Some(rule) = self.no_useless_ternary.as_ref() { + if let Some(rule) = self.no_undeclared_dependencies.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21])); } } - if let Some(rule) = self.use_import_restrictions.as_ref() { + if let Some(rule) = self.no_useless_ternary.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[22])); } } - if let Some(rule) = self.use_jsx_key_in_iterable.as_ref() { + if let Some(rule) = self.use_import_restrictions.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[23])); } } - if let Some(rule) = self.use_node_assert_strict.as_ref() { + if let Some(rule) = self.use_jsx_key_in_iterable.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[24])); } } - if let Some(rule) = self.use_sorted_classes.as_ref() { + if let Some(rule) = self.use_node_assert_strict.as_ref() { if rule.is_enabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[25])); } } + if let Some(rule) = self.use_sorted_classes.as_ref() { + if rule.is_enabled() { + index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[26])); + } + } index_set } pub(crate) fn get_disabled_rules(&self) -> IndexSet<RuleFilter> { diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -2970,76 +2982,81 @@ impl Nursery { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[11])); } } - if let Some(rule) = self.no_focused_tests.as_ref() { + if let Some(rule) = self.no_flat_map_identity.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[12])); } } - if let Some(rule) = self.no_misplaced_assertion.as_ref() { + if let Some(rule) = self.no_focused_tests.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[13])); } } - if let Some(rule) = self.no_namespace_import.as_ref() { + if let Some(rule) = self.no_misplaced_assertion.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[14])); } } - if let Some(rule) = self.no_nodejs_modules.as_ref() { + if let Some(rule) = self.no_namespace_import.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[15])); } } - if let Some(rule) = self.no_re_export_all.as_ref() { + if let Some(rule) = self.no_nodejs_modules.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[16])); } } - if let Some(rule) = self.no_restricted_imports.as_ref() { + if let Some(rule) = self.no_re_export_all.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[17])); } } - if let Some(rule) = self.no_skipped_tests.as_ref() { + if let Some(rule) = self.no_restricted_imports.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[18])); } } - if let Some(rule) = self.no_suspicious_semicolon_in_jsx.as_ref() { + if let Some(rule) = self.no_skipped_tests.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[19])); } } - if let Some(rule) = self.no_undeclared_dependencies.as_ref() { + if let Some(rule) = self.no_suspicious_semicolon_in_jsx.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[20])); } } - if let Some(rule) = self.no_useless_ternary.as_ref() { + if let Some(rule) = self.no_undeclared_dependencies.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[21])); } } - if let Some(rule) = self.use_import_restrictions.as_ref() { + if let Some(rule) = self.no_useless_ternary.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[22])); } } - if let Some(rule) = self.use_jsx_key_in_iterable.as_ref() { + if let Some(rule) = self.use_import_restrictions.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[23])); } } - if let Some(rule) = self.use_node_assert_strict.as_ref() { + if let Some(rule) = self.use_jsx_key_in_iterable.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[24])); } } - if let Some(rule) = self.use_sorted_classes.as_ref() { + if let Some(rule) = self.use_node_assert_strict.as_ref() { if rule.is_disabled() { index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[25])); } } + if let Some(rule) = self.use_sorted_classes.as_ref() { + if rule.is_disabled() { + index_set.insert(RuleFilter::Rule(Self::GROUP_NAME, Self::GROUP_RULES[26])); + } + } index_set } #[doc = r" Checks if, given a rule name, matches one of the rules contained in this category"] diff --git a/crates/biome_configuration/src/linter/rules.rs b/crates/biome_configuration/src/linter/rules.rs --- a/crates/biome_configuration/src/linter/rules.rs +++ b/crates/biome_configuration/src/linter/rules.rs @@ -3124,6 +3141,10 @@ impl Nursery { .no_exports_in_test .as_ref() .map(|conf| (conf.level(), conf.get_options())), + "noFlatMapIdentity" => self + .no_flat_map_identity + .as_ref() + .map(|conf| (conf.level(), conf.get_options())), "noFocusedTests" => self .no_focused_tests .as_ref() diff --git a/crates/biome_diagnostics_categories/src/categories.rs b/crates/biome_diagnostics_categories/src/categories.rs --- a/crates/biome_diagnostics_categories/src/categories.rs +++ b/crates/biome_diagnostics_categories/src/categories.rs @@ -119,6 +119,7 @@ define_categories! { "lint/nursery/noEvolvingAny": "https://biomejs.dev/linter/rules/no-evolving-any", "lint/nursery/noExcessiveNestedTestSuites": "https://biomejs.dev/linter/rules/no-excessive-nested-test-suites", "lint/nursery/noExportsInTest": "https://biomejs.dev/linter/rules/no-exports-in-test", + "lint/nursery/noFlatMapIdentity": "https://biomejs.dev/linter/rules/no-flat-map-identity", "lint/nursery/noFocusedTests": "https://biomejs.dev/linter/rules/no-focused-tests", "lint/nursery/noDuplicateFontNames": "https://biomejs.dev/linter/rules/no-font-family-duplicate-names", "lint/nursery/noMisplacedAssertion": "https://biomejs.dev/linter/rules/no-misplaced-assertion", diff --git a/crates/biome_js_analyze/src/lint/nursery.rs b/crates/biome_js_analyze/src/lint/nursery.rs --- a/crates/biome_js_analyze/src/lint/nursery.rs +++ b/crates/biome_js_analyze/src/lint/nursery.rs @@ -11,6 +11,7 @@ pub mod no_duplicate_test_hooks; pub mod no_evolving_any; pub mod no_excessive_nested_test_suites; pub mod no_exports_in_test; +pub mod no_flat_map_identity; pub mod no_focused_tests; pub mod no_misplaced_assertion; pub mod no_namespace_import; diff --git a/crates/biome_js_analyze/src/lint/nursery.rs b/crates/biome_js_analyze/src/lint/nursery.rs --- a/crates/biome_js_analyze/src/lint/nursery.rs +++ b/crates/biome_js_analyze/src/lint/nursery.rs @@ -39,6 +40,7 @@ declare_group! { self :: no_evolving_any :: NoEvolvingAny , self :: no_excessive_nested_test_suites :: NoExcessiveNestedTestSuites , self :: no_exports_in_test :: NoExportsInTest , + self :: no_flat_map_identity :: NoFlatMapIdentity , self :: no_focused_tests :: NoFocusedTests , self :: no_misplaced_assertion :: NoMisplacedAssertion , self :: no_namespace_import :: NoNamespaceImport , diff --git a/crates/biome_js_analyze/src/options.rs b/crates/biome_js_analyze/src/options.rs --- a/crates/biome_js_analyze/src/options.rs +++ b/crates/biome_js_analyze/src/options.rs @@ -90,6 +90,8 @@ pub type NoExtraBooleanCast = <lint::complexity::no_extra_boolean_cast::NoExtraBooleanCast as biome_analyze::Rule>::Options; pub type NoExtraNonNullAssertion = < lint :: suspicious :: no_extra_non_null_assertion :: NoExtraNonNullAssertion as biome_analyze :: Rule > :: Options ; pub type NoFallthroughSwitchClause = < lint :: suspicious :: no_fallthrough_switch_clause :: NoFallthroughSwitchClause as biome_analyze :: Rule > :: Options ; +pub type NoFlatMapIdentity = + <lint::nursery::no_flat_map_identity::NoFlatMapIdentity as biome_analyze::Rule>::Options; pub type NoFocusedTests = <lint::nursery::no_focused_tests::NoFocusedTests as biome_analyze::Rule>::Options; pub type NoForEach = <lint::complexity::no_for_each::NoForEach as biome_analyze::Rule>::Options; diff --git /dev/null b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/invalid.js new file mode 100644 --- /dev/null +++ b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/invalid.js @@ -0,0 +1,11 @@ +array.flatMap(function f(arr) { return arr }); + +array.flatMap(function (arr) { return arr }); + +array.flatMap((arr) => arr) + +array.flatMap((arr) => {return arr}) + +array.flatMap(arr => arr) + +array.flatMap(arr => {return arr}) \ No newline at end of file diff --git /dev/null b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/invalid.js.snap new file mode 100644 --- /dev/null +++ b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/invalid.js.snap @@ -0,0 +1,167 @@ +--- +source: crates/biome_js_analyze/tests/spec_tests.rs +expression: invalid.js +--- +# Input +```jsx +array.flatMap(function f(arr) { return arr }); + +array.flatMap(function (arr) { return arr }); + +array.flatMap((arr) => arr) + +array.flatMap((arr) => {return arr}) + +array.flatMap(arr => arr) + +array.flatMap(arr => {return arr}) +``` + +# Diagnostics +``` +invalid.js:1:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + > 1 โ”‚ array.flatMap(function f(arr) { return arr }); + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 โ”‚ + 3 โ”‚ array.flatMap(function (arr) { return arr }); + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 1 โ”‚ - array.flatMap(functionยทf(arr)ยท{ยทreturnยทarrยท}); + 1 โ”‚ + array.flat(); + 2 2 โ”‚ + 3 3 โ”‚ array.flatMap(function (arr) { return arr }); + + +``` + +``` +invalid.js:3:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + 1 โ”‚ array.flatMap(function f(arr) { return arr }); + 2 โ”‚ + > 3 โ”‚ array.flatMap(function (arr) { return arr }); + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 4 โ”‚ + 5 โ”‚ array.flatMap((arr) => arr) + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 1 1 โ”‚ array.flatMap(function f(arr) { return arr }); + 2 2 โ”‚ + 3 โ”‚ - array.flatMap(functionยท(arr)ยท{ยทreturnยทarrยท}); + 3 โ”‚ + array.flat(); + 4 4 โ”‚ + 5 5 โ”‚ array.flatMap((arr) => arr) + + +``` + +``` +invalid.js:5:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + 3 โ”‚ array.flatMap(function (arr) { return arr }); + 4 โ”‚ + > 5 โ”‚ array.flatMap((arr) => arr) + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 6 โ”‚ + 7 โ”‚ array.flatMap((arr) => {return arr}) + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 3 3 โ”‚ array.flatMap(function (arr) { return arr }); + 4 4 โ”‚ + 5 โ”‚ - array.flatMap((arr)ยท=>ยทarr) + 5 โ”‚ + array.flat() + 6 6 โ”‚ + 7 7 โ”‚ array.flatMap((arr) => {return arr}) + + +``` + +``` +invalid.js:7:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + 5 โ”‚ array.flatMap((arr) => arr) + 6 โ”‚ + > 7 โ”‚ array.flatMap((arr) => {return arr}) + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 8 โ”‚ + 9 โ”‚ array.flatMap(arr => arr) + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 5 5 โ”‚ array.flatMap((arr) => arr) + 6 6 โ”‚ + 7 โ”‚ - array.flatMap((arr)ยท=>ยท{returnยทarr}) + 7 โ”‚ + array.flat() + 8 8 โ”‚ + 9 9 โ”‚ array.flatMap(arr => arr) + + +``` + +``` +invalid.js:9:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + 7 โ”‚ array.flatMap((arr) => {return arr}) + 8 โ”‚ + > 9 โ”‚ array.flatMap(arr => arr) + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^ + 10 โ”‚ + 11 โ”‚ array.flatMap(arr => {return arr}) + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 7 7 โ”‚ array.flatMap((arr) => {return arr}) + 8 8 โ”‚ + 9 โ”‚ - array.flatMap(arrยท=>ยทarr) + 9 โ”‚ + array.flat() + 10 10 โ”‚ + 11 11 โ”‚ array.flatMap(arr => {return arr}) + + +``` + +``` +invalid.js:11:1 lint/nursery/noFlatMapIdentity FIXABLE โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ! Avoid unnecessary callback in flatMap call. + + 9 โ”‚ array.flatMap(arr => arr) + 10 โ”‚ + > 11 โ”‚ array.flatMap(arr => {return arr}) + โ”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + i You can just use flat to flatten the array. + + i Safe fix: Replace unnecessary flatMap call to flat instead. + + 9 9 โ”‚ array.flatMap(arr => arr) + 10 10 โ”‚ + 11 โ”‚ - array.flatMap(arrยท=>ยท{returnยทarr}) + 11 โ”‚ + array.flat() + + +``` diff --git /dev/null b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/valid.js new file mode 100644 --- /dev/null +++ b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/valid.js @@ -0,0 +1,9 @@ +array.flatMap((arr) => arr * 2); + +array.flatMap(arr => arr * 2); + +flatMap((x) => x); + +flatMap(x => x); + +arr.flatMap((x, y) => (x, y)) \ No newline at end of file diff --git /dev/null b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/valid.js.snap new file mode 100644 --- /dev/null +++ b/crates/biome_js_analyze/tests/specs/nursery/noFlatMapIdentity/valid.js.snap @@ -0,0 +1,16 @@ +--- +source: crates/biome_js_analyze/tests/spec_tests.rs +expression: valid.js +--- +# Input +```jsx +array.flatMap((arr) => arr * 2); + +array.flatMap(arr => arr * 2); + +flatMap((x) => x); + +flatMap(x => x); + +arr.flatMap((x, y) => (x, y)) +``` diff --git a/packages/@biomejs/backend-jsonrpc/src/workspace.ts b/packages/@biomejs/backend-jsonrpc/src/workspace.ts --- a/packages/@biomejs/backend-jsonrpc/src/workspace.ts +++ b/packages/@biomejs/backend-jsonrpc/src/workspace.ts @@ -944,6 +944,10 @@ export interface Nursery { * Disallow using export or module.exports in files containing tests */ noExportsInTest?: RuleConfiguration_for_Null; + /** + * Disallow to use unnecessary callback on flatMap. + */ + noFlatMapIdentity?: RuleConfiguration_for_Null; /** * Disallow focused tests. */ diff --git a/packages/@biomejs/biome/configuration_schema.json b/packages/@biomejs/biome/configuration_schema.json --- a/packages/@biomejs/biome/configuration_schema.json +++ b/packages/@biomejs/biome/configuration_schema.json @@ -1484,6 +1484,13 @@ { "type": "null" } ] }, + "noFlatMapIdentity": { + "description": "Disallow to use unnecessary callback on flatMap.", + "anyOf": [ + { "$ref": "#/definitions/RuleConfiguration" }, + { "type": "null" } + ] + }, "noFocusedTests": { "description": "Disallow focused tests.", "anyOf": [ diff --git a/website/src/content/docs/linter/rules/index.mdx b/website/src/content/docs/linter/rules/index.mdx --- a/website/src/content/docs/linter/rules/index.mdx +++ b/website/src/content/docs/linter/rules/index.mdx @@ -263,6 +263,7 @@ Rules that belong to this group <strong>are not subject to semantic version</str | [noEvolvingAny](/linter/rules/no-evolving-any) | Disallow variables from evolving into <code>any</code> type through reassignments. | | | [noExcessiveNestedTestSuites](/linter/rules/no-excessive-nested-test-suites) | This rule enforces a maximum depth to nested <code>describe()</code> in test files. | | | [noExportsInTest](/linter/rules/no-exports-in-test) | Disallow using <code>export</code> or <code>module.exports</code> in files containing tests | | +| [noFlatMapIdentity](/linter/rules/no-flat-map-identity) | Disallow to use unnecessary callback on <code>flatMap</code>. | <span aria-label="The rule has a safe fix" role="img" title="The rule has a safe fix">๐Ÿ”ง </span> | | [noFocusedTests](/linter/rules/no-focused-tests) | Disallow focused tests. | <span aria-label="The rule has an unsafe fix" role="img" title="The rule has an unsafe fix">โš ๏ธ </span> | | [noMisplacedAssertion](/linter/rules/no-misplaced-assertion) | Checks that the assertion function, for example <code>expect</code>, is placed inside an <code>it()</code> function call. | | | [noNamespaceImport](/linter/rules/no-namespace-import) | Disallow the use of namespace imports. | |
๐Ÿ“Ž Implement `lint/noFlatMapIdentity` - `clippy/flat_map_identity` ### Description Implement [flat_map_identity](https://rust-lang.github.io/rust-clippy/master/#/flat_map_identity). **Want to contribute?** Lets you know you are interested! We will assign you to the issue to prevent several people to work on the same issue. Don't worry, we can unassign you later if you are no longer interested in the issue! Read our [contributing guide](https://github.com/biomejs/biome/blob/main/CONTRIBUTING.md) and [analyzer contributing guide](https://github.com/biomejs/biome/blob/main/crates/biome_analyze/CONTRIBUTING.md). You can use the implementation of [useFlatMap](https://biomejs.dev/linter/rules/use-flat-map/) as a staring point.
i'm interested
2024-04-06T05:05:24Z
0.5
2024-04-14T14:31:41Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "diagnostics::test::diagnostic_size", "diagnostics::test::deserialization_quick_check", "diagnostics::test::deserialization_error", "diagnostics::test::config_already_exists" ]
[]
[]
[]
auto_2025-06-09
biomejs/biome
2,317
biomejs__biome-2317
[ "2245" ]
2b1919494d8eb62221db1742552fea20698d585d
diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b ### Analyzer +#### Bug fixes + +- Now Biome can detect the script language in Svelte and Vue script blocks more reliably ([#2245](https://github.com/biomejs/biome/issues/2245)). Contributed by @Sec-ant + ### CLI #### Bug fixes diff --git a/crates/biome_service/src/file_handlers/mod.rs b/crates/biome_service/src/file_handlers/mod.rs --- a/crates/biome_service/src/file_handlers/mod.rs +++ b/crates/biome_service/src/file_handlers/mod.rs @@ -20,7 +20,8 @@ use biome_css_syntax::CssFileSource; use biome_diagnostics::{Diagnostic, Severity}; use biome_formatter::Printed; use biome_fs::BiomePath; -use biome_js_syntax::{EmbeddingKind, JsFileSource, TextRange, TextSize}; +use biome_js_parser::{parse, JsParserOptions}; +use biome_js_syntax::{EmbeddingKind, JsFileSource, Language, TextRange, TextSize}; use biome_json_syntax::JsonFileSource; use biome_parser::AnyParse; use biome_project::PackageJson; diff --git a/crates/biome_service/src/file_handlers/svelte.rs b/crates/biome_service/src/file_handlers/svelte.rs --- a/crates/biome_service/src/file_handlers/svelte.rs +++ b/crates/biome_service/src/file_handlers/svelte.rs @@ -11,26 +11,22 @@ use crate::WorkspaceError; use biome_formatter::Printed; use biome_fs::BiomePath; use biome_js_parser::{parse_js_with_cache, JsParserOptions}; -use biome_js_syntax::{EmbeddingKind, JsFileSource, TextRange, TextSize}; +use biome_js_syntax::{EmbeddingKind, JsFileSource, Language, TextRange, TextSize}; use biome_parser::AnyParse; use biome_rowan::NodeCache; use lazy_static::lazy_static; use regex::{Match, Regex}; use tracing::debug; +use super::parse_lang_from_script_opening_tag; + #[derive(Debug, Default, PartialEq, Eq)] pub struct SvelteFileHandler; lazy_static! { // https://regex101.com/r/E4n4hh/3 pub static ref SVELTE_FENCE: Regex = Regex::new( - r#"(?ixms)(?:<script[^>]?) - (?: - (?:(lang)\s*=\s*['"](?P<lang>[^'"]*)['"]) - | - (?:(\w+)\s*(?:=\s*['"]([^'"]*)['"])?) - )* - [^>]*>\n(?P<script>(?U:.*))</script>"# + r#"(?ixms)(?<opening><script[^>]*>)\n(?P<script>(?U:.*))</script>"# ) .unwrap(); } diff --git a/crates/biome_service/src/file_handlers/svelte.rs b/crates/biome_service/src/file_handlers/svelte.rs --- a/crates/biome_service/src/file_handlers/svelte.rs +++ b/crates/biome_service/src/file_handlers/svelte.rs @@ -73,13 +69,17 @@ impl SvelteFileHandler { } pub fn file_source(text: &str) -> JsFileSource { - let matches = SVELTE_FENCE.captures(text); - matches - .and_then(|captures| captures.name("lang")) - .filter(|lang| lang.as_str() == "ts") - .map_or(JsFileSource::js_module(), |_| { - JsFileSource::ts().with_embedding_kind(EmbeddingKind::Svelte) + SVELTE_FENCE + .captures(text) + .and_then(|captures| { + match parse_lang_from_script_opening_tag(captures.name("opening")?.as_str()) { + Language::JavaScript => None, + Language::TypeScript { .. } => { + Some(JsFileSource::ts().with_embedding_kind(EmbeddingKind::Svelte)) + } + } }) + .map_or(JsFileSource::js_module(), |fs| fs) } } diff --git a/crates/biome_service/src/file_handlers/svelte.rs b/crates/biome_service/src/file_handlers/svelte.rs --- a/crates/biome_service/src/file_handlers/svelte.rs +++ b/crates/biome_service/src/file_handlers/svelte.rs @@ -119,20 +119,12 @@ fn parse( _settings: SettingsHandle, cache: &mut NodeCache, ) -> ParseResult { - let matches = SVELTE_FENCE.captures(text); - let script = match matches { - Some(ref captures) => &text[captures.name("script").unwrap().range()], - _ => "", - }; + let script = SvelteFileHandler::input(text); + let file_source = SvelteFileHandler::file_source(text); - let language = matches - .and_then(|captures| captures.name("lang")) - .filter(|lang| lang.as_str() == "ts") - .map_or(JsFileSource::js_module(), |_| JsFileSource::ts()); + debug!("Parsing file with language {:?}", file_source); - debug!("Parsing file with language {:?}", language); - - let parse = parse_js_with_cache(script, language, JsParserOptions::default(), cache); + let parse = parse_js_with_cache(script, file_source, JsParserOptions::default(), cache); let root = parse.syntax(); let diagnostics = parse.into_diagnostics(); diff --git a/crates/biome_service/src/file_handlers/svelte.rs b/crates/biome_service/src/file_handlers/svelte.rs --- a/crates/biome_service/src/file_handlers/svelte.rs +++ b/crates/biome_service/src/file_handlers/svelte.rs @@ -142,11 +134,7 @@ fn parse( root.as_send().unwrap(), diagnostics, ), - language: Some(if language.is_typescript() { - JsFileSource::ts().into() - } else { - JsFileSource::js_module().into() - }), + language: Some(file_source.into()), } } diff --git a/crates/biome_service/src/file_handlers/vue.rs b/crates/biome_service/src/file_handlers/vue.rs --- a/crates/biome_service/src/file_handlers/vue.rs +++ b/crates/biome_service/src/file_handlers/vue.rs @@ -11,26 +11,22 @@ use crate::WorkspaceError; use biome_formatter::Printed; use biome_fs::BiomePath; use biome_js_parser::{parse_js_with_cache, JsParserOptions}; -use biome_js_syntax::{EmbeddingKind, JsFileSource, TextRange, TextSize}; +use biome_js_syntax::{EmbeddingKind, JsFileSource, Language, TextRange, TextSize}; use biome_parser::AnyParse; use biome_rowan::NodeCache; use lazy_static::lazy_static; use regex::{Match, Regex}; use tracing::debug; +use super::parse_lang_from_script_opening_tag; + #[derive(Debug, Default, PartialEq, Eq)] pub struct VueFileHandler; lazy_static! { // https://regex101.com/r/E4n4hh/3 pub static ref VUE_FENCE: Regex = Regex::new( - r#"(?ixms)(?:<script[^>]?) - (?: - (?:(lang)\s*=\s*['"](?P<lang>[^'"]*)['"]) - | - (?:(\w+)\s*(?:=\s*['"]([^'"]*)['"])?) - )* - [^>]*>\n(?P<script>(?U:.*))</script>"# + r#"(?ixms)(?<opening><script[^>]*>)\n(?P<script>(?U:.*))</script>"# ) .unwrap(); } diff --git a/crates/biome_service/src/file_handlers/vue.rs b/crates/biome_service/src/file_handlers/vue.rs --- a/crates/biome_service/src/file_handlers/vue.rs +++ b/crates/biome_service/src/file_handlers/vue.rs @@ -73,13 +69,17 @@ impl VueFileHandler { } pub fn file_source(text: &str) -> JsFileSource { - let matches = VUE_FENCE.captures(text); - matches - .and_then(|captures| captures.name("lang")) - .filter(|lang| lang.as_str() == "ts") - .map_or(JsFileSource::js_module(), |_| { - JsFileSource::ts().with_embedding_kind(EmbeddingKind::Vue) + VUE_FENCE + .captures(text) + .and_then(|captures| { + match parse_lang_from_script_opening_tag(captures.name("opening")?.as_str()) { + Language::JavaScript => None, + Language::TypeScript { .. } => { + Some(JsFileSource::ts().with_embedding_kind(EmbeddingKind::Vue)) + } + } }) + .map_or(JsFileSource::js_module(), |fs| fs) } } diff --git a/crates/biome_service/src/file_handlers/vue.rs b/crates/biome_service/src/file_handlers/vue.rs --- a/crates/biome_service/src/file_handlers/vue.rs +++ b/crates/biome_service/src/file_handlers/vue.rs @@ -120,11 +120,11 @@ fn parse( cache: &mut NodeCache, ) -> ParseResult { let script = VueFileHandler::input(text); - let language = VueFileHandler::file_source(text); + let file_source = VueFileHandler::file_source(text); - debug!("Parsing file with language {:?}", language); + debug!("Parsing file with language {:?}", file_source); - let parse = parse_js_with_cache(script, language, JsParserOptions::default(), cache); + let parse = parse_js_with_cache(script, file_source, JsParserOptions::default(), cache); let root = parse.syntax(); let diagnostics = parse.into_diagnostics(); diff --git a/crates/biome_service/src/file_handlers/vue.rs b/crates/biome_service/src/file_handlers/vue.rs --- a/crates/biome_service/src/file_handlers/vue.rs +++ b/crates/biome_service/src/file_handlers/vue.rs @@ -134,11 +134,7 @@ fn parse( root.as_send().unwrap(), diagnostics, ), - language: Some(if language.is_typescript() { - JsFileSource::ts().into() - } else { - JsFileSource::js_module().into() - }), + language: Some(file_source.into()), } } diff --git a/website/src/content/docs/internals/changelog.md b/website/src/content/docs/internals/changelog.md --- a/website/src/content/docs/internals/changelog.md +++ b/website/src/content/docs/internals/changelog.md @@ -19,6 +19,10 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b ### Analyzer +#### Bug fixes + +- Now Biome can detect the script language in Svelte and Vue script blocks more reliably ([#2245](https://github.com/biomejs/biome/issues/2245)). Contributed by @Sec-ant + ### CLI #### Bug fixes
diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -6,26 +6,38 @@ use biome_service::DynRef; use bpaf::Args; use std::path::Path; -const SVELTE_FILE_IMPORTS_BEFORE: &str = r#"<script setup lang="ts"> +const SVELTE_FILE_IMPORTS_BEFORE: &str = r#"<script lang="ts"> import Button from "./components/Button.svelte"; import * as svelteUse from "svelte-use"; </script> <div></div>"#; -const SVELTE_FILE_IMPORTS_AFTER: &str = r#"<script setup lang="ts"> +const SVELTE_FILE_IMPORTS_AFTER: &str = r#"<script lang="ts"> import * as svelteUse from "svelte-use"; import Button from "./components/Button.svelte"; </script> <div></div>"#; +const SVELTE_TS_CONTEXT_MODULE_FILE_UNFORMATTED: &str = r#"<script context="module" lang="ts"> +import Button from "./components/Button.svelte"; +const hello : string = "world"; +</script> +<div></div>"#; + +const SVELTE_TS_CONTEXT_MODULE_FILE_FORMATTED: &str = r#"<script context="module" lang="ts"> +import Button from "./components/Button.svelte"; +const hello: string = "world"; +</script> +<div></div>"#; + #[test] fn sorts_imports_check() { let mut fs = MemoryFileSystem::default(); let mut console = BufferConsole::default(); - let astro_file_path = Path::new("file.svelte"); + let svelte_file_path = Path::new("file.svelte"); fs.insert( - astro_file_path.into(), + svelte_file_path.into(), SVELTE_FILE_IMPORTS_BEFORE.as_bytes(), ); diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -37,7 +49,7 @@ fn sorts_imports_check() { ("check"), "--formatter-enabled=false", "--linter-enabled=false", - astro_file_path.as_os_str().to_str().unwrap(), + svelte_file_path.as_os_str().to_str().unwrap(), ] .as_slice(), ), diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -45,7 +57,7 @@ fn sorts_imports_check() { assert!(result.is_err(), "run_cli returned {result:?}"); - assert_file_contents(&fs, astro_file_path, SVELTE_FILE_IMPORTS_BEFORE); + assert_file_contents(&fs, svelte_file_path, SVELTE_FILE_IMPORTS_BEFORE); assert_cli_snapshot(SnapshotPayload::new( module_path!(), diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -61,9 +73,9 @@ fn sorts_imports_write() { let mut fs = MemoryFileSystem::default(); let mut console = BufferConsole::default(); - let astro_file_path = Path::new("file.svelte"); + let svelte_file_path = Path::new("file.svelte"); fs.insert( - astro_file_path.into(), + svelte_file_path.into(), SVELTE_FILE_IMPORTS_BEFORE.as_bytes(), ); diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -76,7 +88,7 @@ fn sorts_imports_write() { "--formatter-enabled=false", "--linter-enabled=false", "--apply", - astro_file_path.as_os_str().to_str().unwrap(), + svelte_file_path.as_os_str().to_str().unwrap(), ] .as_slice(), ), diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -84,7 +96,7 @@ fn sorts_imports_write() { assert!(result.is_ok(), "run_cli returned {result:?}"); - assert_file_contents(&fs, astro_file_path, SVELTE_FILE_IMPORTS_AFTER); + assert_file_contents(&fs, svelte_file_path, SVELTE_FILE_IMPORTS_AFTER); assert_cli_snapshot(SnapshotPayload::new( module_path!(), diff --git a/crates/biome_cli/tests/cases/handle_svelte_files.rs b/crates/biome_cli/tests/cases/handle_svelte_files.rs --- a/crates/biome_cli/tests/cases/handle_svelte_files.rs +++ b/crates/biome_cli/tests/cases/handle_svelte_files.rs @@ -94,3 +106,78 @@ fn sorts_imports_write() { result, )); } + +#[test] +fn format_svelte_ts_context_module_files() { + let mut fs = MemoryFileSystem::default(); + let mut console = BufferConsole::default(); + + let svelte_file_path = Path::new("file.svelte"); + fs.insert( + svelte_file_path.into(), + SVELTE_TS_CONTEXT_MODULE_FILE_UNFORMATTED.as_bytes(), + ); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("format"), svelte_file_path.as_os_str().to_str().unwrap()].as_slice()), + ); + + assert!(result.is_err(), "run_cli returned {result:?}"); + + assert_file_contents( + &fs, + svelte_file_path, + SVELTE_TS_CONTEXT_MODULE_FILE_UNFORMATTED, + ); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "format_svelte_ts_context_module_files", + fs, + console, + result, + )); +} + +#[test] +fn format_svelte_ts_context_module_files_write() { + let mut fs = MemoryFileSystem::default(); + let mut console = BufferConsole::default(); + + let svelte_file_path = Path::new("file.svelte"); + fs.insert( + svelte_file_path.into(), + SVELTE_TS_CONTEXT_MODULE_FILE_UNFORMATTED.as_bytes(), + ); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from( + [ + "format", + "--write", + svelte_file_path.as_os_str().to_str().unwrap(), + ] + .as_slice(), + ), + ); + + assert!(result.is_ok(), "run_cli returned {result:?}"); + + assert_file_contents( + &fs, + svelte_file_path, + SVELTE_TS_CONTEXT_MODULE_FILE_FORMATTED, + ); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "format_svelte_ts_context_module_files_write", + fs, + console, + result, + )); +} diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/format_svelte_ts_context_module_files.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/format_svelte_ts_context_module_files.snap @@ -0,0 +1,47 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +## `file.svelte` + +```svelte +<script context="module" lang="ts"> +import Button from "./components/Button.svelte"; +const hello : string = "world"; +</script> +<div></div> +``` + +# Termination Message + +```block +format โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ร— Some errors were emitted while running checks. + + + +``` + +# Emitted Messages + +```block +file.svelte format โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ร— Formatter would have printed the following content: + + 1 1 โ”‚ <script context="module" lang="ts"> + 2 โ”‚ - importยทยทยทยทยทButtonยทยทยทยทยทfromยท"./components/Button.svelte"; + 3 โ”‚ - constยทhelloยทยท:ยทยทยทยทยทยทstringยทยทยทยทยทยท=ยท"world"; + 2 โ”‚ + importยทButtonยทfromยท"./components/Button.svelte"; + 3 โ”‚ + constยทhello:ยทstringยท=ยท"world"; + 4 4 โ”‚ </script> + 5 5 โ”‚ <div></div> + + +``` + +```block +Checked 1 file in <TIME>. No fixes needed. +Found 1 error. +``` diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/format_svelte_ts_context_module_files_write.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/format_svelte_ts_context_module_files_write.snap @@ -0,0 +1,19 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +## `file.svelte` + +```svelte +<script context="module" lang="ts"> +import Button from "./components/Button.svelte"; +const hello: string = "world"; +</script> +<div></div> +``` + +# Emitted Messages + +```block +Formatted 1 file in <TIME>. Fixed 1 file. +``` diff --git a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap --- a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap @@ -5,7 +5,7 @@ expression: content ## `file.svelte` ```svelte -<script setup lang="ts"> +<script lang="ts"> import Button from "./components/Button.svelte"; import * as svelteUse from "svelte-use"; </script> diff --git a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap --- a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_check.snap @@ -30,7 +30,7 @@ file.svelte organizeImports โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” ร— Import statements could be sorted: - 1 1 โ”‚ <script setup lang="ts"> + 1 1 โ”‚ <script lang="ts"> 2 โ”‚ - importยทButtonยทfromยท"./components/Button.svelte"; 3 โ”‚ - importยท*ยทasยทsvelteUseยทfromยท"svelte-use"; 2 โ”‚ + importยท*ยทasยทsvelteUseยทfromยท"svelte-use"; diff --git a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap --- a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap @@ -5,7 +5,7 @@ expression: content ## `file.svelte` ```svelte -<script setup lang="ts"> +<script lang="ts"> import * as svelteUse from "svelte-use"; import Button from "./components/Button.svelte"; </script> diff --git a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap --- a/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap +++ b/crates/biome_cli/tests/snapshots/main_cases_handle_svelte_files/sorts_imports_write.snap @@ -17,5 +17,3 @@ import Button from "./components/Button.svelte"; ```block Checked 1 file in <TIME>. Fixed 1 file. ``` - - diff --git a/crates/biome_service/src/file_handlers/mod.rs b/crates/biome_service/src/file_handlers/mod.rs --- a/crates/biome_service/src/file_handlers/mod.rs +++ b/crates/biome_service/src/file_handlers/mod.rs @@ -558,6 +559,44 @@ pub(crate) fn is_diagnostic_error( severity >= Severity::Error } +/// Parse the "lang" attribute from the opening tag of the "\<script\>" block in Svelte or Vue files. +/// This function will return the language based on the existence or the value of the "lang" attribute. +/// We use the JSX parser at the moment to parse the opening tag. So the opening tag should be first +/// matched by regular expressions. +/// +// TODO: We should change the parser when HTMLish languages are supported. +pub(crate) fn parse_lang_from_script_opening_tag(script_opening_tag: &str) -> Language { + parse( + script_opening_tag, + JsFileSource::jsx(), + JsParserOptions::default(), + ) + .try_tree() + .and_then(|tree| { + tree.as_js_module()?.items().into_iter().find_map(|item| { + let expression = item + .as_any_js_statement()? + .as_js_expression_statement()? + .expression() + .ok()?; + let tag = expression.as_jsx_tag_expression()?.tag().ok()?; + let opening_element = tag.as_jsx_element()?.opening_element().ok()?; + let lang_attribute = opening_element.attributes().find_by_name("lang").ok()??; + let attribute_value = lang_attribute.initializer()?.value().ok()?; + let attribute_inner_string = + attribute_value.as_jsx_string()?.inner_string_text().ok()?; + if attribute_inner_string.text() == "ts" { + Some(Language::TypeScript { + definition_file: false, + }) + } else { + None + } + }) + }) + .map_or(Language::JavaScript, |lang| lang) +} + #[test] fn test_order() { for items in diff --git a/crates/biome_service/src/file_handlers/mod.rs b/crates/biome_service/src/file_handlers/mod.rs --- a/crates/biome_service/src/file_handlers/mod.rs +++ b/crates/biome_service/src/file_handlers/mod.rs @@ -569,3 +608,36 @@ fn test_order() { assert!(items[0] < items[1], "{} < {}", items[0], items[1]); } } + +#[test] +fn test_svelte_script_lang() { + const SVELTE_JS_SCRIPT_OPENING_TAG: &str = r#"<script>"#; + const SVELTE_TS_SCRIPT_OPENING_TAG: &str = r#"<script lang="ts">"#; + const SVELTE_CONTEXT_MODULE_JS_SCRIPT_OPENING_TAG: &str = r#"<script context="module">"#; + const SVELTE_CONTEXT_MODULE_TS_SCRIPT_OPENING_TAG: &str = + r#"<script context="module" lang="ts">"#; + + assert!(parse_lang_from_script_opening_tag(SVELTE_JS_SCRIPT_OPENING_TAG).is_javascript()); + assert!(parse_lang_from_script_opening_tag(SVELTE_TS_SCRIPT_OPENING_TAG).is_typescript()); + assert!( + parse_lang_from_script_opening_tag(SVELTE_CONTEXT_MODULE_JS_SCRIPT_OPENING_TAG) + .is_javascript() + ); + assert!( + parse_lang_from_script_opening_tag(SVELTE_CONTEXT_MODULE_TS_SCRIPT_OPENING_TAG) + .is_typescript() + ); +} + +#[test] +fn test_vue_script_lang() { + const VUE_JS_SCRIPT_OPENING_TAG: &str = r#"<script>"#; + const VUE_TS_SCRIPT_OPENING_TAG: &str = r#"<script lang="ts">"#; + const VUE_SETUP_JS_SCRIPT_OPENING_TAG: &str = r#"<script setup>"#; + const VUE_SETUP_TS_SCRIPT_OPENING_TAG: &str = r#"<script setup lang="ts">"#; + + assert!(parse_lang_from_script_opening_tag(VUE_JS_SCRIPT_OPENING_TAG).is_javascript()); + assert!(parse_lang_from_script_opening_tag(VUE_TS_SCRIPT_OPENING_TAG).is_typescript()); + assert!(parse_lang_from_script_opening_tag(VUE_SETUP_JS_SCRIPT_OPENING_TAG).is_javascript()); + assert!(parse_lang_from_script_opening_tag(VUE_SETUP_TS_SCRIPT_OPENING_TAG).is_typescript()); +}
๐Ÿ› In Svelte context=module Scripts error "import { type x ident }' are a TypeScript only feature." ### Environment information ```block CLI: Version: 1.6.3 Color support: true Platform: CPU Architecture: aarch64 OS: macos Environment: BIOME_LOG_DIR: unset NO_COLOR: unset TERM: "xterm-256color" JS_RUNTIME_VERSION: "v20.11.1" JS_RUNTIME_NAME: "node" NODE_PACKAGE_MANAGER: "pnpm/8.15.5" Biome Configuration: Status: Loaded successfully Formatter disabled: false Linter disabled: false Organize imports disabled: false VCS disabled: true Workspace: Open Documents: 0 ``` ### What happened? 1. Have a Svelte component with code below ```svelte <script context="module" lang="ts"> import { timeline, type TimelineSegment } from 'motion' </script> ``` 2. Observe that type imports produce "import { type x ident }' are a TypeScript only feature". If imports are moved into regular svelte block, things work correctly. ### Expected result No error ### Code of Conduct - [X] I agree to follow Biome's Code of Conduct
MouseEvent also fails with code below, interestingly only that part, interface itself does not produce any errors. "Type annotations are a TypeScript only feature. Convert your file to a TypeScript file or remove the syntax." ```svelte <script context="module" lang="ts"> export interface ButtonProps { onclick?: (event: MouseEvent) => void } </script> ``` An option to override parsing would be great, forcing typescript on all "*.svelte" files might be an easy fix to this problem The fix should be fairly easy, we need to update the regex to take `context` into account: https://github.com/biomejs/biome/blob/19d761a3da076c34e602f49639f48785b5d0940c/crates/biome_service/src/file_handlers/svelte.rs#L26-L35 Can anyone help? @ematipico Instead of adding error prone syntaxes to our regexes, what do you think of using our jsx parser (for the time being of course) to parse the matched `<script ... >` openning element? This works for both svelte and vue. ```rust #[test] pub fn jsx_test() { let code = r#" <script context="module" lang="ts"> "#; let root = parse(code, JsFileSource::jsx(), JsParserOptions::default()); let syntax = root.syntax(); dbg!(&syntax, root.diagnostics(), root.has_errors()); } ``` I'm not sure how reliable that would be though. The regex is good because it gives us the offsets we need to extract the code. With the parser, we need to calculate the offsets ourselves, and rely on how well our parser can recover itself and still provide the correct ranges of the script tag. > I'm not sure how reliable that would be though. The regex is good because it gives us the offsets we need to extract the code. > > With the parser, we need to calculate the offsets ourselves, and rely on how well our parser can recover itself and still provide the correct ranges of the script tag. What I wanted to say is that we still use regex to match the script block so we can still have our script body and offsets, but instead we use the JSX parser to parse the opening element to extract the `lang` attribute reliably.
2024-04-05T08:58:51Z
0.5
2024-04-05T11:40:48Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "diagnostics::test::termination_diagnostic_size", "execute::migrate::prettier::test::ok", "metrics::tests::test_timing", "execute::migrate::prettier::test::some_properties", "metrics::tests::test_layer", "commands::check_options" ]
[]
[]
[]
auto_2025-06-09
biomejs/biome
2,300
biomejs__biome-2300
[ "2296" ]
60671ec3a4c59421583d5d1ec8cfe30d45b27cd7
diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -167,6 +167,12 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b ``` </details> +- Added new `--staged` flag to the `check`, `format` and `lint` subcommands. + + This new option allows users to apply the command _only_ to the files that are staged (the + ones that will be committed), which can be very useful to simplify writing git hook scripts + such as `pre-commit`. Contributed by @castarco + #### Enhancements - Improve support of `.prettierignore` when migrating from Prettier diff --git a/crates/biome_cli/src/changed.rs b/crates/biome_cli/src/changed.rs --- a/crates/biome_cli/src/changed.rs +++ b/crates/biome_cli/src/changed.rs @@ -27,3 +27,13 @@ pub(crate) fn get_changed_files( Ok(filtered_changed_files) } + +pub(crate) fn get_staged_files( + fs: &DynRef<'_, dyn FileSystem>, +) -> Result<Vec<OsString>, CliDiagnostic> { + let staged_files = fs.get_staged_files()?; + + let filtered_staged_files = staged_files.iter().map(OsString::from).collect::<Vec<_>>(); + + Ok(filtered_staged_files) +} diff --git a/crates/biome_cli/src/commands/check.rs b/crates/biome_cli/src/commands/check.rs --- a/crates/biome_cli/src/commands/check.rs +++ b/crates/biome_cli/src/commands/check.rs @@ -1,6 +1,7 @@ -use crate::changed::get_changed_files; use crate::cli_options::CliOptions; -use crate::commands::{get_stdin, resolve_manifest, validate_configuration_diagnostics}; +use crate::commands::{ + get_files_to_process, get_stdin, resolve_manifest, validate_configuration_diagnostics, +}; use crate::{ execute_mode, setup_cli_subscriber, CliDiagnostic, CliSession, Execution, TraversalMode, }; diff --git a/crates/biome_cli/src/commands/check.rs b/crates/biome_cli/src/commands/check.rs --- a/crates/biome_cli/src/commands/check.rs +++ b/crates/biome_cli/src/commands/check.rs @@ -26,6 +27,7 @@ pub(crate) struct CheckCommandPayload { pub(crate) formatter_enabled: Option<bool>, pub(crate) linter_enabled: Option<bool>, pub(crate) organize_imports_enabled: Option<bool>, + pub(crate) staged: bool, pub(crate) changed: bool, pub(crate) since: Option<String>, } diff --git a/crates/biome_cli/src/commands/check.rs b/crates/biome_cli/src/commands/check.rs --- a/crates/biome_cli/src/commands/check.rs +++ b/crates/biome_cli/src/commands/check.rs @@ -46,6 +48,7 @@ pub(crate) fn check( organize_imports_enabled, formatter_enabled, since, + staged, changed, } = payload; setup_cli_subscriber(cli_options.log_level, cli_options.log_kind); diff --git a/crates/biome_cli/src/commands/check.rs b/crates/biome_cli/src/commands/check.rs --- a/crates/biome_cli/src/commands/check.rs +++ b/crates/biome_cli/src/commands/check.rs @@ -120,13 +123,12 @@ pub(crate) fn check( let stdin = get_stdin(stdin_file_path, &mut *session.app.console, "check")?; - if since.is_some() && !changed { - return Err(CliDiagnostic::incompatible_arguments("since", "changed")); + if let Some(_paths) = + get_files_to_process(since, changed, staged, &session.app.fs, &fs_configuration)? + { + paths = _paths; } - if changed { - paths = get_changed_files(&session.app.fs, &fs_configuration, since)?; - } session .app .workspace diff --git a/crates/biome_cli/src/commands/format.rs b/crates/biome_cli/src/commands/format.rs --- a/crates/biome_cli/src/commands/format.rs +++ b/crates/biome_cli/src/commands/format.rs @@ -1,6 +1,7 @@ -use crate::changed::get_changed_files; use crate::cli_options::CliOptions; -use crate::commands::{get_stdin, resolve_manifest, validate_configuration_diagnostics}; +use crate::commands::{ + get_files_to_process, get_stdin, resolve_manifest, validate_configuration_diagnostics, +}; use crate::diagnostics::DeprecatedArgument; use crate::{ execute_mode, setup_cli_subscriber, CliDiagnostic, CliSession, Execution, TraversalMode, diff --git a/crates/biome_cli/src/commands/format.rs b/crates/biome_cli/src/commands/format.rs --- a/crates/biome_cli/src/commands/format.rs +++ b/crates/biome_cli/src/commands/format.rs @@ -30,6 +31,7 @@ pub(crate) struct FormatCommandPayload { pub(crate) write: bool, pub(crate) cli_options: CliOptions, pub(crate) paths: Vec<OsString>, + pub(crate) staged: bool, pub(crate) changed: bool, pub(crate) since: Option<String>, } diff --git a/crates/biome_cli/src/commands/format.rs b/crates/biome_cli/src/commands/format.rs --- a/crates/biome_cli/src/commands/format.rs +++ b/crates/biome_cli/src/commands/format.rs @@ -51,6 +53,7 @@ pub(crate) fn format( mut json_formatter, mut css_formatter, since, + staged, changed, } = payload; setup_cli_subscriber(cli_options.log_level, cli_options.log_kind); diff --git a/crates/biome_cli/src/commands/format.rs b/crates/biome_cli/src/commands/format.rs --- a/crates/biome_cli/src/commands/format.rs +++ b/crates/biome_cli/src/commands/format.rs @@ -156,12 +159,10 @@ pub(crate) fn format( let (vcs_base_path, gitignore_matches) = configuration.retrieve_gitignore_matches(&session.app.fs, vcs_base_path.as_deref())?; - if since.is_some() && !changed { - return Err(CliDiagnostic::incompatible_arguments("since", "changed")); - } - - if changed { - paths = get_changed_files(&session.app.fs, &configuration, since)?; + if let Some(_paths) = + get_files_to_process(since, changed, staged, &session.app.fs, &configuration)? + { + paths = _paths; } session diff --git a/crates/biome_cli/src/commands/lint.rs b/crates/biome_cli/src/commands/lint.rs --- a/crates/biome_cli/src/commands/lint.rs +++ b/crates/biome_cli/src/commands/lint.rs @@ -1,6 +1,7 @@ -use crate::changed::get_changed_files; use crate::cli_options::CliOptions; -use crate::commands::{get_stdin, resolve_manifest, validate_configuration_diagnostics}; +use crate::commands::{ + get_files_to_process, get_stdin, resolve_manifest, validate_configuration_diagnostics, +}; use crate::{ execute_mode, setup_cli_subscriber, CliDiagnostic, CliSession, Execution, TraversalMode, }; diff --git a/crates/biome_cli/src/commands/lint.rs b/crates/biome_cli/src/commands/lint.rs --- a/crates/biome_cli/src/commands/lint.rs +++ b/crates/biome_cli/src/commands/lint.rs @@ -24,6 +25,7 @@ pub(crate) struct LintCommandPayload { pub(crate) files_configuration: Option<PartialFilesConfiguration>, pub(crate) paths: Vec<OsString>, pub(crate) stdin_file_path: Option<String>, + pub(crate) staged: bool, pub(crate) changed: bool, pub(crate) since: Option<String>, } diff --git a/crates/biome_cli/src/commands/lint.rs b/crates/biome_cli/src/commands/lint.rs --- a/crates/biome_cli/src/commands/lint.rs +++ b/crates/biome_cli/src/commands/lint.rs @@ -39,6 +41,7 @@ pub(crate) fn lint(session: CliSession, payload: LintCommandPayload) -> Result<( stdin_file_path, vcs_configuration, files_configuration, + staged, changed, since, } = payload; diff --git a/crates/biome_cli/src/commands/lint.rs b/crates/biome_cli/src/commands/lint.rs --- a/crates/biome_cli/src/commands/lint.rs +++ b/crates/biome_cli/src/commands/lint.rs @@ -95,12 +98,10 @@ pub(crate) fn lint(session: CliSession, payload: LintCommandPayload) -> Result<( let (vcs_base_path, gitignore_matches) = fs_configuration.retrieve_gitignore_matches(&session.app.fs, vcs_base_path.as_deref())?; - if since.is_some() && !changed { - return Err(CliDiagnostic::incompatible_arguments("since", "changed")); - } - - if changed { - paths = get_changed_files(&session.app.fs, &fs_configuration, since)?; + if let Some(_paths) = + get_files_to_process(since, changed, staged, &session.app.fs, &fs_configuration)? + { + paths = _paths; } let stdin = get_stdin(stdin_file_path, &mut *session.app.console, "lint")?; diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -1,3 +1,4 @@ +use crate::changed::{get_changed_files, get_staged_files}; use crate::cli_options::{cli_options, CliOptions, ColorsArg}; use crate::diagnostics::DeprecatedConfigurationFile; use crate::execute::Stdin; diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -14,11 +15,11 @@ use biome_configuration::{ use biome_configuration::{ConfigurationDiagnostic, PartialConfiguration}; use biome_console::{markup, Console, ConsoleExt}; use biome_diagnostics::{Diagnostic, PrintDiagnostic}; -use biome_fs::BiomePath; +use biome_fs::{BiomePath, FileSystem}; use biome_service::configuration::LoadedConfiguration; use biome_service::documentation::Doc; use biome_service::workspace::{OpenProjectParams, UpdateProjectParams}; -use biome_service::WorkspaceError; +use biome_service::{DynRef, WorkspaceError}; use bpaf::Bpaf; use std::ffi::OsString; use std::path::PathBuf; diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -109,6 +110,11 @@ pub enum BiomeCommand { #[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)] stdin_file_path: Option<String>, + /// When set to true, only the files that have been staged (the ones prepared to be committed) + /// will be linted. + #[bpaf(long("staged"), switch)] + staged: bool, + /// When set to true, only the files that have been changed compared to your `defaultBranch` /// configuration will be linted. #[bpaf(long("changed"), switch)] diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -150,6 +156,10 @@ pub enum BiomeCommand { /// Example: `echo 'let a;' | biome lint --stdin-file-path=file.js` #[bpaf(long("stdin-file-path"), argument("PATH"), hide_usage)] stdin_file_path: Option<String>, + /// When set to true, only the files that have been staged (the ones prepared to be committed) + /// will be linted. + #[bpaf(long("staged"), switch)] + staged: bool, /// When set to true, only the files that have been changed compared to your `defaultBranch` /// configuration will be linted. #[bpaf(long("changed"), switch)] diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -197,6 +207,11 @@ pub enum BiomeCommand { #[bpaf(switch)] write: bool, + /// When set to true, only the files that have been staged (the ones prepared to be committed) + /// will be linted. + #[bpaf(long("staged"), switch)] + staged: bool, + /// When set to true, only the files that have been changed compared to your `defaultBranch` /// configuration will be linted. #[bpaf(long("changed"), switch)] diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -88,6 +88,7 @@ impl<'app> CliSession<'app> { linter_enabled, organize_imports_enabled, formatter_enabled, + staged, changed, since, } => commands::check::check( diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -102,6 +103,7 @@ impl<'app> CliSession<'app> { linter_enabled, organize_imports_enabled, formatter_enabled, + staged, changed, since, }, diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -115,6 +117,7 @@ impl<'app> CliSession<'app> { stdin_file_path, vcs_configuration, files_configuration, + staged, changed, since, } => commands::lint::lint( diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -128,6 +131,7 @@ impl<'app> CliSession<'app> { stdin_file_path, vcs_configuration, files_configuration, + staged, changed, since, }, diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -165,6 +169,7 @@ impl<'app> CliSession<'app> { files_configuration, json_formatter, css_formatter, + staged, changed, since, } => commands::format::format( diff --git a/crates/biome_cli/src/lib.rs b/crates/biome_cli/src/lib.rs --- a/crates/biome_cli/src/lib.rs +++ b/crates/biome_cli/src/lib.rs @@ -180,6 +185,7 @@ impl<'app> CliSession<'app> { files_configuration, json_formatter, css_formatter, + staged, changed, since, }, diff --git a/crates/biome_fs/src/fs.rs b/crates/biome_fs/src/fs.rs --- a/crates/biome_fs/src/fs.rs +++ b/crates/biome_fs/src/fs.rs @@ -180,6 +180,8 @@ pub trait FileSystem: Send + Sync + RefUnwindSafe { fn get_changed_files(&self, base: &str) -> io::Result<Vec<String>>; + fn get_staged_files(&self) -> io::Result<Vec<String>>; + fn resolve_configuration( &self, specifier: &str, diff --git a/crates/biome_fs/src/fs.rs b/crates/biome_fs/src/fs.rs --- a/crates/biome_fs/src/fs.rs +++ b/crates/biome_fs/src/fs.rs @@ -361,6 +363,10 @@ where T::get_changed_files(self, base) } + fn get_staged_files(&self) -> io::Result<Vec<String>> { + T::get_staged_files(self) + } + fn resolve_configuration( &self, specifier: &str, diff --git a/crates/biome_fs/src/fs/memory.rs b/crates/biome_fs/src/fs/memory.rs --- a/crates/biome_fs/src/fs/memory.rs +++ b/crates/biome_fs/src/fs/memory.rs @@ -28,6 +28,7 @@ pub struct MemoryFileSystem { files: AssertUnwindSafe<RwLock<FxHashMap<PathBuf, FileEntry>>>, errors: FxHashMap<PathBuf, ErrorEntry>, allow_write: bool, + on_get_staged_files: OnGetChangedFiles, on_get_changed_files: OnGetChangedFiles, } diff --git a/crates/biome_fs/src/fs/memory.rs b/crates/biome_fs/src/fs/memory.rs --- a/crates/biome_fs/src/fs/memory.rs +++ b/crates/biome_fs/src/fs/memory.rs @@ -37,6 +38,9 @@ impl Default for MemoryFileSystem { files: Default::default(), errors: Default::default(), allow_write: true, + on_get_staged_files: Some(Arc::new(AssertUnwindSafe(Mutex::new(Some(Box::new( + Vec::new, + )))))), on_get_changed_files: Some(Arc::new(AssertUnwindSafe(Mutex::new(Some(Box::new( Vec::new, )))))), diff --git a/crates/biome_fs/src/fs/memory.rs b/crates/biome_fs/src/fs/memory.rs --- a/crates/biome_fs/src/fs/memory.rs +++ b/crates/biome_fs/src/fs/memory.rs @@ -110,6 +114,13 @@ impl MemoryFileSystem { ) { self.on_get_changed_files = Some(Arc::new(AssertUnwindSafe(Mutex::new(Some(cfn))))); } + + pub fn set_on_get_staged_files( + &mut self, + cfn: Box<dyn FnOnce() -> Vec<String> + Send + RefUnwindSafe + 'static>, + ) { + self.on_get_staged_files = Some(Arc::new(AssertUnwindSafe(Mutex::new(Some(cfn))))); + } } impl FileSystem for MemoryFileSystem { diff --git a/crates/biome_fs/src/fs/memory.rs b/crates/biome_fs/src/fs/memory.rs --- a/crates/biome_fs/src/fs/memory.rs +++ b/crates/biome_fs/src/fs/memory.rs @@ -209,6 +220,16 @@ impl FileSystem for MemoryFileSystem { Ok(cb()) } + fn get_staged_files(&self) -> io::Result<Vec<String>> { + let cb_arc = self.on_get_staged_files.as_ref().unwrap().clone(); + + let mut cb_guard = cb_arc.lock(); + + let cb = cb_guard.take().unwrap(); + + Ok(cb()) + } + fn resolve_configuration( &self, _specifier: &str, diff --git a/crates/biome_fs/src/fs/os.rs b/crates/biome_fs/src/fs/os.rs --- a/crates/biome_fs/src/fs/os.rs +++ b/crates/biome_fs/src/fs/os.rs @@ -123,6 +123,26 @@ impl FileSystem for OsFileSystem { .map(|l| l.to_string()) .collect()) } + + fn get_staged_files(&self) -> io::Result<Vec<String>> { + let output = Command::new("git") + .arg("diff") + .arg("--name-only") + .arg("--relative") + .arg("--staged") + // A: added + // C: copied + // M: modified + // R: renamed + // Source: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203 + .arg("--diff-filter=ACMR") + .output()?; + + Ok(String::from_utf8_lossy(&output.stdout) + .lines() + .map(|l| l.to_string()) + .collect()) + } } struct OsFile { diff --git a/website/src/content/docs/internals/changelog.md b/website/src/content/docs/internals/changelog.md --- a/website/src/content/docs/internals/changelog.md +++ b/website/src/content/docs/internals/changelog.md @@ -173,6 +173,12 @@ our [guidelines for writing a good changelog entry](https://github.com/biomejs/b ``` </details> +- Added new `--staged` flag to the `check`, `format` and `lint` subcommands. + + This new option allows users to apply the command _only_ to the files that are staged (the + ones that will be committed), which can be very useful to simplify writing git hook scripts + such as `pre-commit`. Contributed by @castarco + #### Enhancements - Improve support of `.prettierignore` when migrating from Prettier
diff --git a/crates/biome_cli/src/commands/mod.rs b/crates/biome_cli/src/commands/mod.rs --- a/crates/biome_cli/src/commands/mod.rs +++ b/crates/biome_cli/src/commands/mod.rs @@ -510,6 +525,34 @@ pub(crate) fn get_stdin( Ok(stdin) } +fn get_files_to_process( + since: Option<String>, + changed: bool, + staged: bool, + fs: &DynRef<'_, dyn FileSystem>, + configuration: &PartialConfiguration, +) -> Result<Option<Vec<OsString>>, CliDiagnostic> { + if since.is_some() { + if !changed { + return Err(CliDiagnostic::incompatible_arguments("since", "changed")); + } + if staged { + return Err(CliDiagnostic::incompatible_arguments("since", "staged")); + } + } + + if changed { + if staged { + return Err(CliDiagnostic::incompatible_arguments("changed", "staged")); + } + Ok(Some(get_changed_files(fs, configuration, since)?)) + } else if staged { + Ok(Some(get_staged_files(fs)?)) + } else { + Ok(None) + } +} + /// Tests that all CLI options adhere to the invariants expected by `bpaf`. #[test] fn check_options() { diff --git a/crates/biome_cli/tests/commands/lint.rs b/crates/biome_cli/tests/commands/lint.rs --- a/crates/biome_cli/tests/commands/lint.rs +++ b/crates/biome_cli/tests/commands/lint.rs @@ -3006,6 +3006,171 @@ fn should_not_error_for_no_changed_files_with_no_errors_on_unmatched() { )); } +#[test] +fn should_error_if_changed_flag_and_staged_flag_are_active_at_the_same_time() { + let mut console = BufferConsole::default(); + let mut fs = MemoryFileSystem::default(); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("lint"), "--staged", "--changed"].as_slice()), + ); + + assert!(result.is_err(), "run_cli returned {result:?}"); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "should_error_if_changed_flag_and_staged_flag_are_active_at_the_same_time", + fs, + console, + result, + )); +} + +#[test] +fn should_only_processes_staged_files_when_staged_flag_is_set() { + let mut console = BufferConsole::default(); + let mut fs = MemoryFileSystem::default(); + + fs.set_on_get_staged_files(Box::new(|| vec![String::from("staged.js")])); + fs.set_on_get_changed_files(Box::new(|| vec![String::from("changed.js")])); + + // Staged (prepared to be committed) + fs.insert( + Path::new("staged.js").into(), + r#"console.log('staged');"#.as_bytes(), + ); + + // Changed (already recorded in git history) + fs.insert( + Path::new("changed.js").into(), + r#"console.log('changed');"#.as_bytes(), + ); + + // Unstaged (not yet recorded in git history, and not prepared to be committed) + fs.insert( + Path::new("file2.js").into(), + r#"console.log('file2');"#.as_bytes(), + ); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("lint"), "--staged"].as_slice()), + ); + + assert!(result.is_ok(), "run_cli returned {result:?}"); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "should_only_processes_staged_files_when_staged_flag_is_set", + fs, + console, + result, + )); +} + +#[test] +fn should_only_process_staged_file_if_its_included() { + let mut console = BufferConsole::default(); + let mut fs = MemoryFileSystem::default(); + + fs.set_on_get_staged_files(Box::new(|| { + vec![String::from("file.js"), String::from("file2.js")] + })); + + let file_path = Path::new("biome.json"); + fs.insert( + file_path.into(), + r#" +{ + "files": { + "include": ["file.js"] + }, + "vcs": { + "defaultBranch": "main" + } +} + "# + .as_bytes(), + ); + + fs.insert( + Path::new("file.js").into(), + r#"console.log('file');"#.as_bytes(), + ); + fs.insert( + Path::new("file2.js").into(), + r#"console.log('file2');"#.as_bytes(), + ); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("lint"), "--staged"].as_slice()), + ); + + assert!(result.is_ok(), "run_cli returned {result:?}"); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "should_only_process_staged_file_if_its_included", + fs, + console, + result, + )); +} + +#[test] +fn should_not_process_ignored_file_even_if_its_staged() { + let mut console = BufferConsole::default(); + let mut fs = MemoryFileSystem::default(); + + fs.set_on_get_staged_files(Box::new(|| vec![String::from("file.js")])); + + let file_path = Path::new("biome.json"); + fs.insert( + file_path.into(), + r#" +{ + "files": { + "ignore": ["file.js"] + }, + "vcs": { + "defaultBranch": "main" + } +} + "# + .as_bytes(), + ); + + fs.insert( + Path::new("file.js").into(), + r#"console.log('file');"#.as_bytes(), + ); + fs.insert( + Path::new("file2.js").into(), + r#"console.log('file2');"#.as_bytes(), + ); + + let result = run_cli( + DynRef::Borrowed(&mut fs), + &mut console, + Args::from([("lint"), "--staged"].as_slice()), + ); + + assert!(result.is_err(), "run_cli returned {result:?}"); + + assert_cli_snapshot(SnapshotPayload::new( + module_path!(), + "should_not_process_ignored_file_even_if_its_staged", + fs, + console, + result, + )); +} + #[test] fn lint_syntax_rules() { let mut fs = MemoryFileSystem::default(); diff --git a/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap b/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap @@ -7,7 +7,7 @@ expression: content ```block Runs formatter, linter and import sorting to the requested files. -Usage: check [--apply] [--apply-unsafe] [--changed] [--since=REF] [PATH]... +Usage: check [--apply] [--apply-unsafe] [--staged] [--changed] [--since=REF] [PATH]... The configuration that is contained inside the file `biome.json` --vcs-client-kind=<git> The kind of client. diff --git a/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap b/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_check/check_help.snap @@ -116,6 +116,8 @@ Available options: The file doesn't need to exist on disk, what matters is the extension of the file. Based on the extension, Biome knows how to check the code. Example: `echo 'let a;' | biome check --stdin-file-path=file.js` + --staged When set to true, only the files that have been staged (the ones prepared + to be committed) will be linted. --changed When set to true, only the files that have been changed compared to your `defaultBranch` configuration will be linted. --since=REF Use this to specify the base branch to compare against when you're using diff --git a/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap b/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap @@ -7,7 +7,7 @@ expression: content ```block Run the formatter on a set of files. -Usage: format [--write] [--changed] [--since=REF] [PATH]... +Usage: format [--write] [--staged] [--changed] [--since=REF] [PATH]... Generic options applied to all files --indent-style=<tab|space> The indent style. diff --git a/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap b/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_format/format_help.snap @@ -118,6 +118,8 @@ Available options: the file. Based on the extension, Biome knows how to format the code. Example: `echo 'let a;' | biome format --stdin-file-path=file.js` --write Writes formatted files to file system. + --staged When set to true, only the files that have been staged (the ones prepared + to be committed) will be linted. --changed When set to true, only the files that have been changed compared to your `defaultBranch` configuration will be linted. --since=REF Use this to specify the base branch to compare against when you're using diff --git a/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap b/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap @@ -7,7 +7,7 @@ expression: content ```block Run various checks on a set of files. -Usage: lint [--apply] [--apply-unsafe] [--changed] [--since=REF] [PATH]... +Usage: lint [--apply] [--apply-unsafe] [--staged] [--changed] [--since=REF] [PATH]... Set of properties to integrate Biome with a VCS software. --vcs-client-kind=<git> The kind of client. diff --git a/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap b/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap --- a/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/lint_help.snap @@ -66,6 +66,8 @@ Available options: The file doesn't need to exist on disk, what matters is the extension of the file. Based on the extension, Biome knows how to lint the code. Example: `echo 'let a;' | biome lint --stdin-file-path=file.js` + --staged When set to true, only the files that have been staged (the ones prepared + to be committed) will be linted. --changed When set to true, only the files that have been changed compared to your `defaultBranch` configuration will be linted. --since=REF Use this to specify the base branch to compare against when you're using diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_commands_lint/should_error_if_changed_flag_and_staged_flag_are_active_at_the_same_time.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/should_error_if_changed_flag_and_staged_flag_are_active_at_the_same_time.snap @@ -0,0 +1,14 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +# Termination Message + +```block +flags/invalid โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ร— Incompatible arguments changed and staged + + + +``` diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_commands_lint/should_not_process_ignored_file_even_if_its_staged.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/should_not_process_ignored_file_even_if_its_staged.snap @@ -0,0 +1,45 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +## `biome.json` + +```json +{ + "files": { + "ignore": ["file.js"] + }, + "vcs": { + "defaultBranch": "main" + } +} +``` + +## `file.js` + +```js +console.log('file'); +``` + +## `file2.js` + +```js +console.log('file2'); +``` + +# Termination Message + +```block +internalError/io โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” + + ร— No files were processed in the specified paths. + + + +``` + +# Emitted Messages + +```block +Checked 0 files in <TIME>. No fixes needed. +``` diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_commands_lint/should_only_process_staged_file_if_its_included.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/should_only_process_staged_file_if_its_included.snap @@ -0,0 +1,34 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +## `biome.json` + +```json +{ + "files": { + "include": ["file.js"] + }, + "vcs": { + "defaultBranch": "main" + } +} +``` + +## `file.js` + +```js +console.log('file'); +``` + +## `file2.js` + +```js +console.log('file2'); +``` + +# Emitted Messages + +```block +Checked 1 file in <TIME>. No fixes needed. +``` diff --git /dev/null b/crates/biome_cli/tests/snapshots/main_commands_lint/should_only_processes_staged_files_when_staged_flag_is_set.snap new file mode 100644 --- /dev/null +++ b/crates/biome_cli/tests/snapshots/main_commands_lint/should_only_processes_staged_files_when_staged_flag_is_set.snap @@ -0,0 +1,27 @@ +--- +source: crates/biome_cli/tests/snap_test.rs +expression: content +--- +## `changed.js` + +```js +console.log('changed'); +``` + +## `file2.js` + +```js +console.log('file2'); +``` + +## `staged.js` + +```js +console.log('staged'); +``` + +# Emitted Messages + +```block +Checked 1 file in <TIME>. No fixes needed. +```
๐Ÿ“Ž Feature: --staged option to simplify the creation of git hook scripts ### Description ## Problem Statement As of today, `biome` does not provide a direct mechanism to select (for linting, formatting or checking) only the files that are staged for a commit. We have a "similar" flag, `--changed`, but its main purpose is to be used in CI, and allows us to check only the files that changed between 2 points in history (which can be explicit or implicit). Many people think at first that `--changed` will also help them to select only the files that are staged, not being the case. More advanced users have found workarounds to this issue ( https://github.com/biomejs/biome/issues/1198#issuecomment-1858364218 ), but these involve having to write longer, more complex and slower scripts. Not everyone can come up with these solutions, even if they seem simple after we see them. Others rely on tools such as `lint-staged`, but this involves adding more dependencies to the project (which in this case are much slower than `biome`), and opens up the possibility for more bugs caused by unexpected interactions between `lint-staged` and `biome`. ## Proposal After a discussion held in Discord ( https://discord.com/channels/1132231889290285117/1222450681919832134 ), we agreed that it would be a good idea to introduce a new `--staged` flag for the `lint`, `format` and `check` commands that will make biome take into account only the files that are _staged_. ### Addendum While `--staged` doesn't give us much when we are running "potentially destructive" commands such as `format` or `check --apply` (because we still need to independently obtain a list of staged files so we can re-add them to the "stage" before they are committed), it gives a clear advantage for readonly-mode commands such as `lint` without `--apply`.
2024-04-04T10:25:43Z
0.5
2024-04-12T14:21:49Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "diagnostics::test::termination_diagnostic_size", "execute::migrate::ignorefile::tests::comments_and_empty_lines", "execute::migrate::ignorefile::tests::negated_pattern", "execute::migrate::ignorefile::tests::empty", "execute::migrate::eslint_to_biome::tests::flat_config_single_config_object", "execute::migrate::eslint_to_biome::tests::flat_config_multiple_config_object", "execute::migrate::ignorefile::tests::non_relative_patterns", "execute::migrate::ignorefile::tests::relative_patterns", "execute::migrate::ignorefile::tests::relative_patterns_starting_with_root_slash", "execute::migrate::ignorefile::tests::take_leading_spaces_into_account", "execute::migrate::prettier::tests::ok", "metrics::tests::test_timing", "execute::migrate::prettier::tests::some_properties", "metrics::tests::test_layer", "commands::check_options" ]
[]
[]
[]
auto_2025-06-09
biomejs/biome
2,292
biomejs__biome-2292
[ "2288" ]
cc04271f337cdd5a8af583aed09a44cb72b17a82
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -15,6 +15,10 @(...TRUNCATED)
"diff --git a/crates/biome_cli/tests/cases/diagnostics.rs b/crates/biome_cli/tests/cases/diagnostics(...TRUNCATED)
"๐Ÿ› `organizeImports` causes check to fail but does not print errors with `--diagnostic-level=erro(...TRUNCATED)
2024-04-04T03:40:59Z
0.5
2024-04-07T04:36:07Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
["cases::protected_files::not_process_file_from_stdin_verbose_lint","cases::config_extends::extends_(...TRUNCATED)
["diagnostics::test::termination_diagnostic_size","execute::migrate::prettier::test::ok","execute::m(...TRUNCATED)
[ "commands::explain::explain_help" ]
[]
auto_2025-06-09
biomejs/biome
2,250
biomejs__biome-2250
[ "2243" ]
cad1cfd1e8fc7440960213ce49130670dc90491d
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -13,6 +13,10 @(...TRUNCATED)
"diff --git a/crates/biome_js_analyze/src/utils.rs b/crates/biome_js_analyze/src/utils.rs\n--- a/cra(...TRUNCATED)
"๐Ÿ“ biom crashed\n### Environment information\n\n```bash\nโฏ pnpm biome check . --apply\r\nBiome (...TRUNCATED)
"This error is thrown from this function. Would you please help us narrow down the source code file (...TRUNCATED)
2024-03-31T14:34:47Z
0.5
2024-03-31T16:09:30Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "utils::test::find_variable_position_when_the_operator_has_no_spaces_around" ]
["assists::correctness::organize_imports::test_order","globals::javascript::node::test_order","globa(...TRUNCATED)
[]
[]
auto_2025-06-09
biomejs/biome
2,220
biomejs__biome-2220
[ "2217" ]
b6d4c6e8108c69882d76863a1340080fd2c1fbdc
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -73,6 +73,10 @(...TRUNCATED)
"diff --git a/crates/biome_diagnostics_categories/src/categories.rs b/crates/biome_diagnostics_categ(...TRUNCATED)
"๐Ÿ’… Rename `noSemicolonInJsx` rule?\n### Environment information\n\n```bash\nirrelevant\n```\n\n\n(...TRUNCATED)
"@fujiyamaorange would you like to help? Unfortunately we didn't catch the name of the name early. \(...TRUNCATED)
2024-03-27T00:48:19Z
0.5
2024-03-28T03:06:24Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
["assists::correctness::organize_imports::test_order","globals::javascript::language::test_order","g(...TRUNCATED)
["target/debug/build/biome_diagnostics_categories-50cc392058e367b8/out/categories.rs - category (lin(...TRUNCATED)
[]
[]
auto_2025-06-09
biomejs/biome
2,204
biomejs__biome-2204
[ "2191" ]
62fbec86467946e8d71dcd0098e3d90443208f78
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -9,6 +9,28 @@ (...TRUNCATED)
"diff --git a/crates/biome_cli/tests/commands/lint.rs b/crates/biome_cli/tests/commands/lint.rs\n---(...TRUNCATED)
"๐Ÿ’… recommended: false disables all nested rules\n### Environment information\n\n```bash\nCLI:\r\n(...TRUNCATED)
"~~Sorry, I think this is a regression introduced in #2072, I'll fix it ASAP.~~\r\n\r\nIt's not a re(...TRUNCATED)
2024-03-25T17:24:38Z
0.5
2024-03-26T02:48:16Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
["commands::check::check_help","commands::ci::ci_help","commands::format::format_help","commands::fo(...TRUNCATED)
["diagnostics::test::termination_diagnostic_size","metrics::tests::test_timing","execute::migrate::p(...TRUNCATED)
[ "commands::explain::explain_help" ]
[]
auto_2025-06-09
biomejs/biome
2,169
biomejs__biome-2169
[ "2164" ]
95974a106067083c32066eee28ff95cbc3db9a31
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -9,6 +9,30 @@ (...TRUNCATED)
"diff --git /dev/null b/crates/biome_cli/tests/cases/config_path.rs\nnew file mode 100644\n--- /dev/(...TRUNCATED)
"--config-path fails with JSONC\n### Environment information\n\n```block\nI am using pre-commit hook(...TRUNCATED)
"Could you please tell us how you use the argument via CLI?\nI point it to the containing directory (...TRUNCATED)
2024-03-23T06:22:32Z
0.5
2024-03-23T14:42:31Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
["cases::config_path::set_config_path","commands::check::check_help","commands::ci::ci_help","comman(...TRUNCATED)
["diagnostics::test::termination_diagnostic_size","execute::migrate::prettier::test::ok","metrics::t(...TRUNCATED)
[ "commands::explain::explain_help" ]
[]
auto_2025-06-09
biomejs/biome
2,116
biomejs__biome-2116
[ "2114" ]
984626de115e4b8f64dec97d3f66ba353ebf1b65
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -9,7 +9,7 @@ N(...TRUNCATED)
"diff --git /dev/null b/crates/biome_cli/tests/cases/cts_files.rs\nnew file mode 100644\n--- /dev/nu(...TRUNCATED)
"๐Ÿ› Typescripts \"Module\" syntax is invalid for typescript-enabled common js\n### Environment inf(...TRUNCATED)
2024-03-17T08:06:29Z
0.5
2024-03-18T12:40:11Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "cases::cts_files::should_allow_using_export_statements" ]
["diagnostics::test::termination_diagnostic_size","metrics::tests::test_timing","execute::migrate::p(...TRUNCATED)
[ "commands::explain::explain_help" ]
[]
auto_2025-06-09
biomejs/biome
2,072
biomejs__biome-2072
[ "2028" ]
409eb1083ede5b887e35f4dfa80f860490823b8c
"diff --git a/CHANGELOG.md b/CHANGELOG.md\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -9,6 +9,28 @@ (...TRUNCATED)
"diff --git a/crates/biome_cli/tests/commands/lint.rs b/crates/biome_cli/tests/commands/lint.rs\n---(...TRUNCATED)
"๐Ÿ’… Regression: Disabling one nursery rule disables all nursery rules\n### Environment information(...TRUNCATED)
"I don't think this is a bug because as the schema says the `lint.rules.all` won't enable nursery ru(...TRUNCATED)
2024-03-13T03:42:02Z
0.5
2024-03-13T12:17:28Z
2425ce767fc6a93bbd091a5a9ec18beb5476e204
[ "commands::lint::top_level_all_down_level_empty", "commands::version::ok" ]
["diagnostics::test::termination_diagnostic_size","execute::migrate::prettier::test::ok","metrics::t(...TRUNCATED)
[ "commands::explain::explain_help" ]
[]
auto_2025-06-09
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1