pub const DEFAULT_SPEC: &str = "mainnet";
pub const AVAILABLE_SPECS: &[&str] = &["mainnet", "testnet", "preview", "staging", "dev"];
pub const DEFAULT_RPC_PORT: &str = "8114";
pub const DEFAULT_P2P_PORT: &str = "8115";
const START_MARKER: &str = " # {{";
const END_MAKER: &str = "# }}";
const WILDCARD_BRANCH: &str = "# _ => ";
use std::collections::HashMap;
use std::io;
pub struct Template(String);
pub struct TemplateContext<'a> {
spec: &'a str,
kvs: HashMap<&'a str, &'a str>,
}
impl<'a> TemplateContext<'a> {
pub fn new<I>(spec: &'a str, kvs: I) -> Self
where
I: IntoIterator<Item = (&'a str, &'a str)>,
{
Self {
spec,
kvs: kvs.into_iter().collect(),
}
}
pub fn insert(&mut self, key: &'a str, value: &'a str) {
self.kvs.insert(key, value);
}
}
impl Template {
pub fn new(content: String) -> Self {
Template(content)
}
}
#[allow(unexpected_cfgs)]
fn writeln<W: io::Write>(w: &mut W, s: &str, context: &TemplateContext) -> io::Result<()> {
#[cfg(docker)]
let s = s.replace("127.0.0.1:{rpc_port}", "0.0.0.0:{rpc_port}");
writeln!(
w,
"{}",
context
.kvs
.iter()
.fold(s.replace("\\n", "\n"), |s, (key, value)| s
.replace(format!("{{{key}}}").as_str(), value))
)
}
#[derive(Debug)]
pub enum TemplateState<'a> {
SearchStartMarker,
MatchBranch(&'a str),
SearchEndMarker,
}
impl Template {
pub fn render_to<W: io::Write>(
&self,
w: &mut W,
context: &TemplateContext<'_>,
) -> io::Result<()> {
let spec_branch = format!("# {} => ", context.spec);
let mut state = TemplateState::SearchStartMarker;
for line in self.0.lines() {
match state {
TemplateState::SearchStartMarker => {
if line.ends_with(START_MARKER) {
state = TemplateState::MatchBranch(line);
} else {
writeln!(w, "{line}")?;
}
}
TemplateState::MatchBranch(start_line) => {
if line == END_MAKER {
writeln!(
w,
"{}",
&start_line[..(start_line.len() - START_MARKER.len())],
)?;
state = TemplateState::SearchStartMarker;
} else if line.starts_with(&spec_branch) {
writeln(w, &line[spec_branch.len()..], context)?;
state = TemplateState::SearchEndMarker;
} else if let Some(c) = line.strip_prefix(WILDCARD_BRANCH) {
writeln(w, c, context)?;
state = TemplateState::SearchEndMarker;
}
}
TemplateState::SearchEndMarker => {
if line == END_MAKER {
state = TemplateState::SearchStartMarker;
}
}
}
}
if let TemplateState::MatchBranch(start_line) = state {
writeln!(
w,
"{}",
&start_line[..(start_line.len() - START_MARKER.len())],
)?;
}
Ok(())
}
pub fn render(&self, context: &TemplateContext<'_>) -> io::Result<String> {
let mut out = Vec::new();
self.render_to(&mut out, context)?;
String::from_utf8(out)
.map_err(|from_utf8_err| io::Error::new(io::ErrorKind::InvalidInput, from_utf8_err))
}
}