Skip to content

Commit 32cd3c7

Browse files
authored
Merge pull request #324 from graphql-rust/drop-anyhow
Drop anyhow
2 parents 8dded1c + 9f86113 commit 32cd3c7

File tree

12 files changed

+204
-119
lines changed

12 files changed

+204
-119
lines changed

graphql_client_cli/src/generate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> Result<()> {
5959
options.set_deprecation_strategy(deprecation_strategy);
6060
}
6161

62-
let gen = generate_module_token_stream(query_path.clone(), &schema_path, options)?;
62+
let gen = generate_module_token_stream(query_path.clone(), &schema_path, options).unwrap();
6363

6464
let generated_code = gen.to_string();
6565
let generated_code = if cfg!(feature = "rustfmt") && !no_formatting {

graphql_client_cli/src/introspect_schema.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::format_err;
1+
use anyhow::*;
22
use graphql_client::GraphQLQuery;
33
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE};
44
use std::path::PathBuf;

graphql_client_codegen/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ repository = "https://github.com/graphql-rust/graphql-client"
88
edition = "2018"
99

1010
[dependencies]
11-
anyhow = "1.0"
1211
graphql-introspection-query = { version = "0.1.0", path = "../graphql-introspection-query" }
1312
graphql-parser = "^0.2"
1413
heck = "0.3"

graphql_client_codegen/src/codegen.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::{
77
query::*,
88
schema::{InputId, TypeId},
99
type_qualifiers::GraphqlTypeQualifier,
10-
GraphQLClientCodegenOptions,
10+
GeneralError, GraphQLClientCodegenOptions,
1111
};
1212
use heck::SnakeCase;
1313
use proc_macro2::{Ident, Span, TokenStream};
@@ -20,7 +20,7 @@ pub(crate) fn response_for_query(
2020
operation_id: OperationId,
2121
options: &GraphQLClientCodegenOptions,
2222
query: BoundQuery<'_>,
23-
) -> anyhow::Result<TokenStream> {
23+
) -> Result<TokenStream, GeneralError> {
2424
let all_used_types = all_used_types(operation_id, &query);
2525
let response_derives = render_derives(options.all_response_derives());
2626
let variable_derives = render_derives(options.all_variable_derives());

graphql_client_codegen/src/generated_module.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
use crate::{
22
codegen_options::*,
33
query::{BoundQuery, OperationId},
4+
BoxError,
45
};
56
use heck::*;
67
use proc_macro2::{Ident, Span, TokenStream};
78
use quote::quote;
9+
use thiserror::Error;
10+
11+
#[derive(Debug, Error)]
12+
#[error(
13+
"Could not find an operation named {} in the query document.",
14+
operation_name
15+
)]
16+
struct OperationNotFound {
17+
operation_name: String,
18+
}
819

920
/// This struct contains the parameters necessary to generate code for a given operation.
1021
pub(crate) struct GeneratedModule<'a> {
@@ -17,7 +28,7 @@ pub(crate) struct GeneratedModule<'a> {
1728

