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.

146 lines
4.6KB

  1. use std::collections::HashMap;
  2. use std::fs::{create_dir, remove_dir_all};
  3. use std::path::Path;
  4. use glob::glob;
  5. use tera::{Tera, Context};
  6. use errors::{Result, ResultExt};
  7. use config::{Config, get_config};
  8. use page::Page;
  9. use utils::create_file;
  10. #[derive(Debug)]
  11. pub struct Site {
  12. config: Config,
  13. pages: HashMap<String, Page>,
  14. sections: HashMap<String, Vec<String>>,
  15. templates: Tera,
  16. live_reload: bool,
  17. }
  18. impl Site {
  19. pub fn new(livereload: bool) -> Result<Site> {
  20. let tera = Tera::new("templates/**/*").chain_err(|| "Error parsing templates")?;
  21. let mut site = Site {
  22. config: get_config(),
  23. pages: HashMap::new(),
  24. sections: HashMap::new(),
  25. templates: tera,
  26. live_reload: livereload,
  27. };
  28. site.parse_site()?;
  29. Ok(site)
  30. }
  31. /// Reads all .md files in the `content` directory and create pages
  32. /// out of them
  33. fn parse_site(&mut self) -> Result<()> {
  34. // First step: do all the articles and group article by sections
  35. // hardcoded pattern so can't error
  36. for entry in glob("content/**/*.md").unwrap().filter_map(|e| e.ok()) {
  37. let page = Page::from_file(&entry.as_path(), &self.config)?;
  38. for section in &page.sections {
  39. self.sections.entry(section.clone()).or_insert(vec![]).push(page.slug.clone());
  40. }
  41. self.pages.insert(page.slug.clone(), page);
  42. }
  43. Ok(())
  44. }
  45. // Inject live reload script tag if in live reload mode
  46. fn inject_livereload(&self, html: String) -> String {
  47. if self.live_reload {
  48. return html.replace(
  49. "</body>",
  50. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  51. );
  52. }
  53. html
  54. }
  55. /// Re-parse and re-generate the site
  56. /// Very dumb for now, ideally it would only rebuild what changed
  57. pub fn rebuild(&mut self) -> Result<()> {
  58. self.parse_site()?;
  59. self.build()
  60. }
  61. /// Builds the site to the `public` directory after deleting it
  62. pub fn build(&self) -> Result<()> {
  63. if Path::new("public").exists() {
  64. // Delete current `public` directory so we can start fresh
  65. remove_dir_all("public").chain_err(|| "Couldn't delete `public` directory")?;
  66. }
  67. // Start from scratch
  68. create_dir("public")?;
  69. let public = Path::new("public");
  70. let mut pages = vec![];
  71. // First we render the pages themselves
  72. for page in self.pages.values() {
  73. // Copy the nesting of the content directory if we have sections for that page
  74. let mut current_path = public.to_path_buf();
  75. // This loop happens when the page doesn't have a set URL
  76. for section in &page.sections {
  77. current_path.push(section);
  78. if !current_path.exists() {
  79. create_dir(&current_path)?;
  80. }
  81. }
  82. // if we have a url already set, use that as base
  83. if let Some(ref url) = page.meta.url {
  84. current_path.push(url);
  85. }
  86. // Make sure the folder exists
  87. create_dir(&current_path)?;
  88. // Finally, create a index.html file there with the page rendered
  89. let output = page.render_html(&self.templates, &self.config)?;
  90. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  91. pages.push(page);
  92. }
  93. // Then the section pages
  94. // The folders have already been created in the page loop so no need to `create_dir` here
  95. // for (section, slugs) in &self.sections {
  96. // // TODO
  97. // }
  98. // And finally the index page
  99. let mut context = Context::new();
  100. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  101. context.add("pages", &pages);
  102. context.add("config", &self.config);
  103. let index = self.templates.render("index.html", &context)?;
  104. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  105. self.render_sitemap()?;
  106. Ok(())
  107. }
  108. pub fn render_sitemap(&self) -> Result<()> {
  109. let tpl = String::from_utf8(include_bytes!("templates/sitemap.xml").to_vec()).unwrap();
  110. let mut context = Context::new();
  111. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  112. let sitemap = Tera::one_off(&tpl, &context, false)?;
  113. let public = Path::new("public");
  114. create_file(public.join("sitemap.xml"), &sitemap)?;
  115. Ok(())
  116. }
  117. }