Skip to content

Commit 5fe1036

Browse files
committed
Extract some Tera logic out of site/lib.rs
1 parent d9123a8 commit 5fe1036

File tree

6 files changed

+122
-105
lines changed

6 files changed

+122
-105
lines changed

components/site/src/lib.rs

Lines changed: 16 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
pub mod link_checking;
12
pub mod sass;
23
pub mod sitemap;
3-
pub mod link_checking;
4+
pub mod tpls;
45

56
use std::collections::HashMap;
67
use std::fs::{copy, remove_dir_all};
@@ -12,18 +13,19 @@ use rayon::prelude::*;
1213
use serde_derive::Serialize;
1314
use tera::{Context, Tera};
1415

16+
use crate::link_checking::{check_external_links, check_internal_links_with_anchors};
17+
use crate::tpls::{load_tera, register_early_global_fns, register_tera_global_fns};
1518
use config::{get_config, Config, Taxonomy as TaxonomyConfig};
1619
use errors::{bail, Error, Result};
1720
use front_matter::InsertAnchor;
1821
use library::{
1922
find_taxonomies, sort_actual_pages_by_date, Library, Page, Paginator, Section, Taxonomy,
2023
TaxonomyItem,
2124
};
22-
use templates::{global_fns, render_redirect_template, ZOLA_TERA};
25+
use templates::render_redirect_template;
2326
use utils::fs::{copy_directory, create_directory, create_file, ensure_directory_exists};
2427
use utils::net::get_available_port;
25-
use utils::templates::{render_template, rewrite_theme_paths};
26-
use crate::link_checking::{check_internal_links_with_anchors, check_external_links};
28+
use utils::templates::render_template;
2729

