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.

49 lines
1.4 KiB

7 years ago
  1. use std::error::Error;
  2. use std::fmt;
  3. use std::fs;
  4. use std::os::unix::fs::MetadataExt;
  5. use users::get_user_by_name;
  6. use symbols::Symbol;
  7. use symbols::dir::Dir;
  8. use command_runner::CommandRunner;
  9. pub struct DirFor<'a, D> where D: AsRef<str> + fmt::Display {
  10. dir: Dir<D>,
  11. path: D,
  12. user_name: &'a str,
  13. command_runner: &'a CommandRunner
  14. }
  15. impl<'a, D> DirFor<'a, D> where D: AsRef<str> + fmt::Display + Clone {
  16. pub fn new(path: D, user_name: &'a str, command_runner: &'a CommandRunner) -> Self {
  17. DirFor { dir: Dir::new(path.clone()), path: path, user_name: user_name, command_runner: command_runner }
  18. }
  19. }
  20. impl<'a, D> Symbol for DirFor<'a, D> where D: AsRef<str> + fmt::Display {
  21. fn target_reached(&self) -> Result<bool, Box<Error>> {
  22. match self.dir.target_reached() {
  23. Ok(true) => {
  24. let actual_uid = fs::metadata(self.path.as_ref()).unwrap().uid();
  25. let target_uid = get_user_by_name(self.user_name).unwrap().uid();
  26. Ok(actual_uid == target_uid)
  27. },
  28. res => res
  29. }
  30. }
  31. fn execute(&self) -> Result<(), Box<Error>> {
  32. try!(self.dir.execute());
  33. try!(self.command_runner.run_with_args("chown", &[self.user_name, self.path.as_ref()]));
  34. Ok(())
  35. }
  36. }
  37. impl<'a, D> fmt::Display for DirFor<'a, D> where D: AsRef<str> + fmt::Display {
  38. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>{
  39. write!(f, "Dir {} for {}", self.path, self.user_name)
  40. }
  41. }