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.

1069 lines
38KB

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