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