Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

refactor: replace anyhow with eyre #858

Merged
merged 6 commits into from
Feb 2, 2022
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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
- Significantly refactor `MultiAbigen` module generation. Now allows for lib
generation, and does not make unnecessary disk writes.
[#854](https://github.com/gakonst/ethers-rs/pull/852)
- Refactor `ethers-contract-abigen` to use `eyre` instead of `anyhow` via
[#858](https://github.com/gakonst/ethers-rs/pull/858)

## ethers-contract-abigen

Expand Down
18 changes: 17 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion ethers-contract/ethers-contract-abigen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ keywords = ["ethereum", "web3", "celo", "ethers"]
[dependencies]
ethers-core = { version = "^0.6.0", path = "../../ethers-core", features = ["macros"] }

anyhow = "1.0.37"
Inflector = "0.11"
proc-macro2 = "1.0"
quote = "1.0"
Expand All @@ -26,6 +25,7 @@ once_cell = "1.8.0"
cfg-if = "1.0.0"
dunce = "1.0.2"
walkdir = "2.3.2"
eyre = "0.6.6"

[target.'cfg(target_arch = "wasm32")'.dependencies]
# NOTE: this enables wasm compatibility for getrandom indirectly
Expand Down
6 changes: 3 additions & 3 deletions ethers-contract/ethers-contract-abigen/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ mod types;

use super::{util, Abigen};
use crate::{contract::structs::InternalStructs, rawabi::RawAbi};
use anyhow::{anyhow, Context as _, Result};
use ethers_core::{
abi::{Abi, AbiParser},
macros::{ethers_contract_crate, ethers_core_crate, ethers_providers_crate},
};
use eyre::{eyre, Context as _, Result};

use crate::contract::methods::MethodAlias;
use proc_macro2::{Ident, Literal, TokenStream};
Expand Down Expand Up @@ -153,7 +153,7 @@ impl Context {
pub fn from_abigen(args: Abigen) -> Result<Self> {
// get the actual ABI string
let mut abi_str =
args.abi_source.get().map_err(|e| anyhow!("failed to get ABI JSON: {}", e))?;
args.abi_source.get().map_err(|e| eyre!("failed to get ABI JSON: {}", e))?;

let (abi, human_readable, abi_parser) = parse_abi(&abi_str)?;

Expand Down Expand Up @@ -199,7 +199,7 @@ impl Context {
};

if method_aliases.insert(signature.clone(), alias).is_some() {
return Err(anyhow!("duplicate method signature '{}' in method aliases", signature,))
eyre::bail!("duplicate method signature '{}' in method aliases", signature)
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::{types, util, Context};
use anyhow::Result;
use ethers_core::{
abi::{Event, EventExt, EventParam, ParamType, SolStruct},
macros::{ethers_contract_crate, ethers_core_crate},
};
use eyre::Result;
use inflector::Inflector;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::quote;
Expand Down
54 changes: 27 additions & 27 deletions ethers-contract/ethers-contract-abigen/src/contract/methods.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::{btree_map::Entry, BTreeMap, HashMap};

use anyhow::{Context as _, Result};
use eyre::{Context as _, Result};
use inflector::Inflector;
use proc_macro2::{Literal, TokenStream};
use quote::quote;
Expand Down Expand Up @@ -428,33 +428,33 @@ impl Context {
0 => {
// this may happen if there are functions with different casing,
// like `INDEX`and `index`
if overloaded_fun.name != first_fun.name {
let overloaded_id = overloaded_fun.name.to_snake_case();
let first_fun_id = first_fun.name.to_snake_case();
if first_fun_id != overloaded_id {
// no conflict
overloaded_id
} else {
let overloaded_alias = MethodAlias {
function_name: util::safe_ident(&overloaded_fun.name),
struct_name: util::safe_ident(&overloaded_fun.name),
};
aliases.insert(overloaded_fun.abi_signature(), overloaded_alias);

let first_fun_alias = MethodAlias {
function_name: util::safe_ident(&first_fun.name),
struct_name: util::safe_ident(&first_fun.name),
};
aliases.insert(first_fun.abi_signature(), first_fun_alias);
continue
}

// this should not happen since functions with same
// name and inputs are illegal
eyre::ensure!(
overloaded_fun.name != first_fun.name,
"Function with same name and parameter types defined twice: {}",
overloaded_fun.name
);

let overloaded_id = overloaded_fun.name.to_snake_case();
let first_fun_id = first_fun.name.to_snake_case();
if first_fun_id != overloaded_id {
// no conflict
overloaded_id
} else {
// this should not happen since functions with same name and inputs are
// illegal
anyhow::bail!(
"Function with same name and parameter types defined twice: {}",
overloaded_fun.name
);
let overloaded_alias = MethodAlias {
function_name: util::safe_ident(&overloaded_fun.name),
struct_name: util::safe_ident(&overloaded_fun.name),
};
aliases.insert(overloaded_fun.abi_signature(), overloaded_alias);

let first_fun_alias = MethodAlias {
function_name: util::safe_ident(&first_fun.name),
struct_name: util::safe_ident(&first_fun.name),
};
aliases.insert(first_fun.abi_signature(), first_fun_alias);
continue
}
}
1 => {
Expand Down
26 changes: 10 additions & 16 deletions ethers-contract/ethers-contract-abigen/src/contract/structs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Methods for expanding structs
use std::collections::{HashMap, VecDeque};

use anyhow::{Context as _, Result};
use eyre::{eyre, Result};
use inflector::Inflector;
use proc_macro2::TokenStream;
use quote::quote;
Expand Down Expand Up @@ -55,17 +55,18 @@ impl Context {

/// Generates the type definition for the name that matches the given identifier
fn generate_internal_struct(&self, id: &str) -> Result<TokenStream> {
let sol_struct = self.internal_structs.structs.get(id).context("struct not found")?;
let sol_struct =
self.internal_structs.structs.get(id).ok_or_else(|| eyre!("struct not found"))?;
let struct_name = self
.internal_structs
.rust_type_names
.get(id)
.context(format!("No types found for {}", id))?;
.ok_or_else(|| eyre!("No types found for {}", id))?;
let tuple = self
.internal_structs
.struct_tuples
.get(id)
.context(format!("No types found for {}", id))?
.ok_or_else(|| eyre!("No types found for {}", id))?
.clone();
self.expand_internal_struct(struct_name, sol_struct, tuple)
}
Expand Down Expand Up @@ -102,11 +103,7 @@ impl Context {
fields.push(quote! { pub #field_name: #ty });
}
FieldType::Mapping(_) => {
return Err(anyhow::anyhow!(
"Mapping types in struct `{}` are not supported {:?}",
name,
field
))
eyre::bail!("Mapping types in struct `{}` are not supported {:?}", name, field)
}
}
}
Expand Down Expand Up @@ -137,7 +134,8 @@ impl Context {
}

fn generate_human_readable_struct(&self, name: &str) -> Result<TokenStream> {
let sol_struct = self.abi_parser.structs.get(name).context("struct not found")?;
let sol_struct =
self.abi_parser.structs.get(name).ok_or_else(|| eyre!("struct not found"))?;
let mut fields = Vec::with_capacity(sol_struct.fields().len());
let mut param_types = Vec::with_capacity(sol_struct.fields().len());
for field in sol_struct.fields() {
Expand All @@ -157,18 +155,14 @@ impl Context {
.abi_parser
.struct_tuples
.get(name)
.context(format!("No types found for {}", name))?
.ok_or_else(|| eyre!("No types found for {}", name))?
.clone();
let tuple = ParamType::Tuple(tuple);

param_types.push(struct_ty.as_param(tuple));
}
FieldType::Mapping(_) => {
return Err(anyhow::anyhow!(
"Mapping types in struct `{}` are not supported {:?}",
name,
field
))
eyre::bail!("Mapping types in struct `{}` are not supported {:?}", name, field)
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions ethers-contract/ethers-contract-abigen/src/contract/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::{anyhow, Result};
use ethers_core::{abi::ParamType, macros::ethers_core_crate};
use eyre::{bail, Result};
use proc_macro2::{Literal, TokenStream};
use quote::quote;

Expand All @@ -16,7 +16,7 @@ pub(crate) fn expand(kind: &ParamType) -> Result<TokenStream> {
5..=8 => Ok(quote! { i64 }),
9..=16 => Ok(quote! { i128 }),
17..=32 => Ok(quote! { I256 }),
_ => Err(anyhow!("unsupported solidity type int{}", n)),
_ => bail!("unsupported solidity type int{}", n),
},
ParamType::Uint(n) => match n / 8 {
1 => Ok(quote! { u8 }),
Expand All @@ -25,7 +25,7 @@ pub(crate) fn expand(kind: &ParamType) -> Result<TokenStream> {
5..=8 => Ok(quote! { u64 }),
9..=16 => Ok(quote! { u128 }),
17..=32 => Ok(quote! { #ethers_core::types::U256 }),
_ => Err(anyhow!("unsupported solidity type uint{}", n)),
_ => bail!("unsupported solidity type uint{}", n),
},
ParamType::Bool => Ok(quote! { bool }),
ParamType::String => Ok(quote! { String }),
Expand All @@ -46,9 +46,7 @@ pub(crate) fn expand(kind: &ParamType) -> Result<TokenStream> {
Ok(quote! { [#inner; #size] })
}
ParamType::Tuple(members) => {
if members.is_empty() {
return Err(anyhow!("Tuple must have at least 1 member"))
}
eyre::ensure!(!members.is_empty(), "Tuple must have at least 1 member");

let members = members.iter().map(expand).collect::<Result<Vec<_>, _>>()?;
Ok(quote! { (#(#members,)*) })
Expand Down
6 changes: 3 additions & 3 deletions ethers-contract/ethers-contract-abigen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub use ethers_core::types::Address;
pub use source::Source;
pub use util::parse_address;

use anyhow::Result;
use eyre::Result;
use inflector::Inflector;
use proc_macro2::TokenStream;
use std::{collections::HashMap, fs::File, io::Write, path::Path};
Expand Down Expand Up @@ -90,9 +90,9 @@ impl Abigen {
let name = path
.as_ref()
.file_stem()
.ok_or_else(|| anyhow::format_err!("Missing file stem in path"))?
.ok_or_else(|| eyre::format_err!("Missing file stem in path"))?
.to_str()
.ok_or_else(|| anyhow::format_err!("Unable to convert file stem to string"))?;
.ok_or_else(|| eyre::format_err!("Unable to convert file stem to string"))?;

Self::new(name, std::fs::read_to_string(path.as_ref())?)
}
Expand Down
12 changes: 6 additions & 6 deletions ethers-contract/ethers-contract-abigen/src/multi.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! TODO

use anyhow::Result;
use eyre::Result;
use inflector::Inflector;
use std::{collections::BTreeMap, fs, io::Write, path::Path};

Expand Down Expand Up @@ -388,7 +388,7 @@ impl MultiBindings {
/// # Returns
///
/// `Ok(())` if the freshly generated bindings match with the
/// existing bindings. Otherwise an `Err(_)` containing an `anyhow::Report`
/// existing bindings. Otherwise an `Err(_)` containing an `eyre::Report`
/// with more information.
///
/// # Example
Expand Down Expand Up @@ -437,7 +437,7 @@ impl MultiBindings {
/// # Returns
///
/// `Ok(())` if the freshly generated bindings match with the
/// existing bindings. Otherwise an `Err(_)` containing an `anyhow::Report`
/// existing bindings. Otherwise an `Err(_)` containing an `eyre::Report`
/// with more information.
///
/// # Example
Expand Down Expand Up @@ -468,13 +468,13 @@ impl MultiBindings {
}

fn check_file_in_dir(dir: &Path, file_name: &str, expected_contents: &[u8]) -> Result<()> {
anyhow::ensure!(dir.is_dir(), "Not a directory: {}", dir.display());
eyre::ensure!(dir.is_dir(), "Not a directory: {}", dir.display());

let file_path = dir.join(file_name);
anyhow::ensure!(file_path.is_file(), "Not a file: {}", file_path.display());
eyre::ensure!(file_path.is_file(), "Not a file: {}", file_path.display());

let contents = fs::read(file_path).expect("Unable to read file");
anyhow::ensure!(contents == expected_contents, "file contents do not match");
eyre::ensure!(contents == expected_contents, "file contents do not match");
Ok(())
}

Expand Down
18 changes: 9 additions & 9 deletions ethers-contract/ethers-contract-abigen/src/rustfmt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module implements basic `rustfmt` code formatting.

use anyhow::{anyhow, Result};
use eyre::{eyre, Result};
use std::{
io::Write,
process::{Command, Stdio},
Expand All @@ -18,18 +18,18 @@ where
let stdin = rustfmt
.stdin
.as_mut()
.ok_or_else(|| anyhow!("stdin was not created for `rustfmt` child process"))?;
.ok_or_else(|| eyre!("stdin was not created for `rustfmt` child process"))?;
stdin.write_all(source.as_ref().as_bytes())?;
}

let output = rustfmt.wait_with_output()?;
if !output.status.success() {
return Err(anyhow!(
"`rustfmt` exited with code {}:\n{}",
output.status,
String::from_utf8_lossy(&output.stderr),
))
}

eyre::ensure!(
output.status.success(),
"`rustfmt` exited with code {}:\n{}",
output.status,
String::from_utf8_lossy(&output.stderr),
);

let stdout = String::from_utf8(output.stdout)?;
Ok(stdout)
Expand Down
Loading