A library for writing host-specific, single-binary configuration management and deployment tools
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.1 KiB

  1. use std::error::Error;
  2. use std::fmt;
  3. use std::fs;
  4. use std::io;
  5. use symbols::Symbol;
  6. pub struct Dir<D> where D: AsRef<str> + fmt::Display {
  7. path: D
  8. }
  9. impl<D> Dir<D> where D: AsRef<str> + fmt::Display {
  10. pub fn new(path: D) -> Self {
  11. Dir { path: path }
  12. }
  13. }
  14. impl<D> Symbol for Dir<D> where D: AsRef<str> + fmt::Display {
  15. fn target_reached(&self) -> Result<bool, Box<Error>> {
  16. let metadata = fs::metadata(self.path.as_ref());
  17. // Check if dir exists
  18. if let Err(e) = metadata {
  19. return if e.kind() == io::ErrorKind::NotFound {
  20. Ok(false)
  21. } else {
  22. Err(Box::new(e))
  23. };
  24. }
  25. if metadata.unwrap().is_dir() {
  26. Ok(true)
  27. } else {
  28. Err(Box::new(io::Error::new(io::ErrorKind::AlreadyExists, "Could not create a directory, non-directory file exists")))
  29. }
  30. }
  31. fn execute(&self) -> Result<(), Box<Error>> {
  32. fs::create_dir_all(self.path.as_ref()).map_err(|e| Box::new(e) as Box<Error>)
  33. }
  34. }
  35. impl<D> fmt::Display for Dir<D> where D: AsRef<str> + fmt::Display {
  36. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>{
  37. write!(f, "Dir {}", self.path)
  38. }
  39. }