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.

221 lines
7.7KB

  1. use std::path::{Path, PathBuf};
  2. use config::Config;
  3. use errors::Result;
  4. /// Takes a full path to a file and returns only the components after the first `content` directory
  5. /// Will not return the filename as last component
  6. pub fn find_content_components<P: AsRef<Path>>(path: P) -> Vec<String> {
  7. let path = path.as_ref();
  8. let mut is_in_content = false;
  9. let mut components = vec![];
  10. for section in path.parent().unwrap().components() {
  11. let component = section.as_os_str().to_string_lossy();
  12. if is_in_content {
  13. components.push(component.to_string());
  14. continue;
  15. }
  16. if component == "content" {
  17. is_in_content = true;
  18. }
  19. }
  20. components
  21. }
  22. /// Struct that contains all the information about the actual file
  23. #[derive(Debug, Clone, PartialEq)]
  24. pub struct FileInfo {
  25. /// The full path to the .md file
  26. pub path: PathBuf,
  27. /// The name of the .md file without the extension, always `_index` for sections
  28. /// Doesn't contain the language if there was one in the filename
  29. pub name: String,
  30. /// The .md path, starting from the content directory, with `/` slashes
  31. pub relative: String,
  32. /// Path of the directory containing the .md file
  33. pub parent: PathBuf,
  34. /// Path of the grand parent directory for that file. Only used in sections to find subsections.
  35. pub grand_parent: Option<PathBuf>,
  36. /// The folder names to this section file, starting from the `content` directory
  37. /// For example a file at content/kb/solutions/blabla.md will have 2 components:
  38. /// `kb` and `solutions`
  39. pub components: Vec<String>,
  40. }
  41. impl FileInfo {
  42. pub fn new_page(path: &Path) -> FileInfo {
  43. let file_path = path.to_path_buf();
  44. let mut parent = file_path.parent().unwrap().to_path_buf();
  45. let name = path.file_stem().unwrap().to_string_lossy().to_string();
  46. let mut components = find_content_components(&file_path);
  47. let relative = if !components.is_empty() {
  48. format!("{}/{}.md", components.join("/"), name)
  49. } else {
  50. format!("{}.md", name)
  51. };
  52. // If we have a folder with an asset, don't consider it as a component
  53. // Splitting on `.` as we might have a language so it isn't *only* index but also index.fr
  54. // etc
  55. if !components.is_empty() && name.split('.').collect::<Vec<_>>()[0] == "index" {
  56. components.pop();
  57. // also set parent_path to grandparent instead
  58. parent = parent.parent().unwrap().to_path_buf();
  59. }
  60. FileInfo {
  61. path: file_path,
  62. // We don't care about grand parent for pages
  63. grand_parent: None,
  64. parent,
  65. name,
  66. components,
  67. relative,
  68. }
  69. }
  70. pub fn new_section(path: &Path) -> FileInfo {
  71. let parent = path.parent().unwrap().to_path_buf();
  72. let name = path.file_stem().unwrap().to_string_lossy().to_string();
  73. let components = find_content_components(path);
  74. let relative = if !components.is_empty() {
  75. format!("{}/{}.md", components.join("/"), name)
  76. } else {
  77. format!("{}.md", name)
  78. };
  79. let grand_parent = parent.parent().map(|p| p.to_path_buf());
  80. FileInfo {
  81. path: path.to_path_buf(),
  82. parent,
  83. grand_parent,
  84. name,
  85. components,
  86. relative,
  87. }
  88. }
  89. /// Look for a language in the filename.
  90. /// If a language has been found, update the name of the file in this struct to
  91. /// remove it and return the language code
  92. pub fn find_language(&mut self, config: &Config) -> Result<Option<String>> {
  93. // No languages? Nothing to do
  94. if !config.uses_i18n() {
  95. return Ok(None);
  96. }
  97. if !self.name.contains('.') {
  98. return Ok(None);
  99. }
  100. // Go with the assumption that no one is using `.` in filenames when using i18n
  101. // We can document that
  102. let mut parts: Vec<String> = self.name.splitn(2,'.').map(|s| s.to_string()).collect();
  103. // The language code is not present in the config: typo or the user forgot to add it to the
  104. // config
  105. if !config.languages_codes().contains(&parts[1].as_ref()) {
  106. bail!("File {:?} has a language code of {} which isn't present in the config.toml `languages`", self.path, parts[1]);
  107. }
  108. self.name = parts.swap_remove(0);
  109. let lang = parts.swap_remove(0);
  110. Ok(Some(lang))
  111. }
  112. }
  113. #[doc(hidden)]
  114. impl Default for FileInfo {
  115. fn default() -> FileInfo {
  116. FileInfo {
  117. path: PathBuf::new(),
  118. parent: PathBuf::new(),
  119. grand_parent: None,
  120. name: String::new(),
  121. components: vec![],
  122. relative: String::new(),
  123. }
  124. }
  125. }
  126. #[cfg(test)]
  127. mod tests {
  128. use std::path::Path;
  129. use config::{Config, Language};
  130. use super::{FileInfo, find_content_components};
  131. #[test]
  132. fn can_find_content_components() {
  133. let res =
  134. find_content_components("/home/vincent/code/site/content/posts/tutorials/python.md");
  135. assert_eq!(res, ["posts".to_string(), "tutorials".to_string()]);
  136. }
  137. #[test]
  138. fn can_find_components_in_page_with_assets() {
  139. let file =
  140. FileInfo::new_page(&Path::new("/home/vincent/code/site/content/posts/tutorials/python/index.md"));
  141. assert_eq!(file.components, ["posts".to_string(), "tutorials".to_string()]);
  142. }
  143. #[test]
  144. fn can_find_valid_language_in_page() {
  145. let mut config = Config::default();
  146. config.languages.push(Language {code: String::from("fr"), rss: false});
  147. let mut file =
  148. FileInfo::new_page(&Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"));
  149. let res = file.find_language(&config);
  150. assert!(res.is_ok());
  151. assert_eq!(res.unwrap(), Some(String::from("fr")));
  152. }
  153. #[test]
  154. fn can_find_valid_language_in_page_with_assets() {
  155. let mut config = Config::default();
  156. config.languages.push(Language {code: String::from("fr"), rss: false});
  157. let mut file =
  158. FileInfo::new_page(&Path::new("/home/vincent/code/site/content/posts/tutorials/python/index.fr.md"));
  159. assert_eq!(file.components, ["posts".to_string(), "tutorials".to_string()]);
  160. let res = file.find_language(&config);
  161. assert!(res.is_ok());
  162. assert_eq!(res.unwrap(), Some(String::from("fr")));
  163. }
  164. #[test]
  165. fn do_nothing_on_unknown_language_in_page_with_i18n_off() {
  166. let config = Config::default();
  167. let mut file =
  168. FileInfo::new_page(&Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"));
  169. let res = file.find_language(&config);
  170. assert!(res.is_ok());
  171. assert!(res.unwrap().is_none());
  172. }
  173. #[test]
  174. fn errors_on_unknown_language_in_page_with_i18n_on() {
  175. let mut config = Config::default();
  176. config.languages.push(Language {code: String::from("it"), rss: false});
  177. let mut file =
  178. FileInfo::new_page(&Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"));
  179. let res = file.find_language(&config);
  180. assert!(res.is_err());
  181. }
  182. #[test]
  183. fn can_find_valid_language_in_section() {
  184. let mut config = Config::default();
  185. config.languages.push(Language {code: String::from("fr"), rss: false});
  186. let mut file =
  187. FileInfo::new_section(&Path::new("/home/vincent/code/site/content/posts/tutorials/_index.fr.md"));
  188. let res = file.find_language(&config);
  189. assert!(res.is_ok());
  190. assert_eq!(res.unwrap(), Some(String::from("fr")));
  191. }
  192. }