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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
pub mod graphql;
pub mod handler;
pub mod helper;
pub mod indexer_lib;
pub mod indexer_mapping;
pub mod indexer_mod;
pub mod indexer_setting;
pub mod instruction;
use crate::generator::indexer_mod::INDEXER_MOD;
use crate::schema::Schema;
use handlebars::Handlebars;
use indexer_lib::INDEXER_LIB;
use indexer_mapping::INDEXER_MAPPING;
use indexer_setting::*;
use minifier::json::minify;
use serde_json::json;
use serde_json::Value;
use std::collections::BTreeMap;
use std::fs;
use std::io;
#[derive(Debug)]
#[must_use]
pub struct Generator<'a> {
pub structure_path: &'a str,
pub config_path: &'a str,
pub output_dir: &'a str,
pub schema: Option<Schema>,
pub config: Option<Value>,
pub definitions: BTreeMap<String, Schema>,
}
impl<'a> Generator<'a> {
pub fn builder() -> GeneratorBuilder<'a> {
GeneratorBuilder::default()
}
pub fn generate(&self) -> Result<(), io::Error> {
let ref_schema = self.schema.as_ref();
if let Some(schema) = ref_schema {
let config = self.config.clone().unwrap();
let name = &config["name"].as_str().unwrap_or_default();
let contract_address = &config["contract_address"].as_str().unwrap_or_default();
let start_block = &config["start_block"].as_i64().unwrap_or_default();
let data = self.generate_instruction(schema);
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/generated/instruction.rs"),
&data,
true,
)?;
let data = self.generate_handler(schema);
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/generated/handler.rs"),
&data,
true,
)?;
let lib_content = &Handlebars::new()
.render_template(
INDEXER_LIB,
&json!({
"address": contract_address,
}),
)
.unwrap();
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/lib.rs"),
&lib_content,
true,
)?;
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/mapping.rs"),
&format!("{}", INDEXER_MAPPING),
true,
)?;
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/generated/mod.rs"),
&format!("{}", INDEXER_MOD),
true,
)?;
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/subgraph.yaml"),
&Handlebars::new()
.render_template(
INDEXER_YAML,
&json!({
"name": name,
"address": contract_address,
"start_block": start_block
}),
)
.unwrap(),
true,
)?;
let data = self.generate_graphql_schema(schema);
self.write_to_file(
&format!("{}/{}", self.output_dir, "src/schema.graphql"),
&data,
false,
)?;
self.write_to_file(
&format!("{}/{}", self.output_dir, "Cargo.toml"),
&format!("{}", CARGO_TOML),
false,
)?;
};
Ok(())
}
pub fn write_to_file(
&self,
output_path: &String,
content: &String,
apply_format: bool,
) -> io::Result<()> {
let path = std::path::Path::new(&output_path);
let prefix = path.parent().unwrap();
std::fs::create_dir_all(prefix).unwrap();
match fs::write(output_path, content) {
Ok(_) => {
if apply_format {
use std::process::Command;
let _ = Command::new("rustfmt").arg(output_path).output();
}
log::info!("Write content to file {:?} successfully", &output_path);
Ok(())
}
e @ Err(_) => {
log::info!("Write content to file {:?} fail. {:?}", &output_path, &e);
e
}
}
}
}
pub struct GeneratorBuilder<'a> {
inner: Generator<'a>,
}
impl<'a> Default for GeneratorBuilder<'a> {
fn default() -> Self {
Self {
inner: Generator {
structure_path: "",
config_path: "",
output_dir: "",
schema: None,
config: None,
definitions: BTreeMap::default(),
},
}
}
}
impl<'a> GeneratorBuilder<'a> {
pub fn with_structure_path(mut self, path: &'a str) -> Self {
self.inner.structure_path = path;
let json = std::fs::read_to_string(path)
.unwrap_or_else(|err| panic!("Unable to read `{}`: {}", path, err));
let schema: Schema = serde_json::from_str(&json)
.unwrap_or_else(|err| panic!("Cannot parse `{}` as JSON: {}", path, err));
self.collect_definitions(&schema);
self.inner.schema = Some(schema);
self
}
pub fn with_config_path(mut self, path: &'a str) -> Self {
self.inner.config_path = path;
let json = std::fs::read_to_string(path)
.unwrap_or_else(|err| panic!("Unable to read `{}`: {}", path, err));
let config: Value = serde_json::from_str(&minify(&json))
.unwrap_or_else(|err| panic!("Cannot parse `{}` as JSON: {}", path, err));
self.inner.config = Some(config);
self
}
pub fn with_output_dir(mut self, output_dir: &'a str) -> Self {
self.inner.output_dir = output_dir;
self
}
fn collect_definitions(&mut self, schema: &Schema) {
schema.definitions.iter().for_each(|(name, schema)| {
self.inner.definitions.insert(name.clone(), schema.clone());
self.collect_definitions(schema);
});
}
pub fn build(self) -> Generator<'a> {
self.inner
}
}