You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1019 lines
37KB

  1. extern crate glob;
  2. extern crate rayon;
  3. extern crate serde;
  4. extern crate tera;
  5. #[macro_use]
  6. extern crate serde_derive;
  7. extern crate sass_rs;
  8. #[macro_use]
  9. extern crate errors;
  10. extern crate config;
  11. extern crate front_matter;
  12. extern crate imageproc;
  13. extern crate library;
  14. extern crate search;
  15. extern crate templates;
  16. extern crate utils;
  17. #[cfg(test)]
  18. extern crate tempfile;
  19. mod sitemap;
  20. use std::collections::{HashMap};
  21. use std::fs::{copy, create_dir_all, remove_dir_all};
  22. use std::path::{Path, PathBuf};
  23. use std::sync::{Arc, Mutex, RwLock};
  24. use glob::glob;
  25. use rayon::prelude::*;
  26. use sass_rs::{compile_file, Options as SassOptions, OutputStyle};
  27. use tera::{Context, Tera};
  28. use config::{get_config, Config};
  29. use errors::{Error, Result};
  30. use front_matter::InsertAnchor;
  31. use library::{
  32. find_taxonomies, sort_actual_pages_by_date, Library, Page, Paginator, Section, Taxonomy,
  33. };
  34. use templates::{global_fns, render_redirect_template, ZOLA_TERA};
  35. use utils::fs::{copy_directory, create_directory, create_file, ensure_directory_exists};
  36. use utils::net::get_available_port;
  37. use utils::templates::{render_template, rewrite_theme_paths};
  38. #[derive(Debug)]
  39. pub struct Site {
  40. /// The base path of the zola site
  41. pub base_path: PathBuf,
  42. /// The parsed config for the site
  43. pub config: Config,
  44. pub tera: Tera,
  45. imageproc: Arc<Mutex<imageproc::Processor>>,
  46. // the live reload port to be used if there is one
  47. pub live_reload: Option<u16>,
  48. pub output_path: PathBuf,
  49. content_path: PathBuf,
  50. pub static_path: PathBuf,
  51. pub taxonomies: Vec<Taxonomy>,
  52. /// A map of all .md files (section and pages) and their permalink
  53. /// We need that if there are relative links in the content that need to be resolved
  54. pub permalinks: HashMap<String, String>,
  55. /// Contains all pages and sections of the site
  56. pub library: Arc<RwLock<Library>>,
  57. }
  58. impl Site {
  59. /// Parse a site at the given path. Defaults to the current dir
  60. /// Passing in a path is possible using the `base-path` command line build option
  61. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  62. let path = path.as_ref();
  63. let mut config = get_config(path, config_file);
  64. config.load_extra_syntaxes(path)?;
  65. let tpl_glob =
  66. format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  67. // Only parsing as we might be extending templates from themes and that would error
  68. // as we haven't loaded them yet
  69. let mut tera =
  70. Tera::parse(&tpl_glob).map_err(|e| Error::chain("Error parsing templates", e))?;
  71. if let Some(theme) = config.theme.clone() {
  72. // Grab data from the extra section of the theme
  73. config.merge_with_theme(&path.join("themes").join(&theme).join("theme.toml"))?;
  74. // Test that the templates folder exist for that theme
  75. let theme_path = path.join("themes").join(&theme);
  76. if !theme_path.join("templates").exists() {
  77. bail!("Theme `{}` is missing a templates folder", theme);
  78. }
  79. let theme_tpl_glob = format!(
  80. "{}/{}",
  81. path.to_string_lossy().replace("\\", "/"),
  82. format!("themes/{}/templates/**/*.*ml", theme)
  83. );
  84. let mut tera_theme = Tera::parse(&theme_tpl_glob)
  85. .map_err(|e| Error::chain("Error parsing templates from themes", e))?;
  86. rewrite_theme_paths(&mut tera_theme, &theme);
  87. // TODO: we do that twice, make it dry?
  88. if theme_path.join("templates").join("robots.txt").exists() {
  89. tera_theme
  90. .add_template_file(theme_path.join("templates").join("robots.txt"), None)?;
  91. }
  92. tera_theme.build_inheritance_chains()?;
  93. tera.extend(&tera_theme)?;
  94. }
  95. tera.extend(&ZOLA_TERA)?;
  96. // the `extend` above already does it but hey
  97. tera.build_inheritance_chains()?;
  98. // TODO: Tera doesn't use globset right now so we can load the robots.txt as part
  99. // of the glob above, therefore we load it manually if it exists.
  100. if path.join("templates").join("robots.txt").exists() {
  101. tera.add_template_file(path.join("templates").join("robots.txt"), Some("robots.txt"))?;
  102. }
  103. let content_path = path.join("content");
  104. let static_path = path.join("static");
  105. let imageproc =
  106. imageproc::Processor::new(content_path.clone(), &static_path, &config.base_url);
  107. let site = Site {
  108. base_path: path.to_path_buf(),
  109. config,
  110. tera,
  111. imageproc: Arc::new(Mutex::new(imageproc)),
  112. live_reload: None,
  113. output_path: path.join("public"),
  114. content_path,
  115. static_path,
  116. taxonomies: Vec::new(),
  117. permalinks: HashMap::new(),
  118. // We will allocate it properly later on
  119. library: Arc::new(RwLock::new(Library::new(0, 0, false))),
  120. };
  121. Ok(site)
  122. }
  123. /// The index sections are ALWAYS at those paths
  124. /// There are one index section for the basic language + 1 per language
  125. fn index_section_paths(&self) -> Vec<(PathBuf, Option<String>)> {
  126. let mut res = vec![(self.content_path.join("_index.md"), None)];
  127. for language in &self.config.languages {
  128. res.push((
  129. self.content_path.join(format!("_index.{}.md", language.code)),
  130. Some(language.code.clone()),
  131. ));
  132. }
  133. res
  134. }
  135. /// We avoid the port the server is going to use as it's not bound yet
  136. /// when calling this function and we could end up having tried to bind
  137. /// both http and websocket server to the same port
  138. pub fn enable_live_reload(&mut self, port_to_avoid: u16) {
  139. self.live_reload = get_available_port(port_to_avoid);
  140. }
  141. /// Get the number of orphan (== without section) pages in the site
  142. pub fn get_number_orphan_pages(&self) -> usize {
  143. self.library.read().unwrap().get_all_orphan_pages().len()
  144. }
  145. pub fn set_base_url(&mut self, base_url: String) {
  146. let mut imageproc = self.imageproc.lock().expect("Couldn't lock imageproc (set_base_url)");
  147. imageproc.set_base_url(&base_url);
  148. self.config.base_url = base_url;
  149. }
  150. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  151. self.output_path = path.as_ref().to_path_buf();
  152. }
  153. /// Reads all .md files in the `content` directory and create pages/sections
  154. /// out of them
  155. pub fn load(&mut self) -> Result<()> {
  156. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  157. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  158. let (section_entries, page_entries): (Vec<_>, Vec<_>) = glob(&content_glob)
  159. .expect("Invalid glob")
  160. .filter_map(|e| e.ok())
  161. .filter(|e| !e.as_path().file_name().unwrap().to_str().unwrap().starts_with('.'))
  162. .partition(|entry| {
  163. entry.as_path().file_name().unwrap().to_str().unwrap().starts_with("_index.")
  164. });
  165. self.library = Arc::new(RwLock::new(Library::new(
  166. page_entries.len(),
  167. section_entries.len(),
  168. self.config.is_multilingual(),
  169. )));
  170. let sections = {
  171. let config = &self.config;
  172. section_entries
  173. .into_par_iter()
  174. .map(|entry| {
  175. let path = entry.as_path();
  176. Section::from_file(path, config, &self.base_path)
  177. })
  178. .collect::<Vec<_>>()
  179. };
  180. let pages = {
  181. let config = &self.config;
  182. page_entries
  183. .into_par_iter()
  184. .map(|entry| {
  185. let path = entry.as_path();
  186. Page::from_file(path, config, &self.base_path)
  187. })
  188. .collect::<Vec<_>>()
  189. };
  190. // Kinda duplicated code for add_section/add_page but necessary to do it that
  191. // way because of the borrow checker
  192. for section in sections {
  193. let s = section?;
  194. self.add_section(s, false)?;
  195. }
  196. self.create_default_index_sections()?;
  197. let mut pages_insert_anchors = HashMap::new();
  198. for page in pages {
  199. let p = page?;
  200. pages_insert_anchors.insert(
  201. p.file.path.clone(),
  202. self.find_parent_section_insert_anchor(&p.file.parent.clone(), &p.lang),
  203. );
  204. self.add_page(p, false)?;
  205. }
  206. // taxonomy Tera fns are loaded in `register_early_global_fns`
  207. // so we do need to populate it first.
  208. self.populate_taxonomies()?;
  209. self.register_early_global_fns();
  210. self.populate_sections();
  211. self.render_markdown()?;
  212. self.register_tera_global_fns();
  213. Ok(())
  214. }
  215. /// Insert a default index section for each language if necessary so we don't need to create
  216. /// a _index.md to render the index page at the root of the site
  217. pub fn create_default_index_sections(&mut self) -> Result<()> {
  218. for (index_path, lang) in self.index_section_paths() {
  219. if let Some(ref index_section) = self.library.read().unwrap().get_section(&index_path) {
  220. if self.config.build_search_index && !index_section.meta.in_search_index {
  221. bail!(
  222. "You have enabled search in the config but disabled it in the index section: \
  223. either turn off the search in the config or remote `in_search_index = true` from the \
  224. section front-matter."
  225. )
  226. }
  227. }
  228. let mut library = self.library.write().expect("Get lock for load");
  229. // Not in else because of borrow checker
  230. if !library.contains_section(&index_path) {
  231. let mut index_section = Section::default();
  232. index_section.file.parent = self.content_path.clone();
  233. index_section.file.filename =
  234. index_path.file_name().unwrap().to_string_lossy().to_string();
  235. if let Some(ref l) = lang {
  236. index_section.file.name = format!("_index.{}", l);
  237. index_section.permalink = self.config.make_permalink(l);
  238. let filename = format!("_index.{}.md", l);
  239. index_section.file.path = self.content_path.join(&filename);
  240. index_section.file.relative = filename;
  241. index_section.lang = index_section.file.find_language(&self.config)?;
  242. } else {
  243. index_section.file.name = "_index".to_string();
  244. index_section.permalink = self.config.make_permalink("");
  245. index_section.file.path = self.content_path.join("_index.md");
  246. index_section.file.relative = "_index.md".to_string();
  247. }
  248. library.insert_section(index_section);
  249. }
  250. }
  251. Ok(())
  252. }
  253. /// Render the markdown of all pages/sections
  254. /// Used in a build and in `serve` if a shortcode has changed
  255. pub fn render_markdown(&mut self) -> Result<()> {
  256. // Another silly thing needed to not borrow &self in parallel and
  257. // make the borrow checker happy
  258. let permalinks = &self.permalinks;
  259. let tera = &self.tera;
  260. let config = &self.config;
  261. // This is needed in the first place because of silly borrow checker
  262. let mut pages_insert_anchors = HashMap::new();
  263. for (_, p) in self.library.read().unwrap().pages() {
  264. pages_insert_anchors.insert(
  265. p.file.path.clone(),
  266. self.find_parent_section_insert_anchor(&p.file.parent.clone(), &p.lang),
  267. );
  268. }
  269. let mut library = self.library.write().expect("Get lock for render_markdown");
  270. library
  271. .pages_mut()
  272. .values_mut()
  273. .collect::<Vec<_>>()
  274. .par_iter_mut()
  275. .map(|page| {
  276. let insert_anchor = pages_insert_anchors[&page.file.path];
  277. page.render_markdown(permalinks, tera, config, insert_anchor)
  278. })
  279. .collect::<Result<()>>()?;
  280. library
  281. .sections_mut()
  282. .values_mut()
  283. .collect::<Vec<_>>()
  284. .par_iter_mut()
  285. .map(|section| section.render_markdown(permalinks, tera, config))
  286. .collect::<Result<()>>()?;
  287. Ok(())
  288. }
  289. /// Adds global fns that are to be available to shortcodes while
  290. /// markdown
  291. pub fn register_early_global_fns(&mut self) {
  292. self.tera.register_function(
  293. "get_url",
  294. global_fns::GetUrl::new(self.config.clone(), self.permalinks.clone()),
  295. );
  296. self.tera.register_function(
  297. "resize_image",
  298. global_fns::ResizeImage::new(self.imageproc.clone()),
  299. );
  300. self.tera.register_function("load_data", global_fns::LoadData::new(self.base_path.clone()));
  301. self.tera.register_function("trans", global_fns::Trans::new(self.config.clone()));
  302. self.tera.register_function(
  303. "get_taxonomy_url",
  304. global_fns::GetTaxonomyUrl::new(&self.taxonomies),
  305. );
  306. }
  307. pub fn register_tera_global_fns(&mut self) {
  308. self.tera.register_function(
  309. "get_page",
  310. global_fns::GetPage::new(self.base_path.clone(), self.library.clone()),
  311. );
  312. self.tera.register_function(
  313. "get_section",
  314. global_fns::GetSection::new(self.base_path.clone(), self.library.clone()),
  315. );
  316. self.tera.register_function(
  317. "get_taxonomy",
  318. global_fns::GetTaxonomy::new(self.taxonomies.clone(), self.library.clone()),
  319. );
  320. }
  321. /// Add a page to the site
  322. /// The `render` parameter is used in the serve command, when rebuilding a page.
  323. /// If `true`, it will also render the markdown for that page
  324. /// Returns the previous page struct if there was one at the same path
  325. pub fn add_page(&mut self, mut page: Page, render: bool) -> Result<Option<Page>> {
  326. self.permalinks.insert(page.file.relative.clone(), page.permalink.clone());
  327. if render {
  328. let insert_anchor =
  329. self.find_parent_section_insert_anchor(&page.file.parent, &page.lang);
  330. page.render_markdown(&self.permalinks, &self.tera, &self.config, insert_anchor)?;
  331. }
  332. let mut library = self.library.write().expect("Get lock for add_page");
  333. let prev = library.remove_page(&page.file.path);
  334. library.insert_page(page);
  335. Ok(prev)
  336. }
  337. /// Add a section to the site
  338. /// The `render` parameter is used in the serve command, when rebuilding a page.
  339. /// If `true`, it will also render the markdown for that page
  340. /// Returns the previous section struct if there was one at the same path
  341. pub fn add_section(&mut self, mut section: Section, render: bool) -> Result<Option<Section>> {
  342. self.permalinks.insert(section.file.relative.clone(), section.permalink.clone());
  343. if render {
  344. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  345. }
  346. let mut library = self.library.write().expect("Get lock for add_section");
  347. let prev = library.remove_section(&section.file.path);
  348. library.insert_section(section);
  349. Ok(prev)
  350. }
  351. /// Finds the insert_anchor for the parent section of the directory at `path`.
  352. /// Defaults to `AnchorInsert::None` if no parent section found
  353. pub fn find_parent_section_insert_anchor(
  354. &self,
  355. parent_path: &PathBuf,
  356. lang: &str,
  357. ) -> InsertAnchor {
  358. let parent = if lang != self.config.default_language {
  359. parent_path.join(format!("_index.{}.md", lang))
  360. } else {
  361. parent_path.join("_index.md")
  362. };
  363. match self.library.read().unwrap().get_section(&parent) {
  364. Some(s) => s.meta.insert_anchor_links,
  365. None => InsertAnchor::None,
  366. }
  367. }
  368. /// Find out the direct subsections of each subsection if there are some
  369. /// as well as the pages for each section
  370. pub fn populate_sections(&mut self) {
  371. let mut library = self.library.write().expect("Get lock for populate_sections");
  372. library.populate_sections(&self.config);
  373. }
  374. /// Find all the tags and categories if it's asked in the config
  375. pub fn populate_taxonomies(&mut self) -> Result<()> {
  376. if self.config.taxonomies.is_empty() {
  377. return Ok(());
  378. }
  379. self.taxonomies = find_taxonomies(&self.config, &self.library.read().unwrap())?;
  380. Ok(())
  381. }
  382. /// Inject live reload script tag if in live reload mode
  383. fn inject_livereload(&self, html: String) -> String {
  384. if let Some(port) = self.live_reload {
  385. return html.replace(
  386. "</body>",
  387. &format!(
  388. r#"<script src="/livereload.js?port={}&mindelay=10"></script></body>"#,
  389. port
  390. ),
  391. );
  392. }
  393. html
  394. }
  395. /// Copy the main `static` folder and the theme `static` folder if a theme is used
  396. pub fn copy_static_directories(&self) -> Result<()> {
  397. // The user files will overwrite the theme files
  398. if let Some(ref theme) = self.config.theme {
  399. copy_directory(
  400. &self.base_path.join("themes").join(theme).join("static"),
  401. &self.output_path,
  402. )?;
  403. }
  404. // We're fine with missing static folders
  405. if self.static_path.exists() {
  406. copy_directory(&self.static_path, &self.output_path)?;
  407. }
  408. Ok(())
  409. }
  410. pub fn num_img_ops(&self) -> usize {
  411. let imageproc = self.imageproc.lock().expect("Couldn't lock imageproc (num_img_ops)");
  412. imageproc.num_img_ops()
  413. }
  414. pub fn process_images(&self) -> Result<()> {
  415. let mut imageproc =
  416. self.imageproc.lock().expect("Couldn't lock imageproc (process_images)");
  417. imageproc.prune()?;
  418. imageproc.do_process()
  419. }
  420. /// Deletes the `public` directory if it exists
  421. pub fn clean(&self) -> Result<()> {
  422. if self.output_path.exists() {
  423. // Delete current `public` directory so we can start fresh
  424. remove_dir_all(&self.output_path)
  425. .map_err(|e| Error::chain("Couldn't delete output directory", e))?;
  426. }
  427. Ok(())
  428. }
  429. /// Renders a single content page
  430. pub fn render_page(&self, page: &Page) -> Result<()> {
  431. ensure_directory_exists(&self.output_path)?;
  432. // Copy the nesting of the content directory if we have sections for that page
  433. let mut current_path = self.output_path.to_path_buf();
  434. for component in page.path.split('/') {
  435. current_path.push(component);
  436. if !current_path.exists() {
  437. create_directory(&current_path)?;
  438. }
  439. }
  440. // Make sure the folder exists
  441. create_directory(&current_path)?;
  442. // Finally, create a index.html file there with the page rendered
  443. let output = page.render_html(&self.tera, &self.config, &self.library.read().unwrap())?;
  444. create_file(&current_path.join("index.html"), &self.inject_livereload(output))?;
  445. // Copy any asset we found previously into the same directory as the index.html
  446. for asset in &page.assets {
  447. let asset_path = asset.as_path();
  448. copy(
  449. &asset_path,
  450. &current_path
  451. .join(asset_path.file_name().expect("Couldn't get filename from page asset")),
  452. )?;
  453. }
  454. Ok(())
  455. }
  456. /// Deletes the `public` directory and builds the site
  457. pub fn build(&self) -> Result<()> {
  458. self.clean()?;
  459. // Generate/move all assets before rendering any content
  460. if let Some(ref theme) = self.config.theme {
  461. let theme_path = self.base_path.join("themes").join(theme);
  462. if theme_path.join("sass").exists() {
  463. self.compile_sass(&theme_path)?;
  464. }
  465. }
  466. if self.config.compile_sass {
  467. self.compile_sass(&self.base_path)?;
  468. }
  469. self.process_images()?;
  470. self.copy_static_directories()?;
  471. if self.config.build_search_index {
  472. self.build_search_index()?;
  473. }
  474. // Render aliases first to allow overwriting
  475. self.render_aliases()?;
  476. self.render_sections()?;
  477. self.render_orphan_pages()?;
  478. self.render_sitemap()?;
  479. let library = self.library.read().unwrap();
  480. if self.config.generate_rss {
  481. let pages = if self.config.is_multilingual() {
  482. library
  483. .pages_values()
  484. .iter()
  485. .filter(|p| p.lang == self.config.default_language)
  486. .map(|p| *p)
  487. .collect()
  488. } else {
  489. library.pages_values()
  490. };
  491. self.render_rss_feed(pages, None)?;
  492. }
  493. for lang in &self.config.languages {
  494. if !lang.rss {
  495. continue;
  496. }
  497. let pages =
  498. library.pages_values().iter().filter(|p| p.lang == lang.code).map(|p| *p).collect();
  499. self.render_rss_feed(pages, Some(&PathBuf::from(lang.code.clone())))?;
  500. }
  501. self.render_404()?;
  502. self.render_robots()?;
  503. self.render_taxonomies()?;
  504. Ok(())
  505. }
  506. pub fn build_search_index(&self) -> Result<()> {
  507. // index first
  508. create_file(
  509. &self.output_path.join(&format!("search_index.{}.js", self.config.default_language)),
  510. &format!(
  511. "window.searchIndex = {};",
  512. search::build_index(&self.config.default_language, &self.library.read().unwrap())?
  513. ),
  514. )?;
  515. // then elasticlunr.min.js
  516. create_file(&self.output_path.join("elasticlunr.min.js"), search::ELASTICLUNR_JS)?;
  517. Ok(())
  518. }
  519. pub fn compile_sass(&self, base_path: &Path) -> Result<()> {
  520. ensure_directory_exists(&self.output_path)?;
  521. let sass_path = {
  522. let mut sass_path = PathBuf::from(base_path);
  523. sass_path.push("sass");
  524. sass_path
  525. };
  526. let mut options = SassOptions::default();
  527. options.output_style = OutputStyle::Compressed;
  528. let mut compiled_paths = self.compile_sass_glob(&sass_path, "scss", &options.clone())?;
  529. options.indented_syntax = true;
  530. compiled_paths.extend(self.compile_sass_glob(&sass_path, "sass", &options)?);
  531. compiled_paths.sort();
  532. for window in compiled_paths.windows(2) {
  533. if window[0].1 == window[1].1 {
  534. bail!(
  535. "SASS path conflict: \"{}\" and \"{}\" both compile to \"{}\"",
  536. window[0].0.display(),
  537. window[1].0.display(),
  538. window[0].1.display(),
  539. );
  540. }
  541. }
  542. Ok(())
  543. }
  544. fn compile_sass_glob(
  545. &self,
  546. sass_path: &Path,
  547. extension: &str,
  548. options: &SassOptions,
  549. ) -> Result<Vec<(PathBuf, PathBuf)>> {
  550. let glob_string = format!("{}/**/*.{}", sass_path.display(), extension);
  551. let files = glob(&glob_string)
  552. .expect("Invalid glob for sass")
  553. .filter_map(|e| e.ok())
  554. .filter(|entry| {
  555. !entry.as_path().file_name().unwrap().to_string_lossy().starts_with('_')
  556. })
  557. .collect::<Vec<_>>();
  558. let mut compiled_paths = Vec::new();
  559. for file in files {
  560. let css = compile_file(&file, options.clone())?;
  561. let path_inside_sass = file.strip_prefix(&sass_path).unwrap();
  562. let parent_inside_sass = path_inside_sass.parent();
  563. let css_output_path = self.output_path.join(path_inside_sass).with_extension("css");
  564. if parent_inside_sass.is_some() {
  565. create_dir_all(&css_output_path.parent().unwrap())?;
  566. }
  567. create_file(&css_output_path, &css)?;
  568. compiled_paths.push((path_inside_sass.to_owned(), css_output_path));
  569. }
  570. Ok(compiled_paths)
  571. }
  572. pub fn render_aliases(&self) -> Result<()> {
  573. ensure_directory_exists(&self.output_path)?;
  574. for (_, page) in self.library.read().unwrap().pages() {
  575. for alias in &page.meta.aliases {
  576. let mut output_path = self.output_path.to_path_buf();
  577. let mut split = alias.split('/').collect::<Vec<_>>();
  578. // If the alias ends with an html file name, use that instead of mapping
  579. // as a path containing an `index.html`
  580. let page_name = match split.pop() {
  581. Some(part) if part.ends_with(".html") => part,
  582. Some(part) => {
  583. split.push(part);
  584. "index.html"
  585. }
  586. None => "index.html",
  587. };
  588. for component in split {
  589. output_path.push(&component);
  590. if !output_path.exists() {
  591. create_directory(&output_path)?;
  592. }
  593. }
  594. create_file(
  595. &output_path.join(page_name),
  596. &render_redirect_template(&page.permalink, &self.tera)?,
  597. )?;
  598. }
  599. }
  600. Ok(())
  601. }
  602. /// Renders 404.html
  603. pub fn render_404(&self) -> Result<()> {
  604. ensure_directory_exists(&self.output_path)?;
  605. let mut context = Context::new();
  606. context.insert("config", &self.config);
  607. let output = render_template("404.html", &self.tera, context, &self.config.theme)?;
  608. create_file(&self.output_path.join("404.html"), &self.inject_livereload(output))
  609. }
  610. /// Renders robots.txt
  611. pub fn render_robots(&self) -> Result<()> {
  612. ensure_directory_exists(&self.output_path)?;
  613. let mut context = Context::new();
  614. context.insert("config", &self.config);
  615. create_file(
  616. &self.output_path.join("robots.txt"),
  617. &render_template("robots.txt", &self.tera, context, &self.config.theme)?,
  618. )
  619. }
  620. /// Renders all taxonomies with at least one non-draft post
  621. pub fn render_taxonomies(&self) -> Result<()> {
  622. for taxonomy in &self.taxonomies {
  623. self.render_taxonomy(taxonomy)?;
  624. }
  625. Ok(())
  626. }
  627. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  628. if taxonomy.items.is_empty() {
  629. return Ok(());
  630. }
  631. ensure_directory_exists(&self.output_path)?;
  632. let output_path = if taxonomy.kind.lang != self.config.default_language {
  633. let mid_path = self.output_path.join(&taxonomy.kind.lang);
  634. create_directory(&mid_path)?;
  635. mid_path.join(&taxonomy.kind.name)
  636. } else {
  637. self.output_path.join(&taxonomy.kind.name)
  638. };
  639. let list_output =
  640. taxonomy.render_all_terms(&self.tera, &self.config, &self.library.read().unwrap())?;
  641. create_directory(&output_path)?;
  642. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  643. let library = self.library.read().unwrap();
  644. taxonomy
  645. .items
  646. .par_iter()
  647. .map(|item| {
  648. let path = output_path.join(&item.slug);
  649. if taxonomy.kind.is_paginated() {
  650. self.render_paginated(
  651. &path,
  652. &Paginator::from_taxonomy(&taxonomy, item, &library),
  653. )?;
  654. } else {
  655. let single_output =
  656. taxonomy.render_term(item, &self.tera, &self.config, &library)?;
  657. create_directory(&path)?;
  658. create_file(&path.join("index.html"), &self.inject_livereload(single_output))?;
  659. }
  660. if taxonomy.kind.rss {
  661. self.render_rss_feed(
  662. item.pages.iter().map(|p| library.get_page_by_key(*p)).collect(),
  663. Some(&PathBuf::from(format!("{}/{}", taxonomy.kind.name, item.slug))),
  664. )
  665. } else {
  666. Ok(())
  667. }
  668. })
  669. .collect::<Result<()>>()
  670. }
  671. /// What it says on the tin
  672. pub fn render_sitemap(&self) -> Result<()> {
  673. ensure_directory_exists(&self.output_path)?;
  674. let library = self.library.read().unwrap();
  675. let all_sitemap_entries = sitemap::find_entries(
  676. &library,
  677. &self.taxonomies[..],
  678. &self.config,
  679. );
  680. let sitemap_limit = 30000;
  681. if all_sitemap_entries.len() < sitemap_limit {
  682. // Create single sitemap
  683. let mut context = Context::new();
  684. context.insert("entries", &all_sitemap_entries);
  685. let sitemap = &render_template("sitemap.xml", &self.tera, context, &self.config.theme)?;
  686. create_file(&self.output_path.join("sitemap.xml"), sitemap)?;
  687. return Ok(());
  688. }
  689. // Create multiple sitemaps (max 30000 urls each)
  690. let mut sitemap_index = Vec::new();
  691. for (i, chunk) in
  692. all_sitemap_entries.iter().collect::<Vec<_>>().chunks(sitemap_limit).enumerate()
  693. {
  694. let mut context = Context::new();
  695. context.insert("entries", &chunk);
  696. let sitemap = &render_template("sitemap.xml", &self.tera, context, &self.config.theme)?;
  697. let file_name = format!("sitemap{}.xml", i + 1);
  698. create_file(&self.output_path.join(&file_name), sitemap)?;
  699. let mut sitemap_url: String = self.config.make_permalink(&file_name);
  700. sitemap_url.pop(); // Remove trailing slash
  701. sitemap_index.push(sitemap_url);
  702. }
  703. // Create main sitemap that reference numbered sitemaps
  704. let mut main_context = Context::new();
  705. main_context.insert("sitemaps", &sitemap_index);
  706. let sitemap = &render_template(
  707. "split_sitemap_index.xml",
  708. &self.tera,
  709. main_context,
  710. &self.config.theme,
  711. )?;
  712. create_file(&self.output_path.join("sitemap.xml"), sitemap)?;
  713. Ok(())
  714. }
  715. /// Renders a RSS feed for the given path and at the given path
  716. /// If both arguments are `None`, it will render only the RSS feed for the whole
  717. /// site at the root folder.
  718. pub fn render_rss_feed(
  719. &self,
  720. all_pages: Vec<&Page>,
  721. base_path: Option<&PathBuf>,
  722. ) -> Result<()> {
  723. ensure_directory_exists(&self.output_path)?;
  724. let mut context = Context::new();
  725. let mut pages = all_pages
  726. .into_iter()
  727. .filter(|p| p.meta.date.is_some() && !p.is_draft())
  728. .collect::<Vec<_>>();
  729. // Don't generate a RSS feed if none of the pages has a date
  730. if pages.is_empty() {
  731. return Ok(());
  732. }
  733. pages.par_sort_unstable_by(sort_actual_pages_by_date);
  734. context.insert("last_build_date", &pages[0].meta.date.clone());
  735. let library = self.library.read().unwrap();
  736. // limit to the last n elements if the limit is set; otherwise use all.
  737. let num_entries = self.config.rss_limit.unwrap_or_else(|| pages.len());
  738. let p = pages
  739. .iter()
  740. .take(num_entries)
  741. .map(|x| x.to_serialized_basic(&library))
  742. .collect::<Vec<_>>();
  743. context.insert("pages", &p);
  744. context.insert("config", &self.config);
  745. let rss_feed_url = if let Some(ref base) = base_path {
  746. self.config.make_permalink(&base.join("rss.xml").to_string_lossy().replace('\\', "/"))
  747. } else {
  748. self.config.make_permalink("rss.xml")
  749. };
  750. context.insert("feed_url", &rss_feed_url);
  751. let feed = &render_template("rss.xml", &self.tera, context, &self.config.theme)?;
  752. if let Some(ref base) = base_path {
  753. let mut output_path = self.output_path.clone();
  754. for component in base.components() {
  755. output_path.push(component);
  756. if !output_path.exists() {
  757. create_directory(&output_path)?;
  758. }
  759. }
  760. create_file(&output_path.join("rss.xml"), feed)?;
  761. } else {
  762. create_file(&self.output_path.join("rss.xml"), feed)?;
  763. }
  764. Ok(())
  765. }
  766. /// Renders a single section
  767. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  768. ensure_directory_exists(&self.output_path)?;
  769. let mut output_path = self.output_path.clone();
  770. if section.lang != self.config.default_language {
  771. output_path.push(&section.lang);
  772. if !output_path.exists() {
  773. create_directory(&output_path)?;
  774. }
  775. }
  776. for component in &section.file.components {
  777. output_path.push(component);
  778. if !output_path.exists() {
  779. create_directory(&output_path)?;
  780. }
  781. }
  782. // Copy any asset we found previously into the same directory as the index.html
  783. for asset in &section.assets {
  784. let asset_path = asset.as_path();
  785. copy(
  786. &asset_path,
  787. &output_path.join(
  788. asset_path.file_name().expect("Failed to get asset filename for section"),
  789. ),
  790. )?;
  791. }
  792. if render_pages {
  793. section
  794. .pages
  795. .par_iter()
  796. .map(|k| self.render_page(self.library.read().unwrap().get_page_by_key(*k)))
  797. .collect::<Result<()>>()?;
  798. }
  799. if !section.meta.render {
  800. return Ok(());
  801. }
  802. if let Some(ref redirect_to) = section.meta.redirect_to {
  803. let permalink = self.config.make_permalink(redirect_to);
  804. create_file(
  805. &output_path.join("index.html"),
  806. &render_redirect_template(&permalink, &self.tera)?,
  807. )?;
  808. return Ok(());
  809. }
  810. if section.meta.is_paginated() {
  811. self.render_paginated(
  812. &output_path,
  813. &Paginator::from_section(&section, &self.library.read().unwrap()),
  814. )?;
  815. } else {
  816. let output =
  817. section.render_html(&self.tera, &self.config, &self.library.read().unwrap())?;
  818. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  819. }
  820. Ok(())
  821. }
  822. /// Used only on reload
  823. pub fn render_index(&self) -> Result<()> {
  824. self.render_section(
  825. &self
  826. .library
  827. .read()
  828. .unwrap()
  829. .get_section(&self.content_path.join("_index.md"))
  830. .expect("Failed to get index section"),
  831. false,
  832. )
  833. }
  834. /// Renders all sections
  835. pub fn render_sections(&self) -> Result<()> {
  836. self.library
  837. .read()
  838. .unwrap()
  839. .sections_values()
  840. .into_par_iter()
  841. .map(|s| self.render_section(s, true))
  842. .collect::<Result<()>>()
  843. }
  844. /// Renders all pages that do not belong to any sections
  845. pub fn render_orphan_pages(&self) -> Result<()> {
  846. ensure_directory_exists(&self.output_path)?;
  847. let library = self.library.read().unwrap();
  848. for page in library.get_all_orphan_pages() {
  849. self.render_page(page)?;
  850. }
  851. Ok(())
  852. }
  853. /// Renders a list of pages when the section/index is wanting pagination.
  854. pub fn render_paginated(&self, output_path: &Path, paginator: &Paginator) -> Result<()> {
  855. ensure_directory_exists(&self.output_path)?;
  856. let folder_path = output_path.join(&paginator.paginate_path);
  857. create_directory(&folder_path)?;
  858. paginator
  859. .pagers
  860. .par_iter()
  861. .map(|pager| {
  862. let page_path = folder_path.join(&format!("{}", pager.index));
  863. create_directory(&page_path)?;
  864. let output = paginator.render_pager(
  865. pager,
  866. &self.config,
  867. &self.tera,
  868. &self.library.read().unwrap(),
  869. )?;
  870. if pager.index > 1 {
  871. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  872. } else {
  873. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  874. create_file(
  875. &page_path.join("index.html"),
  876. &render_redirect_template(&paginator.permalink, &self.tera)?,
  877. )?;
  878. }
  879. Ok(())
  880. })
  881. .collect::<Result<()>>()
  882. }
  883. }