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.

1033 lines
37KB

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