2830
#[derive(Debug)]
2931
pub struct Site {
@@ -74,45 +76,12 @@ impl Site {
7476
let mut config = get_config(config_file);
7577
config.load_extra_syntaxes(path)?;
7678

77-
let tpl_glob =
78-
format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
79-
// Only parsing as we might be extending templates from themes and that would error
80-
// as we haven't loaded them yet
81-
let mut tera =
82-
Tera::parse(&tpl_glob).map_err(|e| Error::chain("Error parsing templates", e))?;
8379
if let Some(theme) = config.theme.clone() {
8480
// Grab data from the extra section of the theme
8581
config.merge_with_theme(&path.join("themes").join(&theme).join("theme.toml"))?;
86-
87-
// Test that the templates folder exist for that theme
88-
let theme_path = path.join("themes").join(&theme);
89-
if !theme_path.join("templates").exists() {
90-
bail!("Theme `{}` is missing a templates folder", theme);
91-
}
92-
93-
let theme_tpl_glob = format!(
94-
"{}/{}",
95-
path.to_string_lossy().replace("\\", "/"),
96-
format!("themes/{}/templates/**/*.*ml", theme)
97-
);
98-
let mut tera_theme = Tera::parse(&theme_tpl_glob)
99-
.map_err(|e| Error::chain("Error parsing templates from themes", e))?;
100-
rewrite_theme_paths(&mut tera_theme, &theme);
101-
// TODO: we do that twice, make it dry?
102-
if theme_path.join("templates").join("robots.txt").exists() {
103-
tera_theme
104-
.add_template_file(theme_path.join("templates").join("robots.txt"), None)?;
105-
}
106-
tera.extend(&tera_theme)?;
10782
}
108-
tera.extend(&ZOLA_TERA)?;
109-
tera.build_inheritance_chains()?;
11083

111-
// TODO: Tera doesn't use globset right now so we can load the robots.txt as part
112-
// of the glob above, therefore we load it manually if it exists.
113-
if path.join("templates").join("robots.txt").exists() {
114-
tera.add_template_file(path.join("templates").join("robots.txt"), Some("robots.txt"))?;
115-
}
84+
let tera = load_tera(path, &config)?;
11685

11786
let content_path = path.join("content");
11887
let static_path = path.join("static");
@@ -145,7 +114,7 @@ impl Site {
145114
}
146115

147116
/// The index sections are ALWAYS at those paths
148-
/// There are one index section for the basic language + 1 per language
117+
/// There are one index section for the default language + 1 per language
149118
fn index_section_paths(&self) -> Vec<(PathBuf, Option<String>)> {
150119
let mut res = vec![(self.content_path.join("_index.md"), None)];
151120
for language in &self.config.languages {
@@ -164,11 +133,6 @@ impl Site {
164133
self.live_reload = get_available_port(port_to_avoid);
165134
}
166135

167-
/// Get the number of orphan (== without section) pages in the site
168-
pub fn get_number_orphan_pages(&self) -> usize {
169-
self.library.read().unwrap().get_all_orphan_pages().len()
170-
}
171-
172136
pub fn set_base_url(&mut self, base_url: String) {
173137
let mut imageproc = self.imageproc.lock().expect("Couldn't lock imageproc (set_base_url)");
174138
imageproc.set_base_url(&base_url);
@@ -359,58 +323,14 @@ impl Site {
359323
Ok(())
360324
}
361325

362-
/// Adds global fns that are to be available to shortcodes while
363-
/// markdown
326+
// TODO: remove me in favour of the direct call to the fn once rebuild has changed
364327
pub fn register_early_global_fns(&mut self) {
365-
self.tera.register_function(
366-
"get_url",
367-
global_fns::GetUrl::new(
368-
self.config.clone(),
369-
self.permalinks.clone(),
370-
vec![self.static_path.clone(), self.output_path.clone(), self.content_path.clone()],
371-
),
372-
);
373-
self.tera.register_function(
374-
"resize_image",
375-
global_fns::ResizeImage::new(self.imageproc.clone()),
376-
);
377-
self.tera.register_function(
378-
"get_image_metadata",
379-
global_fns::GetImageMeta::new(self.content_path.clone()),
380-
);
381-
self.tera.register_function("load_data", global_fns::LoadData::new(self.base_path.clone()));
382-
self.tera.register_function("trans", global_fns::Trans::new(self.config.clone()));
383-
self.tera.register_function(
384-
"get_taxonomy_url",
385-
global_fns::GetTaxonomyUrl::new(&self.config.default_language, &self.taxonomies),
386-
);
387-
self.tera.register_function(
388-
"get_file_hash",
389-
global_fns::GetFileHash::new(vec![
390-
self.static_path.clone(),
391-
self.output_path.clone(),
392-
self.content_path.clone(),
393-
]),
394-
);
328+
register_early_global_fns(self);
395329
}
396330

331+
// TODO: remove me in favour of the direct call to the fn once rebuild has changed
397332
pub fn register_tera_global_fns(&mut self) {
398-
self.tera.register_function(
399-
"get_page",
400-
global_fns::GetPage::new(self.base_path.clone(), self.library.clone()),
401-
);
402-
self.tera.register_function(
403-
"get_section",
404-
global_fns::GetSection::new(self.base_path.clone(), self.library.clone()),
405-
);
406-
self.tera.register_function(
407-
"get_taxonomy",
408-
global_fns::GetTaxonomy::new(
409-
&self.config.default_language,
410-
self.taxonomies.clone(),
411-
self.library.clone(),
412-
),
413-
);
333+
register_tera_global_fns(self);
414334
}
415335

416336
/// Add a page to the site
@@ -703,6 +623,8 @@ impl Site {
703623
)
704624
}
705625

626+
/// Renders all the aliases for each page/section: a magic HTML template that redirects to
627+
/// the canonical one
706628
pub fn render_aliases(&self) -> Result<()> {
707629
ensure_directory_exists(&self.output_path)?;
708630
let library = self.library.read().unwrap();
@@ -837,6 +759,7 @@ impl Site {
837759
sitemap_url.pop(); // Remove trailing slash
838760
sitemap_index.push(sitemap_url);
839761
}
762+
840763
// Create main sitemap that reference numbered sitemaps
841764
let mut main_context = Context::new();
842765
main_context.insert("sitemaps", &sitemap_index);
@@ -993,6 +916,7 @@ impl Site {
993916
Ok(())
994917
}
995918

919+
// TODO: remove me when reload has changed
996920
/// Used only on reload
997921
pub fn render_index(&self) -> Result<()> {
998922
self.render_section(
@@ -1061,5 +985,3 @@ impl Site {
1061985
.collect::<Result<()>>()
1062986
}
1063987
}
1064-
1065-
impl Site {}

components/site/src/link_checking.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
21
use rayon::prelude::*;
32

4-
use errors::{Error, ErrorKind, Result};
53
use crate::Site;
6-
4+
use errors::{Error, ErrorKind, Result};
75

86
/// Very similar to check_external_links but can't be merged as far as I can see since we always
97
/// want to check the internal links but only the external in zola check :/
@@ -152,11 +150,7 @@ pub fn check_external_links(site: &Site) -> Result<()> {
152150
.collect()
153151
});
154152

155-
println!(
156-
"> Checked {} external link(s): {} error(s) found.",
157-
all_links.len(),
158-
errors.len()
159-
);
153+
println!("> Checked {} external link(s): {} error(s) found.", all_links.len(), errors.len());
160154

161155
if errors.is_empty() {
162156
return Ok(());

components/site/src/sass.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub fn compile_sass(base_path: &Path, output_path: &Path) -> Result<()> {
1818

1919
let mut options = Options::default();
2020
options.output_style = OutputStyle::Compressed;
21-
let mut compiled_paths = compile_sass_glob(&sass_path, output_path, "scss", &options.clone())?;
21+
let mut compiled_paths = compile_sass_glob(&sass_path, output_path, "scss", &options)?;
2222

2323
options.indented_syntax = true;
2424
compiled_paths.extend(compile_sass_glob(&sass_path, output_path, "sass", &options)?);

components/site/src/tpls.rs

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
use std::path::Path;
2+
3+
use tera::Tera;
4+
5+
use crate::Site;
6+
use config::Config;
7+
use errors::{bail, Error, Result};
8+
use templates::{global_fns, ZOLA_TERA};
9+
use utils::templates::rewrite_theme_paths;
10+
11+
pub fn load_tera(path: &Path, config: &Config) -> Result<Tera> {
12+
let tpl_glob =
13+
format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
14+
15+
// Only parsing as we might be extending templates from themes and that would error
16+
// as we haven't loaded them yet
17+
let mut tera =
18+
Tera::parse(&tpl_glob).map_err(|e| Error::chain("Error parsing templates", e))?;
19+
20+
if let Some(ref theme) = config.theme {
21+
// Test that the templates folder exist for that theme
22+
let theme_path = path.join("themes").join(&theme);
23+
if !theme_path.join("templates").exists() {
24+
bail!("Theme `{}` is missing a templates folder", theme);
25+
}
26+
27+
let theme_tpl_glob = format!(
28+
"{}/{}",
29+
path.to_string_lossy().replace("\\", "/"),
30+
format!("themes/{}/templates/**/*.*ml", theme)
31+
);
32+
let mut tera_theme = Tera::parse(&theme_tpl_glob)
33+
.map_err(|e| Error::chain("Error parsing templates from themes", e))?;
34+
rewrite_theme_paths(&mut tera_theme, &theme);
35+
36+
if theme_path.join("templates").join("robots.txt").exists() {
37+
tera_theme.add_template_file(theme_path.join("templates").join("robots.txt"), None)?;
38+
}
39+
tera.extend(&tera_theme)?;
40+
}
41+
tera.extend(&ZOLA_TERA)?;
42+
tera.build_inheritance_chains()?;
43+
44+
if path.join("templates").join("robots.txt").exists() {
45+
tera.add_template_file(path.join("templates").join("robots.txt"), Some("robots.txt"))?;
46+
}
47+
48+
Ok(tera)
49+
}
50+
51+
/// Adds global fns that are to be available to shortcodes while rendering markdown
52+
pub fn register_early_global_fns(site: &mut Site) {
53+
site.tera.register_function(
54+
"get_url",
55+
global_fns::GetUrl::new(
56+
site.config.clone(),
57+
site.permalinks.clone(),
58+
vec![site.static_path.clone(), site.output_path.clone(), site.content_path.clone()],
59+
),
60+
);
61+
site.tera
62+
.register_function("resize_image", global_fns::ResizeImage::new(site.imageproc.clone()));
63+
site.tera.register_function(
64+
"get_image_metadata",
65+
global_fns::GetImageMeta::new(site.content_path.clone()),
66+
);
67+
site.tera.register_function("load_data", global_fns::LoadData::new(site.base_path.clone()));
68+
site.tera.register_function("trans", global_fns::Trans::new(site.config.clone()));
69+
site.tera.register_function(
70+
"get_taxonomy_url",
71+
global_fns::GetTaxonomyUrl::new(&site.config.default_language, &site.taxonomies),
72+
);
73+
site.tera.register_function(
74+
"get_file_hash",
75+
global_fns::GetFileHash::new(vec![
76+
site.static_path.clone(),
77+
site.output_path.clone(),
78+
site.content_path.clone(),
79+
]),
80+
);
81+
}
82+
83+
/// Functions filled once we have parsed all the pages/sections only, so not available in shortcodes
84+
pub fn register_tera_global_fns(site: &mut Site) {
85+
site.tera.register_function(
86+
"get_page",
87+
global_fns::GetPage::new(site.base_path.clone(), site.library.clone()),
88+
);
89+
site.tera.register_function(
90+
"get_section",
91+
global_fns::GetSection::new(site.base_path.clone(), site.library.clone()),
92+
);
93+
site.tera.register_function(
94+
"get_taxonomy",
95+
global_fns::GetTaxonomy::new(
96+
&site.config.default_language,
97+
site.taxonomies.clone(),
98+
site.library.clone(),
99+
),
100+
);
101+
}

src/cmd/serve.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ use ws::{Message, Sender, WebSocket};
4242

4343
use errors::{Error as ZolaError, Result};
4444
use globset::GlobSet;
45-
use site::Site;
4645
use site::sass::compile_sass;
46+
use site::Site;
4747
use utils::fs::copy_file;
4848

4949
use crate::console;

src/console.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub fn notify_site_size(site: &Site) {
5454
println!(
5555
"-> Creating {} pages ({} orphan), {} sections, and processing {} images",
5656
library.pages().len(),
57-
site.get_number_orphan_pages(),
57+
library.get_all_orphan_pages().len(),
5858
library.sections().len() - 1, // -1 since we do not count the index as a section there
5959
site.num_img_ops(),
6060
);

0 commit comments

Comments
 (0)