Skip to content

Commit

Permalink
feat(graphql_analyze): noAnonymousOperations
Browse files Browse the repository at this point in the history
Disallow operations without name, since GraphQL clients usually use
operations' name to cache.
  • Loading branch information
vohoanglong0107 committed Oct 19, 2024
1 parent 7fffb27 commit aa33e72
Show file tree
Hide file tree
Showing 16 changed files with 361 additions and 100 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

220 changes: 121 additions & 99 deletions crates/biome_configuration/src/analyzer/linter/rules.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/biome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ define_categories! {
"lint/correctness/useValidForDirection": "https://biomejs.dev/linter/rules/use-valid-for-direction",
"lint/correctness/useYield": "https://biomejs.dev/linter/rules/use-yield",
"lint/nursery/colorNoInvalidHex": "https://biomejs.dev/linter/rules/color-no-invalid-hex",
"lint/nursery/noAnonymousOperations": "https://biomejs.dev/linter/rules/no-anonymous-operations",
"lint/nursery/noColorInvalidHex": "https://biomejs.dev/linter/rules/no-color-invalid-hex",
"lint/nursery/noCommonJs": "https://biomejs.dev/linter/rules/no-common-js",
"lint/nursery/noConsole": "https://biomejs.dev/linter/rules/no-console",
Expand Down
1 change: 1 addition & 0 deletions crates/biome_graphql_analyze/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ biome_console = { workspace = true }
biome_deserialize = { workspace = true }
biome_deserialize_macros = { workspace = true }
biome_diagnostics = { workspace = true }
biome_graphql_factory = { workspace = true }
biome_graphql_syntax = { workspace = true }
biome_rowan = { workspace = true }
biome_string_case = { workspace = true }
Expand Down
4 changes: 3 additions & 1 deletion crates/biome_graphql_analyze/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ pub use crate::registry::visit_registry;
use crate::suppression_action::GraphqlSuppressionAction;
use biome_analyze::{
AnalysisFilter, AnalyzerOptions, AnalyzerSignal, ControlFlow, LanguageRoot, MatchQueryParams,
MetadataRegistry, RuleRegistry, SuppressionKind,
MetadataRegistry, RuleAction, RuleRegistry, SuppressionKind,
};
use biome_diagnostics::{category, Error};
use biome_graphql_syntax::GraphqlLanguage;
use biome_suppression::{parse_suppression_comment, SuppressionDiagnostic};
use std::ops::Deref;
use std::sync::LazyLock;

pub(crate) type GraphqlRuleAction = RuleAction<GraphqlLanguage>;

pub static METADATA: LazyLock<MetadataRegistry> = LazyLock::new(|| {
let mut metadata = MetadataRegistry::default();
visit_registry(&mut metadata);
Expand Down
2 changes: 2 additions & 0 deletions crates/biome_graphql_analyze/src/lint/nursery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

use biome_analyze::declare_lint_group;

pub mod no_anonymous_operations;
pub mod no_duplicated_fields;
pub mod use_deprecated_reason;

declare_lint_group! {
pub Nursery {
name : "nursery" ,
rules : [
self :: no_anonymous_operations :: NoAnonymousOperations ,
self :: no_duplicated_fields :: NoDuplicatedFields ,
self :: use_deprecated_reason :: UseDeprecatedReason ,
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
use biome_analyze::{
context::RuleContext, declare_lint_rule, ActionCategory, Ast, FixKind, Rule, RuleDiagnostic,
RuleSource, RuleSourceKind,
};
use biome_console::markup;
use biome_graphql_factory::make;
use biome_graphql_syntax::GraphqlOperationDefinition;
use biome_rowan::{AstNode, AstNodeExt, BatchMutationExt};
use biome_string_case::Case;

use crate::GraphqlRuleAction;

declare_lint_rule! {
/// Require specifying name for GraphQL operations.
///
/// This is useful since most GraphQL client libraries are using the operation name for caching purposes..
///
/// ## Examples
///
/// ### Invalid
///
/// ```graphql,expect_diagnostic
/// query {}
/// ```
///
/// ### Valid
///
/// ```graphql
/// query Human {
/// name
/// }
/// ```
///
pub NoAnonymousOperations {
version: "next",
name: "noAnonymousOperations",
language: "graphql",
sources: &[RuleSource::EslintGraphql("no-anonymous-operations")],
source_kind: RuleSourceKind::SameLogic,
recommended: true,
fix_kind: FixKind::Unsafe,
}
}

impl Rule for NoAnonymousOperations {
type Query = Ast<GraphqlOperationDefinition>;
type State = NoAnonymousOperationsState;
type Signals = Option<Self::State>;
type Options = ();

fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let operation_type = node.ty().ok()?.text();
if node.name().is_some() {
None
} else {
Some(NoAnonymousOperationsState {
operation_type: operation_type.clone(),
suggested_name: get_suggested_name(node, operation_type),
})
}
}

fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();

Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Anonymous GraphQL operations are forbidden. Make sure to name your " {state.operation_type}"!"
},
)
.note(markup! {
"Rename this "{state.operation_type}" to "{state.suggested_name}"."
}),
)
}

fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<GraphqlRuleAction> {
let mut mutation = ctx.root().begin();
let node = ctx.query().clone();
let new_name = make::graphql_name_binding(make::ident(&state.suggested_name));
let new_node = node.clone().detach().with_name(Some(new_name));
mutation.replace_node(node, new_node);

Some(GraphqlRuleAction::new(
ActionCategory::QuickFix,
ctx.metadata().applicability(),
markup! {
"Rename this "{state.operation_type}" to "{state.suggested_name}"."
},
mutation,
))
}
}

fn get_suggested_name(operation: &GraphqlOperationDefinition, operation_type: String) -> String {
let suggested_name = get_suggested_name_base_on_content(operation).unwrap_or(operation_type);
Case::Pascal.convert(&suggested_name)
}

fn get_suggested_name_base_on_content(operation: &GraphqlOperationDefinition) -> Option<String> {
let selection_set = operation.selection_set().ok()?;
let first_field = selection_set
.selections()
.into_iter()
.find_map(|selection| selection.as_graphql_field().cloned())?;

first_field
.alias()
.map(|alias| alias.text())
.or(first_field.name().ok().map(|name| name.text()))
}

pub struct NoAnonymousOperationsState {
operation_type: String,
suggested_name: String,
}
2 changes: 2 additions & 0 deletions crates/biome_graphql_analyze/src/options.rs

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
query { human }
mutation { ...Type }
subscription {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
source: crates/biome_graphql_analyze/tests/spec_tests.rs
expression: invalid.graphql
---
# Input
```graphql
query { human }
mutation { ...Type }
subscription {}
```

# Diagnostics
```
invalid.graphql:1:1 lint/nursery/noAnonymousOperations FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
! Anonymous GraphQL operations are forbidden. Make sure to name your query!
> 1 │ query { human }
│ ^^^^^^^^^^^^^^^
2 │ mutation { ...Type }
3 │ subscription {}
i Rename this query to Human.
i Unsafe fix: Rename this query to Human.
1 │ query·Human{·human·}
│ +++++
```

```
invalid.graphql:2:1 lint/nursery/noAnonymousOperations FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
! Anonymous GraphQL operations are forbidden. Make sure to name your mutation!
1 │ query { human }
> 2 │ mutation { ...Type }
│ ^^^^^^^^^^^^^^^^^^^^
3 │ subscription {}
4 │
i Rename this mutation to Mutation.
i Unsafe fix: Rename this mutation to Mutation.
2 │ mutation·Mutation{·...Type·}
│ ++++++++
```

```
invalid.graphql:3:1 lint/nursery/noAnonymousOperations FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
! Anonymous GraphQL operations are forbidden. Make sure to name your subscription!
1 │ query { human }
2 │ mutation { ...Type }
> 3 │ subscription {}
│ ^^^^^^^^^^^^^^^
4 │
i Rename this subscription to Subscription.
i Unsafe fix: Rename this subscription to Subscription.
3 │ subscription·Subscription{}
│ ++++++++++++
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* should not generate diagnostics */
query myQuery { a }
mutation doSomething { a }
subscription myData { a }
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
source: crates/biome_graphql_analyze/tests/spec_tests.rs
expression: valid.graphql
---
# Input
```graphql
/* should not generate diagnostics */
query myQuery { a }
mutation doSomething { a }
subscription myData { a }
```
1 change: 1 addition & 0 deletions crates/biome_graphql_factory/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use biome_graphql_syntax::GraphqlLanguage;
use biome_rowan::TreeBuilder;

mod generated;
pub mod make;
pub use crate::generated::GraphqlSyntaxFactory;

// Re-exported for tests
Expand Down
7 changes: 7 additions & 0 deletions crates/biome_graphql_factory/src/make.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pub use crate::generated::node_factory::*;
use biome_graphql_syntax::{GraphqlSyntaxKind, GraphqlSyntaxToken};

/// Create a new literal name token with no attached trivia
pub fn ident(text: &str) -> GraphqlSyntaxToken {
GraphqlSyntaxToken::new_detached(GraphqlSyntaxKind::IDENT, text, [], [])
}
5 changes: 5 additions & 0 deletions packages/@biomejs/backend-jsonrpc/src/workspace.ts

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

7 changes: 7 additions & 0 deletions packages/@biomejs/biome/configuration_schema.json

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

0 comments on commit aa33e72

Please sign in to comment.