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.

1217 lines
44KB

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