aboutsummaryrefslogtreecommitdiff
path: root/crates/teraron
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2018-10-16 18:28:43 +0100
committerAleksey Kladov <[email protected]>2018-10-16 18:31:30 +0100
commit514aa3cf853c3c4beef8f827c12328d626f977de (patch)
tree2a10336c3825ad821960c5169b78df17f7bd5f5c /crates/teraron
parent1216878f7be20dd0e652fb8cdc395009fdcfae07 (diff)
extract teraron
Diffstat (limited to 'crates/teraron')
-rw-r--r--crates/teraron/Cargo.toml13
-rw-r--r--crates/teraron/src/lib.rs109
2 files changed, 122 insertions, 0 deletions
diff --git a/crates/teraron/Cargo.toml b/crates/teraron/Cargo.toml
new file mode 100644
index 000000000..7ce9f1aa8
--- /dev/null
+++ b/crates/teraron/Cargo.toml
@@ -0,0 +1,13 @@
1[package]
2name = "teraron"
3version = "0.0.1"
4authors = ["Aleksey Kladov <[email protected]>"]
5repository = "https://github.com/rust-analyzer/teraron"
6description = "Genrate Rust code from a .tera template and a .ron data"
7license = "MIT OR Apache-2.0"
8
9[dependencies]
10failure = "0.1.2"
11tera = "0.11.18"
12ron = "0.4.0"
13heck = "0.3.0"
diff --git a/crates/teraron/src/lib.rs b/crates/teraron/src/lib.rs
new file mode 100644
index 000000000..e464ea080
--- /dev/null
+++ b/crates/teraron/src/lib.rs
@@ -0,0 +1,109 @@
1//! A simple tool to generate rust code by passing a ron value
2//! to a tera template
3
4#[macro_use]
5extern crate failure;
6extern crate tera;
7extern crate ron;
8extern crate heck;
9
10use std::{
11 fs,
12 collections::HashMap,
13 path::Path,
14};
15
16use heck::{CamelCase, ShoutySnakeCase, SnakeCase};
17
18#[derive(Clone, Copy, PartialEq, Eq)]
19pub enum Mode {
20 Overwrite,
21 Verify,
22}
23
24pub use Mode::*;
25
26/// A helper to update file on disk if it has changed.
27/// With verify = false,
28pub fn update(path: &Path, contents: &str, mode: Mode) -> Result<(), failure::Error> {
29 match fs::read_to_string(path) {
30 Ok(ref old_contents) if old_contents == contents => {
31 return Ok(());
32 }
33 _ => (),
34 }
35 if mode == Verify {
36 bail!("`{}` is not up-to-date", path.display());
37 }
38 eprintln!("updating {}", path.display());
39 fs::write(path, contents)?;
40 Ok(())
41}
42
43pub fn generate(
44 template: &Path,
45 src: &Path,
46 mode: Mode,
47) -> Result<(), failure::Error> {
48 assert_eq!(
49 template.extension().and_then(|it| it.to_str()), Some("tera"),
50 "template file must have .rs.tera extension",
51 );
52 let file_name = template.file_stem().unwrap().to_str().unwrap();
53 assert!(
54 file_name.ends_with(".rs"),
55 "template file must have .rs.tera extension",
56 );
57 let tgt = template.with_file_name(file_name);
58 let template = fs::read_to_string(template)?;
59 let src: ron::Value = {
60 let text = fs::read_to_string(src)?;
61 ron::de::from_str(&text)?
62 };
63 let content = render(&template, src)?;
64 update(
65 &tgt,
66 &content,
67 mode,
68 )
69}
70
71pub fn render(
72 template: &str,
73 src: ron::Value,
74) -> Result<String, failure::Error> {
75 let mut tera = mk_tera();
76 tera.add_raw_template("_src", template)
77 .map_err(|e| format_err!("template parsing error: {:?}", e))?;
78 let res = tera.render("_src", &src)
79 .map_err(|e| format_err!("template rendering error: {:?}", e))?;
80 return Ok(res);
81}
82
83fn mk_tera() -> tera::Tera {
84 let mut res = tera::Tera::default();
85 res.register_filter("camel", |arg, _| {
86 Ok(arg.as_str().unwrap().to_camel_case().into())
87 });
88 res.register_filter("snake", |arg, _| {
89 Ok(arg.as_str().unwrap().to_snake_case().into())
90 });
91 res.register_filter("SCREAM", |arg, _| {
92 Ok(arg.as_str().unwrap().to_shouty_snake_case().into())
93 });
94 res.register_function("concat", Box::new(concat));
95 res
96}
97
98fn concat(args: HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
99 let mut elements = Vec::new();
100 for &key in ["a", "b", "c"].iter() {
101 let val = match args.get(key) {
102 Some(val) => val,
103 None => continue,
104 };
105 let val = val.as_array().unwrap();
106 elements.extend(val.iter().cloned());
107 }
108 Ok(tera::Value::Array(elements))
109}