Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add possibility to specify template directories #103

Merged
merged 2 commits into from
Jul 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions askama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,9 @@ fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
/// that have templates, to make sure the crate gets rebuilt when template
/// source code changes.
pub fn rerun_if_templates_changed() {
visit_dirs(&path::template_dir(), &|e: &DirEntry| {
println!("cargo:rerun-if-changed={}", e.path().to_str().unwrap());
}).unwrap();
for template_dir in path::template_dirs().iter() {
visit_dirs(template_dir, &|e: &DirEntry| {
println!("cargo:rerun-if-changed={}", e.path().to_str().unwrap());
}).unwrap();
}
}
6 changes: 4 additions & 2 deletions askama_shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ workspace = ".."

[features]
default = []
serde-json = ["serde", "serde_json"]
serde-json = ["serde_json"]
iron = []
rocket = []

[dependencies]
serde = { version = "1.0", optional = true }
serde = "1.0"
serde_derive = "1.0"
serde_json = { version = "1.0", optional = true }
toml = "0.4"
4 changes: 3 additions & 1 deletion askama_shared/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#![cfg_attr(feature = "cargo-clippy", allow(unused_parens))]

#[cfg(feature = "serde-json")]
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "serde-json")]
extern crate serde_json;
extern crate toml;

pub use error::{Error, Result};
pub use escaping::MarkupDisplay;
Expand Down
92 changes: 72 additions & 20 deletions askama_shared/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,20 @@ use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

use toml;

fn search_template_in_dirs<'a>(dirs: &'a [PathBuf], path: &Path) -> Option<&'a PathBuf> {
dirs.iter().find(|dir| dir.join(path).exists())
}

pub fn get_template_source(tpl_path: &Path) -> String {
let mut path = template_dir();
path.push(tpl_path);
let dirs = template_dirs();
let path = search_template_in_dirs(&dirs, tpl_path)
.map(|dir| dir.join(tpl_path))
.expect(&format!(
"template file '{}' does not exist",
tpl_path.to_str().unwrap()
));
let mut f = match File::open(&path) {
Err(_) => {
let msg = format!("unable to open template file '{}'", &path.to_str().unwrap());
Expand All @@ -22,34 +33,75 @@ pub fn get_template_source(tpl_path: &Path) -> String {
}

pub fn find_template_from_path(path: &str, start_at: Option<&Path>) -> PathBuf {
let root = template_dir();
let dirs = template_dirs();
if let Some(rel) = start_at {
let mut fs_rel_path = root.clone();
fs_rel_path.push(rel);
fs_rel_path = fs_rel_path.with_file_name(path);
let root = search_template_in_dirs(&dirs, rel).expect(&format!(
"unable to find previously available template file '{}'",
rel.to_str().unwrap()
));
let fs_rel_path = root.join(rel).with_file_name(path);
if fs_rel_path.exists() {
return fs_rel_path.strip_prefix(&root).unwrap().to_owned();
}
}

let mut fs_abs_path = root.clone();
let path = Path::new(path);
fs_abs_path.push(Path::new(path));
if fs_abs_path.exists() {
path.to_owned()
} else {
panic!(format!(
"template {:?} not found at {:?}",
path.to_str().unwrap(),
fs_abs_path
));
search_template_in_dirs(&dirs, &path).expect(&format!(
"template {:?} not found in directories {:?}",
path.to_str().unwrap(),
dirs
));
path.to_owned()
}

static CONFIG_FILE_NAME: &str = "askama.toml";

#[derive(Deserialize)]
struct RawConfig {
dirs: Option<Vec<String>>,
}

struct Config {
dirs: Vec<PathBuf>,
}

impl RawConfig {
fn from_file(filename: &PathBuf) -> Option<RawConfig> {
if filename.exists() {
let mut contents = String::new();
File::open(filename)
.unwrap()
.read_to_string(&mut contents)
.unwrap();
Some(toml::from_str(&contents).unwrap())
} else {
None
}
}
}

impl Config {
fn from_file() -> Config {
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let filename = root.join(CONFIG_FILE_NAME);
RawConfig::from_file(&filename).map_or_else(
|| Config {
dirs: vec![root.join("templates")],
},
|config| Config {
dirs: config
.dirs
.unwrap_or_else(|| Vec::new())
.into_iter()
.map(|directory| root.join(directory))
.collect(),
},
)
}
}

pub fn template_dir() -> PathBuf {
let mut path = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
path.push("templates");
path
pub fn template_dirs() -> Vec<PathBuf> {
Config::from_file().dirs
}

#[cfg(test)]
Expand Down