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.

41 lines
1.1KB

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