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.

45 lines
1.2KB

  1. use std::io::prelude::*;
  2. use std::fs::{File, create_dir};
  3. use std::path::Path;
  4. use errors::{Result, ResultExt};
  5. /// Create a file with the content given
  6. pub fn create_file<P: AsRef<Path>>(path: P, content: &str) -> Result<()> {
  7. let mut file = File::create(&path)?;
  8. file.write_all(content.as_bytes())?;
  9. Ok(())
  10. }
  11. /// Create a directory at the given path if it doesn't exist already
  12. pub fn ensure_directory_exists<P: AsRef<Path>>(path: P) -> Result<()> {
  13. let path = path.as_ref();
  14. if !path.exists() {
  15. create_directory(&path)?;
  16. }
  17. Ok(())
  18. }
  19. /// Very similar to `create_dir` from the std except it checks if the folder
  20. /// exists before creating it
  21. pub fn create_directory<P: AsRef<Path>>(path: P) -> Result<()> {
  22. let path = path.as_ref();
  23. if !path.exists() {
  24. create_dir(path)
  25. .chain_err(|| format!("Was not able to create folder {}", path.display()))?;
  26. }
  27. Ok(())
  28. }
  29. /// Return the content of a file, with error handling added
  30. pub fn read_file<P: AsRef<Path>>(path: P) -> Result<String> {
  31. let path = path.as_ref();
  32. let mut content = String::new();
  33. File::open(path)
  34. .chain_err(|| format!("Failed to open '{:?}'", path.display()))?
  35. .read_to_string(&mut content)?;
  36. Ok(content)
  37. }