Skip to content

Commit

Permalink
Allow functions to look into current theme static folder
Browse files Browse the repository at this point in the history
Closes #1416
  • Loading branch information
Keats committed Jun 24, 2021
1 parent 0cd1ea9 commit 545e766
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 73 deletions.
19 changes: 14 additions & 5 deletions components/site/src/tpls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,20 @@ pub fn register_early_global_fns(site: &mut Site) -> TeraResult<()> {
);
site.tera.register_function(
"resize_image",
global_fns::ResizeImage::new(site.base_path.clone(), site.imageproc.clone()),
global_fns::ResizeImage::new(
site.base_path.clone(),
site.imageproc.clone(),
site.config.theme.clone(),
),
);
site.tera.register_function(
"get_image_metadata",
global_fns::GetImageMetadata::new(site.base_path.clone()),
global_fns::GetImageMetadata::new(site.base_path.clone(), site.config.theme.clone()),
);
site.tera.register_function(
"load_data",
global_fns::LoadData::new(site.base_path.clone(), site.config.theme.clone()),
);
site.tera.register_function("load_data", global_fns::LoadData::new(site.base_path.clone()));
site.tera.register_function("trans", global_fns::Trans::new(site.config.clone()));
site.tera.register_function(
"get_taxonomy_url",
Expand All @@ -39,8 +46,10 @@ pub fn register_early_global_fns(site: &mut Site) -> TeraResult<()> {
site.config.slugify.taxonomies,
),
);
site.tera
.register_function("get_file_hash", global_fns::GetFileHash::new(site.base_path.clone()));
site.tera.register_function(
"get_file_hash",
global_fns::GetFileHash::new(site.base_path.clone(), site.config.theme.clone()),
);

Ok(())
}
Expand Down
23 changes: 12 additions & 11 deletions components/templates/src/global_fns/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl TeraFn for GetUrl {
}

