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.

79 lines
1.9 KiB

5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
6 years ago
7 years ago
  1. use std::borrow::{Borrow, Cow};
  2. use std::error::Error;
  3. use std::fmt;
  4. use std::fs;
  5. use std::os::unix::fs::MetadataExt;
  6. use std::path::Path;
  7. use users::get_user_by_name;
  8. use command_runner::CommandRunner;
  9. use resources::Resource;
  10. use symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  11. pub struct Owner<'a, C: 'a + CommandRunner, D>
  12. where
  13. D: AsRef<str>,
  14. {
  15. path: D,
  16. user_name: Cow<'a, str>,
  17. command_runner: &'a C,
  18. }
  19. impl<'a, C: CommandRunner, D> Owner<'a, C, D>
  20. where
  21. D: AsRef<str>,
  22. {
  23. pub fn new(path: D, user_name: Cow<'a, str>, command_runner: &'a C) -> Self {
  24. Owner {
  25. path,
  26. user_name,
  27. command_runner,
  28. }
  29. }
  30. }
  31. impl<'a, C: CommandRunner, D> Symbol for Owner<'a, C, D>
  32. where
  33. D: AsRef<str>,
  34. {
  35. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  36. if !Path::new(self.path.as_ref()).exists() {
  37. return Ok(false);
  38. }
  39. let actual_uid = fs::metadata(self.path.as_ref()).unwrap().uid();
  40. let target_uid = get_user_by_name(self.user_name.borrow()).unwrap().uid();
  41. Ok(actual_uid == target_uid)
  42. }
  43. fn execute(&self) -> Result<(), Box<dyn Error>> {
  44. self.command_runner.run_successfully(
  45. "chown",
  46. &["-R", self.user_name.borrow(), self.path.as_ref()],
  47. )
  48. }
  49. fn get_prerequisites(&self) -> Vec<Resource> {
  50. vec![Resource::new("user", self.user_name.to_string())]
  51. }
  52. fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
  53. Box::new(SymbolAction::new(runner, self))
  54. }
  55. fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
  56. where
  57. Self: 'b,
  58. {
  59. Box::new(OwnedSymbolAction::new(runner, *self))
  60. }
  61. }
  62. impl<'a, C: CommandRunner, D> fmt::Display for Owner<'a, C, D>
  63. where
  64. D: AsRef<str>,
  65. {
  66. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  67. write!(f, "Owner {} for {}", self.user_name, self.path.as_ref())
  68. }
  69. }