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.

835 lines
30KB

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