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.

449 lines
16KB

  1. extern crate site;
  2. #[macro_use]
  3. extern crate errors;
  4. extern crate front_matter;
  5. extern crate library;
  6. use std::path::{Component, Path};
  7. use errors::Result;
  8. use front_matter::{PageFrontMatter, SectionFrontMatter};
  9. use library::{Page, Section};
  10. use site::Site;
  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. /// Changing `transparent`
  31. Transparent,
  32. }
  33. /// Evaluates all the params in the front matter that changed so we can do the smallest
  34. /// delta in the serve command
  35. /// Order matters as the actions will be done in insertion order
  36. fn find_section_front_matter_changes(
  37. current: &SectionFrontMatter,
  38. new: &SectionFrontMatter,
  39. ) -> Vec<SectionChangesNeeded> {
  40. let mut changes_needed = vec![];
  41. if current.sort_by != new.sort_by {
  42. changes_needed.push(SectionChangesNeeded::Sort);
  43. }
  44. if current.transparent != new.transparent {
  45. changes_needed.push(SectionChangesNeeded::Transparent);
  46. }
  47. // We want to hide the section
  48. // TODO: what to do on redirect_path change?
  49. if current.render && !new.render {
  50. changes_needed.push(SectionChangesNeeded::Delete);
  51. // Nothing else we can do
  52. return changes_needed;
  53. }
  54. if current.paginate_by != new.paginate_by
  55. || current.paginate_path != new.paginate_path
  56. || current.insert_anchor_links != new.insert_anchor_links
  57. {
  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(
  70. current: &PageFrontMatter,
  71. other: &PageFrontMatter,
  72. ) -> Vec<PageChangesNeeded> {
  73. let mut changes_needed = vec![];
  74. if current.taxonomies != other.taxonomies {
  75. changes_needed.push(PageChangesNeeded::Taxonomies);
  76. }
  77. if current.date != other.date || current.order != other.order || current.weight != other.weight
  78. {
  79. changes_needed.push(PageChangesNeeded::Sort);
  80. }
  81. changes_needed.push(PageChangesNeeded::Render);
  82. changes_needed
  83. }
  84. /// Handles a path deletion: could be a page, a section, a folder
  85. fn delete_element(site: &mut Site, path: &Path, is_section: bool) -> Result<()> {
  86. {
  87. let mut library = site.library.write().unwrap();
  88. // Ignore the event if this path was not known
  89. if !library.contains_section(&path.to_path_buf())
  90. && !library.contains_page(&path.to_path_buf())
  91. {
  92. return Ok(());
  93. }
  94. if is_section {
  95. if let Some(s) = library.remove_section(&path.to_path_buf()) {
  96. site.permalinks.remove(&s.file.relative);
  97. }
  98. } else if let Some(p) = library.remove_page(&path.to_path_buf()) {
  99. site.permalinks.remove(&p.file.relative);
  100. }
  101. }
  102. site.populate_sections();
  103. site.populate_taxonomies()?;
  104. // Ensure we have our fn updated so it doesn't contain the permalink(s)/section/page deleted
  105. site.register_early_global_fns();
  106. site.register_tera_global_fns();
  107. // Deletion is something that doesn't happen all the time so we
  108. // don't need to optimise it too much
  109. site.build()
  110. }
  111. /// Handles a `_index.md` (a section) being edited in some ways
  112. fn handle_section_editing(site: &mut Site, path: &Path) -> Result<()> {
  113. let section = Section::from_file(path, &site.config)?;
  114. let pathbuf = path.to_path_buf();
  115. match site.add_section(section, true)? {
  116. // Updating a section
  117. Some(prev) => {
  118. site.populate_sections();
  119. {
  120. let library = site.library.read().unwrap();
  121. if library.get_section(&pathbuf).unwrap().meta == prev.meta {
  122. // Front matter didn't change, only content did
  123. // so we render only the section page, not its pages
  124. return site.render_section(&library.get_section(&pathbuf).unwrap(), false);
  125. }
  126. }
  127. // Front matter changed
  128. let changes = find_section_front_matter_changes(
  129. &site.library.read().unwrap().get_section(&pathbuf).unwrap().meta,
  130. &prev.meta,
  131. );
  132. for change in changes {
  133. // Sort always comes first if present so the rendering will be fine
  134. match change {
  135. SectionChangesNeeded::Sort => {
  136. site.register_tera_global_fns();
  137. }
  138. SectionChangesNeeded::Render => site.render_section(
  139. &site.library.read().unwrap().get_section(&pathbuf).unwrap(),
  140. false,
  141. )?,
  142. SectionChangesNeeded::RenderWithPages => site.render_section(
  143. &site.library.read().unwrap().get_section(&pathbuf).unwrap(),
  144. true,
  145. )?,
  146. // not a common enough operation to make it worth optimizing
  147. SectionChangesNeeded::Delete | SectionChangesNeeded::Transparent => {
  148. site.build()?;
  149. }
  150. };
  151. }
  152. Ok(())
  153. }
  154. // New section, only render that one
  155. None => {
  156. site.populate_sections();
  157. site.register_tera_global_fns();
  158. site.render_section(&site.library.read().unwrap().get_section(&pathbuf).unwrap(), true)
  159. }
  160. }
  161. }
  162. macro_rules! render_parent_sections {
  163. ($site: expr, $path: expr) => {
  164. for s in $site.library.read().unwrap().find_parent_sections($path) {
  165. $site.render_section(s, false)?;
  166. }
  167. };
  168. }
  169. /// Handles a page being edited in some ways
  170. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  171. let page = Page::from_file(path, &site.config)?;
  172. let pathbuf = path.to_path_buf();
  173. match site.add_page(page, true)? {
  174. // Updating a page
  175. Some(prev) => {
  176. site.populate_sections();
  177. site.populate_taxonomies()?;
  178. site.register_tera_global_fns();
  179. {
  180. let library = site.library.read().unwrap();
  181. // Front matter didn't change, only content did
  182. if library.get_page(&pathbuf).unwrap().meta == prev.meta {
  183. // Other than the page itself, the summary might be seen
  184. // on a paginated list for a blog for example
  185. if library.get_page(&pathbuf).unwrap().summary.is_some() {
  186. render_parent_sections!(site, path);
  187. }
  188. return site.render_page(&library.get_page(&pathbuf).unwrap());
  189. }
  190. }
  191. // Front matter changed
  192. let changes = find_page_front_matter_changes(
  193. &site.library.read().unwrap().get_page(&pathbuf).unwrap().meta,
  194. &prev.meta,
  195. );
  196. for change in changes {
  197. site.register_tera_global_fns();
  198. // Sort always comes first if present so the rendering will be fine
  199. match change {
  200. PageChangesNeeded::Taxonomies => {
  201. site.populate_taxonomies()?;
  202. site.render_taxonomies()?;
  203. }
  204. PageChangesNeeded::Sort => {
  205. site.render_index()?;
  206. }
  207. PageChangesNeeded::Render => {
  208. render_parent_sections!(site, path);
  209. site.render_page(
  210. &site.library.read().unwrap().get_page(&path.to_path_buf()).unwrap(),
  211. )?;
  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_early_global_fns();
  222. site.register_tera_global_fns();
  223. // No need to optimise that yet, we can revisit if it becomes an issue
  224. site.build()
  225. }
  226. }
  227. }
  228. /// What happens when we rename a file/folder in the content directory.
  229. /// Note that this is only called for folders when it isn't empty
  230. pub fn after_content_rename(site: &mut Site, old: &Path, new: &Path) -> Result<()> {
  231. let new_path = if new.is_dir() {
  232. if new.join("_index.md").exists() {
  233. // This is a section keep the dir folder to differentiate from renaming _index.md
  234. // which doesn't do the same thing
  235. new.to_path_buf()
  236. } else if new.join("index.md").exists() {
  237. new.join("index.md")
  238. } else {
  239. bail!("Got unexpected folder {:?} while handling renaming that was not expected", new);
  240. }
  241. } else {
  242. new.to_path_buf()
  243. };
  244. // A section folder has been renamed: just reload the whole site and rebuild it as we
  245. // do not really know what needs to be rendered
  246. if new_path.is_dir() {
  247. site.load()?;
  248. return site.build();
  249. }
  250. // We ignore renames on non-markdown files for now
  251. if let Some(ext) = new_path.extension() {
  252. if ext != "md" {
  253. return Ok(());
  254. }
  255. }
  256. // Renaming a file to _index.md, let the section editing do something and hope for the best
  257. if new_path.file_name().unwrap() == "_index.md" {
  258. // We aren't entirely sure where the original thing was so just try to delete whatever was
  259. // at the old path
  260. {
  261. let mut library = site.library.write().unwrap();
  262. library.remove_page(&old.to_path_buf());
  263. library.remove_section(&old.to_path_buf());
  264. }
  265. return handle_section_editing(site, &new_path);
  266. }
  267. // If it is a page, just delete what was there before and
  268. // fake it's a new page
  269. let old_path = if new_path.file_name().unwrap() == "index.md" {
  270. old.join("index.md")
  271. } else {
  272. old.to_path_buf()
  273. };
  274. site.library.write().unwrap().remove_page(&old_path);
  275. handle_page_editing(site, &new_path)
  276. }
  277. /// What happens when a section or a page is created/edited
  278. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  279. let is_section = path.file_name().unwrap() == "_index.md";
  280. let is_md = path.extension().unwrap() == "md";
  281. let index = path.parent().unwrap().join("index.md");
  282. let mut potential_indices = vec![path.parent().unwrap().join("index.md")];
  283. for language in &site.config.languages {
  284. potential_indices.push(path.parent().unwrap().join(format!("index.{}.md", language.code)));
  285. }
  286. let colocated_index = potential_indices.contains(&path.to_path_buf());
  287. // A few situations can happen:
  288. // 1. Change on .md files
  289. // a. Is there already an `index.md`? Return an error if it's something other than delete
  290. // b. Deleted? remove the element
  291. // c. Edited?
  292. // 1. filename is `_index.md`, this is a section
  293. // 1. it's a page otherwise
  294. // 2. Change on non .md files
  295. // a. Try to find a corresponding `_index.md`
  296. // 1. Nothing? Return Ok
  297. // 2. Something? Update the page
  298. if is_md {
  299. // only delete if it was able to be added in the first place
  300. if !index.exists() && !path.exists() {
  301. return delete_element(site, path, is_section);
  302. }
  303. // Added another .md in a assets directory
  304. if index.exists() && path.exists() && !colocated_index {
  305. bail!(
  306. "Change on {:?} detected but only files named `index.md` with an optional language code are allowed",
  307. path.display()
  308. );
  309. } else if index.exists() && !path.exists() {
  310. // deleted the wrong .md, do nothing
  311. return Ok(());
  312. }
  313. if is_section {
  314. handle_section_editing(site, path)
  315. } else {
  316. handle_page_editing(site, path)
  317. }
  318. } else if index.exists() {
  319. handle_page_editing(site, &index)
  320. } else {
  321. Ok(())
  322. }
  323. }
  324. /// What happens when a template is changed
  325. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  326. site.tera.full_reload()?;
  327. let filename = path.file_name().unwrap().to_str().unwrap();
  328. match filename {
  329. "sitemap.xml" => site.render_sitemap(),
  330. "rss.xml" => site.render_rss_feed(site.library.read().unwrap().pages_values(), None),
  331. "robots.txt" => site.render_robots(),
  332. "single.html" | "list.html" => site.render_taxonomies(),
  333. "page.html" => {
  334. site.render_sections()?;
  335. site.render_orphan_pages()
  336. }
  337. "section.html" => site.render_sections(),
  338. "404.html" => site.render_404(),
  339. // Either the index or some unknown template changed
  340. // We can't really know what this change affects so rebuild all
  341. // the things
  342. _ => {
  343. // If we are updating a shortcode, re-render the markdown of all pages/site
  344. // because we have no clue which one needs rebuilding
  345. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  346. // everything
  347. if path.components().any(|x| x == Component::Normal("shortcodes".as_ref())) {
  348. site.render_markdown()?;
  349. }
  350. site.populate_sections();
  351. site.populate_taxonomies()?;
  352. site.render_sections()?;
  353. site.render_orphan_pages()?;
  354. site.render_taxonomies()
  355. }
  356. }
  357. }
  358. #[cfg(test)]
  359. mod tests {
  360. use std::collections::HashMap;
  361. use super::{
  362. find_page_front_matter_changes, find_section_front_matter_changes, PageChangesNeeded,
  363. SectionChangesNeeded,
  364. };
  365. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  366. #[test]
  367. fn can_find_taxonomy_changes_in_page_frontmatter() {
  368. let mut taxonomies = HashMap::new();
  369. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  370. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  371. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  372. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  373. }
  374. #[test]
  375. fn can_find_multiple_changes_in_page_frontmatter() {
  376. let mut taxonomies = HashMap::new();
  377. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  378. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  379. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  380. assert_eq!(
  381. changes,
  382. vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]
  383. );
  384. }
  385. #[test]
  386. fn can_find_sort_changes_in_section_frontmatter() {
  387. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  388. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  389. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  390. }
  391. #[test]
  392. fn can_find_render_changes_in_section_frontmatter() {
  393. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  394. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  395. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  396. }
  397. #[test]
  398. fn can_find_paginate_by_changes_in_section_frontmatter() {
  399. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  400. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  401. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  402. }
  403. }