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.

72 lines
1.9 KiB

7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 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
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::error::Error;
  2. use std::fmt;
  3. use std::fs::File as FsFile;
  4. use std::io::{Read, Write};
  5. use std::path::Path;
  6. use resources::Resource;
  7. use symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  8. pub struct File<C: AsRef<str>, D: AsRef<Path>> {
  9. path: D,
  10. content: C,
  11. }
  12. impl<C: AsRef<str>, D: AsRef<Path>> File<C, D> {
  13. pub fn new(path: D, content: C) -> Self {
  14. Self { path, content }
  15. }
  16. }
  17. impl<C: AsRef<str>, D: AsRef<Path>> Symbol for File<C, D> {
  18. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  19. if !self.path.as_ref().exists() {
  20. return Ok(false);
  21. }
  22. let file = FsFile::open(self.path.as_ref())?;
  23. // Check if content is the same
  24. let mut file_content = file.bytes();
  25. let mut target_content = self.content.as_ref().bytes();
  26. loop {
  27. match (file_content.next(), target_content.next()) {
  28. (None, None) => return Ok(true),
  29. (Some(Ok(a)), Some(b)) if a == b => {}
  30. (Some(Err(e)), _) => return Err(Box::new(e)),
  31. (_, _) => return Ok(false),
  32. }
  33. }
  34. }
  35. fn execute(&self) -> Result<(), Box<dyn Error>> {
  36. let mut file = FsFile::create(self.path.as_ref())?;
  37. file.write_all(self.content.as_ref().as_bytes())?;
  38. Ok(())
  39. }
  40. fn get_prerequisites(&self) -> Vec<Resource> {
  41. if let Some(parent) = self.path.as_ref().parent() {
  42. vec![Resource::new("dir", parent.to_str().unwrap())]
  43. } else {
  44. vec![]
  45. }
  46. }
  47. fn as_action<'a>(&'a self, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a> {
  48. Box::new(SymbolAction::new(runner, self))
  49. }
  50. fn into_action<'a>(self: Box<Self>, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a>
  51. where
  52. Self: 'a,
  53. {
  54. Box::new(OwnedSymbolAction::new(runner, *self))
  55. }
  56. }
  57. impl<C: AsRef<str>, D: AsRef<Path>> fmt::Display for File<C, D> {
  58. fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  59. write!(f, "File {}", self.path.as_ref().display())
  60. }
  61. }