From cba75ea9957354a4a9eb6152952bcf44f81fccb3 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Tue, 11 Feb 2025 16:01:36 +0000 Subject: [PATCH 01/25] fix formatting --- graphql_client_codegen/src/codegen/selection.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index 04e276d4..6b6677dd 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -406,11 +406,15 @@ impl ExpandedField<'_> { }; let is_id = self.field_type == "ID"; - let is_required = self.field_type_qualifiers.contains(&GraphqlTypeQualifier::Required); + let is_required = self + .field_type_qualifiers + .contains(&GraphqlTypeQualifier::Required); let id_deserialize_with = if is_id && is_required { Some(quote!(#[serde(deserialize_with = "graphql_client::serde_with::deserialize_id")])) } else if is_id { - Some(quote!(#[serde(deserialize_with = "graphql_client::serde_with::deserialize_option_id")])) + Some( + quote!(#[serde(deserialize_with = "graphql_client::serde_with::deserialize_option_id")]), + ) } else { None }; From e7321458e669705b090c7822cf5ec280aee23e61 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:02:31 +0000 Subject: [PATCH 02/25] use inline format args (clippy::uninlined_format_args) --- examples/github/examples/github.rs | 2 +- examples/web/src/lib.rs | 7 +++---- graphql_client/src/lib.rs | 6 +++--- graphql_client/tests/extern_enums.rs | 6 +++--- graphql_client/tests/interfaces.rs | 4 ++-- graphql_client/tests/json_schema.rs | 2 +- graphql_client/tests/skip_serializing_none.rs | 4 ++-- graphql_client_cli/src/generate.rs | 8 ++++---- .../src/introspection_schema.rs | 20 ++++++------------- graphql_client_codegen/src/codegen.rs | 2 +- graphql_client_codegen/src/lib.rs | 12 +++++------ graphql_client_codegen/src/query.rs | 6 ++---- graphql_client_codegen/src/tests/mod.rs | 2 +- graphql_query_derive/src/attributes.rs | 6 +++--- graphql_query_derive/src/lib.rs | 7 ++----- 15 files changed, 39 insertions(+), 55 deletions(-) diff --git a/examples/github/examples/github.rs b/examples/github/examples/github.rs index 707d79f0..65874fe4 100644 --- a/examples/github/examples/github.rs +++ b/examples/github/examples/github.rs @@ -52,7 +52,7 @@ fn main() -> Result<(), anyhow::Error> { .default_headers( std::iter::once(( reqwest::header::AUTHORIZATION, - reqwest::header::HeaderValue::from_str(&format!("Bearer {}", github_api_token)) + reqwest::header::HeaderValue::from_str(&format!("Bearer {github_api_token}")) .unwrap(), )) .collect(), diff --git a/examples/web/src/lib.rs b/examples/web/src/lib.rs index cfb23020..57cd77ec 100644 --- a/examples/web/src/lib.rs +++ b/examples/web/src/lib.rs @@ -36,7 +36,7 @@ async fn load_more() -> Result { let response = post_graphql::(&client, url, variables) .await .map_err(|err| { - log(&format!("Could not fetch puppies. error: {:?}", err)); + log(&format!("Could not fetch puppies. error: {err:?}")); JsValue::NULL })?; render_response(response); @@ -77,7 +77,7 @@ fn add_load_more_button() { fn render_response(response: graphql_client::Response) { use std::fmt::Write; - log(&format!("response body\n\n{:?}", response)); + log(&format!("response body\n\n{response:?}")); let parent = document().body().expect_throw("no body"); @@ -116,8 +116,7 @@ fn render_response(response: graphql_client::Responseresponse:
{}
", - inner_html + "

response:

