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.

330 lines
11KB

  1. use std::collections::HashMap;
  2. use slotmap::Key;
  3. use slug::slugify;
  4. use tera::{Context, Tera};
  5. use config::{Config, Taxonomy as TaxonomyConfig};
  6. use errors::{Result, ResultExt};
  7. use utils::templates::render_template;
  8. use content::SerializingPage;
  9. use library::Library;
  10. use sorting::sort_pages_by_date;
  11. #[derive(Debug, Clone, PartialEq, Serialize)]
  12. pub struct SerializedTaxonomyItem<'a> {
  13. name: &'a str,
  14. slug: &'a str,
  15. permalink: &'a str,
  16. pages: Vec<SerializingPage<'a>>,
  17. }
  18. impl<'a> SerializedTaxonomyItem<'a> {
  19. pub fn from_item(item: &'a TaxonomyItem, library: &'a Library) -> Self {
  20. let mut pages = vec![];
  21. for key in &item.pages {
  22. let page = library.get_page_by_key(*key);
  23. pages.push(page.to_serialized_basic(library));
  24. }
  25. SerializedTaxonomyItem {
  26. name: &item.name,
  27. slug: &item.slug,
  28. permalink: &item.permalink,
  29. pages,
  30. }
  31. }
  32. }
  33. /// A taxonomy with all its pages
  34. #[derive(Debug, Clone, PartialEq)]
  35. pub struct TaxonomyItem {
  36. pub name: String,
  37. pub slug: String,
  38. pub permalink: String,
  39. pub pages: Vec<Key>,
  40. }
  41. impl TaxonomyItem {
  42. pub fn new(name: &str, path: &str, config: &Config, keys: Vec<Key>, library: &Library) -> Self {
  43. // Taxonomy are almost always used for blogs so we filter by dates
  44. // and it's not like we can sort things across sections by anything other
  45. // than dates
  46. let data = keys
  47. .iter()
  48. .map(|k| {
  49. if let Some(page) = library.pages().get(*k) {
  50. (k, page.meta.datetime, page.permalink.as_ref())
  51. } else {
  52. unreachable!("Sorting got an unknown page")
  53. }
  54. })
  55. .collect();
  56. let (mut pages, ignored_pages) = sort_pages_by_date(data);
  57. let slug = slugify(name);
  58. let permalink = config.make_permalink(&format!("/{}/{}", path, slug));
  59. // We still append pages without dates at the end
  60. pages.extend(ignored_pages);
  61. TaxonomyItem { name: name.to_string(), permalink, slug, pages }
  62. }
  63. pub fn serialize<'a>(&'a self, library: &'a Library) -> SerializedTaxonomyItem<'a> {
  64. SerializedTaxonomyItem::from_item(self, library)
  65. }
  66. }
  67. #[derive(Debug, Clone, PartialEq, Serialize)]
  68. pub struct SerializedTaxonomy<'a> {
  69. kind: &'a TaxonomyConfig,
  70. items: Vec<SerializedTaxonomyItem<'a>>,
  71. }
  72. impl<'a> SerializedTaxonomy<'a> {
  73. pub fn from_taxonomy(taxonomy: &'a Taxonomy, library: &'a Library) -> Self {
  74. let items: Vec<SerializedTaxonomyItem> =
  75. taxonomy.items.iter().map(|i| SerializedTaxonomyItem::from_item(i, library)).collect();
  76. SerializedTaxonomy { kind: &taxonomy.kind, items }
  77. }
  78. }
  79. /// All different taxonomies we have and their content
  80. #[derive(Debug, Clone, PartialEq)]
  81. pub struct Taxonomy {
  82. pub kind: TaxonomyConfig,
  83. // this vec is sorted by the count of item
  84. pub items: Vec<TaxonomyItem>,
  85. }
  86. impl Taxonomy {
  87. fn new(
  88. kind: TaxonomyConfig,
  89. config: &Config,
  90. items: HashMap<String, Vec<Key>>,
  91. library: &Library,
  92. ) -> Taxonomy {
  93. let mut sorted_items = vec![];
  94. for (name, pages) in items {
  95. sorted_items.push(TaxonomyItem::new(&name, &kind.name, config, pages, library));
  96. }
  97. sorted_items.sort_by(|a, b| a.name.cmp(&b.name));
  98. Taxonomy { kind, items: sorted_items }
  99. }
  100. pub fn len(&self) -> usize {
  101. self.items.len()
  102. }
  103. pub fn is_empty(&self) -> bool {
  104. self.len() == 0
  105. }
  106. pub fn render_term(
  107. &self,
  108. item: &TaxonomyItem,
  109. tera: &Tera,
  110. config: &Config,
  111. library: &Library,
  112. ) -> Result<String> {
  113. let mut context = Context::new();
  114. context.insert("config", config);
  115. context.insert("term", &SerializedTaxonomyItem::from_item(item, library));
  116. context.insert("taxonomy", &self.kind);
  117. context.insert(
  118. "current_url",
  119. &config.make_permalink(&format!("{}/{}", self.kind.name, item.slug)),
  120. );
  121. context.insert("current_path", &format!("/{}/{}", self.kind.name, item.slug));
  122. render_template(&format!("{}/single.html", self.kind.name), tera, &context, &config.theme)
  123. .chain_err(|| format!("Failed to render single term {} page.", self.kind.name))
  124. }
  125. pub fn render_all_terms(
  126. &self,
  127. tera: &Tera,
  128. config: &Config,
  129. library: &Library,
  130. ) -> Result<String> {
  131. let mut context = Context::new();
  132. context.insert("config", config);
  133. let terms: Vec<SerializedTaxonomyItem> =
  134. self.items.iter().map(|i| SerializedTaxonomyItem::from_item(i, library)).collect();
  135. context.insert("terms", &terms);
  136. context.insert("taxonomy", &self.kind);
  137. context.insert("current_url", &config.make_permalink(&self.kind.name));
  138. context.insert("current_path", &self.kind.name);
  139. render_template(&format!("{}/list.html", self.kind.name), tera, &context, &config.theme)
  140. .chain_err(|| format!("Failed to render a list of {} page.", self.kind.name))
  141. }
  142. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializedTaxonomy<'a> {
  143. SerializedTaxonomy::from_taxonomy(self, library)
  144. }
  145. }
  146. pub fn find_taxonomies(config: &Config, library: &Library) -> Result<Vec<Taxonomy>> {
  147. let taxonomies_def = {
  148. let mut m = HashMap::new();
  149. for t in &config.taxonomies {
  150. m.insert(t.name.clone(), t);
  151. }
  152. m
  153. };
  154. let mut all_taxonomies = HashMap::new();
  155. for (key, page) in library.pages() {
  156. // Draft are not part of taxonomies
  157. if page.is_draft() {
  158. continue;
  159. }
  160. for (name, val) in &page.meta.taxonomies {
  161. if taxonomies_def.contains_key(name) {
  162. all_taxonomies.entry(name).or_insert_with(HashMap::new);
  163. for v in val {
  164. all_taxonomies
  165. .get_mut(name)
  166. .unwrap()
  167. .entry(v.to_string())
  168. .or_insert_with(|| vec![])
  169. .push(key);
  170. }
  171. } else {
  172. bail!(
  173. "Page `{}` has taxonomy `{}` which is not defined in config.toml",
  174. page.file.path.display(),
  175. name
  176. );
  177. }
  178. }
  179. }
  180. let mut taxonomies = vec![];
  181. for (name, taxo) in all_taxonomies {
  182. taxonomies.push(Taxonomy::new(taxonomies_def[name].clone(), config, taxo, library));
  183. }
  184. Ok(taxonomies)
  185. }
  186. #[cfg(test)]
  187. mod tests {
  188. use super::*;
  189. use std::collections::HashMap;
  190. use config::{Config, Taxonomy as TaxonomyConfig};
  191. use content::Page;
  192. use library::Library;
  193. #[test]
  194. fn can_make_taxonomies() {
  195. let mut config = Config::default();
  196. let mut library = Library::new(2, 0, false);
  197. config.taxonomies = vec![
  198. TaxonomyConfig { name: "categories".to_string(), ..TaxonomyConfig::default() },
  199. TaxonomyConfig { name: "tags".to_string(), ..TaxonomyConfig::default() },
  200. TaxonomyConfig { name: "authors".to_string(), ..TaxonomyConfig::default() },
  201. ];
  202. let mut page1 = Page::default();
  203. let mut taxo_page1 = HashMap::new();
  204. taxo_page1.insert("tags".to_string(), vec!["rust".to_string(), "db".to_string()]);
  205. taxo_page1.insert("categories".to_string(), vec!["Programming tutorials".to_string()]);
  206. page1.meta.taxonomies = taxo_page1;
  207. library.insert_page(page1);
  208. let mut page2 = Page::default();
  209. let mut taxo_page2 = HashMap::new();
  210. taxo_page2.insert("tags".to_string(), vec!["rust".to_string(), "js".to_string()]);
  211. taxo_page2.insert("categories".to_string(), vec!["Other".to_string()]);
  212. page2.meta.taxonomies = taxo_page2;
  213. library.insert_page(page2);
  214. let mut page3 = Page::default();
  215. let mut taxo_page3 = HashMap::new();
  216. taxo_page3.insert("tags".to_string(), vec!["js".to_string()]);
  217. taxo_page3.insert("authors".to_string(), vec!["Vincent Prouillet".to_string()]);
  218. page3.meta.taxonomies = taxo_page3;
  219. library.insert_page(page3);
  220. let taxonomies = find_taxonomies(&config, &library).unwrap();
  221. let (tags, categories, authors) = {
  222. let mut t = None;
  223. let mut c = None;
  224. let mut a = None;
  225. for x in taxonomies {
  226. match x.kind.name.as_ref() {
  227. "tags" => t = Some(x),
  228. "categories" => c = Some(x),
  229. "authors" => a = Some(x),
  230. _ => unreachable!(),
  231. }
  232. }
  233. (t.unwrap(), c.unwrap(), a.unwrap())
  234. };
  235. assert_eq!(tags.items.len(), 3);
  236. assert_eq!(categories.items.len(), 2);
  237. assert_eq!(authors.items.len(), 1);
  238. assert_eq!(tags.items[0].name, "db");
  239. assert_eq!(tags.items[0].slug, "db");
  240. assert_eq!(tags.items[0].permalink, "http://a-website.com/tags/db/");
  241. assert_eq!(tags.items[0].pages.len(), 1);
  242. assert_eq!(tags.items[1].name, "js");
  243. assert_eq!(tags.items[1].slug, "js");
  244. assert_eq!(tags.items[1].permalink, "http://a-website.com/tags/js/");
  245. assert_eq!(tags.items[1].pages.len(), 2);
  246. assert_eq!(tags.items[2].name, "rust");
  247. assert_eq!(tags.items[2].slug, "rust");
  248. assert_eq!(tags.items[2].permalink, "http://a-website.com/tags/rust/");
  249. assert_eq!(tags.items[2].pages.len(), 2);
  250. assert_eq!(categories.items[0].name, "Other");
  251. assert_eq!(categories.items[0].slug, "other");
  252. assert_eq!(categories.items[0].permalink, "http://a-website.com/categories/other/");
  253. assert_eq!(categories.items[0].pages.len(), 1);
  254. assert_eq!(categories.items[1].name, "Programming tutorials");
  255. assert_eq!(categories.items[1].slug, "programming-tutorials");
  256. assert_eq!(
  257. categories.items[1].permalink,
  258. "http://a-website.com/categories/programming-tutorials/"
  259. );
  260. assert_eq!(categories.items[1].pages.len(), 1);
  261. }
  262. #[test]
  263. fn errors_on_unknown_taxonomy() {
  264. let mut config = Config::default();
  265. let mut library = Library::new(2, 0, false);
  266. config.taxonomies =
  267. vec![TaxonomyConfig { name: "authors".to_string(), ..TaxonomyConfig::default() }];
  268. let mut page1 = Page::default();
  269. let mut taxo_page1 = HashMap::new();
  270. taxo_page1.insert("tags".to_string(), vec!["rust".to_string(), "db".to_string()]);
  271. page1.meta.taxonomies = taxo_page1;
  272. library.insert_page(page1);
  273. let taxonomies = find_taxonomies(&config, &library);
  274. assert!(taxonomies.is_err());
  275. let err = taxonomies.unwrap_err();
  276. // no path as this is created by Default
  277. assert_eq!(
  278. err.description(),
  279. "Page `` has taxonomy `tags` which is not defined in config.toml"
  280. );
  281. }
  282. }