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.

982 lines
35KB

  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. self.render_rss_feed(self.library.pages_values(), None)?;
  450. }
  451. self.render_404()?;
  452. self.render_robots()?;
  453. self.render_taxonomies()?;
  454. if let Some(ref theme) = self.config.theme {
  455. let theme_path = self.base_path.join("themes").join(theme);
  456. if theme_path.join("sass").exists() {
  457. self.compile_sass(&theme_path)?;
  458. }
  459. }
  460. if self.config.compile_sass {
  461. self.compile_sass(&self.base_path)?;
  462. }
  463. self.process_images()?;
  464. self.copy_static_directories()?;
  465. if self.config.build_search_index {
  466. self.build_search_index()?;
  467. }
  468. Ok(())
  469. }
  470. pub fn build_search_index(&self) -> Result<()> {
  471. // index first
  472. create_file(
  473. &self.output_path.join(&format!("search_index.{}.js", self.config.default_language)),
  474. &format!(
  475. "window.searchIndex = {};",
  476. search::build_index(&self.config.default_language, &self.library)?
  477. ),
  478. )?;
  479. // then elasticlunr.min.js
  480. create_file(&self.output_path.join("elasticlunr.min.js"), search::ELASTICLUNR_JS)?;
  481. Ok(())
  482. }
  483. pub fn compile_sass(&self, base_path: &Path) -> Result<()> {
  484. ensure_directory_exists(&self.output_path)?;
  485. let sass_path = {
  486. let mut sass_path = PathBuf::from(base_path);
  487. sass_path.push("sass");
  488. sass_path
  489. };
  490. let mut options = SassOptions::default();
  491. options.output_style = OutputStyle::Compressed;
  492. let mut compiled_paths = self.compile_sass_glob(&sass_path, "scss", &options.clone())?;
  493. options.indented_syntax = true;
  494. compiled_paths.extend(self.compile_sass_glob(&sass_path, "sass", &options)?);
  495. compiled_paths.sort();
  496. for window in compiled_paths.windows(2) {
  497. if window[0].1 == window[1].1 {
  498. bail!(
  499. "SASS path conflict: \"{}\" and \"{}\" both compile to \"{}\"",
  500. window[0].0.display(),
  501. window[1].0.display(),
  502. window[0].1.display(),
  503. );
  504. }
  505. }
  506. Ok(())
  507. }
  508. fn compile_sass_glob(
  509. &self,
  510. sass_path: &Path,
  511. extension: &str,
  512. options: &SassOptions,
  513. ) -> Result<Vec<(PathBuf, PathBuf)>> {
  514. let glob_string = format!("{}/**/*.{}", sass_path.display(), extension);
  515. let files = glob(&glob_string)
  516. .unwrap()
  517. .filter_map(|e| e.ok())
  518. .filter(|entry| {
  519. !entry.as_path().file_name().unwrap().to_string_lossy().starts_with('_')
  520. })
  521. .collect::<Vec<_>>();
  522. let mut compiled_paths = Vec::new();
  523. for file in files {
  524. let css = compile_file(&file, options.clone())?;
  525. let path_inside_sass = file.strip_prefix(&sass_path).unwrap();
  526. let parent_inside_sass = path_inside_sass.parent();
  527. let css_output_path = self.output_path.join(path_inside_sass).with_extension("css");
  528. if parent_inside_sass.is_some() {
  529. create_dir_all(&css_output_path.parent().unwrap())?;
  530. }
  531. create_file(&css_output_path, &css)?;
  532. compiled_paths.push((path_inside_sass.to_owned(), css_output_path));
  533. }
  534. Ok(compiled_paths)
  535. }
  536. pub fn render_aliases(&self) -> Result<()> {
  537. ensure_directory_exists(&self.output_path)?;
  538. for (_, page) in self.library.pages() {
  539. for alias in &page.meta.aliases {
  540. let mut output_path = self.output_path.to_path_buf();
  541. let mut split = alias.split('/').collect::<Vec<_>>();
  542. // If the alias ends with an html file name, use that instead of mapping
  543. // as a path containing an `index.html`
  544. let page_name = match split.pop() {
  545. Some(part) if part.ends_with(".html") => part,
  546. Some(part) => {
  547. split.push(part);
  548. "index.html"
  549. }
  550. None => "index.html",
  551. };
  552. for component in split {
  553. output_path.push(&component);
  554. if !output_path.exists() {
  555. create_directory(&output_path)?;
  556. }
  557. }
  558. create_file(
  559. &output_path.join(page_name),
  560. &render_redirect_template(&page.permalink, &self.tera)?,
  561. )?;
  562. }
  563. }
  564. Ok(())
  565. }
  566. /// Renders 404.html
  567. pub fn render_404(&self) -> Result<()> {
  568. ensure_directory_exists(&self.output_path)?;
  569. let mut context = Context::new();
  570. context.insert("config", &self.config);
  571. let output = render_template("404.html", &self.tera, &context, &self.config.theme)?;
  572. create_file(&self.output_path.join("404.html"), &self.inject_livereload(output))
  573. }
  574. /// Renders robots.txt
  575. pub fn render_robots(&self) -> Result<()> {
  576. ensure_directory_exists(&self.output_path)?;
  577. let mut context = Context::new();
  578. context.insert("config", &self.config);
  579. create_file(
  580. &self.output_path.join("robots.txt"),
  581. &render_template("robots.txt", &self.tera, &context, &self.config.theme)?,
  582. )
  583. }
  584. /// Renders all taxonomies with at least one non-draft post
  585. pub fn render_taxonomies(&self) -> Result<()> {
  586. for taxonomy in &self.taxonomies {
  587. self.render_taxonomy(taxonomy)?;
  588. }
  589. Ok(())
  590. }
  591. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  592. if taxonomy.items.is_empty() {
  593. return Ok(());
  594. }
  595. ensure_directory_exists(&self.output_path)?;
  596. let output_path = self.output_path.join(&taxonomy.kind.name);
  597. let list_output = taxonomy.render_all_terms(&self.tera, &self.config, &self.library)?;
  598. create_directory(&output_path)?;
  599. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  600. taxonomy
  601. .items
  602. .par_iter()
  603. .map(|item| {
  604. let path = output_path.join(&item.slug);
  605. if taxonomy.kind.is_paginated() {
  606. self.render_paginated(
  607. &path,
  608. &Paginator::from_taxonomy(&taxonomy, item, &self.library),
  609. )?;
  610. } else {
  611. let single_output =
  612. taxonomy.render_term(item, &self.tera, &self.config, &self.library)?;
  613. create_directory(&path)?;
  614. create_file(&path.join("index.html"), &self.inject_livereload(single_output))?;
  615. }
  616. if taxonomy.kind.rss {
  617. self.render_rss_feed(
  618. item.pages.iter().map(|p| self.library.get_page_by_key(*p)).collect(),
  619. Some(&PathBuf::from(format!("{}/{}", taxonomy.kind.name, item.slug))),
  620. )
  621. } else {
  622. Ok(())
  623. }
  624. })
  625. .collect::<Result<()>>()
  626. }
  627. /// What it says on the tin
  628. pub fn render_sitemap(&self) -> Result<()> {
  629. ensure_directory_exists(&self.output_path)?;
  630. let mut context = Context::new();
  631. let mut pages = self
  632. .library
  633. .pages_values()
  634. .iter()
  635. .filter(|p| !p.is_draft())
  636. .map(|p| {
  637. let date = match p.meta.date {
  638. Some(ref d) => Some(d.to_string()),
  639. None => None,
  640. };
  641. SitemapEntry::new(p.permalink.clone(), date)
  642. })
  643. .collect::<Vec<_>>();
  644. pages.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  645. context.insert("pages", &pages);
  646. let mut sections = self
  647. .library
  648. .sections_values()
  649. .iter()
  650. .map(|s| SitemapEntry::new(s.permalink.clone(), None))
  651. .collect::<Vec<_>>();
  652. for section in
  653. self.library.sections_values().iter().filter(|s| s.meta.paginate_by.is_some())
  654. {
  655. let number_pagers = (section.pages.len() as f64
  656. / section.meta.paginate_by.unwrap() as f64)
  657. .ceil() as isize;
  658. for i in 1..=number_pagers {
  659. let permalink =
  660. format!("{}{}/{}/", section.permalink, section.meta.paginate_path, i);
  661. sections.push(SitemapEntry::new(permalink, None))
  662. }
  663. }
  664. sections.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  665. context.insert("sections", &sections);
  666. let mut taxonomies = vec![];
  667. for taxonomy in &self.taxonomies {
  668. let name = &taxonomy.kind.name;
  669. let mut terms = vec![];
  670. terms.push(SitemapEntry::new(self.config.make_permalink(name), None));
  671. for item in &taxonomy.items {
  672. terms.push(SitemapEntry::new(
  673. self.config.make_permalink(&format!("{}/{}", &name, item.slug)),
  674. None,
  675. ));
  676. if taxonomy.kind.is_paginated() {
  677. let number_pagers = (item.pages.len() as f64
  678. / taxonomy.kind.paginate_by.unwrap() as f64)
  679. .ceil() as isize;
  680. for i in 1..=number_pagers {
  681. let permalink = self.config.make_permalink(&format!(
  682. "{}/{}/{}/{}",
  683. name,
  684. item.slug,
  685. taxonomy.kind.paginate_path(),
  686. i
  687. ));
  688. terms.push(SitemapEntry::new(permalink, None))
  689. }
  690. }
  691. }
  692. terms.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  693. taxonomies.push(terms);
  694. }
  695. context.insert("taxonomies", &taxonomies);
  696. context.insert("config", &self.config);
  697. let sitemap = &render_template("sitemap.xml", &self.tera, &context, &self.config.theme)?;
  698. create_file(&self.output_path.join("sitemap.xml"), sitemap)?;
  699. Ok(())
  700. }
  701. /// Renders a RSS feed for the given path and at the given path
  702. /// If both arguments are `None`, it will render only the RSS feed for the whole
  703. /// site at the root folder.
  704. pub fn render_rss_feed(
  705. &self,
  706. all_pages: Vec<&Page>,
  707. base_path: Option<&PathBuf>,
  708. ) -> Result<()> {
  709. ensure_directory_exists(&self.output_path)?;
  710. let mut context = Context::new();
  711. let mut pages = all_pages
  712. .into_iter()
  713. .filter(|p| p.meta.date.is_some() && !p.is_draft())
  714. .collect::<Vec<_>>();
  715. // Don't generate a RSS feed if none of the pages has a date
  716. if pages.is_empty() {
  717. return Ok(());
  718. }
  719. pages.par_sort_unstable_by(sort_actual_pages_by_date);
  720. context.insert("last_build_date", &pages[0].meta.date.clone());
  721. // limit to the last n elements if the limit is set; otherwise use all.
  722. let num_entries = self.config.rss_limit.unwrap_or_else(|| pages.len());
  723. let p = pages
  724. .iter()
  725. .take(num_entries)
  726. .map(|x| x.to_serialized_basic(&self.library))
  727. .collect::<Vec<_>>();
  728. context.insert("pages", &p);
  729. context.insert("config", &self.config);
  730. let rss_feed_url = if let Some(ref base) = base_path {
  731. self.config.make_permalink(&base.join("rss.xml").to_string_lossy().replace('\\', "/"))
  732. } else {
  733. self.config.make_permalink("rss.xml")
  734. };
  735. context.insert("feed_url", &rss_feed_url);
  736. let feed = &render_template("rss.xml", &self.tera, &context, &self.config.theme)?;
  737. if let Some(ref base) = base_path {
  738. let mut output_path = self.output_path.clone();
  739. for component in base.components() {
  740. output_path.push(component);
  741. if !output_path.exists() {
  742. create_directory(&output_path)?;
  743. }
  744. }
  745. create_file(&output_path.join("rss.xml"), feed)?;
  746. } else {
  747. create_file(&self.output_path.join("rss.xml"), feed)?;
  748. }
  749. Ok(())
  750. }
  751. /// Renders a single section
  752. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  753. ensure_directory_exists(&self.output_path)?;
  754. let mut output_path = self.output_path.clone();
  755. if let Some(ref lang) = section.lang {
  756. output_path.push(lang);
  757. }
  758. for component in &section.file.components {
  759. output_path.push(component);
  760. if !output_path.exists() {
  761. create_directory(&output_path)?;
  762. }
  763. }
  764. // Copy any asset we found previously into the same directory as the index.html
  765. for asset in &section.assets {
  766. let asset_path = asset.as_path();
  767. copy(&asset_path, &output_path.join(asset_path.file_name().unwrap()))?;
  768. }
  769. if render_pages {
  770. section
  771. .pages
  772. .par_iter()
  773. .map(|k| self.render_page(self.library.get_page_by_key(*k)))
  774. .collect::<Result<()>>()?;
  775. }
  776. if !section.meta.render {
  777. return Ok(());
  778. }
  779. if let Some(ref redirect_to) = section.meta.redirect_to {
  780. let permalink = self.config.make_permalink(redirect_to);
  781. create_file(
  782. &output_path.join("index.html"),
  783. &render_redirect_template(&permalink, &self.tera)?,
  784. )?;
  785. return Ok(());
  786. }
  787. if section.meta.is_paginated() {
  788. self.render_paginated(&output_path, &Paginator::from_section(&section, &self.library))?;
  789. } else {
  790. let output = section.render_html(&self.tera, &self.config, &self.library)?;
  791. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  792. }
  793. Ok(())
  794. }
  795. /// Used only on reload
  796. pub fn render_index(&self) -> Result<()> {
  797. self.render_section(
  798. &self.library.get_section(&self.content_path.join("_index.md")).unwrap(),
  799. false,
  800. )
  801. }
  802. /// Renders all sections
  803. pub fn render_sections(&self) -> Result<()> {
  804. self.library
  805. .sections_values()
  806. .into_par_iter()
  807. .map(|s| self.render_section(s, true))
  808. .collect::<Result<()>>()
  809. }
  810. /// Renders all pages that do not belong to any sections
  811. pub fn render_orphan_pages(&self) -> Result<()> {
  812. ensure_directory_exists(&self.output_path)?;
  813. for page in self.get_all_orphan_pages() {
  814. self.render_page(page)?;
  815. }
  816. Ok(())
  817. }
  818. /// Renders a list of pages when the section/index is wanting pagination.
  819. pub fn render_paginated(&self, output_path: &Path, paginator: &Paginator) -> Result<()> {
  820. ensure_directory_exists(&self.output_path)?;
  821. let folder_path = output_path.join(&paginator.paginate_path);
  822. create_directory(&folder_path)?;
  823. paginator
  824. .pagers
  825. .par_iter()
  826. .map(|pager| {
  827. let page_path = folder_path.join(&format!("{}", pager.index));
  828. create_directory(&page_path)?;
  829. let output =
  830. paginator.render_pager(pager, &self.config, &self.tera, &self.library)?;
  831. if pager.index > 1 {
  832. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  833. } else {
  834. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  835. create_file(
  836. &page_path.join("index.html"),
  837. &render_redirect_template(&paginator.permalink, &self.tera)?,
  838. )?;
  839. }
  840. Ok(())
  841. })
  842. .collect::<Result<()>>()
  843. }
  844. }