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.

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