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.

71 lines
1.9KB

  1. use std::io::prelude::*;
  2. use std::fs::{File, create_dir};
  3. use std::path::Path;
  4. use errors::{Result, ResultExt};
  5. pub fn create_file<P: AsRef<Path>>(path: P, content: &str) -> Result<()> {
  6. let mut file = File::create(&path)?;
  7. file.write_all(content.as_bytes())?;
  8. Ok(())
  9. }
  10. /// Very similar to `create_dir` from the std except it checks if the folder
  11. /// exists before creating it
  12. pub fn create_directory<P: AsRef<Path>>(path: P) -> Result<()> {
  13. let path = path.as_ref();
  14. if !path.exists() {
  15. create_dir(path)
  16. .chain_err(|| format!("Was not able to create folder {}", path.display()))?;
  17. }
  18. Ok(())
  19. }
  20. /// Return the content of a file, with error handling added
  21. pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String> {
  22. let path = path.as_ref();
  23. let mut content = String::new();
  24. File::open(path)
  25. .chain_err(|| format!("Failed to open '{:?}'", path.display()))?
  26. .read_to_string(&mut content)?;
  27. Ok(content)
  28. }
  29. /// Takes a full path to a .md and returns only the components after the first `content` directory
  30. /// Will not return the filename as last component
  31. pub fn find_content_components<P: AsRef<Path>>(path: P) -> Vec<String> {
  32. let path = path.as_ref();
  33. let mut is_in_content = false;
  34. let mut components = vec![];
  35. for section in path.parent().unwrap().components() {
  36. let component = section.as_ref().to_string_lossy();
  37. if is_in_content {
  38. components.push(component.to_string());
  39. continue;
  40. }
  41. if component == "content" {
  42. is_in_content = true;
  43. }
  44. }
  45. components
  46. }
  47. #[cfg(test)]
  48. mod tests {
  49. use super::{find_content_components};
  50. #[test]
  51. fn test_find_content_components() {
  52. let res = find_content_components("/home/vincent/code/site/content/posts/tutorials/python.md");
  53. assert_eq!(res, ["posts".to_string(), "tutorials".to_string()]);
  54. }
  55. }