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.

548 lines
19KB

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