|
| 1 | +use std::collections::HashSet; |
| 2 | + |
| 3 | +use biome_analyze::{ |
| 4 | + Ast, Rule, RuleDiagnostic, RuleSource, context::RuleContext, declare_lint_rule, |
| 5 | +}; |
| 6 | +use biome_console::markup; |
| 7 | +use biome_graphql_syntax::GraphqlObjectValue; |
| 8 | +use biome_rowan::{AstNode, TokenText}; |
| 9 | +use biome_rule_options::use_unique_input_field_names::UseUniqueInputFieldNamesOptions; |
| 10 | + |
| 11 | +declare_lint_rule! { |
| 12 | + /// Require fields within an input object to be unique. |
| 13 | + /// |
| 14 | + /// A GraphQL input object value is only valid if all supplied fields are uniquely named. |
| 15 | + /// |
| 16 | + /// ## Examples |
| 17 | + /// |
| 18 | + /// ### Invalid |
| 19 | + /// |
| 20 | + /// ```graphql,expect_diagnostic |
| 21 | + /// query { |
| 22 | + /// field(arg: { f1: "value", f1: "value" }) |
| 23 | + /// } |
| 24 | + /// ``` |
| 25 | + /// |
| 26 | + /// ### Valid |
| 27 | + /// |
| 28 | + /// ```graphql |
| 29 | + /// query { |
| 30 | + /// field(arg: { f1: "value", f2: "value" }) |
| 31 | + /// } |
| 32 | + /// ``` |
| 33 | + /// |
| 34 | + pub UseUniqueInputFieldNames { |
| 35 | + version: "next", |
| 36 | + name: "useUniqueInputFieldNames", |
| 37 | + language: "graphql", |
| 38 | + recommended: false, |
| 39 | + sources: &[RuleSource::EslintGraphql("unique-input-field-names").same()], |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl Rule for UseUniqueInputFieldNames { |
| 44 | + type Query = Ast<GraphqlObjectValue>; |
| 45 | + type State = (); |
| 46 | + type Signals = Option<Self::State>; |
| 47 | + type Options = UseUniqueInputFieldNamesOptions; |
| 48 | + |
| 49 | + fn run(ctx: &RuleContext<Self>) -> Self::Signals { |
| 50 | + let node = ctx.query(); |
| 51 | + let mut found: HashSet<TokenText> = HashSet::new(); |
| 52 | + |
| 53 | + for element in node.members() { |
| 54 | + if let Some(name) = element.name().ok() |
| 55 | + && let Some(value_token) = name.value_token().ok() |
| 56 | + { |
| 57 | + let string = value_token.token_text(); |
| 58 | + if found.contains(&string) { |
| 59 | + return Some(()); |
| 60 | + } else { |
| 61 | + found.insert(string); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + None |
| 67 | + } |
| 68 | + |
| 69 | + fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { |
| 70 | + let span = ctx.query().range(); |
| 71 | + Some( |
| 72 | + RuleDiagnostic::new( |
| 73 | + rule_category!(), |
| 74 | + span, |
| 75 | + markup! { |
| 76 | + "Duplicate input field name." |
| 77 | + }, |
| 78 | + ) |
| 79 | + .note(markup! { |
| 80 | + "A GraphQL input object value is only valid if all supplied fields are uniquely named. Make sure to name every input field differently." |
| 81 | + }), |
| 82 | + ) |
| 83 | + } |
| 84 | +} |
0 commit comments