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.

931 lines
33KB

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