ethbind_rust/
pretty.rs

1use std::{env, fs, path::PathBuf, process::Command};
2
3use ethbind_gen::Contract;
4use sha3::{Digest, Keccak256};
5
6/// The trait to support `Rust` language formatting
7pub trait RustPretty {
8    /// Invoke this `fn` to perform the `formatting codes action`
9    fn pretty(&mut self) -> anyhow::Result<()>;
10}
11
12impl RustPretty for Contract {
13    fn pretty(&mut self) -> anyhow::Result<()> {
14        let rust_fmt_path =
15            PathBuf::from(env::var("CARGO_HOME").expect("Get CARGO_HOME")).join("bin/rustfmt");
16
17        for file in &mut self.files {
18            let temp_file_name = format!(
19                "{:x}",
20                Keccak256::new()
21                    .chain_update(file.data.as_bytes())
22                    .finalize()
23            );
24
25            let path = env::temp_dir().join(temp_file_name);
26
27            fs::write(&path, file.data.as_bytes())?;
28
29            // Call rustfmt to fmt tmp file
30            let mut child = Command::new(&rust_fmt_path)
31                .args(["--edition", "2021", path.to_str().unwrap()])
32                .spawn()?;
33
34            child.wait()?;
35
36            let formated = fs::read_to_string(path).expect("Read formated codes");
37
38            file.data = formated;
39        }
40
41        Ok(())
42    }
43}
44
45impl RustPretty for Vec<Contract> {
46    fn pretty(&mut self) -> anyhow::Result<()> {
47        for c in self {
48            c.pretty()?;
49        }
50
51        Ok(())
52    }
53}