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.

260 lines
9.2KB

  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 on-disk filename, will differ from the `name` when there is a language code in it
  28. pub filename: String,
  29. /// The name of the .md file without the extension, always `_index` for sections
  30. /// Doesn't contain the language if there was one in the filename
  31. pub name: String,
  32. /// The .md path, starting from the content directory, with `/` slashes
  33. pub relative: String,
  34. /// Path of the directory containing the .md file
  35. pub parent: PathBuf,
  36. /// Path of the grand parent directory for that file. Only used in sections to find subsections.
  37. pub grand_parent: Option<PathBuf>,
  38. /// The folder names to this section file, starting from the `content` directory
  39. /// For example a file at content/kb/solutions/blabla.md will have 2 components:
  40. /// `kb` and `solutions`
  41. pub components: Vec<String>,
  42. /// This is `parent` + `name`, used to find content referring to the same content but in
  43. /// various languages.
  44. pub canonical: PathBuf,
  45. }
  46. impl FileInfo {
  47. pub fn new_page(path: &Path, base_path: &PathBuf) -> FileInfo {
  48. let file_path = path.to_path_buf();
  49. let mut parent = file_path.parent().expect("Get parent of page").to_path_buf();
  50. let name = path.file_stem().unwrap().to_string_lossy().to_string();
  51. let mut components = find_content_components(
  52. &file_path.strip_prefix(base_path).expect("Strip base path prefix for page"),
  53. );
  54. let relative = if !components.is_empty() {
  55. format!("{}/{}.md", components.join("/"), name)
  56. } else {
  57. format!("{}.md", name)
  58. };
  59. // If we have a folder with an asset, don't consider it as a component
  60. // Splitting on `.` as we might have a language so it isn't *only* index but also index.fr
  61. // etc
  62. if !components.is_empty() && name.split('.').collect::<Vec<_>>()[0] == "index" {
  63. components.pop();
  64. // also set parent_path to grandparent instead
  65. parent = parent.parent().unwrap().to_path_buf();
  66. }
  67. FileInfo {
  68. filename: file_path.file_name().unwrap().to_string_lossy().to_string(),
  69. path: file_path,
  70. // We don't care about grand parent for pages
  71. grand_parent: None,
  72. canonical: parent.join(&name),
  73. parent,
  74. name,
  75. components,
  76. relative,
  77. }
  78. }
  79. pub fn new_section(path: &Path, base_path: &PathBuf) -> FileInfo {
  80. let file_path = path.to_path_buf();
  81. let parent = path.parent().expect("Get parent of section").to_path_buf();
  82. let name = path.file_stem().unwrap().to_string_lossy().to_string();
  83. let components = find_content_components(
  84. &file_path.strip_prefix(base_path).expect("Strip base path prefix for section"),
  85. );
  86. let relative = if !components.is_empty() {
  87. format!("{}/{}.md", components.join("/"), name)
  88. } else {
  89. format!("{}.md", name)
  90. };
  91. let grand_parent = parent.parent().map(|p| p.to_path_buf());
  92. FileInfo {
  93. filename: file_path.file_name().unwrap().to_string_lossy().to_string(),
  94. path: file_path,
  95. canonical: parent.join(&name),
  96. parent,
  97. grand_parent,
  98. name,
  99. components,
  100. relative,
  101. }
  102. }
  103. /// Look for a language in the filename.
  104. /// If a language has been found, update the name of the file in this struct to
  105. /// remove it and return the language code
  106. pub fn find_language(&mut self, config: &Config) -> Result<String> {
  107. // No languages? Nothing to do
  108. if !config.is_multilingual() {
  109. return Ok(config.default_language.clone());
  110. }
  111. if !self.name.contains('.') {
  112. return Ok(config.default_language.clone());
  113. }
  114. // Go with the assumption that no one is using `.` in filenames when using i18n
  115. // We can document that
  116. let mut parts: Vec<String> = self.name.splitn(2, '.').map(|s| s.to_string()).collect();
  117. // The language code is not present in the config: typo or the user forgot to add it to the
  118. // config
  119. if !config.languages_codes().contains(&parts[1].as_ref()) {
  120. bail!("File {:?} has a language code of {} which isn't present in the config.toml `languages`", self.path, parts[1]);
  121. }
  122. self.name = parts.swap_remove(0);
  123. self.canonical = self.parent.join(&self.name);
  124. let lang = parts.swap_remove(0);
  125. Ok(lang)
  126. }
  127. }
  128. #[doc(hidden)]
  129. impl Default for FileInfo {
  130. fn default() -> FileInfo {
  131. FileInfo {
  132. path: PathBuf::new(),
  133. parent: PathBuf::new(),
  134. grand_parent: None,
  135. filename: String::new(),
  136. name: String::new(),
  137. components: vec![],
  138. relative: String::new(),
  139. canonical: PathBuf::new(),
  140. }
  141. }
  142. }
  143. #[cfg(test)]
  144. mod tests {
  145. use std::path::{Path, PathBuf};
  146. use config::{Config, Language};
  147. use super::{find_content_components, FileInfo};
  148. #[test]
  149. fn can_find_content_components() {
  150. let res =
  151. find_content_components("/home/vincent/code/site/content/posts/tutorials/python.md");
  152. assert_eq!(res, ["posts".to_string(), "tutorials".to_string()]);
  153. }
  154. #[test]
  155. fn can_find_components_in_page_with_assets() {
  156. let file = FileInfo::new_page(
  157. &Path::new("/home/vincent/code/site/content/posts/tutorials/python/index.md"),
  158. &PathBuf::new(),
  159. );
  160. assert_eq!(file.components, ["posts".to_string(), "tutorials".to_string()]);
  161. }
  162. #[test]
  163. fn doesnt_fail_with_multiple_content_directories() {
  164. let file = FileInfo::new_page(
  165. &Path::new("/home/vincent/code/content/site/content/posts/tutorials/python/index.md"),
  166. &PathBuf::from("/home/vincent/code/content/site"),
  167. );
  168. assert_eq!(file.components, ["posts".to_string(), "tutorials".to_string()]);
  169. }
  170. #[test]
  171. fn can_find_valid_language_in_page() {
  172. let mut config = Config::default();
  173. config.languages.push(Language { code: String::from("fr"), rss: false });
  174. let mut file = FileInfo::new_page(
  175. &Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"),
  176. &PathBuf::new(),
  177. );
  178. let res = file.find_language(&config);
  179. assert!(res.is_ok());
  180. assert_eq!(res.unwrap(), "fr");
  181. }
  182. #[test]
  183. fn can_find_valid_language_in_page_with_assets() {
  184. let mut config = Config::default();
  185. config.languages.push(Language { code: String::from("fr"), rss: false });
  186. let mut file = FileInfo::new_page(
  187. &Path::new("/home/vincent/code/site/content/posts/tutorials/python/index.fr.md"),
  188. &PathBuf::new(),
  189. );
  190. assert_eq!(file.components, ["posts".to_string(), "tutorials".to_string()]);
  191. let res = file.find_language(&config);
  192. assert!(res.is_ok());
  193. assert_eq!(res.unwrap(), "fr");
  194. }
  195. #[test]
  196. fn do_nothing_on_unknown_language_in_page_with_i18n_off() {
  197. let config = Config::default();
  198. let mut file = FileInfo::new_page(
  199. &Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"),
  200. &PathBuf::new(),
  201. );
  202. let res = file.find_language(&config);
  203. assert!(res.is_ok());
  204. assert_eq!(res.unwrap(), config.default_language);
  205. }
  206. #[test]
  207. fn errors_on_unknown_language_in_page_with_i18n_on() {
  208. let mut config = Config::default();
  209. config.languages.push(Language { code: String::from("it"), rss: false });
  210. let mut file = FileInfo::new_page(
  211. &Path::new("/home/vincent/code/site/content/posts/tutorials/python.fr.md"),
  212. &PathBuf::new(),
  213. );
  214. let res = file.find_language(&config);
  215. assert!(res.is_err());
  216. }
  217. #[test]
  218. fn can_find_valid_language_in_section() {
  219. let mut config = Config::default();
  220. config.languages.push(Language { code: String::from("fr"), rss: false });
  221. let mut file = FileInfo::new_section(
  222. &Path::new("/home/vincent/code/site/content/posts/tutorials/_index.fr.md"),
  223. &PathBuf::new(),
  224. );
  225. let res = file.find_language(&config);
  226. assert!(res.is_ok());
  227. assert_eq!(res.unwrap(), "fr");
  228. }
  229. }