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.

1103 lines
39KB

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