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.

358 lines
13KB

  1. use std::collections::{HashMap, HashSet};
  2. use std::path::{Path, PathBuf};
  3. use slotmap::{DenseSlotMap, Key};
  4. use front_matter::SortBy;
  5. use content::{Page, Section};
  6. use sorting::{find_siblings, sort_pages_by_date, sort_pages_by_weight};
  7. /// Houses everything about pages and sections
  8. /// Think of it as a database where each page and section has an id (Key here)
  9. /// that can be used to find the actual value
  10. /// Sections and pages can then refer to other elements by those keys, which are very cheap to
  11. /// copy.
  12. /// We can assume the keys are always existing as removing a page/section deletes all references
  13. /// to that key.
  14. #[derive(Debug)]
  15. pub struct Library {
  16. /// All the pages of the site
  17. pages: DenseSlotMap<Page>,
  18. /// All the sections of the site
  19. sections: DenseSlotMap<Section>,
  20. /// A mapping path -> key for pages so we can easily get their key
  21. paths_to_pages: HashMap<PathBuf, Key>,
  22. /// A mapping path -> key for sections so we can easily get their key
  23. pub paths_to_sections: HashMap<PathBuf, Key>,
  24. }
  25. impl Library {
  26. pub fn new(cap_pages: usize, cap_sections: usize) -> Self {
  27. Library {
  28. pages: DenseSlotMap::with_capacity(cap_pages),
  29. sections: DenseSlotMap::with_capacity(cap_sections),
  30. paths_to_pages: HashMap::with_capacity(cap_pages),
  31. paths_to_sections: HashMap::with_capacity(cap_sections),
  32. }
  33. }
  34. /// Add a section and return its Key
  35. pub fn insert_section(&mut self, section: Section) -> Key {
  36. let path = section.file.path.clone();
  37. let key = self.sections.insert(section);
  38. self.paths_to_sections.insert(path, key);
  39. key
  40. }
  41. /// Add a page and return its Key
  42. pub fn insert_page(&mut self, page: Page) -> Key {
  43. let path = page.file.path.clone();
  44. let key = self.pages.insert(page);
  45. self.paths_to_pages.insert(path, key);
  46. key
  47. }
  48. pub fn pages(&self) -> &DenseSlotMap<Page> {
  49. &self.pages
  50. }
  51. pub fn pages_mut(&mut self) -> &mut DenseSlotMap<Page> {
  52. &mut self.pages
  53. }
  54. pub fn pages_values(&self) -> Vec<&Page> {
  55. self.pages.values().collect::<Vec<_>>()
  56. }
  57. pub fn sections(&self) -> &DenseSlotMap<Section> {
  58. &self.sections
  59. }
  60. pub fn sections_mut(&mut self) -> &mut DenseSlotMap<Section> {
  61. &mut self.sections
  62. }
  63. pub fn sections_values(&self) -> Vec<&Section> {
  64. self.sections.values().collect::<Vec<_>>()
  65. }
  66. /// Find out the direct subsections of each subsection if there are some
  67. /// as well as the pages for each section
  68. pub fn populate_sections(&mut self) {
  69. let root_path =
  70. self.sections.values().find(|s| s.is_index()).map(|s| s.file.parent.clone()).unwrap();
  71. // We are going to get both the ancestors and grandparents for each section in one go
  72. let mut ancestors: HashMap<PathBuf, Vec<_>> = HashMap::new();
  73. let mut subsections: HashMap<PathBuf, Vec<_>> = HashMap::new();
  74. for section in self.sections.values_mut() {
  75. // Make sure the pages of a section are empty since we can call that many times on `serve`
  76. section.pages = vec![];
  77. section.ignored_pages = vec![];
  78. if let Some(ref grand_parent) = section.file.grand_parent {
  79. subsections
  80. // Using the original filename to work for multi-lingual sections
  81. .entry(grand_parent.join(&section.file.filename))
  82. .or_insert_with(|| vec![])
  83. .push(section.file.path.clone());
  84. }
  85. // Index has no ancestors, no need to go through it
  86. if section.is_index() {
  87. ancestors.insert(section.file.path.clone(), vec![]);
  88. continue;
  89. }
  90. let mut path = root_path.clone();
  91. let root_key = self.paths_to_sections[&root_path.join(&section.file.filename)];
  92. // Index section is the first ancestor of every single section
  93. let mut parents = vec![root_key];
  94. for component in &section.file.components {
  95. path = path.join(component);
  96. // Skip itself
  97. if path == section.file.parent {
  98. continue;
  99. }
  100. if let Some(section_key) =
  101. self.paths_to_sections.get(&path.join(&section.file.filename))
  102. {
  103. parents.push(*section_key);
  104. }
  105. }
  106. ancestors.insert(section.file.path.clone(), parents);
  107. }
  108. for (key, page) in &mut self.pages {
  109. let parent_filename = if let Some(ref lang) = page.lang {
  110. format!("_index.{}.md", lang)
  111. } else {
  112. "_index.md".to_string()
  113. };
  114. let mut parent_section_path = page.file.parent.join(&parent_filename);
  115. while let Some(section_key) = self.paths_to_sections.get(&parent_section_path) {
  116. let parent_is_transparent;
  117. // We need to get a reference to a section later so keep the scope of borrowing small
  118. {
  119. let mut section = self.sections.get_mut(*section_key).unwrap();
  120. section.pages.push(key);
  121. parent_is_transparent = section.meta.transparent;
  122. }
  123. page.ancestors =
  124. ancestors.get(&parent_section_path).cloned().unwrap_or_else(|| vec![]);
  125. // Don't forget to push the actual parent
  126. page.ancestors.push(*section_key);
  127. // Find the page template if one of a parent has page_template set
  128. // Stops after the first one found, keep in mind page.ancestors
  129. // is [index, ..., parent] so we need to reverse it first
  130. if page.meta.template.is_none() {
  131. for ancestor in page.ancestors.iter().rev() {
  132. let s = self.sections.get(*ancestor).unwrap();
  133. if s.meta.page_template.is_some() {
  134. page.meta.template = s.meta.page_template.clone();
  135. break;
  136. }
  137. }
  138. }
  139. if !parent_is_transparent {
  140. break;
  141. }
  142. // We've added `_index(.{LANG})?.md` so if we are here so we need to go up twice
  143. match parent_section_path.clone().parent().unwrap().parent() {
  144. Some(parent) => parent_section_path = parent.join(&parent_filename),
  145. None => break,
  146. }
  147. }
  148. }
  149. self.sort_sections_pages();
  150. let sections = self.paths_to_sections.clone();
  151. let mut sections_weight = HashMap::new();
  152. for (key, section) in &self.sections {
  153. sections_weight.insert(key, section.meta.weight);
  154. }
  155. for section in self.sections.values_mut() {
  156. if let Some(ref children) = subsections.get(&section.file.path) {
  157. let mut children: Vec<_> = children.iter().map(|p| sections[p]).collect();
  158. children.sort_by(|a, b| sections_weight[a].cmp(&sections_weight[b]));
  159. section.subsections = children;
  160. }
  161. section.ancestors =
  162. ancestors.get(&section.file.path).cloned().unwrap_or_else(|| vec![]);
  163. }
  164. }
  165. /// Sort all sections pages
  166. pub fn sort_sections_pages(&mut self) {
  167. let mut updates = HashMap::new();
  168. for (key, section) in &self.sections {
  169. let (sorted_pages, cannot_be_sorted_pages) = match section.meta.sort_by {
  170. SortBy::None => continue,
  171. SortBy::Date => {
  172. let data = section
  173. .pages
  174. .iter()
  175. .map(|k| {
  176. if let Some(page) = self.pages.get(*k) {
  177. (k, page.meta.datetime, page.permalink.as_ref())
  178. } else {
  179. unreachable!("Sorting got an unknown page")
  180. }
  181. })
  182. .collect();
  183. sort_pages_by_date(data)
  184. }
  185. SortBy::Weight => {
  186. let data = section
  187. .pages
  188. .iter()
  189. .map(|k| {
  190. if let Some(page) = self.pages.get(*k) {
  191. (k, page.meta.weight, page.permalink.as_ref())
  192. } else {
  193. unreachable!("Sorting got an unknown page")
  194. }
  195. })
  196. .collect();
  197. sort_pages_by_weight(data)
  198. }
  199. };
  200. updates.insert(key, (sorted_pages, cannot_be_sorted_pages, section.meta.sort_by));
  201. }
  202. for (key, (sorted, cannot_be_sorted, sort_by)) in updates {
  203. // Find sibling between sorted pages first
  204. let with_siblings = find_siblings(
  205. sorted
  206. .iter()
  207. .map(|k| {
  208. if let Some(page) = self.pages.get(*k) {
  209. (k, page.is_draft())
  210. } else {
  211. unreachable!("Sorting got an unknown page")
  212. }
  213. })
  214. .collect(),
  215. );
  216. for (k2, val1, val2) in with_siblings {
  217. if let Some(page) = self.pages.get_mut(k2) {
  218. match sort_by {
  219. SortBy::Date => {
  220. page.earlier = val2;
  221. page.later = val1;
  222. }
  223. SortBy::Weight => {
  224. page.lighter = val1;
  225. page.heavier = val2;
  226. }
  227. SortBy::None => unreachable!("Impossible to find siblings in SortBy::None"),
  228. }
  229. } else {
  230. unreachable!("Sorting got an unknown page")
  231. }
  232. }
  233. if let Some(s) = self.sections.get_mut(key) {
  234. s.pages = sorted;
  235. s.ignored_pages = cannot_be_sorted;
  236. }
  237. }
  238. }
  239. /// Find all the orphan pages: pages that are in a folder without an `_index.md`
  240. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  241. let pages_in_sections =
  242. self.sections.values().flat_map(|s| &s.pages).collect::<HashSet<_>>();
  243. self.pages
  244. .iter()
  245. .filter(|(key, _)| !pages_in_sections.contains(&key))
  246. .map(|(_, page)| page)
  247. .collect()
  248. }
  249. pub fn find_parent_section<P: AsRef<Path>>(&self, path: P) -> Option<&Section> {
  250. let page_key = self.paths_to_pages[path.as_ref()];
  251. for s in self.sections.values() {
  252. if s.pages.contains(&page_key) {
  253. return Some(s);
  254. }
  255. }
  256. None
  257. }
  258. /// Only used in tests
  259. pub fn get_section_key<P: AsRef<Path>>(&self, path: P) -> Option<&Key> {
  260. self.paths_to_sections.get(path.as_ref())
  261. }
  262. pub fn get_section<P: AsRef<Path>>(&self, path: P) -> Option<&Section> {
  263. self.sections.get(self.paths_to_sections.get(path.as_ref()).cloned().unwrap_or_default())
  264. }
  265. pub fn get_section_mut<P: AsRef<Path>>(&mut self, path: P) -> Option<&mut Section> {
  266. self.sections
  267. .get_mut(self.paths_to_sections.get(path.as_ref()).cloned().unwrap_or_default())
  268. }
  269. pub fn get_section_by_key(&self, key: Key) -> &Section {
  270. self.sections.get(key).unwrap()
  271. }
  272. pub fn get_section_mut_by_key(&mut self, key: Key) -> &mut Section {
  273. self.sections.get_mut(key).unwrap()
  274. }
  275. pub fn get_section_path_by_key(&self, key: Key) -> &str {
  276. &self.get_section_by_key(key).file.relative
  277. }
  278. pub fn get_page<P: AsRef<Path>>(&self, path: P) -> Option<&Page> {
  279. self.pages.get(self.paths_to_pages.get(path.as_ref()).cloned().unwrap_or_default())
  280. }
  281. pub fn get_page_by_key(&self, key: Key) -> &Page {
  282. self.pages.get(key).unwrap()
  283. }
  284. pub fn get_page_mut_by_key(&mut self, key: Key) -> &mut Page {
  285. self.pages.get_mut(key).unwrap()
  286. }
  287. pub fn remove_section<P: AsRef<Path>>(&mut self, path: P) -> Option<Section> {
  288. if let Some(k) = self.paths_to_sections.remove(path.as_ref()) {
  289. self.sections.remove(k)
  290. } else {
  291. None
  292. }
  293. }
  294. pub fn remove_page<P: AsRef<Path>>(&mut self, path: P) -> Option<Page> {
  295. if let Some(k) = self.paths_to_pages.remove(path.as_ref()) {
  296. self.pages.remove(k)
  297. } else {
  298. None
  299. }
  300. }
  301. /// Used in rebuild, to check if we know it already
  302. pub fn contains_section<P: AsRef<Path>>(&self, path: P) -> bool {
  303. self.paths_to_sections.contains_key(path.as_ref())
  304. }
  305. /// Used in rebuild, to check if we know it already
  306. pub fn contains_page<P: AsRef<Path>>(&self, path: P) -> bool {
  307. self.paths_to_pages.contains_key(path.as_ref())
  308. }
  309. }