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.

389 lines
15KB

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