use cargo_metadata::{DependencyKind, MetadataCommand};
use once_cell::sync::Lazy;
use syn::Path;
static ETHERS_CRATES: Lazy<(&'static str, &'static str, &'static str)> =
Lazy::new(determine_ethers_crates);
pub fn ethers_core_crate() -> Path {
syn::parse_str(ETHERS_CRATES.0).expect("valid path; qed")
}
pub fn ethers_contract_crate() -> Path {
syn::parse_str(ETHERS_CRATES.1).expect("valid path; qed")
}
pub fn ethers_providers_crate() -> Path {
syn::parse_str(ETHERS_CRATES.2).expect("valid path; qed")
}
pub fn determine_ethers_crates() -> (&'static str, &'static str, &'static str) {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("No Manifest found");
let lock_file = format!("{}/Cargo.lock", manifest_dir);
let needs_lock_file_cleanup = !std::path::Path::new(&lock_file).exists();
let res = MetadataCommand::new()
.manifest_path(&format!("{}/Cargo.toml", manifest_dir))
.exec()
.ok()
.and_then(|metadata| {
metadata.root_package().and_then(|pkg| {
pkg.dependencies.iter().filter(|dep| dep.kind == DependencyKind::Normal).find_map(
|dep| {
(dep.name == "ethers")
.then(|| ("ethers::core", "ethers::contract", "ethers::providers"))
},
)
})
})
.unwrap_or(("ethers_core", "ethers_contract", "ethers_providers"));
if needs_lock_file_cleanup {
let _ = std::fs::remove_file(lock_file);
}
res
}