1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::path::{Path, PathBuf};
use crate::{generate_abi_code, normalize_path};
use anyhow::Context;
use quote::quote;
#[derive(Debug, Clone)]
pub struct Abigen {
abi_path: PathBuf,
}
impl Abigen {
pub fn new<S: AsRef<str>>(_contract_name: S, path: S) -> Result<Self, anyhow::Error> {
let path = normalize_path(path.as_ref()).context("normalize path")?;
Ok(Self { abi_path: path })
}
pub fn generate(&self) -> Result<GeneratedBindings, anyhow::Error> {
let item =
generate_abi_code(self.abi_path.to_string_lossy()).context("generating abi code")?;
let file = quote! {
mod __remove__ {
#item
}
};
let file = syn::File {
attrs: vec![],
items: vec![syn::parse2(file).context("parsing generated code")?],
shebang: None,
};
let code = prettyplease::unparse(&file);
let mut lines = code.lines();
lines.next();
lines.next_back();
Ok(GeneratedBindings {
code: lines.collect::<Vec<_>>().join("\n"),
})
}
}
pub struct GeneratedBindings {
code: String,
}
impl GeneratedBindings {
pub fn write_to_file<P: AsRef<Path>>(&self, p: P) -> Result<(), anyhow::Error> {
let path = normalize_path(p.as_ref()).context("normalize path")?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating directories for {}", parent.to_string_lossy()))?
}
std::fs::write(path, &self.code)
.with_context(|| format!("writing file {}", p.as_ref().to_string_lossy()))
}
}