if cachebust {
match search_for_file(&self.base_path, &path_with_lang)
match search_for_file(&self.base_path, &path_with_lang, &self.config.theme)
.map_err(|e| format!("`get_url`: {}", e))?
.and_then(|(p, _)| fs::File::open(&p).ok())
.and_then(|f| compute_file_hash::<Sha256>(f, false).ok())
Expand Down Expand Up @@ -141,10 +141,11 @@ impl TeraFn for GetUrl {
#[derive(Debug)]
pub struct GetFileHash {
base_path: PathBuf,
theme: Option<String>,
}
impl GetFileHash {
pub fn new(base_path: PathBuf) -> Self {
Self { base_path }
pub fn new(base_path: PathBuf, theme: Option<String>) -> Self {
Self { base_path, theme }
}
}

Expand All @@ -168,7 +169,7 @@ impl TeraFn for GetFileHash {
)
.unwrap_or(true);

let file_path = match search_for_file(&self.base_path, &path)
let file_path = match search_for_file(&self.base_path, &path, &self.theme)
.map_err(|e| format!("`get_file_hash`: {}", e))?
{
Some((f, _)) => f,
Expand Down Expand Up @@ -358,7 +359,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha256_no_base64() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
args.insert("sha_type".to_string(), to_value(256).unwrap());
Expand All @@ -372,7 +373,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha256_base64() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
args.insert("sha_type".to_string(), to_value(256).unwrap());
Expand All @@ -383,7 +384,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha384_no_base64() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
args.insert("base64".to_string(), to_value(false).unwrap());
Expand All @@ -396,7 +397,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha384() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
assert_eq!(
Expand All @@ -408,7 +409,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha512_no_base64() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
args.insert("sha_type".to_string(), to_value(512).unwrap());
Expand All @@ -422,7 +423,7 @@ title = "A title"
#[test]
fn can_get_file_hash_sha512() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("app.css").unwrap());
args.insert("sha_type".to_string(), to_value(512).unwrap());
Expand All @@ -435,7 +436,7 @@ title = "A title"
#[test]
fn error_when_file_not_found_for_hash() {
let dir = create_temp_dir();
let static_fn = GetFileHash::new(dir.into_path());
let static_fn = GetFileHash::new(dir.into_path(), None);
let mut args = HashMap::new();
args.insert("path".to_string(), to_value("doesnt-exist").unwrap());
let err = format!("{}", static_fn.call(&args).unwrap_err());
Expand Down
12 changes: 10 additions & 2 deletions components/templates/src/global_fns/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,20 @@ use utils::fs::is_path_in_directory;
/// 1. base_path + path
/// 2. base_path + static + path
/// 3. base_path + content + path
/// 4. base_path + themes + {current_theme} + static + path
/// A path starting with @/ will replace it with `content/` and a path starting with `/` will have
/// it removed.
/// It also returns the unified path so it can be used as unique hash for a given file.
/// It will error if the file is not contained in the Zola directory.
pub fn search_for_file(base_path: &Path, path: &str) -> Result<Option<(PathBuf, String)>> {
let search_paths = [base_path.join("static"), base_path.join("content")];
pub fn search_for_file(
base_path: &Path,
path: &str,
theme: &Option<String>,
) -> Result<Option<(PathBuf, String)>> {
let mut search_paths = vec![base_path.join("static"), base_path.join("content")];
if let Some(t) = theme {
search_paths.push(base_path.join("themes").join(t).join("static"));
}
let actual_path = if path.starts_with("@/") {
Cow::Owned(path.replace("@/", "content/"))
} else {
Expand Down
43 changes: 35 additions & 8 deletions components/templates/src/global_fns/images.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@ use crate::global_fns::helpers::search_for_file;
pub struct ResizeImage {
/// The base path of the Zola site
base_path: PathBuf,
theme: Option<String>,
imageproc: Arc<Mutex<imageproc::Processor>>,
}

impl ResizeImage {
pub fn new(base_path: PathBuf, imageproc: Arc<Mutex<imageproc::Processor>>) -> Self {
Self { base_path, imageproc }
pub fn new(
base_path: PathBuf,
imageproc: Arc<Mutex<imageproc::Processor>>,
theme: Option<String>,
) -> Self {
Self { base_path, imageproc, theme }
}
}

Expand Down Expand Up @@ -55,7 +60,7 @@ impl TeraFn for ResizeImage {
}

let mut imageproc = self.imageproc.lock().unwrap();
let (file_path, unified_path) = match search_for_file(&self.base_path, &path)
let (file_path, unified_path) = match search_for_file(&self.base_path, &path, &self.theme)
.map_err(|e| format!("`resize_image`: {}", e))?
{
Some(f) => f,
Expand All @@ -76,12 +81,13 @@ impl TeraFn for ResizeImage {
pub struct GetImageMetadata {
/// The base path of the Zola site
base_path: PathBuf,
theme: Option<String>,
result_cache: Arc<Mutex<HashMap<String, Value>>>,
}

impl GetImageMetadata {
pub fn new(base_path: PathBuf) -> Self {
Self { base_path, result_cache: Arc::new(Mutex::new(HashMap::new())) }
pub fn new(base_path: PathBuf, theme: Option<String>) -> Self {
Self { base_path, result_cache: Arc::new(Mutex::new(HashMap::new())), theme }
}
}

Expand All @@ -99,7 +105,7 @@ impl TeraFn for GetImageMetadata {
)
.unwrap_or(false);

let (src_path, unified_path) = match search_for_file(&self.base_path, &path)
let (src_path, unified_path) = match search_for_file(&self.base_path, &path, &self.theme)
.map_err(|e| format!("`get_image_metadata`: {}", e))?
{
Some((f, p)) => (f, p),
Expand Down Expand Up @@ -142,10 +148,16 @@ mod tests {
let dir = tempdir().unwrap();
create_dir_all(dir.path().join("content").join("gallery")).unwrap();
create_dir_all(dir.path().join("static")).unwrap();
create_dir_all(dir.path().join("themes").join("name").join("static")).unwrap();
copy("gutenberg.jpg", dir.path().join("content").join("gutenberg.jpg")).unwrap();
copy("gutenberg.jpg", dir.path().join("content").join("gallery").join("asset.jpg"))
.unwrap();
copy("gutenberg.jpg", dir.path().join("static").join("gutenberg.jpg")).unwrap();
copy(
"gutenberg.jpg",
dir.path().join("themes").join("name").join("static").join("in-theme.jpg"),
)
.unwrap();
dir
}

Expand All @@ -156,7 +168,11 @@ mod tests {
let dir = create_dir_with_image();
let imageproc = imageproc::Processor::new(dir.path().to_path_buf(), &Config::default());

let static_fn = ResizeImage::new(dir.path().to_path_buf(), Arc::new(Mutex::new(imageproc)));
let static_fn = ResizeImage::new(
dir.path().to_path_buf(),
Arc::new(Mutex::new(imageproc)),
Some("name".to_owned()),
);
let mut args = HashMap::new();
args.insert("height".to_string(), to_value(40).unwrap());
args.insert("width".to_string(), to_value(40).unwrap());
Expand Down Expand Up @@ -212,14 +228,25 @@ mod tests {
data["url"],
to_value("http://a-website.com/processed_images/6296a3c153f701be00.jpg").unwrap()
);

// 6. Looking up a file in the theme
args.insert("path".to_string(), to_value("in-theme.jpg").unwrap());
assert_eq!(
data["static_path"],
to_value(&format!("{}", static_path.join("6296a3c153f701be00.jpg").display())).unwrap()
);
assert_eq!(
data["url"],
to_value("http://a-website.com/processed_images/6296a3c153f701be00.jpg").unwrap()
);
}

// TODO: consider https://github.com/getzola/zola/issues/1161
#[test]
fn can_get_image_metadata() {
let dir = create_dir_with_image();

let static_fn = GetImageMetadata::new(dir.path().to_path_buf());
let static_fn = GetImageMetadata::new(dir.path().to_path_buf(), None);

// Let's test a few scenarii
let mut args = HashMap::new();
Expand Down
Loading

0 comments on commit 545e766

Please sign in to comment.