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.

667 lines
23KB

  1. use std::collections::{HashMap};
  2. use std::iter::FromIterator;
  3. use std::fs::{remove_dir_all, copy, create_dir_all};
  4. use std::path::{Path, PathBuf};
  5. use glob::glob;
  6. use tera::{Tera, Context};
  7. use slug::slugify;
  8. use walkdir::WalkDir;
  9. use errors::{Result, ResultExt};
  10. use config::{Config, get_config};
  11. use page::{Page, populate_previous_and_next_pages, sort_pages};
  12. use pagination::Paginator;
  13. use utils::{create_file, create_directory};
  14. use section::{Section};
  15. use front_matter::{SortBy};
  16. use filters;
  17. use global_fns;
  18. lazy_static! {
  19. pub static ref GUTENBERG_TERA: Tera = {
  20. let mut tera = Tera::default();
  21. tera.add_raw_templates(vec![
  22. ("rss.xml", include_str!("templates/rss.xml")),
  23. ("sitemap.xml", include_str!("templates/sitemap.xml")),
  24. ("robots.txt", include_str!("templates/robots.txt")),
  25. ("anchor-link.html", include_str!("templates/anchor-link.html")),
  26. ("shortcodes/youtube.html", include_str!("templates/shortcodes/youtube.html")),
  27. ("shortcodes/vimeo.html", include_str!("templates/shortcodes/vimeo.html")),
  28. ("shortcodes/gist.html", include_str!("templates/shortcodes/gist.html")),
  29. ("internal/alias.html", include_str!("templates/internal/alias.html")),
  30. ]).unwrap();
  31. tera
  32. };
  33. }
  34. /// Renders the `internal/alias.html` template that will redirect
  35. /// via refresh to the url given
  36. fn render_alias(url: &str, tera: &Tera) -> Result<String> {
  37. let mut context = Context::new();
  38. context.add("url", &url);
  39. tera.render("internal/alias.html", &context)
  40. .chain_err(|| format!("Failed to render alias for '{}'", url))
  41. }
  42. #[derive(Debug, PartialEq)]
  43. enum RenderList {
  44. Tags,
  45. Categories,
  46. }
  47. /// A tag or category
  48. #[derive(Debug, Serialize, PartialEq)]
  49. struct ListItem {
  50. name: String,
  51. slug: String,
  52. count: usize,
  53. }
  54. impl ListItem {
  55. pub fn new(name: &str, count: usize) -> ListItem {
  56. ListItem {
  57. name: name.to_string(),
  58. slug: slugify(name),
  59. count: count,
  60. }
  61. }
  62. }
  63. #[derive(Debug)]
  64. pub struct Site {
  65. pub base_path: PathBuf,
  66. pub config: Config,
  67. pub pages: HashMap<PathBuf, Page>,
  68. pub sections: HashMap<PathBuf, Section>,
  69. pub tera: Tera,
  70. live_reload: bool,
  71. output_path: PathBuf,
  72. static_path: PathBuf,
  73. pub tags: HashMap<String, Vec<PathBuf>>,
  74. pub categories: HashMap<String, Vec<PathBuf>>,
  75. pub permalinks: HashMap<String, String>,
  76. }
  77. impl Site {
  78. /// Parse a site at the given path. Defaults to the current dir
  79. /// Passing in a path is only used in tests
  80. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  81. let path = path.as_ref();
  82. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  83. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  84. tera.extend(&GUTENBERG_TERA)?;
  85. tera.register_filter("markdown", filters::markdown);
  86. tera.register_filter("base64_encode", filters::base64_encode);
  87. tera.register_filter("base64_decode", filters::base64_decode);
  88. let site = Site {
  89. base_path: path.to_path_buf(),
  90. config: get_config(path, config_file),
  91. pages: HashMap::new(),
  92. sections: HashMap::new(),
  93. tera: tera,
  94. live_reload: false,
  95. output_path: path.join("public"),
  96. static_path: path.join("static"),
  97. tags: HashMap::new(),
  98. categories: HashMap::new(),
  99. permalinks: HashMap::new(),
  100. };
  101. Ok(site)
  102. }
  103. /// What the function name says
  104. pub fn enable_live_reload(&mut self) {
  105. self.live_reload = true;
  106. }
  107. /// Gets the path of all ignored pages in the site
  108. pub fn get_ignored_pages(&self) -> Vec<PathBuf> {
  109. self.sections
  110. .values()
  111. .flat_map(|s| s.ignored_pages.iter().map(|p| p.file_path.clone()))
  112. .collect()
  113. }
  114. /// Get all the orphan (== without section) pages in the site
  115. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  116. let mut pages_in_sections = vec![];
  117. let mut orphans = vec![];
  118. for s in self.sections.values() {
  119. pages_in_sections.extend(s.all_pages_path());
  120. }
  121. for page in self.pages.values() {
  122. if !pages_in_sections.contains(&page.file_path) {
  123. orphans.push(page);
  124. }
  125. }
  126. orphans
  127. }
  128. /// Used by tests to change the output path to a tmp dir
  129. #[doc(hidden)]
  130. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  131. self.output_path = path.as_ref().to_path_buf();
  132. }
  133. /// Reads all .md files in the `content` directory and create pages/sections
  134. /// out of them
  135. pub fn load(&mut self) -> Result<()> {
  136. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  137. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  138. // TODO: make that parallel, that's the main bottleneck
  139. // `add_section` and `add_page` can't be used in the parallel version afaik
  140. for entry in glob(&content_glob).unwrap().filter_map(|e| e.ok()) {
  141. let path = entry.as_path();
  142. if path.file_name().unwrap() == "_index.md" {
  143. self.add_section(path)?;
  144. } else {
  145. self.add_page(path)?;
  146. }
  147. }
  148. // A map of all .md files (section and pages) and their permalink
  149. // We need that if there are relative links in the content that need to be resolved
  150. let mut permalinks = HashMap::new();
  151. for page in self.pages.values() {
  152. permalinks.insert(page.relative_path.clone(), page.permalink.clone());
  153. }
  154. for section in self.sections.values() {
  155. permalinks.insert(section.relative_path.clone(), section.permalink.clone());
  156. }
  157. for page in self.pages.values_mut() {
  158. page.render_markdown(&permalinks, &self.tera, &self.config)?;
  159. }
  160. self.permalinks = permalinks;
  161. self.populate_sections();
  162. self.populate_tags_and_categories();
  163. self.tera.register_global_function("get_page", global_fns::make_get_page(&self.pages));
  164. Ok(())
  165. }
  166. /// Simple wrapper fn to avoid repeating that code in several places
  167. fn add_page(&mut self, path: &Path) -> Result<()> {
  168. let page = Page::from_file(&path, &self.config)?;
  169. self.pages.insert(page.file_path.clone(), page);
  170. Ok(())
  171. }
  172. /// Simple wrapper fn to avoid repeating that code in several places
  173. fn add_section(&mut self, path: &Path) -> Result<()> {
  174. let section = Section::from_file(path, &self.config)?;
  175. self.sections.insert(section.parent_path.clone(), section);
  176. Ok(())
  177. }
  178. /// Called in serve, add a page again updating permalinks and its content
  179. /// The bool in the result is whether the front matter has been updated or not
  180. fn add_page_and_render(&mut self, path: &Path) -> Result<(bool, Page)> {
  181. let existing_page = self.pages.get(path).expect("Page was supposed to exist in add_page_and_render").clone();
  182. self.add_page(path)?;
  183. let mut page = self.pages.get_mut(path).unwrap();
  184. self.permalinks.insert(page.relative_path.clone(), page.permalink.clone());
  185. page.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  186. Ok((existing_page.meta != page.meta, page.clone()))
  187. }
  188. /// Find out the direct subsections of each subsection if there are some
  189. /// as well as the pages for each section
  190. fn populate_sections(&mut self) {
  191. for page in self.pages.values() {
  192. if self.sections.contains_key(&page.parent_path) {
  193. self.sections.get_mut(&page.parent_path).unwrap().pages.push(page.clone());
  194. }
  195. }
  196. let mut grandparent_paths = HashMap::new();
  197. for section in self.sections.values() {
  198. let grand_parent = section.parent_path.parent().unwrap().to_path_buf();
  199. grandparent_paths.entry(grand_parent).or_insert_with(|| vec![]).push(section.clone());
  200. }
  201. for (parent_path, section) in &mut self.sections {
  202. // TODO: avoid this clone
  203. let (mut sorted_pages, cannot_be_sorted_pages) = sort_pages(section.pages.clone(), section.meta.sort_by());
  204. sorted_pages = populate_previous_and_next_pages(&sorted_pages);
  205. section.pages = sorted_pages;
  206. section.ignored_pages = cannot_be_sorted_pages;
  207. match grandparent_paths.get(parent_path) {
  208. Some(paths) => section.subsections.extend(paths.clone()),
  209. None => continue,
  210. };
  211. }
  212. }
  213. /// Separated from `parse` for easier testing
  214. pub fn populate_tags_and_categories(&mut self) {
  215. for page in self.pages.values() {
  216. if let Some(ref category) = page.meta.category {
  217. self.categories
  218. .entry(category.to_string())
  219. .or_insert_with(|| vec![])
  220. .push(page.file_path.clone());
  221. }
  222. if let Some(ref tags) = page.meta.tags {
  223. for tag in tags {
  224. self.tags
  225. .entry(tag.to_string())
  226. .or_insert_with(|| vec![])
  227. .push(page.file_path.clone());
  228. }
  229. }
  230. }
  231. }
  232. /// Inject live reload script tag if in live reload mode
  233. fn inject_livereload(&self, html: String) -> String {
  234. if self.live_reload {
  235. return html.replace(
  236. "</body>",
  237. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  238. );
  239. }
  240. html
  241. }
  242. pub fn ensure_public_directory_exists(&self) -> Result<()> {
  243. let public = self.output_path.clone();
  244. if !public.exists() {
  245. create_directory(&public)?;
  246. }
  247. Ok(())
  248. }
  249. /// Copy static file to public directory.
  250. pub fn copy_static_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  251. let relative_path = path.as_ref().strip_prefix(&self.static_path).unwrap();
  252. let target_path = self.output_path.join(relative_path);
  253. if let Some(parent_directory) = target_path.parent() {
  254. create_dir_all(parent_directory)?;
  255. }
  256. copy(path.as_ref(), &target_path)?;
  257. Ok(())
  258. }
  259. /// Copy the content of the `static` folder into the `public` folder
  260. pub fn copy_static_directory(&self) -> Result<()> {
  261. for entry in WalkDir::new(&self.static_path).into_iter().filter_map(|e| e.ok()) {
  262. let relative_path = entry.path().strip_prefix(&self.static_path).unwrap();
  263. let target_path = self.output_path.join(relative_path);
  264. if entry.path().is_dir() {
  265. if !target_path.exists() {
  266. create_directory(&target_path)?;
  267. }
  268. } else {
  269. let entry_fullpath = self.base_path.join(entry.path());
  270. self.copy_static_file(entry_fullpath)?;
  271. }
  272. }
  273. Ok(())
  274. }
  275. /// Deletes the `public` directory if it exists
  276. pub fn clean(&self) -> Result<()> {
  277. if self.output_path.exists() {
  278. // Delete current `public` directory so we can start fresh
  279. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete `public` directory")?;
  280. }
  281. Ok(())
  282. }
  283. pub fn rebuild_after_content_change(&mut self, path: &Path) -> Result<()> {
  284. let is_section = path.ends_with("_index.md");
  285. if path.exists() {
  286. // file exists, either a new one or updating content
  287. if is_section {
  288. self.add_section(path)?;
  289. } else {
  290. // probably just an update so just re-parse that page
  291. let (frontmatter_changed, page) = self.add_page_and_render(path)?;
  292. // TODO: can probably be smarter and check what changed
  293. if frontmatter_changed {
  294. self.populate_sections();
  295. self.populate_tags_and_categories();
  296. self.build()?;
  297. } else {
  298. self.render_page(&page)?;
  299. }
  300. }
  301. } else {
  302. // File doesn't exist -> a deletion so we remove it from everything
  303. let relative_path = if is_section {
  304. self.sections[path].relative_path.clone()
  305. } else {
  306. self.pages[path].relative_path.clone()
  307. };
  308. self.permalinks.remove(&relative_path);
  309. if is_section {
  310. self.sections.remove(path);
  311. } else {
  312. self.pages.remove(path);
  313. }
  314. // TODO: probably no need to do that, we should be able to only re-render a page or a section.
  315. self.populate_sections();
  316. self.populate_tags_and_categories();
  317. self.build()?;
  318. }
  319. Ok(())
  320. }
  321. pub fn rebuild_after_template_change(&mut self, path: &Path) -> Result<()> {
  322. self.tera.full_reload()?;
  323. match path.file_name().unwrap().to_str().unwrap() {
  324. "sitemap.xml" => self.render_sitemap(),
  325. "rss.xml" => self.render_rss_feed(),
  326. _ => self.build() // TODO: change that
  327. }
  328. }
  329. /// Renders a single content page
  330. pub fn render_page(&self, page: &Page) -> Result<()> {
  331. self.ensure_public_directory_exists()?;
  332. // Copy the nesting of the content directory if we have sections for that page
  333. let mut current_path = self.output_path.to_path_buf();
  334. for component in page.path.split('/') {
  335. current_path.push(component);
  336. if !current_path.exists() {
  337. create_directory(&current_path)?;
  338. }
  339. }
  340. // Make sure the folder exists
  341. create_directory(&current_path)?;
  342. // Finally, create a index.html file there with the page rendered
  343. let output = page.render_html(&self.tera, &self.config)?;
  344. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  345. // Copy any asset we found previously into the same directory as the index.html
  346. for asset in &page.assets {
  347. let asset_path = asset.as_path();
  348. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  349. }
  350. Ok(())
  351. }
  352. /// Builds the site to the `public` directory after deleting it
  353. pub fn build(&self) -> Result<()> {
  354. self.clean()?;
  355. self.render_sections()?;
  356. self.render_orphan_pages()?;
  357. self.render_sitemap()?;
  358. if self.config.generate_rss.unwrap() {
  359. self.render_rss_feed()?;
  360. }
  361. self.render_robots()?;
  362. if self.config.generate_categories_pages.unwrap() {
  363. self.render_categories_and_tags(RenderList::Categories)?;
  364. }
  365. if self.config.generate_tags_pages.unwrap() {
  366. self.render_categories_and_tags(RenderList::Tags)?;
  367. }
  368. self.copy_static_directory()
  369. }
  370. /// Renders robots.txt
  371. fn render_robots(&self) -> Result<()> {
  372. self.ensure_public_directory_exists()?;
  373. create_file(
  374. self.output_path.join("robots.txt"),
  375. &self.tera.render("robots.txt", &Context::new())?
  376. )
  377. }
  378. /// Render the /{categories, list} pages and each individual category/tag page
  379. /// They are the same thing fundamentally, a list of pages with something in common
  380. fn render_categories_and_tags(&self, kind: RenderList) -> Result<()> {
  381. let items = match kind {
  382. RenderList::Categories => &self.categories,
  383. RenderList::Tags => &self.tags,
  384. };
  385. if items.is_empty() {
  386. return Ok(());
  387. }
  388. let (list_tpl_name, single_tpl_name, name, var_name) = if kind == RenderList::Categories {
  389. ("categories.html", "category.html", "categories", "category")
  390. } else {
  391. ("tags.html", "tag.html", "tags", "tag")
  392. };
  393. self.ensure_public_directory_exists()?;
  394. // Create the categories/tags directory first
  395. let public = self.output_path.clone();
  396. let mut output_path = public.to_path_buf();
  397. output_path.push(name);
  398. create_directory(&output_path)?;
  399. // Then render the index page for that kind.
  400. // We sort by number of page in that category/tag
  401. let mut sorted_items = vec![];
  402. for (item, count) in Vec::from_iter(items).into_iter().map(|(a, b)| (a, b.len())) {
  403. sorted_items.push(ListItem::new(item, count));
  404. }
  405. sorted_items.sort_by(|a, b| b.count.cmp(&a.count));
  406. let mut context = Context::new();
  407. context.add(name, &sorted_items);
  408. context.add("config", &self.config);
  409. context.add("current_url", &self.config.make_permalink(name));
  410. context.add("current_path", &format!("/{}", name));
  411. // And render it immediately
  412. let list_output = self.tera.render(list_tpl_name, &context)?;
  413. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  414. // Now, each individual item
  415. for (item_name, pages_paths) in items.iter() {
  416. let pages: Vec<&Page> = self.pages
  417. .iter()
  418. .filter(|&(path, _)| pages_paths.contains(path))
  419. .map(|(_, page)| page)
  420. .collect();
  421. // TODO: how to sort categories and tag content?
  422. // Have a setting in config.toml or a _category.md and _tag.md
  423. // The latter is more in line with the rest of Gutenberg but order ordering
  424. // doesn't really work across sections.
  425. let mut context = Context::new();
  426. let slug = slugify(&item_name);
  427. context.add(var_name, &item_name);
  428. context.add(&format!("{}_slug", var_name), &slug);
  429. context.add("pages", &pages);
  430. context.add("config", &self.config);
  431. context.add("current_url", &self.config.make_permalink(&format!("{}/{}", name, slug)));
  432. context.add("current_path", &format!("/{}/{}", name, slug));
  433. let single_output = self.tera.render(single_tpl_name, &context)?;
  434. create_directory(&output_path.join(&slug))?;
  435. create_file(
  436. output_path.join(&slug).join("index.html"),
  437. &self.inject_livereload(single_output)
  438. )?;
  439. }
  440. Ok(())
  441. }
  442. fn render_sitemap(&self) -> Result<()> {
  443. self.ensure_public_directory_exists()?;
  444. let mut context = Context::new();
  445. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  446. context.add("sections", &self.sections.values().collect::<Vec<&Section>>());
  447. let mut categories = vec![];
  448. if self.config.generate_categories_pages.unwrap() && !self.categories.is_empty() {
  449. categories.push(self.config.make_permalink("categories"));
  450. for category in self.categories.keys() {
  451. categories.push(
  452. self.config.make_permalink(&format!("categories/{}", slugify(category)))
  453. );
  454. }
  455. }
  456. context.add("categories", &categories);
  457. let mut tags = vec![];
  458. if self.config.generate_tags_pages.unwrap() && !self.tags.is_empty() {
  459. tags.push(self.config.make_permalink("tags"));
  460. for tag in self.tags.keys() {
  461. tags.push(
  462. self.config.make_permalink(&format!("tags/{}", slugify(tag)))
  463. );
  464. }
  465. }
  466. context.add("tags", &tags);
  467. let sitemap = self.tera.render("sitemap.xml", &context)?;
  468. create_file(self.output_path.join("sitemap.xml"), &sitemap)?;
  469. Ok(())
  470. }
  471. fn render_rss_feed(&self) -> Result<()> {
  472. self.ensure_public_directory_exists()?;
  473. let mut context = Context::new();
  474. let pages = self.pages.values()
  475. .filter(|p| p.meta.date.is_some())
  476. .take(15) // limit to the last 15 elements
  477. .map(|p| p.clone())
  478. .collect::<Vec<Page>>();
  479. // Don't generate a RSS feed if none of the pages has a date
  480. if pages.is_empty() {
  481. return Ok(());
  482. }
  483. context.add("last_build_date", &pages[0].meta.date);
  484. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  485. context.add("pages", &sorted_pages);
  486. context.add("config", &self.config);
  487. let rss_feed_url = if self.config.base_url.ends_with('/') {
  488. format!("{}{}", self.config.base_url, "rss.xml")
  489. } else {
  490. format!("{}/{}", self.config.base_url, "rss.xml")
  491. };
  492. context.add("feed_url", &rss_feed_url);
  493. let sitemap = self.tera.render("rss.xml", &context)?;
  494. create_file(self.output_path.join("rss.xml"), &sitemap)?;
  495. Ok(())
  496. }
  497. fn render_sections(&self) -> Result<()> {
  498. self.ensure_public_directory_exists()?;
  499. let public = self.output_path.clone();
  500. let sections: HashMap<String, Section> = self.sections
  501. .values()
  502. .map(|s| (s.components.join("/"), s.clone()))
  503. .collect();
  504. for section in self.sections.values() {
  505. let mut output_path = public.to_path_buf();
  506. for component in &section.components {
  507. output_path.push(component);
  508. if !output_path.exists() {
  509. create_directory(&output_path)?;
  510. }
  511. }
  512. for page in &section.pages {
  513. self.render_page(page)?;
  514. }
  515. if !section.meta.should_render() {
  516. continue;
  517. }
  518. if section.meta.is_paginated() {
  519. self.render_paginated(&output_path, section)?;
  520. } else {
  521. let output = section.render_html(
  522. &sections,
  523. &self.tera,
  524. &self.config,
  525. )?;
  526. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  527. }
  528. }
  529. Ok(())
  530. }
  531. /// Renders all pages that do not belong to any sections
  532. fn render_orphan_pages(&self) -> Result<()> {
  533. self.ensure_public_directory_exists()?;
  534. for page in self.get_all_orphan_pages() {
  535. self.render_page(page)?;
  536. }
  537. Ok(())
  538. }
  539. /// Renders a list of pages when the section/index is wanting pagination.
  540. fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  541. self.ensure_public_directory_exists()?;
  542. let paginate_path = match section.meta.paginate_path {
  543. Some(ref s) => s.clone(),
  544. None => unreachable!()
  545. };
  546. let paginator = Paginator::new(&section.pages, section);
  547. for (i, pager) in paginator.pagers.iter().enumerate() {
  548. let folder_path = output_path.join(&paginate_path);
  549. let page_path = folder_path.join(&format!("{}", i + 1));
  550. create_directory(&folder_path)?;
  551. create_directory(&page_path)?;
  552. let output = paginator.render_pager(pager, self)?;
  553. if i > 0 {
  554. create_file(page_path.join("index.html"), &self.inject_livereload(output))?;
  555. } else {
  556. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  557. create_file(page_path.join("index.html"), &render_alias(&section.permalink, &self.tera)?)?;
  558. }
  559. }
  560. Ok(())
  561. }
  562. }