{inner_html}
" )); parent .append_child(&response) diff --git a/graphql_client/src/lib.rs b/graphql_client/src/lib.rs index 67364730..bc3d1a85 100644 --- a/graphql_client/src/lib.rs +++ b/graphql_client/src/lib.rs @@ -122,8 +122,8 @@ pub enum PathFragment { impl Display for PathFragment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - PathFragment::Key(ref key) => write!(f, "{}", key), - PathFragment::Index(ref idx) => write!(f, "{}", idx), + PathFragment::Key(ref key) => write!(f, "{key}"), + PathFragment::Index(ref idx) => write!(f, "{idx}"), } } } @@ -217,7 +217,7 @@ impl Display for Error { fragments .iter() .fold(String::new(), |mut acc, item| { - let _ = write!(acc, "{}/", item); + let _ = write!(acc, "{item}/"); acc }) .trim_end_matches('/') diff --git a/graphql_client/tests/extern_enums.rs b/graphql_client/tests/extern_enums.rs index 7a4accc2..b2dee682 100644 --- a/graphql_client/tests/extern_enums.rs +++ b/graphql_client/tests/extern_enums.rs @@ -50,7 +50,7 @@ pub struct MultipleExternEnumsQuery; fn single_extern_enum() { const RESPONSE: &str = include_str!("extern_enums/single_extern_enum_response.json"); - println!("{:?}", RESPONSE); + println!("{RESPONSE:?}"); let response_data: single_extern_enum_query::ResponseData = serde_json::from_str(RESPONSE).unwrap(); @@ -67,11 +67,11 @@ fn single_extern_enum() { fn multiple_extern_enums() { const RESPONSE: &str = include_str!("extern_enums/multiple_extern_enums_response.json"); - println!("{:?}", RESPONSE); + println!("{RESPONSE:?}"); let response_data: multiple_extern_enums_query::ResponseData = serde_json::from_str(RESPONSE).unwrap(); - println!("{:?}", response_data); + println!("{response_data:?}"); let expected = multiple_extern_enums_query::ResponseData { distance: 100, diff --git a/graphql_client/tests/interfaces.rs b/graphql_client/tests/interfaces.rs index 6fc2e134..334dfef5 100644 --- a/graphql_client/tests/interfaces.rs +++ b/graphql_client/tests/interfaces.rs @@ -14,10 +14,10 @@ pub struct InterfaceQuery; fn interface_deserialization() { use interface_query::*; - println!("{:?}", RESPONSE); + println!("{RESPONSE:?}"); let response_data: interface_query::ResponseData = serde_json::from_str(RESPONSE).unwrap(); - println!("{:?}", response_data); + println!("{response_data:?}"); let expected = ResponseData { everything: Some(vec![ diff --git a/graphql_client/tests/json_schema.rs b/graphql_client/tests/json_schema.rs index 86e2298f..b34a0e04 100644 --- a/graphql_client/tests/json_schema.rs +++ b/graphql_client/tests/json_schema.rs @@ -33,7 +33,7 @@ fn json_schemas_work_with_and_without_data_field() { serde_json::from_value(response).unwrap(); assert_eq!( - format!("{:?}", schema_1_result), + format!("{schema_1_result:?}"), format!("{:?}", schema_2_result) ); } diff --git a/graphql_client/tests/skip_serializing_none.rs b/graphql_client/tests/skip_serializing_none.rs index bf177da4..fe33afa3 100644 --- a/graphql_client/tests/skip_serializing_none.rs +++ b/graphql_client/tests/skip_serializing_none.rs @@ -27,7 +27,7 @@ fn skip_serializing_none() { let stringified = serde_json::to_string(&query).expect("SkipSerializingNoneMutation is valid"); - println!("{}", stringified); + println!("{stringified}"); assert!(stringified.contains(r#""param":{"data":{"name":"test"}}"#)); assert!(stringified.contains(r#""nonOptionalInt":1337"#)); @@ -48,7 +48,7 @@ fn skip_serializing_none() { }), }); let stringified = serde_json::to_string(&query).expect("SkipSerializingNoneMutation is valid"); - println!("{}", stringified); + println!("{stringified}"); assert!(stringified.contains(r#""param":{"data":{"name":"test"}}"#)); assert!(stringified.contains(r#""nonOptionalInt":1337"#)); assert!(stringified.contains(r#""nonOptionalList":[]"#)); diff --git a/graphql_client_cli/src/generate.rs b/graphql_client_cli/src/generate.rs index 2871887e..b783295a 100644 --- a/graphql_client_cli/src/generate.rs +++ b/graphql_client_cli/src/generate.rs @@ -91,9 +91,9 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> CliResult<()> { } let gen = generate_module_token_stream(query_path.clone(), &schema_path, options) - .map_err(|err| Error::message(format!("Error generating module code: {}", err)))?; + .map_err(|err| Error::message(format!("Error generating module code: {err}")))?; - let generated_code = format!("{}\n{}", WARNING_SUPPRESSION, gen); + let generated_code = format!("{WARNING_SUPPRESSION}\n{gen}"); let generated_code = if !no_formatting { format(&generated_code)? } else { @@ -120,7 +120,7 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> CliResult<()> { format!("Creating file at {}", dest_file_path.display()), ) })?; - write!(file, "{}", generated_code)?; + write!(file, "{generated_code}")?; Ok(()) } @@ -134,7 +134,7 @@ fn format(code: &str) -> CliResult { .spawn() .map_err(|err| Error::source_with_message(err, "Error spawning rustfmt".to_owned()))?; let child_stdin = child.stdin.as_mut().unwrap(); - write!(child_stdin, "{}", code)?; + write!(child_stdin, "{code}")?; let output = child.wait_with_output()?; diff --git a/graphql_client_cli/src/introspection_schema.rs b/graphql_client_cli/src/introspection_schema.rs index 9f3e348f..a9360bdb 100644 --- a/graphql_client_cli/src/introspection_schema.rs +++ b/graphql_client_cli/src/introspection_schema.rs @@ -80,9 +80,9 @@ pub fn introspect_schema( let error_message = match res.text() { Ok(msg) => match serde_json::from_str::(&msg) { Ok(json) => format!("HTTP {}\n{}", status, serde_json::to_string_pretty(&json)?), - Err(_) => format!("HTTP {}: {}", status, msg), + Err(_) => format!("HTTP {status}: {msg}"), }, - Err(_) => format!("HTTP {}", status), + Err(_) => format!("HTTP {status}"), }; return Err(Error::message(error_message)); } @@ -113,8 +113,7 @@ impl FromStr for Header { // error: colon required for name/value pair if !input.contains(':') { return Err(format!( - "Invalid header input. A colon is required to separate the name and value. [{}]", - input + "Invalid header input. A colon is required to separate the name and value. [{input}]" )); } @@ -126,16 +125,14 @@ impl FromStr for Header { // error: field name must be if name.is_empty() { return Err(format!( - "Invalid header input. Field name is required before colon. [{}]", - input + "Invalid header input. Field name is required before colon. [{input}]" )); } // error: no whitespace in field name if name.split_whitespace().count() > 1 { return Err(format!( - "Invalid header input. Whitespace not allowed in field name. [{}]", - input + "Invalid header input. Whitespace not allowed in field name. [{input}]" )); } @@ -196,12 +193,7 @@ mod tests { let header = Header::from_str(input); assert!(header.is_ok(), "Expected ok: [{}]", input); - assert_eq!( - header.unwrap(), - **expected, - "Expected equality: [{}]", - input - ); + assert_eq!(header.unwrap(), **expected, "Expected equality: [{input}]"); } } } diff --git a/graphql_client_codegen/src/codegen.rs b/graphql_client_codegen/src/codegen.rs index 007dce86..5aff54c9 100644 --- a/graphql_client_codegen/src/codegen.rs +++ b/graphql_client_codegen/src/codegen.rs @@ -181,7 +181,7 @@ fn generate_scalar_definitions<'a, 'schema: 'a>( fn render_derives<'a>(derives: impl Iterator) -> impl quote::ToTokens { let idents = derives.map(|s| { syn::parse_str::(s) - .map_err(|e| format!("couldn't parse {} as a derive Path: {}", s, e)) + .map_err(|e| format!("couldn't parse {s} as a derive Path: {e}")) .unwrap() }); diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index 8d087057..32c71cb8 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -61,7 +61,7 @@ fn get_set_cached( fn query_document(query_string: &str) -> Result { let document = graphql_parser::parse_query(query_string) - .map_err(|err| GeneralError(format!("Query parser error: {}", err)))? + .map_err(|err| GeneralError(format!("Query parser error: {err}")))? .into_static(); Ok(document) } @@ -83,7 +83,7 @@ fn get_set_schema_from_file(schema_path: &std::path::Path) -> Schema { let schema_string = read_file(schema_path).unwrap(); match schema_extension { "graphql" | "graphqls"| "gql" => { - let s = graphql_parser::schema::parse_schema::<&str>(&schema_string).map_err(|parser_error| GeneralError(format!("Parser error: {}", parser_error))).unwrap(); + let s = graphql_parser::schema::parse_schema::<&str>(&schema_string).map_err(|parser_error| GeneralError(format!("Parser error: {parser_error}"))).unwrap(); Schema::from(s) } "json" => { @@ -179,8 +179,8 @@ impl Display for ReadFileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ReadFileError::FileNotFound { path, .. } => { - write!(f, "Could not find file with path: {}\n - Hint: file paths in the GraphQLQuery attribute are relative to the project root (location of the Cargo.toml). Example: query_path = \"src/my_query.graphql\".", path) + write!(f, "Could not find file with path: {path}\n + Hint: file paths in the GraphQLQuery attribute are relative to the project root (location of the Cargo.toml). Example: query_path = \"src/my_query.graphql\".") } ReadFileError::ReadError { path, .. } => { f.write_str("Error reading file at: ")?; @@ -232,8 +232,6 @@ fn derive_operation_not_found_error( let available_operations: String = available_operations.join(", "); format!( - "The struct name does not match any defined operation in the query file.\nStruct name: {}\nDefined operations: {}", - struct_ident, - available_operations, + "The struct name does not match any defined operation in the query file.\nStruct name: {struct_ident}\nDefined operations: {available_operations}", ) } diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index bb2b6318..a2f5fca2 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -260,8 +260,7 @@ where parent.add_to_selection_set(query, id); } else { return Err(QueryValidationError::new(format!( - "Invalid field selection on union field ({:?})", - parent + "Invalid field selection on union field ({parent:?})" ))); } } @@ -387,8 +386,7 @@ where other => { if !selection_set.items.is_empty() { return Err(QueryValidationError::new(format!( - "Selection set on non-object, non-interface type. ({:?})", - other + "Selection set on non-object, non-interface type. ({other:?})" ))); } } diff --git a/graphql_client_codegen/src/tests/mod.rs b/graphql_client_codegen/src/tests/mod.rs index 263001c6..b518ceaf 100644 --- a/graphql_client_codegen/src/tests/mod.rs +++ b/graphql_client_codegen/src/tests/mod.rs @@ -117,7 +117,7 @@ fn skip_serializing_none_should_generate_serde_skip_serializing() { match r { Ok(_) => { - println!("{}", generated_code); + println!("{generated_code}"); assert!(generated_code.contains("skip_serializing_if")); } Err(e) => { diff --git a/graphql_query_derive/src/attributes.rs b/graphql_query_derive/src/attributes.rs index 99158217..51ef227f 100644 --- a/graphql_query_derive/src/attributes.rs +++ b/graphql_query_derive/src/attributes.rs @@ -27,7 +27,7 @@ pub fn ident_exists(ast: &syn::DeriveInput, ident: &str) -> Result<(), syn::Erro Err(syn::Error::new_spanned( ast, - format!("Ident `{}` not found", ident), + format!("Ident `{ident}` not found"), )) } @@ -56,7 +56,7 @@ pub fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result panic!("parsed unexpectedly"), - Err(e) => assert_eq!(&format!("{}", e), DEPRECATION_ERROR), + Err(e) => assert_eq!(&format!("{e}"), DEPRECATION_ERROR), }; } diff --git a/graphql_query_derive/src/lib.rs b/graphql_query_derive/src/lib.rs index 0eea2c16..a6038967 100644 --- a/graphql_query_derive/src/lib.rs +++ b/graphql_query_derive/src/lib.rs @@ -32,10 +32,7 @@ fn graphql_query_derive_inner( generate_module_token_stream(query_path, &schema_path, options) .map(Into::into) .map_err(|err| { - syn::Error::new_spanned( - ast, - format!("Failed to generate GraphQLQuery impl: {}", err), - ) + syn::Error::new_spanned(ast, format!("Failed to generate GraphQLQuery impl: {err}")) }) } @@ -48,7 +45,7 @@ fn build_query_and_schema_path(input: &syn::DeriveInput) -> Result<(PathBuf, Pat })?; let query_path = attributes::extract_attr(input, "query_path")?; - let query_path = format!("{}/{}", cargo_manifest_dir, query_path); + let query_path = format!("{cargo_manifest_dir}/{query_path}"); let query_path = Path::new(&query_path).to_path_buf(); let schema_path = attributes::extract_attr(input, "schema_path")?; let schema_path = Path::new(&cargo_manifest_dir).join(schema_path); From 9fc24cc7e0993986e97231b108c0d3330d4c5929 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:03:06 +0000 Subject: [PATCH 03/25] use 'Self' keyword (clippy::use_self) --- .../src/introspection_response.rs | 120 +++++++++--------- graphql_client/src/lib.rs | 4 +- graphql_client_cli/src/error.rs | 6 +- .../src/codegen/selection.rs | 2 +- graphql_client_codegen/src/codegen_options.rs | 4 +- graphql_client_codegen/src/deprecation.rs | 6 +- graphql_client_codegen/src/lib.rs | 9 +- graphql_client_codegen/src/normalization.rs | 4 +- graphql_client_codegen/src/query.rs | 4 +- graphql_client_codegen/src/query/selection.rs | 43 +++---- graphql_client_codegen/src/schema.rs | 38 +++--- graphql_client_codegen/src/type_qualifiers.rs | 2 +- 12 files changed, 121 insertions(+), 121 deletions(-) diff --git a/graphql-introspection-query/src/introspection_response.rs b/graphql-introspection-query/src/introspection_response.rs index 63d673c1..65cf6b67 100644 --- a/graphql-introspection-query/src/introspection_response.rs +++ b/graphql-introspection-query/src/introspection_response.rs @@ -28,25 +28,25 @@ pub enum __DirectiveLocation { impl Serialize for __DirectiveLocation { fn serialize(&self, ser: S) -> Result { ser.serialize_str(match *self { - __DirectiveLocation::QUERY => "QUERY", - __DirectiveLocation::MUTATION => "MUTATION", - __DirectiveLocation::SUBSCRIPTION => "SUBSCRIPTION", - __DirectiveLocation::FIELD => "FIELD", - __DirectiveLocation::FRAGMENT_DEFINITION => "FRAGMENT_DEFINITION", - __DirectiveLocation::FRAGMENT_SPREAD => "FRAGMENT_SPREAD", - __DirectiveLocation::INLINE_FRAGMENT => "INLINE_FRAGMENT", - __DirectiveLocation::SCHEMA => "SCHEMA", - __DirectiveLocation::SCALAR => "SCALAR", - __DirectiveLocation::OBJECT => "OBJECT", - __DirectiveLocation::FIELD_DEFINITION => "FIELD_DEFINITION", - __DirectiveLocation::ARGUMENT_DEFINITION => "ARGUMENT_DEFINITION", - __DirectiveLocation::INTERFACE => "INTERFACE", - __DirectiveLocation::UNION => "UNION", - __DirectiveLocation::ENUM => "ENUM", - __DirectiveLocation::ENUM_VALUE => "ENUM_VALUE", - __DirectiveLocation::INPUT_OBJECT => "INPUT_OBJECT", - __DirectiveLocation::INPUT_FIELD_DEFINITION => "INPUT_FIELD_DEFINITION", - __DirectiveLocation::Other(ref s) => s.as_str(), + Self::QUERY => "QUERY", + Self::MUTATION => "MUTATION", + Self::SUBSCRIPTION => "SUBSCRIPTION", + Self::FIELD => "FIELD", + Self::FRAGMENT_DEFINITION => "FRAGMENT_DEFINITION", + Self::FRAGMENT_SPREAD => "FRAGMENT_SPREAD", + Self::INLINE_FRAGMENT => "INLINE_FRAGMENT", + Self::SCHEMA => "SCHEMA", + Self::SCALAR => "SCALAR", + Self::OBJECT => "OBJECT", + Self::FIELD_DEFINITION => "FIELD_DEFINITION", + Self::ARGUMENT_DEFINITION => "ARGUMENT_DEFINITION", + Self::INTERFACE => "INTERFACE", + Self::UNION => "UNION", + Self::ENUM => "ENUM", + Self::ENUM_VALUE => "ENUM_VALUE", + Self::INPUT_OBJECT => "INPUT_OBJECT", + Self::INPUT_FIELD_DEFINITION => "INPUT_FIELD_DEFINITION", + Self::Other(ref s) => s.as_str(), }) } } @@ -55,25 +55,25 @@ impl<'de> Deserialize<'de> for __DirectiveLocation { fn deserialize>(deserializer: D) -> Result { let s = <&'de str>::deserialize(deserializer)?; match s { - "QUERY" => Ok(__DirectiveLocation::QUERY), - "MUTATION" => Ok(__DirectiveLocation::MUTATION), - "SUBSCRIPTION" => Ok(__DirectiveLocation::SUBSCRIPTION), - "FIELD" => Ok(__DirectiveLocation::FIELD), - "FRAGMENT_DEFINITION" => Ok(__DirectiveLocation::FRAGMENT_DEFINITION), - "FRAGMENT_SPREAD" => Ok(__DirectiveLocation::FRAGMENT_SPREAD), - "INLINE_FRAGMENT" => Ok(__DirectiveLocation::INLINE_FRAGMENT), - "SCHEMA" => Ok(__DirectiveLocation::SCHEMA), - "SCALAR" => Ok(__DirectiveLocation::SCALAR), - "OBJECT" => Ok(__DirectiveLocation::OBJECT), - "FIELD_DEFINITION" => Ok(__DirectiveLocation::FIELD_DEFINITION), - "ARGUMENT_DEFINITION" => Ok(__DirectiveLocation::ARGUMENT_DEFINITION), - "INTERFACE" => Ok(__DirectiveLocation::INTERFACE), - "UNION" => Ok(__DirectiveLocation::UNION), - "ENUM" => Ok(__DirectiveLocation::ENUM), - "ENUM_VALUE" => Ok(__DirectiveLocation::ENUM_VALUE), - "INPUT_OBJECT" => Ok(__DirectiveLocation::INPUT_OBJECT), - "INPUT_FIELD_DEFINITION" => Ok(__DirectiveLocation::INPUT_FIELD_DEFINITION), - _ => Ok(__DirectiveLocation::Other(s.to_string())), + "QUERY" => Ok(Self::QUERY), + "MUTATION" => Ok(Self::MUTATION), + "SUBSCRIPTION" => Ok(Self::SUBSCRIPTION), + "FIELD" => Ok(Self::FIELD), + "FRAGMENT_DEFINITION" => Ok(Self::FRAGMENT_DEFINITION), + "FRAGMENT_SPREAD" => Ok(Self::FRAGMENT_SPREAD), + "INLINE_FRAGMENT" => Ok(Self::INLINE_FRAGMENT), + "SCHEMA" => Ok(Self::SCHEMA), + "SCALAR" => Ok(Self::SCALAR), + "OBJECT" => Ok(Self::OBJECT), + "FIELD_DEFINITION" => Ok(Self::FIELD_DEFINITION), + "ARGUMENT_DEFINITION" => Ok(Self::ARGUMENT_DEFINITION), + "INTERFACE" => Ok(Self::INTERFACE), + "UNION" => Ok(Self::UNION), + "ENUM" => Ok(Self::ENUM), + "ENUM_VALUE" => Ok(Self::ENUM_VALUE), + "INPUT_OBJECT" => Ok(Self::INPUT_OBJECT), + "INPUT_FIELD_DEFINITION" => Ok(Self::INPUT_FIELD_DEFINITION), + _ => Ok(Self::Other(s.to_string())), } } } @@ -94,15 +94,15 @@ pub enum __TypeKind { impl Serialize for __TypeKind { fn serialize(&self, ser: S) -> Result { ser.serialize_str(match *self { - __TypeKind::SCALAR => "SCALAR", - __TypeKind::OBJECT => "OBJECT", - __TypeKind::INTERFACE => "INTERFACE", - __TypeKind::UNION => "UNION", - __TypeKind::ENUM => "ENUM", - __TypeKind::INPUT_OBJECT => "INPUT_OBJECT", - __TypeKind::LIST => "LIST", - __TypeKind::NON_NULL => "NON_NULL", - __TypeKind::Other(ref s) => s.as_str(), + Self::SCALAR => "SCALAR", + Self::OBJECT => "OBJECT", + Self::INTERFACE => "INTERFACE", + Self::UNION => "UNION", + Self::ENUM => "ENUM", + Self::INPUT_OBJECT => "INPUT_OBJECT", + Self::LIST => "LIST", + Self::NON_NULL => "NON_NULL", + Self::Other(ref s) => s.as_str(), }) } } @@ -111,15 +111,15 @@ impl<'de> Deserialize<'de> for __TypeKind { fn deserialize>(deserializer: D) -> Result { let s = <&'de str>::deserialize(deserializer)?; match s { - "SCALAR" => Ok(__TypeKind::SCALAR), - "OBJECT" => Ok(__TypeKind::OBJECT), - "INTERFACE" => Ok(__TypeKind::INTERFACE), - "UNION" => Ok(__TypeKind::UNION), - "ENUM" => Ok(__TypeKind::ENUM), - "INPUT_OBJECT" => Ok(__TypeKind::INPUT_OBJECT), - "LIST" => Ok(__TypeKind::LIST), - "NON_NULL" => Ok(__TypeKind::NON_NULL), - _ => Ok(__TypeKind::Other(s.to_string())), + "SCALAR" => Ok(Self::SCALAR), + "OBJECT" => Ok(Self::OBJECT), + "INTERFACE" => Ok(Self::INTERFACE), + "UNION" => Ok(Self::UNION), + "ENUM" => Ok(Self::ENUM), + "INPUT_OBJECT" => Ok(Self::INPUT_OBJECT), + "LIST" => Ok(Self::LIST), + "NON_NULL" => Ok(Self::NON_NULL), + _ => Ok(Self::Other(s.to_string())), } } } @@ -288,15 +288,15 @@ pub enum IntrospectionResponse { impl IntrospectionResponse { pub fn as_schema(&self) -> &SchemaContainer { match self { - IntrospectionResponse::FullResponse(full_response) => &full_response.data, - IntrospectionResponse::Schema(schema) => schema, + Self::FullResponse(full_response) => &full_response.data, + Self::Schema(schema) => schema, } } pub fn into_schema(self) -> SchemaContainer { match self { - IntrospectionResponse::FullResponse(full_response) => full_response.data, - IntrospectionResponse::Schema(schema) => schema, + Self::FullResponse(full_response) => full_response.data, + Self::Schema(schema) => schema, } } } diff --git a/graphql_client/src/lib.rs b/graphql_client/src/lib.rs index bc3d1a85..5ebfd679 100644 --- a/graphql_client/src/lib.rs +++ b/graphql_client/src/lib.rs @@ -122,8 +122,8 @@ pub enum PathFragment { impl Display for PathFragment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - PathFragment::Key(ref key) => write!(f, "{key}"), - PathFragment::Index(ref idx) => write!(f, "{idx}"), + Self::Key(ref key) => write!(f, "{key}"), + Self::Index(ref idx) => write!(f, "{idx}"), } } } diff --git a/graphql_client_cli/src/error.rs b/graphql_client_cli/src/error.rs index feb682c2..488077eb 100644 --- a/graphql_client_cli/src/error.rs +++ b/graphql_client_cli/src/error.rs @@ -9,7 +9,7 @@ pub struct Error { impl Error { #[track_caller] pub fn message(msg: String) -> Self { - Error { + Self { source: None, message: Some(msg), location: std::panic::Location::caller(), @@ -21,7 +21,7 @@ impl Error { source: impl std::error::Error + Send + Sync + 'static, message: String, ) -> Self { - let mut err = Error::message(message); + let mut err = Self::message(message); err.source = Some(Box::new(source)); err } @@ -56,7 +56,7 @@ where { #[track_caller] fn from(err: T) -> Self { - Error { + Self { message: None, source: Some(Box::new(err)), location: std::panic::Location::caller(), diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index 6b6677dd..33b58c75 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -91,7 +91,7 @@ impl<'a> VariantSelection<'a> { selection: &'a Selection, type_id: TypeId, query: &BoundQuery<'a>, - ) -> Option> { + ) -> Option { match selection { Selection::InlineFragment(inline_fragment) => { Some(VariantSelection::InlineFragment(inline_fragment)) diff --git a/graphql_client_codegen/src/codegen_options.rs b/graphql_client_codegen/src/codegen_options.rs index 006ae727..f473a717 100644 --- a/graphql_client_codegen/src/codegen_options.rs +++ b/graphql_client_codegen/src/codegen_options.rs @@ -53,8 +53,8 @@ pub struct GraphQLClientCodegenOptions { impl GraphQLClientCodegenOptions { /// Creates an empty options object with default params. It probably wants to be configured. - pub fn new(mode: CodegenMode) -> GraphQLClientCodegenOptions { - GraphQLClientCodegenOptions { + pub fn new(mode: CodegenMode) -> Self { + Self { mode, variables_derives: Default::default(), response_derives: Default::default(), diff --git a/graphql_client_codegen/src/deprecation.rs b/graphql_client_codegen/src/deprecation.rs index 4c5566c2..ca0bf7bd 100644 --- a/graphql_client_codegen/src/deprecation.rs +++ b/graphql_client_codegen/src/deprecation.rs @@ -24,9 +24,9 @@ impl std::str::FromStr for DeprecationStrategy { fn from_str(s: &str) -> Result { match s.trim() { - "allow" => Ok(DeprecationStrategy::Allow), - "deny" => Ok(DeprecationStrategy::Deny), - "warn" => Ok(DeprecationStrategy::Warn), + "allow" => Ok(Self::Allow), + "deny" => Ok(Self::Deny), + "warn" => Ok(Self::Warn), _ => Err(()), } } diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index 32c71cb8..ed476cf2 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -178,11 +178,11 @@ enum ReadFileError { impl Display for ReadFileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ReadFileError::FileNotFound { path, .. } => { + Self::FileNotFound { path, .. } => { write!(f, "Could not find file with path: {path}\n Hint: file paths in the GraphQLQuery attribute are relative to the project root (location of the Cargo.toml). Example: query_path = \"src/my_query.graphql\".") } - ReadFileError::ReadError { path, .. } => { + Self::ReadError { path, .. } => { f.write_str("Error reading file at: ")?; f.write_str(path) } @@ -193,8 +193,9 @@ impl Display for ReadFileError { impl std::error::Error for ReadFileError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - ReadFileError::FileNotFound { io_error, .. } - | ReadFileError::ReadError { io_error, .. } => Some(io_error), + Self::FileNotFound { io_error, .. } | Self::ReadError { io_error, .. } => { + Some(io_error) + } } } } diff --git a/graphql_client_codegen/src/normalization.rs b/graphql_client_codegen/src/normalization.rs index 90275d4e..dd3e20a4 100644 --- a/graphql_client_codegen/src/normalization.rs +++ b/graphql_client_codegen/src/normalization.rs @@ -56,8 +56,8 @@ impl std::str::FromStr for Normalization { fn from_str(s: &str) -> Result { match s.trim() { - "none" => Ok(Normalization::None), - "rust" => Ok(Normalization::Rust), + "none" => Ok(Self::None), + "rust" => Ok(Self::Rust), _ => Err(()), } } diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index a2f5fca2..dc84af6a 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -38,7 +38,7 @@ impl std::error::Error for QueryValidationError {} impl QueryValidationError { pub(crate) fn new(message: String) -> Self { - QueryValidationError { message } + Self { message } } } @@ -49,7 +49,7 @@ pub(crate) struct OperationId(u32); impl OperationId { pub(crate) fn new(idx: usize) -> Self { - OperationId(idx as u32) + Self(idx as u32) } } diff --git a/graphql_client_codegen/src/query/selection.rs b/graphql_client_codegen/src/query/selection.rs index 018e6f22..869457fa 100644 --- a/graphql_client_codegen/src/query/selection.rs +++ b/graphql_client_codegen/src/query/selection.rs @@ -78,11 +78,11 @@ pub(super) enum SelectionParent { impl SelectionParent { fn schema_type_id(&self, query: &BoundQuery<'_>) -> TypeId { match self { - SelectionParent::Fragment(fragment_id) => query.query.get_fragment(*fragment_id).on, - SelectionParent::Operation(operation_id) => { + Self::Fragment(fragment_id) => query.query.get_fragment(*fragment_id).on, + Self::Operation(operation_id) => { TypeId::Object(query.query.get_operation(*operation_id).object_id) } - SelectionParent::Field(id) => { + Self::Field(id) => { let field_id = query .query .get_selection(*id) @@ -91,7 +91,7 @@ impl SelectionParent { .field_id; query.schema.get_field(field_id).r#type.id } - SelectionParent::InlineFragment(id) => { + Self::InlineFragment(id) => { { query.query.get_selection(*id).as_inline_fragment().unwrap() }.type_id } } @@ -99,8 +99,7 @@ impl SelectionParent { pub(super) fn add_to_selection_set(&self, q: &mut Query, selection_id: SelectionId) { match self { - SelectionParent::Field(parent_selection_id) - | SelectionParent::InlineFragment(parent_selection_id) => { + Self::Field(parent_selection_id) | Self::InlineFragment(parent_selection_id) => { let parent_selection = q .selections .get_mut(parent_selection_id.0 as usize) @@ -112,7 +111,7 @@ impl SelectionParent { other => unreachable!("impossible parent selection: {:?}", other), } } - SelectionParent::Fragment(fragment_id) => { + Self::Fragment(fragment_id) => { let fragment = q .fragments .get_mut(fragment_id.0 as usize) @@ -120,7 +119,7 @@ impl SelectionParent { fragment.selection_set.push(selection_id); } - SelectionParent::Operation(operation_id) => { + Self::Operation(operation_id) => { let operation = q .operations .get_mut(operation_id.0 as usize) @@ -133,11 +132,11 @@ impl SelectionParent { pub(crate) fn to_path_segment(self, query: &BoundQuery<'_>) -> String { match self { - SelectionParent::Field(id) | SelectionParent::InlineFragment(id) => { + Self::Field(id) | Self::InlineFragment(id) => { query.query.get_selection(id).to_path_segment(query) } - SelectionParent::Operation(id) => query.query.get_operation(id).to_path_segment(), - SelectionParent::Fragment(id) => query.query.get_fragment(id).to_path_segment(), + Self::Operation(id) => query.query.get_operation(id).to_path_segment(), + Self::Fragment(id) => query.query.get_fragment(id).to_path_segment(), } } } @@ -153,21 +152,21 @@ pub(crate) enum Selection { impl Selection { pub(crate) fn as_selected_field(&self) -> Option<&SelectedField> { match self { - Selection::Field(f) => Some(f), + Self::Field(f) => Some(f), _ => None, } } pub(crate) fn as_inline_fragment(&self) -> Option<&InlineFragment> { match self { - Selection::InlineFragment(f) => Some(f), + Self::InlineFragment(f) => Some(f), _ => None, } } pub(crate) fn collect_used_types(&self, used_types: &mut UsedTypes, query: &BoundQuery<'_>) { match self { - Selection::Field(field) => { + Self::Field(field) => { let stored_field = query.schema.get_field(field.field_id); used_types.types.insert(stored_field.r#type.id); @@ -176,7 +175,7 @@ impl Selection { selection.collect_used_types(used_types, query); } } - Selection::InlineFragment(inline_fragment) => { + Self::InlineFragment(inline_fragment) => { used_types.types.insert(inline_fragment.type_id); for selection_id in self.subselection() { @@ -184,7 +183,7 @@ impl Selection { selection.collect_used_types(used_types, query); } } - Selection::FragmentSpread(fragment_id) => { + Self::FragmentSpread(fragment_id) => { // This is necessary to avoid infinite recursion. if used_types.fragments.contains(fragment_id) { return; @@ -198,13 +197,13 @@ impl Selection { selection.collect_used_types(used_types, query); } } - Selection::Typename => (), + Self::Typename => (), } } pub(crate) fn contains_fragment(&self, fragment_id: ResolvedFragmentId, query: &Query) -> bool { match self { - Selection::FragmentSpread(id) => *id == fragment_id, + Self::FragmentSpread(id) => *id == fragment_id, _ => self.subselection().iter().any(|selection_id| { query .get_selection(*selection_id) @@ -215,15 +214,15 @@ impl Selection { pub(crate) fn subselection(&self) -> &[SelectionId] { match self { - Selection::Field(field) => field.selection_set.as_slice(), - Selection::InlineFragment(inline_fragment) => &inline_fragment.selection_set, + Self::Field(field) => field.selection_set.as_slice(), + Self::InlineFragment(inline_fragment) => &inline_fragment.selection_set, _ => &[], } } pub(super) fn to_path_segment(&self, query: &BoundQuery<'_>) -> String { match self { - Selection::Field(field) => field + Self::Field(field) => field .alias .as_ref() .map(|alias| alias.to_upper_camel_case()) @@ -234,7 +233,7 @@ impl Selection { .name .to_upper_camel_case() }), - Selection::InlineFragment(inline_fragment) => format!( + Self::InlineFragment(inline_fragment) => format!( "On{}", inline_fragment .type_id diff --git a/graphql_client_codegen/src/schema.rs b/graphql_client_codegen/src/schema.rs index 00bc77ca..01292dab 100644 --- a/graphql_client_codegen/src/schema.rs +++ b/graphql_client_codegen/src/schema.rs @@ -98,68 +98,68 @@ pub(crate) enum TypeId { impl TypeId { fn r#enum(id: usize) -> Self { - TypeId::Enum(EnumId(id)) + Self::Enum(EnumId(id)) } fn interface(id: usize) -> Self { - TypeId::Interface(InterfaceId(id)) + Self::Interface(InterfaceId(id)) } fn union(id: usize) -> Self { - TypeId::Union(UnionId(id)) + Self::Union(UnionId(id)) } fn object(id: u32) -> Self { - TypeId::Object(ObjectId(id)) + Self::Object(ObjectId(id)) } fn input(id: u32) -> Self { - TypeId::Input(InputId(id)) + Self::Input(InputId(id)) } fn as_interface_id(&self) -> Option { match self { - TypeId::Interface(id) => Some(*id), + Self::Interface(id) => Some(*id), _ => None, } } fn as_object_id(&self) -> Option { match self { - TypeId::Object(id) => Some(*id), + Self::Object(id) => Some(*id), _ => None, } } pub(crate) fn as_input_id(&self) -> Option { match self { - TypeId::Input(id) => Some(*id), + Self::Input(id) => Some(*id), _ => None, } } pub(crate) fn as_scalar_id(&self) -> Option { match self { - TypeId::Scalar(id) => Some(*id), + Self::Scalar(id) => Some(*id), _ => None, } } pub(crate) fn as_enum_id(&self) -> Option { match self { - TypeId::Enum(id) => Some(*id), + Self::Enum(id) => Some(*id), _ => None, } } pub(crate) fn name<'a>(&self, schema: &'a Schema) -> &'a str { match self { - TypeId::Object(obj) => schema.get_object(*obj).name.as_str(), - TypeId::Scalar(s) => schema.get_scalar(*s).name.as_str(), - TypeId::Interface(s) => schema.get_interface(*s).name.as_str(), - TypeId::Union(s) => schema.get_union(*s).name.as_str(), - TypeId::Enum(s) => schema.get_enum(*s).name.as_str(), - TypeId::Input(s) => schema.get_input(*s).name.as_str(), + Self::Object(obj) => schema.get_object(*obj).name.as_str(), + Self::Scalar(s) => schema.get_scalar(*s).name.as_str(), + Self::Interface(s) => schema.get_interface(*s).name.as_str(), + Self::Union(s) => schema.get_union(*s).name.as_str(), + Self::Enum(s) => schema.get_enum(*s).name.as_str(), + Self::Input(s) => schema.get_input(*s).name.as_str(), } } } @@ -219,8 +219,8 @@ pub(crate) struct Schema { } impl Schema { - pub(crate) fn new() -> Schema { - let mut schema = Schema { + pub(crate) fn new() -> Self { + let mut schema = Self { stored_objects: Vec::new(), stored_interfaces: Vec::new(), stored_fields: Vec::new(), @@ -443,7 +443,7 @@ where T: graphql_parser::query::Text<'doc>, T::Value: AsRef, { - fn from(ast: graphql_parser::schema::Document<'doc, T>) -> Schema { + fn from(ast: graphql_parser::schema::Document<'doc, T>) -> Self { graphql_parser_conversion::build_schema(ast) } } diff --git a/graphql_client_codegen/src/type_qualifiers.rs b/graphql_client_codegen/src/type_qualifiers.rs index 972fdb54..4d231505 100644 --- a/graphql_client_codegen/src/type_qualifiers.rs +++ b/graphql_client_codegen/src/type_qualifiers.rs @@ -6,7 +6,7 @@ pub(crate) enum GraphqlTypeQualifier { impl GraphqlTypeQualifier { pub(crate) fn is_required(&self) -> bool { - *self == GraphqlTypeQualifier::Required + *self == Self::Required } } From 890979d0541c57a3e3337fb9cbfacff517a5b215 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:04:06 +0000 Subject: [PATCH 04/25] use semicolon if nothing returned (clippy::semicolon_if_nothing_returned) --- examples/web/src/lib.rs | 2 +- graphql_client/src/lib.rs | 6 +++--- graphql_client/tests/interfaces.rs | 2 +- graphql_client_codegen/src/codegen/selection.rs | 2 +- graphql_client_codegen/src/codegen_options.rs | 4 ++-- graphql_client_codegen/src/query.rs | 8 ++++---- graphql_client_codegen/src/schema/json_conversion.rs | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/examples/web/src/lib.rs b/examples/web/src/lib.rs index 57cd77ec..b8440b47 100644 --- a/examples/web/src/lib.rs +++ b/examples/web/src/lib.rs @@ -15,7 +15,7 @@ use wasm_bindgen_futures::future_to_promise; struct PuppySmiles; fn log(s: &str) { - web_sys::console::log_1(&JsValue::from_str(s)) + web_sys::console::log_1(&JsValue::from_str(s)); } lazy_static! { diff --git a/graphql_client/src/lib.rs b/graphql_client/src/lib.rs index 5ebfd679..93e3073d 100644 --- a/graphql_client/src/lib.rs +++ b/graphql_client/src/lib.rs @@ -328,7 +328,7 @@ mod tests { path: None, extensions: None, } - ) + ); } #[test] @@ -363,7 +363,7 @@ mod tests { ]), extensions: None, } - ) + ); } #[test] @@ -407,6 +407,6 @@ mod tests { ]), extensions: expected_extensions, } - ) + ); } } diff --git a/graphql_client/tests/interfaces.rs b/graphql_client/tests/interfaces.rs index 334dfef5..ba6db525 100644 --- a/graphql_client/tests/interfaces.rs +++ b/graphql_client/tests/interfaces.rs @@ -174,5 +174,5 @@ fn fragment_in_interface() { }, ]) } - ) + ); } diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index 33b58c75..091b375a 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -521,7 +521,7 @@ impl<'a> ExpandedSelection<'a> { } fn push_type_alias(&mut self, alias: TypeAlias<'a>) { - self.aliases.push(alias) + self.aliases.push(alias); } fn push_variant(&mut self, variant: ExpandedVariant<'a>) { diff --git a/graphql_client_codegen/src/codegen_options.rs b/graphql_client_codegen/src/codegen_options.rs index f473a717..621869cc 100644 --- a/graphql_client_codegen/src/codegen_options.rs +++ b/graphql_client_codegen/src/codegen_options.rs @@ -198,7 +198,7 @@ impl GraphQLClientCodegenOptions { /// Set the custom scalar definitions module pub fn set_custom_scalars_module(&mut self, module: syn::Path) { - self.custom_scalars_module = Some(module) + self.custom_scalars_module = Some(module); } /// Get the externally defined enums type names @@ -223,7 +223,7 @@ impl GraphQLClientCodegenOptions { /// Set the graphql client codegen option's skip none value. pub fn set_skip_serializing_none(&mut self, skip_serializing_none: bool) { - self.skip_serializing_none = skip_serializing_none + self.skip_serializing_none = skip_serializing_none; } /// Get a reference to the graphql client codegen option's skip none value. diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index dc84af6a..d2bb450c 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -75,10 +75,10 @@ where for definition in &query.definitions { match definition { graphql_parser::query::Definition::Fragment(fragment) => { - resolve_fragment(&mut resolved_query, schema, fragment)? + resolve_fragment(&mut resolved_query, schema, fragment)?; } graphql_parser::query::Definition::Operation(operation) => { - resolve_operation(&mut resolved_query, schema, operation)? + resolve_operation(&mut resolved_query, schema, operation)?; } } } @@ -96,7 +96,7 @@ where query: &resolved_query, schema, }, - )? + )?; } Ok(resolved_query) @@ -607,7 +607,7 @@ impl ResolvedVariable { let input = schema.get_input(input_id); - input.used_input_ids_recursive(used_types, schema) + input.used_input_ids_recursive(used_types, schema); } type_id @ TypeId::Scalar(_) | type_id @ TypeId::Enum(_) => { used_types.types.insert(type_id); diff --git a/graphql_client_codegen/src/schema/json_conversion.rs b/graphql_client_codegen/src/schema/json_conversion.rs index 18dea687..db8f06bb 100644 --- a/graphql_client_codegen/src/schema/json_conversion.rs +++ b/graphql_client_codegen/src/schema/json_conversion.rs @@ -50,7 +50,7 @@ fn convert(src: &mut JsonSchema, schema: &mut Schema) { } for enm in enums_mut(src) { - ingest_enum(schema, enm) + ingest_enum(schema, enm); } for interface in interfaces_mut(src) { @@ -62,7 +62,7 @@ fn convert(src: &mut JsonSchema, schema: &mut Schema) { } for unn in unions_mut(src) { - ingest_union(schema, unn) + ingest_union(schema, unn); } for input in inputs_mut(src) { From 3fbac33cfc2b2da2fea123b4f8ba5612a1d6e14f Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:06:00 +0000 Subject: [PATCH 05/25] remove explicit 'iter' loops (clippy::explicit_iter_loop) --- Cargo.lock | 75 +++---------------- .../src/introspection_schema.rs | 12 +-- graphql_client_codegen/src/query.rs | 4 +- .../src/query/validation.rs | 2 +- .../src/schema/graphql_parser_conversion.rs | 6 +- 5 files changed, 19 insertions(+), 80 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 461021eb..d7ba93aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -88,17 +88,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] - [[package]] name = "autocfg" version = "1.4.0" @@ -311,42 +300,19 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "env_filter" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" -dependencies = [ - "log", - "regex", -] - [[package]] name = "env_logger" -version = "0.5.13" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" dependencies = [ - "atty", - "humantime 1.3.0", + "humantime", + "is-terminal", "log", "regex", "termcolor", ] -[[package]] -name = "env_logger" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcaee3d8e3cfc3fd92428d477bc97fc29ec8716d180c0d74c643bb26166660e0" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "humantime 2.1.0", - "log", -] - [[package]] name = "equivalent" version = "1.0.1" @@ -511,8 +477,9 @@ dependencies = [ name = "graphql_client_cli" version = "0.14.0" dependencies = [ + "anstyle", "clap", - "env_logger 0.11.6", + "env_logger", "graphql_client", "graphql_client_codegen", "log", @@ -552,7 +519,7 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", - "env_logger 0.5.13", + "env_logger", "graphql_client", "log", "prettytable-rs", @@ -564,7 +531,7 @@ name = "graphql_query_hasura_example" version = "0.1.0" dependencies = [ "anyhow", - "env_logger 0.5.13", + "env_logger", "graphql_client", "log", "prettytable-rs", @@ -603,15 +570,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - [[package]] name = "hermit-abi" version = "0.4.0" @@ -658,15 +616,6 @@ version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2d708df4e7140240a16cd6ab0ab65c972d7433ab77819ea693fde9c43811e2a" -[[package]] -name = "humantime" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" -dependencies = [ - "quick-error", -] - [[package]] name = "humantime" version = "2.1.0" @@ -907,7 +856,7 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e19b23d53f35ce9f56aebc7d1bb4e6ac1e9c0db7ac85c8d1760c04379edced37" dependencies = [ - "hermit-abi 0.4.0", + "hermit-abi", "libc", "windows-sys 0.59.0", ] @@ -1138,12 +1087,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quinn" version = "0.11.6" diff --git a/graphql_client_cli/src/introspection_schema.rs b/graphql_client_cli/src/introspection_schema.rs index a9360bdb..8faf3127 100644 --- a/graphql_client_cli/src/introspection_schema.rs +++ b/graphql_client_cli/src/introspection_schema.rs @@ -151,14 +151,12 @@ mod tests { fn it_errors_invalid_headers() { // https://tools.ietf.org/html/rfc7230#section-3.2 - for input in [ + for input in &[ "X-Name Value", // error: colon required for name/value pair ": Value", // error: field name must be "X Name: Value", // error: no whitespace in field name "X\tName: Value", // error: no whitespace in field name (tab) - ] - .iter() - { + ] { let header = Header::from_str(input); assert!(header.is_err(), "Expected error: [{}]", input); @@ -178,7 +176,7 @@ mod tests { value: "Value:".to_string(), }; - for (input, expected) in [ + for (input, expected) in &[ ("X-Name: Value", &expected1), // ideal ("X-Name:Value", &expected1), // no optional whitespace ("X-Name: Value ", &expected1), // with optional whitespace @@ -187,9 +185,7 @@ mod tests { // not allowed per RFC, but we'll forgive ("X-Name : Value", &expected1), (" X-Name: Value", &expected1), - ] - .iter() - { + ] { let header = Header::from_str(input); assert!(header.is_ok(), "Expected ok: [{}]", input); diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index d2bb450c..dc289c5a 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -252,7 +252,7 @@ fn resolve_union_selection<'doc, T>( where T: graphql_parser::query::Text<'doc>, { - for item in selection_set.items.iter() { + for item in &selection_set.items { match item { graphql_parser::query::Selection::Field(field) => { if field.name.as_ref() == TYPENAME_FIELD { @@ -298,7 +298,7 @@ fn resolve_object_selection<'a, 'doc, T>( where T: graphql_parser::query::Text<'doc>, { - for item in selection_set.items.iter() { + for item in &selection_set.items { match item { graphql_parser::query::Selection::Field(field) => { if field.name.as_ref() == TYPENAME_FIELD { diff --git a/graphql_client_codegen/src/query/validation.rs b/graphql_client_codegen/src/query/validation.rs index ee0a48f5..6129aaf6 100644 --- a/graphql_client_codegen/src/query/validation.rs +++ b/graphql_client_codegen/src/query/validation.rs @@ -4,7 +4,7 @@ use crate::schema::TypeId; pub(super) fn validate_typename_presence( query: &BoundQuery<'_>, ) -> Result<(), QueryValidationError> { - for fragment in query.query.fragments.iter() { + for fragment in &query.query.fragments { let type_id = match fragment.on { id @ TypeId::Interface(_) | id @ TypeId::Union(_) => id, _ => continue, diff --git a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs index b235e7ae..f8617179 100644 --- a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs +++ b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs @@ -179,7 +179,7 @@ fn ingest_object<'doc, T>( .unwrap(); let mut field_ids = Vec::with_capacity(obj.fields.len()); - for field in obj.fields.iter_mut() { + for field in &mut obj.fields { let field = super::StoredField { name: field.name.as_ref().into(), r#type: resolve_field_type(schema, &field.field_type), @@ -216,7 +216,7 @@ fn ingest_object_type_extension<'doc, T>( .unwrap(); let mut field_ids = Vec::with_capacity(ext.fields.len()); - for field in ext.fields.iter_mut() { + for field in &mut ext.fields { let field = super::StoredField { name: field.name.as_ref().into(), r#type: resolve_field_type(schema, &field.field_type), @@ -285,7 +285,7 @@ fn ingest_interface<'doc, T>( let mut field_ids = Vec::with_capacity(interface.fields.len()); - for field in interface.fields.iter_mut() { + for field in &mut interface.fields { let field = super::StoredField { name: field.name.as_ref().into(), r#type: resolve_field_type(schema, &field.field_type), From 11d24944c46bce3e1f9c9c292fc01a2d8b471495 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:07:00 +0000 Subject: [PATCH 06/25] avoid cloning when you can copy (clippy::cloned_instead_of_copied) --- graphql_client/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphql_client/src/lib.rs b/graphql_client/src/lib.rs index 93e3073d..6b77ac1c 100644 --- a/graphql_client/src/lib.rs +++ b/graphql_client/src/lib.rs @@ -230,7 +230,7 @@ impl Display for Error { .locations .as_ref() .and_then(|locations| locations.iter().next()) - .cloned() + .copied() .unwrap_or_default(); write!(f, "{}:{}:{}: {}", path, loc.line, loc.column, self.message) From 47f7315e17b776e836306234ca91f337daaf8933 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:11:59 +0000 Subject: [PATCH 07/25] remove unnecessary semicolons (clippy::unnecessary_semicolons) --- graphql_client_cli/src/introspection_schema.rs | 2 +- graphql_client_codegen/src/codegen/selection.rs | 2 +- graphql_client_codegen/src/query.rs | 2 +- .../src/schema/graphql_parser_conversion.rs | 2 +- graphql_client_codegen/src/tests/mod.rs | 8 ++++---- graphql_query_derive/src/attributes.rs | 2 +- graphql_query_derive/src/lib.rs | 8 ++++---- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/graphql_client_cli/src/introspection_schema.rs b/graphql_client_cli/src/introspection_schema.rs index 8faf3127..26bd76fa 100644 --- a/graphql_client_cli/src/introspection_schema.rs +++ b/graphql_client_cli/src/introspection_schema.rs @@ -67,7 +67,7 @@ pub fn introspect_schema( if let Some(token) = authorization { req_builder = req_builder.bearer_auth(token.as_str()); - }; + } let res = req_builder.json(&request_body).send()?; diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index 091b375a..c755f34e 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -332,7 +332,7 @@ fn calculate_selection<'a>( ); } TypeId::Input(_) => unreachable!("field selection on input type"), - }; + } } Selection::Typename => (), Selection::InlineFragment(_inline) => (), diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index dc289c5a..20ea9212 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -390,7 +390,7 @@ where ))); } } - }; + } Ok(()) } diff --git a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs index f8617179..92141060 100644 --- a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs +++ b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs @@ -76,7 +76,7 @@ where .names .get("Subscription") .and_then(|id| id.as_object_id()); - }; + } } fn populate_names_map<'doc, T>(schema: &mut Schema, definitions: &[Definition<'doc, T>]) diff --git a/graphql_client_codegen/src/tests/mod.rs b/graphql_client_codegen/src/tests/mod.rs index b518ceaf..6e19d2e3 100644 --- a/graphql_client_codegen/src/tests/mod.rs +++ b/graphql_client_codegen/src/tests/mod.rs @@ -39,7 +39,7 @@ fn schema_with_keywords_works() { Err(e) => { panic!("Error: {}\n Generated content: {}\n", e, &generated_code); } - }; + } } #[test] @@ -67,7 +67,7 @@ fn fragments_other_variant_should_generate_unknown_other_variant() { Err(e) => { panic!("Error: {}\n Generated content: {}\n", e, &generated_code); } - }; + } } #[test] @@ -95,7 +95,7 @@ fn fragments_other_variant_false_should_not_generate_unknown_other_variant() { Err(e) => { panic!("Error: {}\n Generated content: {}\n", e, &generated_code); } - }; + } } #[test] @@ -123,5 +123,5 @@ fn skip_serializing_none_should_generate_serde_skip_serializing() { Err(e) => { panic!("Error: {}\n Generated content: {}\n", e, &generated_code); } - }; + } } diff --git a/graphql_query_derive/src/attributes.rs b/graphql_query_derive/src/attributes.rs index 51ef227f..c401d480 100644 --- a/graphql_query_derive/src/attributes.rs +++ b/graphql_query_derive/src/attributes.rs @@ -185,7 +185,7 @@ mod test { match extract_deprecation_strategy(&parsed) { Ok(_) => panic!("parsed unexpectedly"), Err(e) => assert_eq!(&format!("{e}"), DEPRECATION_ERROR), - }; + } } #[test] diff --git a/graphql_query_derive/src/lib.rs b/graphql_query_derive/src/lib.rs index a6038967..ee97193a 100644 --- a/graphql_query_derive/src/lib.rs +++ b/graphql_query_derive/src/lib.rs @@ -70,21 +70,21 @@ fn build_graphql_client_derive_options( if let Some(variables_derives) = variables_derives { options.set_variables_derives(variables_derives); - }; + } if let Some(response_derives) = response_derives { options.set_response_derives(response_derives); - }; + } // The user can determine what to do about deprecations. if let Ok(deprecation_strategy) = attributes::extract_deprecation_strategy(input) { options.set_deprecation_strategy(deprecation_strategy); - }; + } // The user can specify the normalization strategy. if let Ok(normalization) = attributes::extract_normalization(input) { options.set_normalization(normalization); - }; + } // The user can give a path to a module that provides definitions for the custom scalars. if let Some(custom_scalars_module) = custom_scalars_module { From fc7608589a178cd8392f74d63fe9dac964bda4ea Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:34:14 +0000 Subject: [PATCH 08/25] nest or patterns (clippy::unnested_or_patterns) --- graphql_client_codegen/src/query.rs | 2 +- graphql_client_codegen/src/query/validation.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/graphql_client_codegen/src/query.rs b/graphql_client_codegen/src/query.rs index 20ea9212..d64bc28e 100644 --- a/graphql_client_codegen/src/query.rs +++ b/graphql_client_codegen/src/query.rs @@ -609,7 +609,7 @@ impl ResolvedVariable { input.used_input_ids_recursive(used_types, schema); } - type_id @ TypeId::Scalar(_) | type_id @ TypeId::Enum(_) => { + type_id @ (TypeId::Scalar(_) | TypeId::Enum(_)) => { used_types.types.insert(type_id); } _ => (), diff --git a/graphql_client_codegen/src/query/validation.rs b/graphql_client_codegen/src/query/validation.rs index 6129aaf6..7bbc03c6 100644 --- a/graphql_client_codegen/src/query/validation.rs +++ b/graphql_client_codegen/src/query/validation.rs @@ -6,7 +6,7 @@ pub(super) fn validate_typename_presence( ) -> Result<(), QueryValidationError> { for fragment in &query.query.fragments { let type_id = match fragment.on { - id @ TypeId::Interface(_) | id @ TypeId::Union(_) => id, + id @ (TypeId::Interface(_) | TypeId::Union(_)) => id, _ => continue, }; @@ -25,7 +25,7 @@ pub(super) fn validate_typename_presence( .selections() .filter_map(|(selection_id, selection)| match selection { Selection::Field(field) => match query.schema.get_field(field.field_id).r#type.id { - id @ TypeId::Interface(_) | id @ TypeId::Union(_) => { + id @ (TypeId::Interface(_) | TypeId::Union(_)) => { Some((selection_id, id, &field.selection_set)) } _ => None, From f78c26c8c67f02916be1cc599cbb2f22c87ae2aa Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:35:30 +0000 Subject: [PATCH 09/25] use 'if let' rather than single match 'else' block (clippy::single_match_else) --- graphql_client_codegen/src/codegen.rs | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/graphql_client_codegen/src/codegen.rs b/graphql_client_codegen/src/codegen.rs index 5aff54c9..37d4d85b 100644 --- a/graphql_client_codegen/src/codegen.rs +++ b/graphql_client_codegen/src/codegen.rs @@ -326,17 +326,16 @@ where .map(|(name, r#type)| { let field_name = Ident::new(name, Span::call_site()); let provided_value = object_map.get(name); - match provided_value { - Some(default_value) => { - let value = graphql_parser_value_to_literal( - default_value, - r#type.id, - r#type.is_optional(), - query, - ); - quote!(#field_name: #value) - } - None => quote!(#field_name: None), + if let Some(default_value) = provided_value { + let value = graphql_parser_value_to_literal( + default_value, + r#type.id, + r#type.is_optional(), + query, + ); + quote!(#field_name: #value) + } else { + quote!(#field_name: None) } }) .collect(); From b4a69b7baa3ac230f23aed9fb58e155ac47cd0e0 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:41:58 +0000 Subject: [PATCH 10/25] collapse some 'if else' blocks --- .../src/query/validation.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/graphql_client_codegen/src/query/validation.rs b/graphql_client_codegen/src/query/validation.rs index 7bbc03c6..7a6071b0 100644 --- a/graphql_client_codegen/src/query/validation.rs +++ b/graphql_client_codegen/src/query/validation.rs @@ -5,9 +5,8 @@ pub(super) fn validate_typename_presence( query: &BoundQuery<'_>, ) -> Result<(), QueryValidationError> { for fragment in &query.query.fragments { - let type_id = match fragment.on { - id @ (TypeId::Interface(_) | TypeId::Union(_)) => id, - _ => continue, + let type_id @ (TypeId::Interface(_) | TypeId::Union(_)) = fragment.on else { + continue; }; if !selection_set_contains_type_name(fragment.on, &fragment.selection_set, query.query) { @@ -23,14 +22,15 @@ pub(super) fn validate_typename_presence( query .query .selections() - .filter_map(|(selection_id, selection)| match selection { - Selection::Field(field) => match query.schema.get_field(field.field_id).r#type.id { - id @ (TypeId::Interface(_) | TypeId::Union(_)) => { - Some((selection_id, id, &field.selection_set)) + .filter_map(|(selection_id, selection)| { + if let Selection::Field(field) = selection { + let field_type_id = query.schema.get_field(field.field_id).r#type.id; + + if matches!(field_type_id, TypeId::Interface(_) | TypeId::Union(_)) { + return Some((selection_id, field_type_id, &field.selection_set)); } - _ => None, - }, - _ => None, + } + None }); for selection in union_and_interface_field_selections { From 81abeb1dd58e62c4a680601d3c717f79e56a9902 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:44:52 +0000 Subject: [PATCH 11/25] remove needless raw string hashes (clippy::needless_raw_string_hashes) --- graphql_client_codegen/src/constants.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/graphql_client_codegen/src/constants.rs b/graphql_client_codegen/src/constants.rs index c051347f..1e4c84e4 100644 --- a/graphql_client_codegen/src/constants.rs +++ b/graphql_client_codegen/src/constants.rs @@ -1,13 +1,13 @@ pub(crate) const TYPENAME_FIELD: &str = "__typename"; -pub(crate) const MULTIPLE_SUBSCRIPTION_FIELDS_ERROR: &str = r##" +pub(crate) const MULTIPLE_SUBSCRIPTION_FIELDS_ERROR: &str = r" Multiple-field queries on the root subscription field are forbidden by the spec. See: https://github.com/facebook/graphql/blob/master/spec/Section%205%20--%20Validation.md#subscription-operation-definitions -"##; +"; /// Error message when a selection set is the root of a query. -pub(crate) const SELECTION_SET_AT_ROOT: &str = r#" +pub(crate) const SELECTION_SET_AT_ROOT: &str = r" Operations in queries must be named. Instead of this: @@ -33,4 +33,4 @@ query UserRepositories { } } } -"#; +"; From 72b4292acd12375c54c60154e9b1348184187485 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:47:07 +0000 Subject: [PATCH 12/25] remove wildcard imports (clippy::wildcard_imports) --- examples/github/examples/github.rs | 6 +++--- examples/hasura/examples/hasura.rs | 6 +++--- examples/web/src/lib.rs | 2 +- graphql_client_codegen/src/codegen.rs | 7 +++++-- graphql_client_codegen/src/codegen/selection.rs | 2 +- graphql_client_codegen/src/generated_module.rs | 4 ++-- graphql_client_codegen/src/lib.rs | 4 ++-- graphql_client_codegen/src/query/fragments.rs | 2 +- graphql_client_codegen/src/query/operations.rs | 2 +- .../src/schema/json_conversion.rs | 13 +++---------- 10 files changed, 22 insertions(+), 26 deletions(-) diff --git a/examples/github/examples/github.rs b/examples/github/examples/github.rs index 65874fe4..7c18ea18 100644 --- a/examples/github/examples/github.rs +++ b/examples/github/examples/github.rs @@ -1,9 +1,9 @@ use ::reqwest::blocking::Client; -use anyhow::*; +use anyhow::{format_err, Ok, Result}; use clap::Parser; use graphql_client::{reqwest::post_graphql_blocking as post_graphql, GraphQLQuery}; -use log::*; -use prettytable::*; +use log::info; +use prettytable::row; #[allow(clippy::upper_case_acronyms)] type URI = String; diff --git a/examples/hasura/examples/hasura.rs b/examples/hasura/examples/hasura.rs index 0fe9c467..59399339 100644 --- a/examples/hasura/examples/hasura.rs +++ b/examples/hasura/examples/hasura.rs @@ -1,7 +1,7 @@ use ::reqwest::blocking::Client; use graphql_client::{reqwest::post_graphql_blocking as post_graphql, GraphQLQuery}; -use log::*; -use prettytable::*; +use log::{error, info}; +use prettytable::row; type Bpchar = String; type Timestamptz = String; @@ -16,7 +16,7 @@ type Timestamptz = String; struct UpsertIssue; fn main() -> Result<(), anyhow::Error> { - use upsert_issue::{IssuesUpdateColumn::*, *}; + use upsert_issue::{IssuesInsertInput, IssuesUpdateColumn::*, Variables}; env_logger::init(); let v = Variables { diff --git a/examples/web/src/lib.rs b/examples/web/src/lib.rs index b8440b47..01b0b1a9 100644 --- a/examples/web/src/lib.rs +++ b/examples/web/src/lib.rs @@ -1,5 +1,5 @@ use graphql_client::{reqwest::post_graphql, GraphQLQuery}; -use lazy_static::*; +use lazy_static::lazy_static; use std::cell::RefCell; use std::sync::Mutex; use wasm_bindgen::prelude::*; diff --git a/graphql_client_codegen/src/codegen.rs b/graphql_client_codegen/src/codegen.rs index 37d4d85b..d6c92647 100644 --- a/graphql_client_codegen/src/codegen.rs +++ b/graphql_client_codegen/src/codegen.rs @@ -4,7 +4,10 @@ mod selection; mod shared; use crate::{ - query::*, + query::{ + all_used_types, operation_has_no_variables, walk_operation_variables, BoundQuery, + OperationId, ResolvedVariable, UsedTypes, + }, schema::{InputId, TypeId}, type_qualifiers::GraphqlTypeQualifier, GeneralError, GraphQLClientCodegenOptions, @@ -12,7 +15,7 @@ use crate::{ use heck::ToSnakeCase; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; -use selection::*; +use selection::render_response_data_fields; use std::collections::BTreeMap; /// The main code generation function. diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index c755f34e..6bf80ea9 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -14,7 +14,7 @@ use crate::{ type_qualifiers::GraphqlTypeQualifier, GraphQLClientCodegenOptions, }; -use heck::*; +use heck::ToSnakeCase; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use std::borrow::Cow; diff --git a/graphql_client_codegen/src/generated_module.rs b/graphql_client_codegen/src/generated_module.rs index b225d001..922364a1 100644 --- a/graphql_client_codegen/src/generated_module.rs +++ b/graphql_client_codegen/src/generated_module.rs @@ -1,9 +1,9 @@ use crate::{ - codegen_options::*, + codegen_options::CodegenMode, query::{BoundQuery, OperationId}, BoxError, }; -use heck::*; +use heck::ToSnakeCase; use proc_macro2::{Ident, Span, TokenStream}; use quote::quote; use std::{error::Error, fmt::Display}; diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index ed476cf2..92b34b82 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -4,9 +4,9 @@ //! Crate for Rust code generation from a GraphQL query, schema, and options. -use lazy_static::*; +use lazy_static::lazy_static; use proc_macro2::TokenStream; -use quote::*; +use quote::quote; use schema::Schema; mod codegen; diff --git a/graphql_client_codegen/src/query/fragments.rs b/graphql_client_codegen/src/query/fragments.rs index 9f5c73b2..832cd4b3 100644 --- a/graphql_client_codegen/src/query/fragments.rs +++ b/graphql_client_codegen/src/query/fragments.rs @@ -1,6 +1,6 @@ use super::{Query, ResolvedFragmentId, SelectionId}; use crate::schema::TypeId; -use heck::*; +use heck::ToUpperCamelCase; #[derive(Debug)] pub(crate) struct ResolvedFragment { diff --git a/graphql_client_codegen/src/query/operations.rs b/graphql_client_codegen/src/query/operations.rs index fe7149ac..cd0d1a95 100644 --- a/graphql_client_codegen/src/query/operations.rs +++ b/graphql_client_codegen/src/query/operations.rs @@ -1,6 +1,6 @@ use super::SelectionId; use crate::schema::ObjectId; -use heck::*; +use heck::ToUpperCamelCase; #[derive(Debug, Clone)] pub(crate) enum OperationType { diff --git a/graphql_client_codegen/src/schema/json_conversion.rs b/graphql_client_codegen/src/schema/json_conversion.rs index db8f06bb..9e2ab2bf 100644 --- a/graphql_client_codegen/src/schema/json_conversion.rs +++ b/graphql_client_codegen/src/schema/json_conversion.rs @@ -146,14 +146,7 @@ fn ingest_enum(schema: &mut Schema, enm: &mut FullType) { .as_mut() .expect("enm.enum_values.as_mut()") .iter_mut() - .map(|v| { - std::mem::take( - v.name - .as_mut() - .take() - .expect("variant.name.as_mut().take()"), - ) - }) + .map(|v| std::mem::take(v.name.as_mut().expect("variant.name.as_mut().take()"))) .collect(); let enm = super::StoredEnum { name, variants }; @@ -321,7 +314,7 @@ fn resolve_input_field_type( } fn json_type_qualifiers_depth(typeref: &mut TypeRef) -> usize { - use graphql_introspection_query::introspection_response::*; + use graphql_introspection_query::introspection_response::__TypeKind; match (typeref.kind.as_mut(), typeref.of_type.as_mut()) { (Some(__TypeKind::NON_NULL), Some(inner)) => 1 + json_type_qualifiers_depth(inner), @@ -333,7 +326,7 @@ fn json_type_qualifiers_depth(typeref: &mut TypeRef) -> usize { fn from_json_type_inner(schema: &mut Schema, inner: &mut TypeRef) -> super::StoredFieldType { use crate::type_qualifiers::GraphqlTypeQualifier; - use graphql_introspection_query::introspection_response::*; + use graphql_introspection_query::introspection_response::__TypeKind; let qualifiers_depth = json_type_qualifiers_depth(inner); let mut qualifiers = Vec::with_capacity(qualifiers_depth); From d43b2074f8a76af2e7f0f065f297e4a9da8de3d6 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:51:48 +0000 Subject: [PATCH 13/25] bump MSRV --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a78811b8..d348ccb3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,4 +12,4 @@ members = [ ] [workspace.package] -rust-version = "1.64.0" +rust-version = "1.79.0" From 0e9fb1ac66dc9dae6f3b8747c20beac8fa9bc492 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 09:52:26 +0000 Subject: [PATCH 14/25] flip unnecessary booleans (clippy::if_not_else) --- graphql_client_cli/src/generate.rs | 6 +++--- graphql_client_codegen/src/codegen.rs | 6 +++--- graphql_client_codegen/src/codegen/selection.rs | 6 +++--- graphql_client_codegen/src/codegen/shared.rs | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/graphql_client_cli/src/generate.rs b/graphql_client_cli/src/generate.rs index b783295a..7326b26e 100644 --- a/graphql_client_cli/src/generate.rs +++ b/graphql_client_cli/src/generate.rs @@ -94,10 +94,10 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> CliResult<()> { .map_err(|err| Error::message(format!("Error generating module code: {err}")))?; let generated_code = format!("{WARNING_SUPPRESSION}\n{gen}"); - let generated_code = if !no_formatting { - format(&generated_code)? - } else { + let generated_code = if no_formatting { generated_code + } else { + format(&generated_code)? }; let query_file_name: OsString = diff --git a/graphql_client_codegen/src/codegen.rs b/graphql_client_codegen/src/codegen.rs index d6c92647..318656fa 100644 --- a/graphql_client_codegen/src/codegen.rs +++ b/graphql_client_codegen/src/codegen.rs @@ -147,10 +147,10 @@ fn generate_variable_struct_field( let ident = Ident::new(&safe_name, Span::call_site()); let rename_annotation = shared::field_rename_annotation(&variable.name, &safe_name); let skip_serializing_annotation = if *options.skip_serializing_none() { - if variable.r#type.qualifiers.first() != Some(&GraphqlTypeQualifier::Required) { - Some(quote!(#[serde(skip_serializing_if = "Option::is_none")])) - } else { + if variable.r#type.qualifiers.first() == Some(&GraphqlTypeQualifier::Required) { None + } else { + Some(quote!(#[serde(skip_serializing_if = "Option::is_none")])) } } else { None diff --git a/graphql_client_codegen/src/codegen/selection.rs b/graphql_client_codegen/src/codegen/selection.rs index 6bf80ea9..8638d87e 100644 --- a/graphql_client_codegen/src/codegen/selection.rs +++ b/graphql_client_codegen/src/codegen/selection.rs @@ -598,7 +598,9 @@ impl<'a> ExpandedSelection<'a> { continue; } - let (on_field, on_enum) = if !on_variants.is_empty() { + let (on_field, on_enum) = if on_variants.is_empty() { + (None, None) + } else { let enum_name = Ident::new(&format!("{}On", ty.name), Span::call_site()); let on_field = quote!(#[serde(flatten)] pub on: #enum_name); @@ -612,8 +614,6 @@ impl<'a> ExpandedSelection<'a> { ); (Some(on_field), Some(on_enum)) - } else { - (None, None) }; let tokens = quote! { diff --git a/graphql_client_codegen/src/codegen/shared.rs b/graphql_client_codegen/src/codegen/shared.rs index 9bffe3bf..d209bbb5 100644 --- a/graphql_client_codegen/src/codegen/shared.rs +++ b/graphql_client_codegen/src/codegen/shared.rs @@ -24,10 +24,10 @@ pub(crate) fn keyword_replace<'a>(needle: impl Into>) -> Cow<'a, st /// the equivalent rust name, produces a serde annotation to map them during /// (de)serialization if it is necessary, otherwise an empty TokenStream. pub(crate) fn field_rename_annotation(graphql_name: &str, rust_name: &str) -> Option { - if graphql_name != rust_name { - Some(quote!(#[serde(rename = #graphql_name)])) - } else { + if graphql_name == rust_name { None + } else { + Some(quote!(#[serde(rename = #graphql_name)])) } } From 61880681ca9c2b42e9e8caf6968d640de7bf0061 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 11:21:29 +0000 Subject: [PATCH 15/25] remove redundant 'else' block (clippy::redundant_else) --- graphql_client_codegen/src/schema.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/graphql_client_codegen/src/schema.rs b/graphql_client_codegen/src/schema.rs index 01292dab..f4c6108e 100644 --- a/graphql_client_codegen/src/schema.rs +++ b/graphql_client_codegen/src/schema.rs @@ -381,11 +381,10 @@ impl StoredInputType { TypeId::Input(input_id) => { if used_types.types.contains(&type_id) { continue; - } else { - used_types.types.insert(type_id); - let input = schema.get_input(input_id); - input.used_input_ids_recursive(used_types, schema); } + used_types.types.insert(type_id); + let input = schema.get_input(input_id); + input.used_input_ids_recursive(used_types, schema); } TypeId::Enum(_) | TypeId::Scalar(_) => { used_types.types.insert(type_id); From cf1249803c08cd4a331c73fdebe5c85ccc8d0341 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 11:24:18 +0000 Subject: [PATCH 16/25] use 'assert' macro (clippy::manual_assert) --- graphql_client_cli/src/generate.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/graphql_client_cli/src/generate.rs b/graphql_client_cli/src/generate.rs index 7326b26e..da45ef20 100644 --- a/graphql_client_cli/src/generate.rs +++ b/graphql_client_cli/src/generate.rs @@ -138,12 +138,11 @@ fn format(code: &str) -> CliResult { let output = child.wait_with_output()?; - if !output.status.success() { - panic!( - "rustfmt error\n\n{}", - String::from_utf8_lossy(&output.stderr) - ); - } + assert!( + output.status.success(), + "rustfmt error\n\n{}", + String::from_utf8_lossy(&output.stderr) + ); Ok(String::from_utf8(output.stdout)?) } From 11714a623690f1fa75e7000c73574154b68b8cd4 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 31 Jan 2025 11:26:44 +0000 Subject: [PATCH 17/25] explicitly match unit values (clippy::ignored_unit_patterns) --- graphql_query_derive/src/attributes.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphql_query_derive/src/attributes.rs b/graphql_query_derive/src/attributes.rs index c401d480..888721d3 100644 --- a/graphql_query_derive/src/attributes.rs +++ b/graphql_query_derive/src/attributes.rs @@ -107,7 +107,7 @@ pub fn extract_deprecation_strategy( .to_lowercase() .as_str() .parse() - .map_err(|_| syn::Error::new_spanned(ast, DEPRECATION_ERROR.to_owned())) + .map_err(|()| syn::Error::new_spanned(ast, DEPRECATION_ERROR.to_owned())) } /// Get the deprecation from a struct attribute in the derive case. @@ -116,7 +116,7 @@ pub fn extract_normalization(ast: &syn::DeriveInput) -> Result bool { From 50c184b218f7b8f3166c0889c1b122ad4fcf6e39 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 07:33:28 +0000 Subject: [PATCH 18/25] remove some redundant closures (clippy::redundant_closure) --- graphql_client_codegen/src/codegen_options.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphql_client_codegen/src/codegen_options.rs b/graphql_client_codegen/src/codegen_options.rs index 621869cc..ce00ed8d 100644 --- a/graphql_client_codegen/src/codegen_options.rs +++ b/graphql_client_codegen/src/codegen_options.rs @@ -109,7 +109,7 @@ impl GraphQLClientCodegenOptions { .as_deref() .into_iter() .flat_map(|s| s.split(',')) - .map(|s| s.trim()); + .map(str::trim); std::iter::once("Serialize").chain(additional) } @@ -130,7 +130,7 @@ impl GraphQLClientCodegenOptions { .as_deref() .into_iter() .flat_map(|s| s.split(',')) - .map(|s| s.trim()) + .map(str::trim) } /// Comma-separated list of additional traits we want to derive for responses. From d52a52dc96d0ddee6460742c3aa41c8cdab2839d Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 07:39:13 +0000 Subject: [PATCH 19/25] remove use of 'lazy_static' (clippy::non_std_lazy_statics) --- Cargo.lock | 2 -- examples/web/Cargo.toml | 1 - examples/web/src/lib.rs | 6 ++---- graphql_client_codegen/Cargo.toml | 1 - graphql_client_codegen/src/lib.rs | 9 ++++----- 5 files changed, 6 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7ba93aa..377c7db3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -496,7 +496,6 @@ dependencies = [ "graphql-introspection-query", "graphql-parser", "heck", - "lazy_static", "proc-macro2", "quote", "serde", @@ -1899,7 +1898,6 @@ version = "0.1.0" dependencies = [ "graphql_client", "js-sys", - "lazy_static", "reqwest", "wasm-bindgen", "wasm-bindgen-futures", diff --git a/examples/web/Cargo.toml b/examples/web/Cargo.toml index ae65e942..eec87fb7 100644 --- a/examples/web/Cargo.toml +++ b/examples/web/Cargo.toml @@ -10,7 +10,6 @@ crate-type = ["cdylib", "rlib"] [dependencies] graphql_client = { path = "../../graphql_client", features = ["reqwest"] } wasm-bindgen = "^0.2" -lazy_static = "1.0.1" js-sys = "0.3.6" wasm-bindgen-futures = "0.4.18" reqwest = "0.12" diff --git a/examples/web/src/lib.rs b/examples/web/src/lib.rs index 01b0b1a9..d1a107f1 100644 --- a/examples/web/src/lib.rs +++ b/examples/web/src/lib.rs @@ -1,5 +1,4 @@ use graphql_client::{reqwest::post_graphql, GraphQLQuery}; -use lazy_static::lazy_static; use std::cell::RefCell; use std::sync::Mutex; use wasm_bindgen::prelude::*; @@ -18,9 +17,8 @@ fn log(s: &str) { web_sys::console::log_1(&JsValue::from_str(s)); } -lazy_static! { - static ref LAST_ENTRY: Mutex>> = Mutex::new(RefCell::new(None)); -} +static LAST_ENTRY: std::sync::LazyLock>>> = + std::sync::LazyLock::new(|| Mutex::new(RefCell::new(None))); async fn load_more() -> Result { let url = "https://www.graphqlhub.com/graphql"; diff --git a/graphql_client_codegen/Cargo.toml b/graphql_client_codegen/Cargo.toml index 8f30cbb4..3502cec6 100644 --- a/graphql_client_codegen/Cargo.toml +++ b/graphql_client_codegen/Cargo.toml @@ -11,7 +11,6 @@ edition = "2018" graphql-introspection-query = { version = "0.2.0", path = "../graphql-introspection-query" } graphql-parser = "0.4" heck = ">=0.4, <=0.5" -lazy_static = "1.3" proc-macro2 = { version = "^1.0", features = [] } quote = "^1.0" serde_json = "1.0" diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index 92b34b82..8bd21070 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -4,7 +4,6 @@ //! Crate for Rust code generation from a GraphQL query, schema, and options. -use lazy_static::lazy_static; use proc_macro2::TokenStream; use quote::quote; use schema::Schema; @@ -45,10 +44,10 @@ type BoxError = Box; type CacheMap = std::sync::Mutex>; type QueryDocument = graphql_parser::query::Document<'static, String>; -lazy_static! { - static ref SCHEMA_CACHE: CacheMap = CacheMap::default(); - static ref QUERY_CACHE: CacheMap<(String, QueryDocument)> = CacheMap::default(); -} +static SCHEMA_CACHE: std::sync::LazyLock> = + std::sync::LazyLock::new(CacheMap::default); +static QUERY_CACHE: std::sync::LazyLock> = + std::sync::LazyLock::new(CacheMap::default); fn get_set_cached( cache: &CacheMap, From a65d465584d0a349ded1a5e6389df4c39f8016d3 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 07:51:35 +0000 Subject: [PATCH 20/25] bump msrv --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index d348ccb3..27fd4e9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,4 +12,4 @@ members = [ ] [workspace.package] -rust-version = "1.79.0" +rust-version = "1.80.1" From 6cf04770d41d0a5d81ae7b03843213c8c1737469 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 07:56:58 +0000 Subject: [PATCH 21/25] remove some needlessly mutable references (clippy::needless_pass_by_ref_mut) --- .../src/schema/graphql_parser_conversion.rs | 8 +++----- graphql_client_codegen/src/schema/json_conversion.rs | 9 +++------ 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs index 92141060..ccebded3 100644 --- a/graphql_client_codegen/src/schema/graphql_parser_conversion.rs +++ b/graphql_client_codegen/src/schema/graphql_parser_conversion.rs @@ -151,7 +151,7 @@ where }); } -fn ingest_union<'doc, T>(schema: &mut Schema, union: &mut UnionType<'doc, T>) +fn ingest_union<'doc, T>(schema: &mut Schema, union: &UnionType<'doc, T>) where T: graphql_parser::query::Text<'doc>, { @@ -238,10 +238,8 @@ fn ingest_object_type_extension<'doc, T>( object.fields.extend(field_ids); } -fn ingest_scalar<'doc, T>( - schema: &mut Schema, - scalar: &mut graphql_parser::schema::ScalarType<'doc, T>, -) where +fn ingest_scalar<'doc, T>(schema: &mut Schema, scalar: &graphql_parser::schema::ScalarType<'doc, T>) +where T: graphql_parser::query::Text<'doc>, { let name: String = scalar.name.as_ref().into(); diff --git a/graphql_client_codegen/src/schema/json_conversion.rs b/graphql_client_codegen/src/schema/json_conversion.rs index 9e2ab2bf..dd0f4041 100644 --- a/graphql_client_codegen/src/schema/json_conversion.rs +++ b/graphql_client_codegen/src/schema/json_conversion.rs @@ -297,14 +297,11 @@ fn ingest_input(schema: &mut Schema, input: &mut FullType) { schema.stored_inputs.push(input); } -fn resolve_field_type(schema: &mut Schema, typeref: &mut TypeRef) -> super::StoredFieldType { +fn resolve_field_type(schema: &Schema, typeref: &mut TypeRef) -> super::StoredFieldType { from_json_type_inner(schema, typeref) } -fn resolve_input_field_type( - schema: &mut Schema, - typeref: &mut TypeRef, -) -> super::StoredInputFieldType { +fn resolve_input_field_type(schema: &Schema, typeref: &mut TypeRef) -> super::StoredInputFieldType { let field_type = from_json_type_inner(schema, typeref); super::StoredInputFieldType { @@ -324,7 +321,7 @@ fn json_type_qualifiers_depth(typeref: &mut TypeRef) -> usize { } } -fn from_json_type_inner(schema: &mut Schema, inner: &mut TypeRef) -> super::StoredFieldType { +fn from_json_type_inner(schema: &Schema, inner: &mut TypeRef) -> super::StoredFieldType { use crate::type_qualifiers::GraphqlTypeQualifier; use graphql_introspection_query::introspection_response::__TypeKind; From 154d29d249ecee2a9b58b1e552fb2035ddc8a656 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 08:08:00 +0000 Subject: [PATCH 22/25] general refactoring --- graphql_client_cli/src/generate.rs | 2 +- graphql_client_codegen/src/lib.rs | 12 ++++++------ graphql_client_codegen/src/schema.rs | 15 ++++++--------- .../src/schema/json_conversion.rs | 4 ++-- graphql_client_codegen/src/tests/mod.rs | 8 ++++---- graphql_query_derive/src/lib.rs | 2 +- 6 files changed, 20 insertions(+), 23 deletions(-) diff --git a/graphql_client_cli/src/generate.rs b/graphql_client_cli/src/generate.rs index da45ef20..614a2f0f 100644 --- a/graphql_client_cli/src/generate.rs +++ b/graphql_client_cli/src/generate.rs @@ -90,7 +90,7 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> CliResult<()> { options.set_custom_scalars_module(custom_scalars_module); } - let gen = generate_module_token_stream(query_path.clone(), &schema_path, options) + let gen = generate_module_token_stream(&query_path, &schema_path, &options) .map_err(|err| Error::message(format!("Error generating module code: {err}")))?; let generated_code = format!("{WARNING_SUPPRESSION}\n{gen}"); diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index 8bd21070..4820194d 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -96,11 +96,11 @@ fn get_set_schema_from_file(schema_path: &std::path::Path) -> Schema { /// Generates Rust code given a path to a query file, a path to a schema file, and options. pub fn generate_module_token_stream( - query_path: std::path::PathBuf, + query_path: &std::path::Path, schema_path: &std::path::Path, - options: GraphQLClientCodegenOptions, + options: &GraphQLClientCodegenOptions, ) -> Result { - let query = get_set_query_from_file(query_path.as_path()); + let query = get_set_query_from_file(query_path); let schema = get_set_schema_from_file(schema_path); generate_module_token_stream_inner(&query, &schema, options) @@ -110,7 +110,7 @@ pub fn generate_module_token_stream( pub fn generate_module_token_stream_from_string( query_string: &str, schema_path: &std::path::Path, - options: GraphQLClientCodegenOptions, + options: &GraphQLClientCodegenOptions, ) -> Result { let query = (query_string.to_string(), query_document(query_string)?); let schema = get_set_schema_from_file(schema_path); @@ -122,7 +122,7 @@ pub fn generate_module_token_stream_from_string( fn generate_module_token_stream_inner( query: &(String, QueryDocument), schema: &Schema, - options: GraphQLClientCodegenOptions, + options: &GraphQLClientCodegenOptions, ) -> Result { let (query_string, query_document) = query; @@ -157,7 +157,7 @@ fn generate_module_token_stream_inner( schema, resolved_query: &query, operation: &operation.1.name, - options: &options, + options, } .to_token_stream()?; modules.push(generated); diff --git a/graphql_client_codegen/src/schema.rs b/graphql_client_codegen/src/schema.rs index f4c6108e..f3e136a6 100644 --- a/graphql_client_codegen/src/schema.rs +++ b/graphql_client_codegen/src/schema.rs @@ -362,15 +362,12 @@ impl Schema { } fn find_type_id(&self, type_name: &str) -> TypeId { - match self.names.get(type_name) { - Some(id) => *id, - None => { - panic!( - "graphql-client-codegen internal error: failed to resolve TypeId for `{}°.", - type_name - ); - } - } + self.names.get(type_name).copied().unwrap_or_else(|| { + panic!( + "graphql-client-codegen internal error: failed to resolve TypeId for `{}°.", + type_name + ) + }) } } diff --git a/graphql_client_codegen/src/schema/json_conversion.rs b/graphql_client_codegen/src/schema/json_conversion.rs index dd0f4041..4033bbfb 100644 --- a/graphql_client_codegen/src/schema/json_conversion.rs +++ b/graphql_client_codegen/src/schema/json_conversion.rs @@ -172,7 +172,7 @@ fn ingest_interface(schema: &mut Schema, iface: &mut FullType) { schema, &mut field.type_.as_mut().expect("take field type").type_ref, ), - deprecation: if let Some(true) = field.is_deprecated { + deprecation: if field.is_deprecated == Some(true) { Some(field.deprecation_reason.clone()) } else { None @@ -207,7 +207,7 @@ fn ingest_object(schema: &mut Schema, object: &mut FullType) { schema, &mut field.type_.as_mut().expect("take field type").type_ref, ), - deprecation: if let Some(true) = field.is_deprecated { + deprecation: if field.is_deprecated == Some(true) { Some(field.deprecation_reason.clone()) } else { None diff --git a/graphql_client_codegen/src/tests/mod.rs b/graphql_client_codegen/src/tests/mod.rs index 6e19d2e3..496fd43c 100644 --- a/graphql_client_codegen/src/tests/mod.rs +++ b/graphql_client_codegen/src/tests/mod.rs @@ -23,7 +23,7 @@ fn schema_with_keywords_works() { let options = GraphQLClientCodegenOptions::new(CodegenMode::Cli); let generated_tokens = - generate_module_token_stream_from_string(query_string, &schema_path, options) + generate_module_token_stream_from_string(query_string, &schema_path, &options) .expect("Generate keywords module"); let generated_code = generated_tokens.to_string(); @@ -52,7 +52,7 @@ fn fragments_other_variant_should_generate_unknown_other_variant() { options.set_fragments_other_variant(true); let generated_tokens = - generate_module_token_stream_from_string(query_string, &schema_path, options) + generate_module_token_stream_from_string(query_string, &schema_path, &options) .expect("Generate foobars module"); let generated_code = generated_tokens.to_string(); @@ -80,7 +80,7 @@ fn fragments_other_variant_false_should_not_generate_unknown_other_variant() { options.set_fragments_other_variant(false); let generated_tokens = - generate_module_token_stream_from_string(query_string, &schema_path, options) + generate_module_token_stream_from_string(query_string, &schema_path, &options) .expect("Generate foobars module token stream"); let generated_code = generated_tokens.to_string(); @@ -108,7 +108,7 @@ fn skip_serializing_none_should_generate_serde_skip_serializing() { options.set_skip_serializing_none(true); let generated_tokens = - generate_module_token_stream_from_string(query_string, &schema_path, options) + generate_module_token_stream_from_string(query_string, &schema_path, &options) .expect("Generate foobars module"); let generated_code = generated_tokens.to_string(); diff --git a/graphql_query_derive/src/lib.rs b/graphql_query_derive/src/lib.rs index ee97193a..dcb320f0 100644 --- a/graphql_query_derive/src/lib.rs +++ b/graphql_query_derive/src/lib.rs @@ -29,7 +29,7 @@ fn graphql_query_derive_inner( let (query_path, schema_path) = build_query_and_schema_path(&ast)?; let options = build_graphql_client_derive_options(&ast, query_path.clone())?; - generate_module_token_stream(query_path, &schema_path, options) + generate_module_token_stream(&query_path, &schema_path, &options) .map(Into::into) .map_err(|err| { syn::Error::new_spanned(ast, format!("Failed to generate GraphQLQuery impl: {err}")) From 2ec7fc96b90b310a52c9008f3069c49e72c5c0a0 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 19:51:07 +0000 Subject: [PATCH 23/25] deglob another import --- examples/hasura/examples/hasura.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/hasura/examples/hasura.rs b/examples/hasura/examples/hasura.rs index 59399339..5f20f2fd 100644 --- a/examples/hasura/examples/hasura.rs +++ b/examples/hasura/examples/hasura.rs @@ -16,7 +16,11 @@ type Timestamptz = String; struct UpsertIssue; fn main() -> Result<(), anyhow::Error> { - use upsert_issue::{IssuesInsertInput, IssuesUpdateColumn::*, Variables}; + use upsert_issue::{ + IssuesInsertInput, + IssuesUpdateColumn::{Name, SalesforceUpdatedAt, Status}, + Variables, + }; env_logger::init(); let v = Variables { From bacc0116f8c4e804d73246543e7344779313019a Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 2 Feb 2025 19:55:45 +0000 Subject: [PATCH 24/25] remove unnecessary wraps (clippy::unnecessary_wraps) --- graphql_client_codegen/src/codegen.rs | 10 ++++------ graphql_client_codegen/src/generated_module.rs | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/graphql_client_codegen/src/codegen.rs b/graphql_client_codegen/src/codegen.rs index 318656fa..d12cf0a4 100644 --- a/graphql_client_codegen/src/codegen.rs +++ b/graphql_client_codegen/src/codegen.rs @@ -10,7 +10,7 @@ use crate::{ }, schema::{InputId, TypeId}, type_qualifiers::GraphqlTypeQualifier, - GeneralError, GraphQLClientCodegenOptions, + GraphQLClientCodegenOptions, }; use heck::ToSnakeCase; use proc_macro2::{Ident, Span, TokenStream}; @@ -23,7 +23,7 @@ pub(crate) fn response_for_query( operation_id: OperationId, options: &GraphQLClientCodegenOptions, query: BoundQuery<'_>, -) -> Result { +) -> TokenStream { let serde = options.serde_path(); let all_used_types = all_used_types(operation_id, &query); @@ -47,7 +47,7 @@ pub(crate) fn response_for_query( let definitions = render_response_data_fields(operation_id, options, &query).render(&response_derives); - let q = quote! { + quote! { use #serde::{Serialize, Deserialize}; use super::*; @@ -71,9 +71,7 @@ pub(crate) fn response_for_query( #(#fragment_definitions)* #definitions - }; - - Ok(q) + } } fn generate_variables_struct( diff --git a/graphql_client_codegen/src/generated_module.rs b/graphql_client_codegen/src/generated_module.rs index 922364a1..1844d0a4 100644 --- a/graphql_client_codegen/src/generated_module.rs +++ b/graphql_client_codegen/src/generated_module.rs @@ -42,7 +42,7 @@ impl GeneratedModule<'_> { query: self.resolved_query, schema: self.schema, }, - )?) + )) } fn root(&self) -> Result { From d2f53d0bad9649b3b2fc8fdf89b82b8e8f28f091 Mon Sep 17 00:00:00 2001 From: "daniel.eades" Date: Fri, 7 Feb 2025 14:25:20 +0000 Subject: [PATCH 25/25] minor refactoring --- graphql_client_codegen/src/generated_module.rs | 10 ++++++---- graphql_client_codegen/src/lib.rs | 3 +-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/graphql_client_codegen/src/generated_module.rs b/graphql_client_codegen/src/generated_module.rs index 1844d0a4..2083216f 100644 --- a/graphql_client_codegen/src/generated_module.rs +++ b/graphql_client_codegen/src/generated_module.rs @@ -15,9 +15,11 @@ struct OperationNotFound { impl Display for OperationNotFound { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Could not find an operation named ")?; - f.write_str(&self.operation_name)?; - f.write_str(" in the query document.") + write!( + f, + "Could not find an operation named {} in the query document.", + &self.operation_name, + ) } } @@ -78,7 +80,7 @@ impl GeneratedModule<'_> { let query_string = &self.query_string; let impls = self.build_impls()?; - let struct_declaration: Option<_> = match self.options.mode { + let struct_declaration = match self.options.mode { CodegenMode::Cli => Some(quote!(#module_visibility struct #operation_name_ident;)), // The struct is already present in derive mode. CodegenMode::Derive => None, diff --git a/graphql_client_codegen/src/lib.rs b/graphql_client_codegen/src/lib.rs index 4820194d..4634ee3d 100644 --- a/graphql_client_codegen/src/lib.rs +++ b/graphql_client_codegen/src/lib.rs @@ -182,8 +182,7 @@ impl Display for ReadFileError { Hint: file paths in the GraphQLQuery attribute are relative to the project root (location of the Cargo.toml). Example: query_path = \"src/my_query.graphql\".") } Self::ReadError { path, .. } => { - f.write_str("Error reading file at: ")?; - f.write_str(path) + write!(f, "Error reading file at: {path}") } } }