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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use diem_types::transaction::ScriptABI;
use serde_generate::CustomCode;
use std::{ffi::OsStr, fs, io::Read, path::Path};
pub mod cpp;
pub mod csharp;
pub mod golang;
pub mod java;
pub mod python3;
pub mod rust;
pub mod typescript;
mod common;
fn get_abi_paths(dir: &Path) -> std::io::Result<Vec<String>> {
let mut abi_paths = Vec::new();
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
abi_paths.append(&mut get_abi_paths(&path)?);
} else if let Some("abi") = path.extension().and_then(OsStr::to_str) {
abi_paths.push(path.to_str().unwrap().to_string());
}
}
}
Ok(abi_paths)
}
pub fn read_abis(dir_paths: &[impl AsRef<Path>]) -> anyhow::Result<Vec<ScriptABI>> {
let mut abis = Vec::<ScriptABI>::new();
for dir in dir_paths.iter() {
for path in get_abi_paths(dir.as_ref())? {
let mut buffer = Vec::new();
let mut f = std::fs::File::open(path)?;
f.read_to_end(&mut buffer)?;
abis.push(bcs::from_bytes(&buffer)?);
}
}
#[allow(clippy::unnecessary_sort_by)]
abis.sort_by(|a, b| a.name().cmp(b.name()));
Ok(abis)
}
pub trait SourceInstaller {
type Error;
fn install_transaction_builders(
&self,
name: &str,
abis: &[ScriptABI],
) -> std::result::Result<(), Self::Error>;
}
pub fn read_custom_code_from_paths<'a, I>(package: &'a [&'a str], paths: I) -> CustomCode
where
I: Iterator<Item = std::path::PathBuf>,
{
paths
.map(|path| {
let container_name = path
.file_stem()
.expect("file name must have a non-empty stem")
.to_str()
.expect("file names must be valid UTF8")
.to_string();
let mut container_path = package.iter().map(|s| s.to_string()).collect::<Vec<_>>();
container_path.push(container_name);
let content = std::fs::read_to_string(path).expect("custom code file must be readable");
let lines = content.lines().skip_while(|line| {
line.starts_with("// ") || line.starts_with("# ") || line.is_empty()
});
let mut code = lines.collect::<Vec<_>>().join("\n");
if !code.ends_with('\n') {
code += "\n";
}
(container_path, code)
})
.collect()
}