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.

1014 lines
36KB

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