Move template metadata processing into askama crate

This commit is contained in:
Dirkjan Ochtman 2017-02-17 15:07:35 +01:00
parent 210ed06bdb
commit 2c069acd5f
2 changed files with 36 additions and 35 deletions

View File

@ -17,8 +17,39 @@ mod path;
pub mod filters;
pub use path::rerun_if_templates_changed;
pub fn build_template(path: &str, ast: &syn::DeriveInput) -> String {
let src = path::get_template_source(path);
let nodes = parser::parse(&src);
generator::generate(ast, path, nodes)
struct TemplateMeta {
path: String,
}
fn get_template_meta(ast: &syn::DeriveInput) -> TemplateMeta {
let mut path = None;
let attr = ast.attrs.iter().find(|a| a.name() == "template").unwrap();
if let syn::MetaItem::List(_, ref inner) = attr.value {
for nm_item in inner {
if let &syn::NestedMetaItem::MetaItem(ref item) = nm_item {
if let &syn::MetaItem::NameValue(ref key, ref val) = item {
match key.as_ref() {
"path" => if let &syn::Lit::Str(ref s, _) = val {
path = Some(s.clone());
} else {
panic!("template path must be string literal");
},
_ => { panic!("unsupported annotation key found") }
}
}
}
}
}
if path.is_none() {
panic!("template path not found in struct attributes");
}
TemplateMeta { path: path.unwrap() }
}
pub fn build_template(ast: &syn::DeriveInput) -> String {
let meta = get_template_meta(ast);
let src = path::get_template_source(&meta.path);
let nodes = parser::parse(&src);
generator::generate(ast, &meta.path, nodes)
}

View File

@ -4,35 +4,6 @@ extern crate syn;
use proc_macro::TokenStream;
struct TemplateMeta {
path: String,
}
fn get_path_from_attrs(attrs: &[syn::Attribute]) -> TemplateMeta {
let mut path = None;
let attr = attrs.iter().find(|a| a.name() == "template").unwrap();
if let syn::MetaItem::List(_, ref inner) = attr.value {
for nm_item in inner {
if let &syn::NestedMetaItem::MetaItem(ref item) = nm_item {
if let &syn::MetaItem::NameValue(ref key, ref val) = item {
match key.as_ref() {
"path" => if let &syn::Lit::Str(ref s, _) = val {
path = Some(s.clone());
} else {
panic!("template path must be string literal");
},
_ => { panic!("unsupported annotation key found") }
}
}
}
}
}
if path.is_none() {
panic!("template path not found in struct attributes");
}
TemplateMeta { path: path.unwrap() }
}
#[proc_macro_derive(Template, attributes(template))]
pub fn derive_template(input: TokenStream) -> TokenStream {
let ast = syn::parse_derive_input(&input.to_string()).unwrap();
@ -40,6 +11,5 @@ pub fn derive_template(input: TokenStream) -> TokenStream {
syn::Body::Struct(ref data) => data,
_ => panic!("#[derive(Template)] can only be used with structs"),
};
let meta = get_path_from_attrs(&ast.attrs);
askama::build_template(&meta.path, &ast).parse().unwrap()
askama::build_template(&ast).parse().unwrap()
}