1829
impl<'a> GeneratedModule<'a> {
1930
/// Generate the items for the variables and the response that will go inside the module.
20-
fn build_impls(&self) -> anyhow::Result<TokenStream> {
31+
fn build_impls(&self) -> Result<TokenStream, BoxError> {
2132
Ok(crate::codegen::response_for_query(
2233
self.root()?,
2334
&self.options,
@@ -28,21 +39,18 @@ impl<'a> GeneratedModule<'a> {
2839
)?)
2940
}
3041

31-
fn root(&self) -> anyhow::Result<OperationId> {
42+
fn root(&self) -> Result<OperationId, OperationNotFound> {
3243
let op_name = self.options.normalization().operation(self.operation);
3344
self.resolved_query
3445
.select_operation(&op_name, *self.options.normalization())
3546
.map(|op| op.0)
36-
.ok_or_else(|| {
37-
anyhow::anyhow!(
38-
"Could not find an operation named {} in the query document.",
39-
op_name
40-
)
47+
.ok_or_else(|| OperationNotFound {
48+
operation_name: op_name.into(),
4149
})
4250
}
4351

4452
/// Generate the module and all the code inside.
45-
pub(crate) fn to_token_stream(&self) -> anyhow::Result<TokenStream> {
53+
pub(crate) fn to_token_stream(&self) -> Result<TokenStream, BoxError> {
4654
let module_name = Ident::new(&self.operation.to_snake_case(), Span::call_site());
4755
let module_visibility = &self.options.module_visibility();
4856
let operation_name = self.operation;
@@ -76,6 +84,8 @@ impl<'a> GeneratedModule<'a> {
7684
#module_visibility mod #module_name {
7785
#![allow(dead_code)]
7886

87+
use std::result::Result;
88+
7989
pub const OPERATION_NAME: &'static str = #operation_name;
8090
pub const QUERY: &'static str = #query_string;
8191

graphql_client_codegen/src/lib.rs

Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
//!
77
//! It is not meant to be used directly by users of the library.
88
9-
use anyhow::format_err;
109
use lazy_static::*;
1110
use proc_macro2::TokenStream;
1211
use quote::*;
@@ -30,8 +29,14 @@ mod tests;
3029

3130
pub use crate::codegen_options::{CodegenMode, GraphQLClientCodegenOptions};
3231

33-
use std::collections::HashMap;
32+
use std::{collections::HashMap, io};
33+
use thiserror::Error;
3434

35+
#[derive(Debug, Error)]
36+
#[error("{0}")]
37+
struct GeneralError(String);
38+
39+
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
3540
type CacheMap<T> = std::sync::Mutex<HashMap<std::path::PathBuf, T>>;
3641

3742
lazy_static! {
@@ -45,7 +50,7 @@ pub fn generate_module_token_stream(
4550
query_path: std::path::PathBuf,
4651
schema_path: &std::path::Path,
4752
options: GraphQLClientCodegenOptions,
48-
) -> anyhow::Result<TokenStream> {
53+
) -> Result<TokenStream, BoxError> {
4954
use std::collections::hash_map;
5055

5156
let schema_extension = schema_path
@@ -62,14 +67,14 @@ pub fn generate_module_token_stream(
6267
let schema_string = read_file(v.key())?;
6368
let schema = match schema_extension {
6469
"graphql" | "gql" => {
65-
let s = graphql_parser::schema::parse_schema(&schema_string).map_err(|parser_error| anyhow::anyhow!("Parser error: {}", parser_error))?;
70+
let s = graphql_parser::schema::parse_schema(&schema_string).map_err(|parser_error| GeneralError(format!("Parser error: {}", parser_error)))?;
6671
schema::Schema::from(s)
6772
}
6873
"json" => {
6974
let parsed: graphql_introspection_query::introspection_response::IntrospectionResponse = serde_json::from_str(&schema_string)?;
7075
schema::Schema::from(parsed)
7176
}
72-
extension => panic!("Unsupported extension for the GraphQL schema: {} (only .json and .graphql are supported)", extension)
77+
extension => return Err(GeneralError(format!("Unsupported extension for the GraphQL schema: {} (only .json and .graphql are supported)", extension)).into())
7378
};
7479

7580
v.insert(schema).clone()
@@ -85,7 +90,7 @@ pub fn generate_module_token_stream(
8590
hash_map::Entry::Vacant(v) => {
8691
let query_string = read_file(v.key())?;
8792
let query = graphql_parser::parse_query(&query_string)
88-
.map_err(|err| anyhow::anyhow!("Query parser error: {}", err))?;
93+
.map_err(|err| GeneralError(format!("Query parser error: {}", err)))?;
8994
v.insert((query_string, query)).clone()
9095
}
9196
}
@@ -104,10 +109,11 @@ pub fn generate_module_token_stream(
104109
(Some(ops), _) => ops,
105110
(None, &CodegenMode::Cli) => query.operations().collect(),
106111
(None, &CodegenMode::Derive) => {
107-
return Err(derive_operation_not_found_error(
112+
return Err(GeneralError(derive_operation_not_found_error(
108113
options.struct_ident(),
109114
&query,
110-
));
115+
))
116+
.into());
111117
}
112118
};
113119

@@ -131,30 +137,49 @@ pub fn generate_module_token_stream(
131137
Ok(modules)
132138
}
133139

134-
fn read_file(path: &std::path::Path) -> anyhow::Result<String> {
140+
#[derive(Debug, Error)]
141+
enum ReadFileError {
142+
#[error(
143+
"Could not find file with path: {}\
144+
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\".",
145+
path
146+
)]
147+
FileNotFound {
148+
path: String,
149+
#[source]
150+
io_error: io::Error,
151+
},
152+
#[error("Error reading file at: {}", path)]
153+
ReadError {
154+
path: String,
155+
#[source]
156+
io_error: io::Error,
157+
},
158+
}
159+
160+
fn read_file(path: &std::path::Path) -> Result<String, ReadFileError> {
135161
use std::fs;
136162
use std::io::prelude::*;
137163

138164
let mut out = String::new();
139-
let mut file = fs::File::open(path).map_err(|io_err| {
140-
let err: anyhow::Error = io_err.into();
141-
err.context(format!(
142-
r#"
143-
Could not find file with path: {}
144-
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".
145-
"#,
146-
path.display()
147-
))
165+
let mut file = fs::File::open(path).map_err(|io_error| ReadFileError::FileNotFound {
166+
io_error,
167+
path: path.display().to_string(),
148168
})?;
149-
file.read_to_string(&mut out)?;
169+
170+
file.read_to_string(&mut out)
171+
.map_err(|io_error| ReadFileError::ReadError {
172+
io_error,
173+
path: path.display().to_string(),
174+
})?;
150175
Ok(out)
151176
}
152177

153178
/// In derive mode, build an error when the operation with the same name as the struct is not found.
154179
fn derive_operation_not_found_error(
155180
ident: Option<&proc_macro2::Ident>,
156181
query: &crate::query::Query,
157-
) -> anyhow::Error {
182+
) -> String {
158183
let operation_name = ident.map(ToString::to_string);
159184
let struct_ident = operation_name.as_deref().unwrap_or("");
160185

@@ -164,7 +189,7 @@ fn derive_operation_not_found_error(
164189
.collect();
165190
let available_operations: String = available_operations.join(", ");
166191

167-
return format_err!(
192+
return format!(
168193
"The struct name does not match any defined operation in the query file.\nStruct name: {}\nDefined operations: {}",
169194
struct_ident,
170195
available_operations,

0 commit comments

Comments
 (0)