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.

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