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.

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