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.

41 lines
1.2 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 command_runner::CommandRunner;
  8. pub struct Owner<'a, D> where D: AsRef<str> + fmt::Display {
  9. path: D,
  10. user_name: &'a str,
  11. command_runner: &'a CommandRunner
  12. }
  13. impl<'a, D> Owner<'a, D> where D: AsRef<str> + fmt::Display {
  14. pub fn new(path: D, user_name: &'a str, command_runner: &'a CommandRunner) -> Self {
  15. Owner { path: path, user_name: user_name, command_runner: command_runner }
  16. }
  17. }
  18. impl<'a, D> Symbol for Owner<'a, D> where D: AsRef<str> + fmt::Display {
  19. fn target_reached(&self) -> Result<bool, Box<Error>> {
  20. let actual_uid = fs::metadata(self.path.as_ref()).unwrap().uid();
  21. let target_uid = get_user_by_name(self.user_name).unwrap().uid();
  22. Ok(actual_uid == target_uid)
  23. }
  24. fn execute(&self) -> Result<(), Box<Error>> {
  25. try!(self.command_runner.run_with_args("chown", &[self.user_name, self.path.as_ref()]));
  26. Ok(())
  27. }
  28. }
  29. impl<'a, D> fmt::Display for Owner<'a, D> where D: AsRef<str> + fmt::Display {
  30. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>{
  31. write!(f, "Owner {} for {}", self.user_name, self.path)
  32. }
  33. }