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.

347 lines
13KB

  1. extern crate site;
  2. #[macro_use]
  3. extern crate errors;
  4. extern crate library;
  5. extern crate front_matter;
  6. use std::path::{Path, Component};
  7. use errors::Result;
  8. use site::Site;
  9. use library::{Page, Section};
  10. use front_matter::{PageFrontMatter, SectionFrontMatter};
  11. #[derive(Debug, Clone, Copy, PartialEq)]
  12. pub enum PageChangesNeeded {
  13. /// Editing `taxonomies`
  14. Taxonomies,
  15. /// Editing `date`, `order` or `weight`
  16. Sort,
  17. /// Editing anything causes a re-render of the page
  18. Render,
  19. }
  20. #[derive(Debug, Clone, Copy, PartialEq)]
  21. pub enum SectionChangesNeeded {
  22. /// Editing `sort_by`
  23. Sort,
  24. /// Editing `title`, `description`, `extra`, `template` or setting `render` to true
  25. Render,
  26. /// Editing `paginate_by`, `paginate_path` or `insert_anchor_links`
  27. RenderWithPages,
  28. /// Setting `render` to false
  29. Delete,
  30. }
  31. /// Evaluates all the params in the front matter that changed so we can do the smallest
  32. /// delta in the serve command
  33. /// Order matters as the actions will be done in insertion order
  34. fn find_section_front_matter_changes(current: &SectionFrontMatter, new: &SectionFrontMatter) -> Vec<SectionChangesNeeded> {
  35. let mut changes_needed = vec![];
  36. if current.sort_by != new.sort_by {
  37. changes_needed.push(SectionChangesNeeded::Sort);
  38. }
  39. // We want to hide the section
  40. // TODO: what to do on redirect_path change?
  41. if current.render && !new.render {
  42. changes_needed.push(SectionChangesNeeded::Delete);
  43. // Nothing else we can do
  44. return changes_needed;
  45. }
  46. if current.paginate_by != new.paginate_by
  47. || current.paginate_path != new.paginate_path
  48. || current.insert_anchor_links != new.insert_anchor_links {
  49. changes_needed.push(SectionChangesNeeded::RenderWithPages);
  50. // Nothing else we can do
  51. return changes_needed;
  52. }
  53. // Any new change will trigger a re-rendering of the section page only
  54. changes_needed.push(SectionChangesNeeded::Render);
  55. changes_needed
  56. }
  57. /// Evaluates all the params in the front matter that changed so we can do the smallest
  58. /// delta in the serve command
  59. /// Order matters as the actions will be done in insertion order
  60. fn find_page_front_matter_changes(current: &PageFrontMatter, other: &PageFrontMatter) -> Vec<PageChangesNeeded> {
  61. let mut changes_needed = vec![];
  62. if current.taxonomies != other.taxonomies {
  63. changes_needed.push(PageChangesNeeded::Taxonomies);
  64. }
  65. if current.date != other.date || current.order != other.order || current.weight != other.weight {
  66. changes_needed.push(PageChangesNeeded::Sort);
  67. }
  68. changes_needed.push(PageChangesNeeded::Render);
  69. changes_needed
  70. }
  71. /// Handles a path deletion: could be a page, a section, a folder
  72. fn delete_element(site: &mut Site, path: &Path, is_section: bool) -> Result<()> {
  73. // Ignore the event if this path was not known
  74. if !site.library.contains_section(&path.to_path_buf()) && !site.library.contains_page(&path.to_path_buf()) {
  75. return Ok(());
  76. }
  77. if is_section {
  78. if let Some(s) = site.library.remove_section(&path.to_path_buf()) {
  79. site.permalinks.remove(&s.file.relative);
  80. }
  81. } else if let Some(p) = site.library.remove_page(&path.to_path_buf()) {
  82. site.permalinks.remove(&p.file.relative);
  83. if !p.meta.taxonomies.is_empty() {
  84. site.populate_taxonomies()?;
  85. }
  86. }
  87. site.populate_sections();
  88. // Ensure we have our fn updated so it doesn't contain the permalink(s)/section/page deleted
  89. site.register_early_global_fns();
  90. site.register_tera_global_fns();
  91. // Deletion is something that doesn't happen all the time so we
  92. // don't need to optimise it too much
  93. site.build()
  94. }
  95. /// Handles a `_index.md` (a section) being edited in some ways
  96. fn handle_section_editing(site: &mut Site, path: &Path) -> Result<()> {
  97. let section = Section::from_file(path, &site.config)?;
  98. let pathbuf = path.to_path_buf();
  99. match site.add_section(section, true)? {
  100. // Updating a section
  101. Some(prev) => {
  102. site.populate_sections();
  103. if site.library.get_section(&pathbuf).unwrap().meta == prev.meta {
  104. // Front matter didn't change, only content did
  105. // so we render only the section page, not its pages
  106. return site.render_section(&site.library.get_section(&pathbuf).unwrap(), false);
  107. }
  108. // Front matter changed
  109. for changes in find_section_front_matter_changes(&site.library.get_section(&pathbuf).unwrap().meta, &prev.meta) {
  110. // Sort always comes first if present so the rendering will be fine
  111. match changes {
  112. SectionChangesNeeded::Sort => {
  113. site.register_tera_global_fns();
  114. }
  115. SectionChangesNeeded::Render => site.render_section(&site.library.get_section(&pathbuf).unwrap(), false)?,
  116. SectionChangesNeeded::RenderWithPages => site.render_section(&site.library.get_section(&pathbuf).unwrap(), true)?,
  117. // not a common enough operation to make it worth optimizing
  118. SectionChangesNeeded::Delete => {
  119. site.build()?;
  120. }
  121. };
  122. }
  123. Ok(())
  124. }
  125. // New section, only render that one
  126. None => {
  127. site.populate_sections();
  128. site.register_tera_global_fns();
  129. site.render_section(&site.library.get_section(&pathbuf).unwrap(), true)
  130. }
  131. }
  132. }
  133. macro_rules! render_parent_section {
  134. ($site: expr, $path: expr) => {
  135. if let Some(s) = $site.library.find_parent_section($path) {
  136. $site.render_section(s, false)?;
  137. };
  138. }
  139. }
  140. /// Handles a page being edited in some ways
  141. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  142. let page = Page::from_file(path, &site.config)?;
  143. let pathbuf = path.to_path_buf();
  144. match site.add_page(page, true)? {
  145. // Updating a page
  146. Some(prev) => {
  147. site.populate_sections();
  148. // Front matter didn't change, only content did
  149. if site.library.get_page(&pathbuf).unwrap().meta == prev.meta {
  150. // Other than the page itself, the summary might be seen
  151. // on a paginated list for a blog for example
  152. if site.library.get_page(&pathbuf).unwrap().summary.is_some() {
  153. render_parent_section!(site, path);
  154. }
  155. site.register_tera_global_fns();
  156. return site.render_page(&site.library.get_page(&pathbuf).unwrap());
  157. }
  158. // Front matter changed
  159. for changes in find_page_front_matter_changes(&site.library.get_page(&pathbuf).unwrap().meta, &prev.meta) {
  160. site.register_tera_global_fns();
  161. // Sort always comes first if present so the rendering will be fine
  162. match changes {
  163. PageChangesNeeded::Taxonomies => {
  164. site.populate_taxonomies()?;
  165. site.render_taxonomies()?;
  166. }
  167. PageChangesNeeded::Sort => {
  168. site.render_index()?;
  169. }
  170. PageChangesNeeded::Render => {
  171. render_parent_section!(site, path);
  172. site.render_page(&site.library.get_page(&path.to_path_buf()).unwrap())?;
  173. }
  174. };
  175. }
  176. Ok(())
  177. }
  178. // It's a new page!
  179. None => {
  180. site.populate_sections();
  181. site.populate_taxonomies()?;
  182. site.register_early_global_fns();
  183. site.register_tera_global_fns();
  184. // No need to optimise that yet, we can revisit if it becomes an issue
  185. site.build()
  186. }
  187. }
  188. }
  189. /// What happens when a section or a page is changed
  190. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  191. let is_section = path.file_name().unwrap() == "_index.md";
  192. let is_md = path.extension().unwrap() == "md";
  193. let index = path.parent().unwrap().join("index.md");
  194. // A few situations can happen:
  195. // 1. Change on .md files
  196. // a. Is there an `index.md`? Return an error if it's something other than delete
  197. // b. Deleted? remove the element
  198. // c. Edited?
  199. // 1. filename is `_index.md`, this is a section
  200. // 1. it's a page otherwise
  201. // 2. Change on non .md files
  202. // a. Try to find a corresponding `_index.md`
  203. // 1. Nothing? Return Ok
  204. // 2. Something? Update the page
  205. if is_md {
  206. // only delete if it was able to be added in the first place
  207. if !index.exists() && !path.exists() {
  208. delete_element(site, path, is_section)?;
  209. }
  210. // Added another .md in a assets directory
  211. if index.exists() && path.exists() && path != index {
  212. bail!(
  213. "Change on {:?} detected but there is already an `index.md` in the same folder",
  214. path.display()
  215. );
  216. } else if index.exists() && !path.exists() {
  217. // deleted the wrong .md, do nothing
  218. return Ok(());
  219. }
  220. if is_section {
  221. handle_section_editing(site, path)
  222. } else {
  223. handle_page_editing(site, path)
  224. }
  225. } else if index.exists() {
  226. handle_page_editing(site, &index)
  227. } else {
  228. Ok(())
  229. }
  230. }
  231. /// What happens when a template is changed
  232. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  233. site.tera.full_reload()?;
  234. let filename = path.file_name().unwrap().to_str().unwrap();
  235. match filename {
  236. "sitemap.xml" => site.render_sitemap(),
  237. "rss.xml" => site.render_rss_feed(site.library.pages_values(), None),
  238. "robots.txt" => site.render_robots(),
  239. "single.html" | "list.html" => site.render_taxonomies(),
  240. "page.html" => {
  241. site.render_sections()?;
  242. site.render_orphan_pages()
  243. }
  244. "section.html" => site.render_sections(),
  245. // Either the index or some unknown template changed
  246. // We can't really know what this change affects so rebuild all
  247. // the things
  248. _ => {
  249. // If we are updating a shortcode, re-render the markdown of all pages/site
  250. // because we have no clue which one needs rebuilding
  251. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  252. // everything
  253. if path.components().any(|x| x == Component::Normal("shortcodes".as_ref())) {
  254. site.render_markdown()?;
  255. }
  256. site.populate_sections();
  257. site.render_sections()?;
  258. site.render_orphan_pages()?;
  259. site.render_taxonomies()
  260. }
  261. }
  262. }
  263. #[cfg(test)]
  264. mod tests {
  265. use std::collections::HashMap;
  266. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  267. use super::{
  268. find_page_front_matter_changes, find_section_front_matter_changes,
  269. PageChangesNeeded, SectionChangesNeeded,
  270. };
  271. #[test]
  272. fn can_find_taxonomy_changes_in_page_frontmatter() {
  273. let mut taxonomies = HashMap::new();
  274. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  275. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  276. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  277. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  278. }
  279. #[test]
  280. fn can_find_multiple_changes_in_page_frontmatter() {
  281. let mut taxonomies = HashMap::new();
  282. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  283. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  284. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  285. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]);
  286. }
  287. #[test]
  288. fn can_find_sort_changes_in_section_frontmatter() {
  289. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  290. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  291. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  292. }
  293. #[test]
  294. fn can_find_render_changes_in_section_frontmatter() {
  295. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  296. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  297. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  298. }
  299. #[test]
  300. fn can_find_paginate_by_changes_in_section_frontmatter() {
  301. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  302. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  303. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  304. }
  305. }