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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
//! # Introduction
//!
//! This is a simple template tool that works with variable names and
//! [`HashMap`] of [`String`]. The [`Template`] can be parsed from
//! [`str`] and then you can render it using the variables in
//! [`HashMap`] and any shell commands running through [`Exec`].
//!
//! # Features
//! - Parse the template from a [`str`] that's easy to write,
//! - Support for alternatives in case some variables are not present,
//! - Support for literal strings inside the alternative options,
//! - Support for the date time format using [`chrono`],
//! - Support for any arbitrary commands, etc.
//!
//! # Limitations
//! - You cannot use positional arguments in this template system, only named ones.
//! - I haven't tested variety of names, although they should work try to keep the names identifier friendly.
//! - Currently doesn't have format specifiers, for now you can use the command options with `printf` bash command to format things the way you want.
//! Like a template `this is $(printf "%.2f" {weight}) kg.` should be rendered with the correct float formatting.
use anyhow::{Context, Error};
use chrono::Local;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::io::Read;
use std::path::PathBuf;
use subprocess::Exec;
/// Character to separate the variables. If the first variable is not present it'll use the one behind it and so on. Keep it at the end, if you want a empty string instead of error on missing variable.
pub static OPTIONAL_RENDER_CHAR: char = '?';
/// Character that should be in the beginning of the variable to determine it as datetime format.
pub static TIME_FORMAT_CHAR: char = '%';
/// Quote characters to use to make a value literal instead of a variable. In combination with [`OPTIONAL_RENDER_CHAR`] it can be used as a default value when variable(s) is/are not present.
pub static LITERAL_VALUE_QUOTE_CHAR: char = '"';
static LITERAL_REPLACEMENTS: [&str; 6] = [
"", // to replace {} as empty string.
"{", // to replace {{} as {
"}", // to replace {}} as }
"?", "%", "\"", // to use these chars without their special meanings
];
lazy_static! {
static ref VARIABLE_REGEX: Regex = Regex::new(r"\{(.*?)\}").unwrap();
static ref SHELL_COMMAND_REGEX: Regex = Regex::new(r"[$]\((.*?)\)").unwrap();
}
/// Runs a command and returns the output of the command or the error
fn cmd_output(cmd: &str, wd: &PathBuf) -> Result<String, Error> {
let mut out: String = String::new();
Exec::shell(cmd)
.cwd(wd)
.stream_stdout()?
.read_to_string(&mut out)?;
Ok(out)
}
/// Parts that make up a [`Template<'a>`]. You can have literal strings, variables, time date format, command, or optional format with [`OPTIONAL_RENDER_CHAR`].
///
/// [`TemplatePart<'a>::Lit`] = Literal Strings like `"hi "` in `"hi {name}"`
/// [`TemplatePart<'a>::Var`] = Variable part like `"name"` in `"hi {name}"`
/// [`TemplatePart<'a>::Time`] = Date time format like `"%F"` in `"Today: {%F}"`
/// [`TemplatePart<'a>::Cmd`] = Command like `"echo world"` in `"hello $(echo world)"`
/// [`TemplatePart<'a>::Any`] = Optional format like `"name?age"` in `"hello {name?age}"`
///
/// [`TemplatePart<'a>::Cmd`] and [`TemplatePart<'a>::Any`] can in turn contain other [`TemplatePart<'a>`] inside them. Haven't tested on nesting complex ones within each other though.
#[derive(Debug)]
pub enum TemplatePart<'a> {
Lit(&'a str),
Var(&'a str),
Time(&'a str),
Cmd(Vec<TemplatePart<'a>>),
Any(Vec<TemplatePart<'a>>),
}
/// Main Template that get's passed around, consists of `[Vec`] of [`TemplatePart<'a>`]
///
/// ```rust
/// # use std::error::Error;
/// # use std::collections::HashMap;
/// # use std::path::PathBuf;
/// # use string_template_plus::{Render, RenderOptions, parse_template};
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let templ = parse_template("hello {nickname?name}. You're $(printf \"%.1f\" {weight})kg").unwrap();
/// let mut vars: HashMap<String, String> = HashMap::new();
/// vars.insert("name".into(), "John".into());
/// vars.insert("weight".into(), "132.3423".into());
/// let rendered = templ
/// .render(&RenderOptions {
/// wd: PathBuf::from("."),
/// variables: vars,
/// })
/// .unwrap();
/// assert_eq!(rendered, "hello John. You're 132.3kg");
/// # Ok(())
/// }
pub type Template<'a> = Vec<TemplatePart<'a>>;
pub trait Render {
fn render(&self, op: &RenderOptions) -> Result<String, Error>;
}
#[derive(Default)]
pub struct RenderOptions {
pub wd: PathBuf,
pub variables: HashMap<String, String>,
}
impl<'a> Render for TemplatePart<'a> {
fn render(&self, op: &RenderOptions) -> Result<String, Error> {
match self {
TemplatePart::Lit(l) => Ok(l.to_string()),
TemplatePart::Var(v) => op
.variables
.get(*v)
.map(|s| s.to_string())
.context("No such variable in the RenderOptions"),
TemplatePart::Time(t) => Ok(Local::now().format(t).to_string()),
TemplatePart::Cmd(c) => cmd_output(&c.render(op)?, &op.wd),
TemplatePart::Any(a) => a
.iter()
.filter_map(|p| p.render(op).ok())
.next()
.context("None of the alternatives given were found"),
}
}
}
impl<'a> Render for Template<'a> {
fn render(&self, op: &RenderOptions) -> Result<String, Error> {
self.iter()
.map(|p| p.render(op))
.collect::<Result<Vec<String>, Error>>()
.map(|v| v.join(""))
}
}
fn parse_single_part(part: &str) -> TemplatePart {
if LITERAL_REPLACEMENTS.contains(&part) {
// the input_map.get() is not working for "", idk why
TemplatePart::Lit("")
} else if part.starts_with(LITERAL_VALUE_QUOTE_CHAR) && part.ends_with(LITERAL_VALUE_QUOTE_CHAR)
{
TemplatePart::Lit(&part[1..(part.len() - 1)])
} else if part.starts_with(TIME_FORMAT_CHAR) {
TemplatePart::Time(part)
} else {
TemplatePart::Var(part)
}
}
fn parse_variables(templ: &str) -> Template {
let mut last_match = 0usize;
let mut template_parts = Vec::new();
for cap in VARIABLE_REGEX.captures_iter(templ) {
let m = cap.get(0).unwrap();
template_parts.push(TemplatePart::Lit(&templ[last_match..m.start()]));
let cg = cap.get(1).unwrap();
let cap_slice = &templ[cg.start()..cg.end()];
if cap_slice.contains(OPTIONAL_RENDER_CHAR) {
let parts = cap_slice
.split(OPTIONAL_RENDER_CHAR)
.map(|s| s.trim())
.map(parse_single_part)
.collect();
template_parts.push(TemplatePart::Any(parts));
} else {
template_parts.push(parse_single_part(cap_slice));
}
last_match = m.end();
}
template_parts.push(TemplatePart::Lit(&templ[last_match..]));
template_parts
}
/// Parses the template from string and makes a [`Template<'a>`]. Which you can render later.
pub fn parse_template(templ_str: &str) -> Result<Template, String> {
let mut last_match = 0usize;
let mut template_parts = Vec::new();
for cmd in SHELL_COMMAND_REGEX.captures_iter(templ_str) {
let m = cmd.get(0).unwrap();
let cmd = cmd.get(1).unwrap();
let mut pts = parse_variables(&templ_str[last_match..m.start()]);
template_parts.append(&mut pts);
template_parts.push(TemplatePart::Cmd(parse_variables(
&templ_str[cmd.start()..cmd.end()],
)));
last_match = m.end();
}
let mut pts = parse_variables(&templ_str[last_match..]);
template_parts.append(&mut pts);
Ok(template_parts)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lit() {
let templ = parse_template("hello name").unwrap();
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
assert_eq!(rendered, "hello name");
}
#[test]
fn test_vars() {
let templ = parse_template("hello {name}").unwrap();
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
assert_eq!(rendered, "hello world");
}
#[test]
#[should_panic]
fn test_novars() {
let templ = parse_template("hello {name}").unwrap();
let vars: HashMap<String, String> = HashMap::new();
templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
}
#[test]
fn test_novars_opt() {
let templ = parse_template("hello {name?}").unwrap();
let vars: HashMap<String, String> = HashMap::new();
let rendered = templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
assert_eq!(rendered, "hello ");
}
#[test]
fn test_optional() {
let templ = parse_template("hello {age?name}").unwrap();
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
assert_eq!(rendered, "hello world");
}
#[test]
fn test_optional_lit() {
let templ = parse_template("hello {age?\"20\"}").unwrap();
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
variables: vars,
..Default::default()
})
.unwrap();
assert_eq!(rendered, "hello 20");
}
#[test]
fn test_command() {
let templ = parse_template("hello $(echo {name})").unwrap();
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
wd: PathBuf::from("."),
variables: vars,
})
.unwrap();
assert_eq!(rendered, "hello world\n");
}
#[test]
fn test_time() {
let templ = parse_template("hello {name} at {%Y-%m-%d}").unwrap();
let timefmt = Local::now().format("%Y-%m-%d");
let output = format!("hello world at {}", timefmt);
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
wd: PathBuf::from("."),
variables: vars,
})
.unwrap();
assert_eq!(rendered, output);
}
#[test]
fn test_var_or_time() {
let templ = parse_template("hello {name} at {age?%Y-%m-%d}").unwrap();
let timefmt = Local::now().format("%Y-%m-%d");
let output = format!("hello world at {}", timefmt);
let mut vars: HashMap<String, String> = HashMap::new();
vars.insert("name".into(), "world".into());
let rendered = templ
.render(&RenderOptions {
wd: PathBuf::from("."),
variables: vars,
})
.unwrap();
assert_eq!(rendered, output);
}
}