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.

872 lines
31KB

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