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.

354 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. // Copy the section data so we don't end up with an almost empty object
  103. {
  104. let s = site.library.get_section_mut(&pathbuf).unwrap();
  105. s.pages = prev.pages;
  106. s.ignored_pages = prev.ignored_pages;
  107. s.subsections = prev.subsections;
  108. }
  109. if site.library.get_section(&pathbuf).unwrap().meta == prev.meta {
  110. // Front matter didn't change, only content did
  111. // so we render only the section page, not its pages
  112. return site.render_section(&site.library.get_section(&pathbuf).unwrap(), false);
  113. }
  114. // Front matter changed
  115. for changes in find_section_front_matter_changes(&site.library.get_section(&pathbuf).unwrap().meta, &prev.meta) {
  116. // Sort always comes first if present so the rendering will be fine
  117. match changes {
  118. SectionChangesNeeded::Sort => {
  119. site.register_tera_global_fns();
  120. }
  121. SectionChangesNeeded::Render => site.render_section(&site.library.get_section(&pathbuf).unwrap(), false)?,
  122. SectionChangesNeeded::RenderWithPages => site.render_section(&site.library.get_section(&pathbuf).unwrap(), true)?,
  123. // not a common enough operation to make it worth optimizing
  124. SectionChangesNeeded::Delete => {
  125. site.populate_sections();
  126. site.build()?;
  127. }
  128. };
  129. }
  130. Ok(())
  131. }
  132. // New section, only render that one
  133. None => {
  134. site.populate_sections();
  135. site.register_tera_global_fns();
  136. site.render_section(&site.library.get_section(&pathbuf).unwrap(), true)
  137. }
  138. }
  139. }
  140. macro_rules! render_parent_section {
  141. ($site: expr, $path: expr) => {
  142. if let Some(s) = $site.library.find_parent_section($path) {
  143. $site.render_section(s, false)?;
  144. };
  145. }
  146. }
  147. /// Handles a page being edited in some ways
  148. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  149. let page = Page::from_file(path, &site.config)?;
  150. let pathbuf = path.to_path_buf();
  151. match site.add_page(page, true)? {
  152. // Updating a page
  153. Some(prev) => {
  154. site.populate_sections();
  155. // Front matter didn't change, only content did
  156. if site.library.get_page(&pathbuf).unwrap().meta == prev.meta {
  157. // Other than the page itself, the summary might be seen
  158. // on a paginated list for a blog for example
  159. if site.library.get_page(&pathbuf).unwrap().summary.is_some() {
  160. render_parent_section!(site, path);
  161. }
  162. site.register_tera_global_fns();
  163. return site.render_page(&site.library.get_page(&pathbuf).unwrap());
  164. }
  165. // Front matter changed
  166. for changes in find_page_front_matter_changes(&site.library.get_page(&pathbuf).unwrap().meta, &prev.meta) {
  167. site.register_tera_global_fns();
  168. // Sort always comes first if present so the rendering will be fine
  169. match changes {
  170. PageChangesNeeded::Taxonomies => {
  171. site.populate_taxonomies()?;
  172. site.render_taxonomies()?;
  173. }
  174. PageChangesNeeded::Sort => {
  175. site.render_index()?;
  176. }
  177. PageChangesNeeded::Render => {
  178. render_parent_section!(site, path);
  179. site.render_page(&site.library.get_page(&path.to_path_buf()).unwrap())?;
  180. }
  181. };
  182. }
  183. Ok(())
  184. }
  185. // It's a new page!
  186. None => {
  187. site.populate_sections();
  188. site.populate_taxonomies()?;
  189. site.register_early_global_fns();
  190. site.register_tera_global_fns();
  191. // No need to optimise that yet, we can revisit if it becomes an issue
  192. site.build()
  193. }
  194. }
  195. }
  196. /// What happens when a section or a page is changed
  197. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  198. let is_section = path.file_name().unwrap() == "_index.md";
  199. let is_md = path.extension().unwrap() == "md";
  200. let index = path.parent().unwrap().join("index.md");
  201. // A few situations can happen:
  202. // 1. Change on .md files
  203. // a. Is there an `index.md`? Return an error if it's something other than delete
  204. // b. Deleted? remove the element
  205. // c. Edited?
  206. // 1. filename is `_index.md`, this is a section
  207. // 1. it's a page otherwise
  208. // 2. Change on non .md files
  209. // a. Try to find a corresponding `_index.md`
  210. // 1. Nothing? Return Ok
  211. // 2. Something? Update the page
  212. if is_md {
  213. // only delete if it was able to be added in the first place
  214. if !index.exists() && !path.exists() {
  215. delete_element(site, path, is_section)?;
  216. }
  217. // Added another .md in a assets directory
  218. if index.exists() && path.exists() && path != index {
  219. bail!(
  220. "Change on {:?} detected but there is already an `index.md` in the same folder",
  221. path.display()
  222. );
  223. } else if index.exists() && !path.exists() {
  224. // deleted the wrong .md, do nothing
  225. return Ok(());
  226. }
  227. if is_section {
  228. handle_section_editing(site, path)
  229. } else {
  230. handle_page_editing(site, path)
  231. }
  232. } else if index.exists() {
  233. handle_page_editing(site, &index)
  234. } else {
  235. Ok(())
  236. }
  237. }
  238. /// What happens when a template is changed
  239. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  240. site.tera.full_reload()?;
  241. let filename = path.file_name().unwrap().to_str().unwrap();
  242. match filename {
  243. "sitemap.xml" => site.render_sitemap(),
  244. "rss.xml" => site.render_rss_feed(site.library.pages_values(), None),
  245. "robots.txt" => site.render_robots(),
  246. "single.html" | "list.html" => site.render_taxonomies(),
  247. "page.html" => {
  248. site.render_sections()?;
  249. site.render_orphan_pages()
  250. }
  251. "section.html" => site.render_sections(),
  252. // Either the index or some unknown template changed
  253. // We can't really know what this change affects so rebuild all
  254. // the things
  255. _ => {
  256. // If we are updating a shortcode, re-render the markdown of all pages/site
  257. // because we have no clue which one needs rebuilding
  258. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  259. // everything
  260. if path.components().any(|x| x == Component::Normal("shortcodes".as_ref())) {
  261. site.render_markdown()?;
  262. }
  263. site.populate_sections();
  264. site.render_sections()?;
  265. site.render_orphan_pages()?;
  266. site.render_taxonomies()
  267. }
  268. }
  269. }
  270. #[cfg(test)]
  271. mod tests {
  272. use std::collections::HashMap;
  273. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  274. use super::{
  275. find_page_front_matter_changes, find_section_front_matter_changes,
  276. PageChangesNeeded, SectionChangesNeeded,
  277. };
  278. #[test]
  279. fn can_find_taxonomy_changes_in_page_frontmatter() {
  280. let mut taxonomies = HashMap::new();
  281. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  282. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  283. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  284. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  285. }
  286. #[test]
  287. fn can_find_multiple_changes_in_page_frontmatter() {
  288. let mut taxonomies = HashMap::new();
  289. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  290. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  291. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  292. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]);
  293. }
  294. #[test]
  295. fn can_find_sort_changes_in_section_frontmatter() {
  296. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  297. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  298. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  299. }
  300. #[test]
  301. fn can_find_render_changes_in_section_frontmatter() {
  302. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  303. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  304. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  305. }
  306. #[test]
  307. fn can_find_paginate_by_changes_in_section_frontmatter() {
  308. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  309. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  310. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  311. }
  312. }