Skip to content

Switch all examples and crates to anyhow #319

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ A typed GraphQL client library for Rust.
)]
pub struct UnionQuery;

fn perform_my_query(variables: union_query::Variables) -> Result<(), failure::Error> {
fn perform_my_query(variables: union_query::Variables) -> Result<(), anyhow::Error> {

// this is the important line
let request_body = UnionQuery::build_query(variables);
Expand Down
2 changes: 1 addition & 1 deletion examples/github/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ authors = ["Tom Houlé <[email protected]>"]
edition = "2018"

[dev-dependencies]
failure = "*"
anyhow = "*"
graphql_client = { path = "../../graphql_client" }
serde = "^1.0"
reqwest = "^0.9"
Expand Down
6 changes: 3 additions & 3 deletions examples/github/examples/github.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use failure::*;
use anyhow::*;
use graphql_client::*;
use log::*;
use prettytable::*;
Expand Down Expand Up @@ -27,15 +27,15 @@ struct Env {
github_api_token: String,
}

fn parse_repo_name(repo_name: &str) -> Result<(&str, &str), failure::Error> {
fn parse_repo_name(repo_name: &str) -> Result<(&str, &str), anyhow::Error> {
let mut parts = repo_name.split('/');
match (parts.next(), parts.next()) {
(Some(owner), Some(name)) => Ok((owner, name)),
_ => Err(format_err!("wrong format for the repository name param (we expect something like facebook/graphql)"))
}
}

fn main() -> Result<(), failure::Error> {
fn main() -> Result<(), anyhow::Error> {
dotenv::dotenv().ok();
env_logger::init();

Expand Down
2 changes: 1 addition & 1 deletion examples/hasura/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ authors = ["Mark Catley <[email protected]>"]
edition = "2018"

[dev-dependencies]
failure = "*"
anyhow = "*"
graphql_client = { path = "../../graphql_client" }
serde = "1.0"
serde_derive = "1.0"
Expand Down
2 changes: 1 addition & 1 deletion examples/hasura/examples/hasura.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type Timestamptz = String;
)]
struct UpsertIssue;

fn main() -> Result<(), failure::Error> {
fn main() -> Result<(), anyhow::Error> {
use upsert_issue::{IssuesUpdateColumn::*, *};
dotenv::dotenv().ok();
env_logger::init();
Expand Down
6 changes: 4 additions & 2 deletions graphql_client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ edition = "2018"

[dependencies]
doc-comment = "^0.3"
failure = { version = "0.1", optional = true }
anyhow = { version = "1.0", optional = true }
thiserror = { version = "1.0", optional = true }
graphql_query_derive = { path = "../graphql_query_derive", version = "0.9.0" }
serde_json = "1.0"
serde = { version = "^1.0.78", features = ["derive"] }
Expand Down Expand Up @@ -56,7 +57,8 @@ wasm-bindgen-test = "^0.2"

[features]
web = [
"failure",
"anyhow",
"thiserror",
"futures",
"js-sys",
"log",
Expand Down
6 changes: 3 additions & 3 deletions graphql_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ doc_comment::doctest!("../../README.md");
/// )]
/// struct StarWarsQuery;
///
/// fn main() -> Result<(), failure::Error> {
/// fn main() -> Result<(), anyhow::Error> {
/// use graphql_client::GraphQLQuery;
///
/// let variables = star_wars_query::Variables {
Expand Down Expand Up @@ -130,7 +130,7 @@ impl Display for PathFragment {
/// # something: i32
/// # }
/// #
/// # fn main() -> Result<(), failure::Error> {
/// # fn main() -> Result<(), anyhow::Error> {
/// use graphql_client::*;
///
/// let body: Response<ResponseData> = serde_json::from_value(json!({
Expand Down Expand Up @@ -247,7 +247,7 @@ impl Display for Error {
/// # dogs: Vec<Dog>,
/// # }
/// #
/// # fn main() -> Result<(), failure::Error> {
/// # fn main() -> Result<(), anyhow::Error> {
/// use graphql_client::Response;
///
/// let body: Response<ResponseData> = serde_json::from_value(json!({
Expand Down
22 changes: 11 additions & 11 deletions graphql_client/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
//! [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen).

use crate::*;
use failure::*;
use futures::{Future, IntoFuture};
use log::*;
use std::collections::HashMap;
use thiserror::*;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;

Expand All @@ -24,33 +24,33 @@ pub struct Client {
/// All the ways a request can go wrong.
///
/// not exhaustive
#[derive(Debug, Fail, PartialEq)]
#[derive(Debug, Error, PartialEq)]
pub enum ClientError {
/// The body couldn't be built
#[fail(display = "Request body is not a valid string")]
#[error("Request body is not a valid string")]
Body,
/// An error caused by window.fetch
#[fail(display = "Network error")]
#[error("Network error")]
Network(String),
/// Error in a dynamic JS cast that should have worked
#[fail(display = "JS casting error")]
#[error("JS casting error")]
Cast,
/// No window object could be retrieved
#[fail(
display = "No Window object available - the client works only in a browser (non-worker) context"
#[error(
"No Window object available - the client works only in a browser (non-worker) context"
)]
NoWindow,
/// Response shape does not match the generated code
#[fail(display = "Response shape error")]
#[error("Response shape error")]
ResponseShape,
/// Response could not be converted to text
#[fail(display = "Response conversion to text failed (Response.text threw)")]
#[error("Response conversion to text failed (Response.text threw)")]
ResponseText,
/// Exception thrown when building the request
#[fail(display = "Error building the request")]
#[error("Error building the request")]
RequestError,
/// Other JS exception
#[fail(display = "Unexpected JS exception")]
#[error("Unexpected JS exception")]
JsException,
}

Expand Down
2 changes: 1 addition & 1 deletion graphql_client_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ name = "graphql-client"
path = "src/main.rs"

[dependencies]
failure = "^0.1"
anyhow = "1.0"
reqwest = "^0.9"
graphql_client = { version = "0.9.0", path = "../graphql_client" }
graphql_client_codegen = { path = "../graphql_client_codegen/", version = "0.9.0" }
Expand Down
6 changes: 3 additions & 3 deletions graphql_client_cli/src/generate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use failure::*;
use anyhow::*;
use graphql_client_codegen::{
generate_module_token_stream, CodegenMode, GraphQLClientCodegenOptions,
};
Expand All @@ -19,7 +19,7 @@ pub(crate) struct CliCodegenParams {
pub output_directory: Option<PathBuf>,
}

pub(crate) fn generate_code(params: CliCodegenParams) -> Result<(), failure::Error> {
pub(crate) fn generate_code(params: CliCodegenParams) -> Result<()> {
let CliCodegenParams {
variables_derives,
response_derives,
Expand Down Expand Up @@ -59,7 +59,7 @@ pub(crate) fn generate_code(params: CliCodegenParams) -> Result<(), failure::Err
options.set_deprecation_strategy(deprecation_strategy);
}

let gen = generate_module_token_stream(query_path.clone(), &schema_path, options)?;
let gen = generate_module_token_stream(query_path.clone(), &schema_path, options).map_err(|fail| fail.compat())?;

let generated_code = gen.to_string();
let generated_code = if cfg!(feature = "rustfmt") && !no_formatting {
Expand Down
6 changes: 3 additions & 3 deletions graphql_client_cli/src/introspect_schema.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use failure::format_err;
use anyhow::format_err;
use graphql_client::GraphQLQuery;
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE};
use std::path::PathBuf;
Expand All @@ -18,7 +18,7 @@ pub fn introspect_schema(
output: Option<PathBuf>,
authorization: Option<String>,
headers: Vec<Header>,
) -> Result<(), failure::Error> {
) -> anyhow::Result<()> {
use std::io::Write;

let out: Box<dyn Write> = match output {
Expand Down Expand Up @@ -73,7 +73,7 @@ pub struct Header {
}

impl FromStr for Header {
type Err = failure::Error;
type Err = anyhow::Error;

fn from_str(input: &str) -> Result<Self, Self::Err> {
// error: colon required for name/value pair
Expand Down
2 changes: 1 addition & 1 deletion graphql_client_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ enum Cli {
},
}

fn main() -> Result<(), failure::Error> {
fn main() -> anyhow::Result<()> {
set_env_logger();

let cli = Cli::from_args();
Expand Down
2 changes: 1 addition & 1 deletion graphql_query_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ edition = "2018"
proc-macro = true

[dependencies]
failure = "^0.1"
anyhow = "1.0"
syn = { version = "^1.0", features = ["extra-traits"] }
proc-macro2 = { version = "^1.0", features = [] }
graphql_client_codegen = { path = "../graphql_client_codegen/", version = "0.9.0" }
10 changes: 4 additions & 6 deletions graphql_query_derive/src/attributes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use failure::*;
use anyhow::*;
use graphql_client_codegen::deprecation::DeprecationStrategy;
use graphql_client_codegen::normalization::Normalization;
use syn;
Expand All @@ -12,7 +12,7 @@ fn path_to_match() -> syn::Path {
}

/// Extract an configuration parameter specified in the `graphql` attribute.
pub fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result<String, failure::Error> {
pub fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result<String> {
let attributes = &ast.attrs;
let graphql_path = path_to_match();
let attribute = attributes
Expand All @@ -38,9 +38,7 @@ pub fn extract_attr(ast: &syn::DeriveInput, attr: &str) -> Result<String, failur
}

/// Get the deprecation from a struct attribute in the derive case.
pub fn extract_deprecation_strategy(
ast: &syn::DeriveInput,
) -> Result<DeprecationStrategy, failure::Error> {
pub fn extract_deprecation_strategy(ast: &syn::DeriveInput) -> Result<DeprecationStrategy> {
extract_attr(&ast, "deprecated")?
.to_lowercase()
.as_str()
Expand All @@ -49,7 +47,7 @@ pub fn extract_deprecation_strategy(
}

/// Get the deprecation from a struct attribute in the derive case.
pub fn extract_normalization(ast: &syn::DeriveInput) -> Result<Normalization, failure::Error> {
pub fn extract_normalization(ast: &syn::DeriveInput) -> Result<Normalization> {
extract_attr(&ast, "normalization")?
.to_lowercase()
.as_str()
Expand Down
19 changes: 6 additions & 13 deletions graphql_query_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extern crate proc_macro;
/// Derive-related code. This will be moved into graphql_query_derive.
mod attributes;

use failure::ResultExt;
use anyhow::Context;
use graphql_client_codegen::{
generate_module_token_stream, CodegenMode, GraphQLClientCodegenOptions,
};
Expand All @@ -15,35 +15,28 @@ use proc_macro2::TokenStream;
pub fn derive_graphql_query(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
match graphql_query_derive_inner(input) {
Ok(ts) => ts,
Err(err) => panic!(
"{}",
err.iter_chain()
.fold(String::new(), |mut acc, item| {
acc.push_str(&format!("{}\n", item));
acc
})
.trim_end_matches('\n')
),
Err(err) => panic!("{:?}", err),
}
}

fn graphql_query_derive_inner(
input: proc_macro::TokenStream,
) -> Result<proc_macro::TokenStream, failure::Error> {
) -> Result<proc_macro::TokenStream, anyhow::Error> {
let input = TokenStream::from(input);
let ast = syn::parse2(input).context("Derive input parsing.")?;
let (query_path, schema_path) = build_query_and_schema_path(&ast)?;
let options = build_graphql_client_derive_options(&ast, query_path.to_path_buf())?;
Ok(
generate_module_token_stream(query_path, &schema_path, options)
.map(Into::into)
.map_err(|fail| fail.compat())
.context("Code generation failed.")?,
)
}

fn build_query_and_schema_path(
input: &syn::DeriveInput,
) -> Result<(PathBuf, PathBuf), failure::Error> {
) -> Result<(PathBuf, PathBuf), anyhow::Error> {
let cargo_manifest_dir = ::std::env::var("CARGO_MANIFEST_DIR")
.context("Checking that the CARGO_MANIFEST_DIR env variable is defined.")?;

Expand All @@ -60,7 +53,7 @@ fn build_query_and_schema_path(
fn build_graphql_client_derive_options(
input: &syn::DeriveInput,
query_path: PathBuf,
) -> Result<GraphQLClientCodegenOptions, failure::Error> {
) -> Result<GraphQLClientCodegenOptions, anyhow::Error> {
let variables_derives = attributes::extract_attr(input, "variables_derives").ok();
let response_derives = attributes::extract_attr(input, "response_derives").ok();

Expand Down