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.

43 lines
1.1 KiB

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
  1. use crate::symbols::Symbol;
  2. use std::error::Error;
  3. use std::fs::File as FsFile;
  4. use std::io::{Read, Write};
  5. use std::path::Path;
  6. #[derive(Debug)]
  7. pub struct File<D, C> {
  8. path: D,
  9. content: C,
  10. }
  11. impl<D, C> File<D, C> {
  12. pub fn new(path: D, content: C) -> Self {
  13. Self { path, content }
  14. }
  15. }
  16. impl<D: AsRef<Path>, C: AsRef<str>> Symbol for File<D, C> {
  17. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  18. if !self.path.as_ref().exists() {
  19. return Ok(false);
  20. }
  21. let file = FsFile::open(self.path.as_ref())?;
  22. // Check if content is the same
  23. let mut file_content = file.bytes();
  24. let mut target_content = self.content.as_ref().bytes();
  25. loop {
  26. match (file_content.next(), target_content.next()) {
  27. (None, None) => return Ok(true),
  28. (Some(Ok(a)), Some(b)) if a == b => {}
  29. (Some(Err(e)), _) => return Err(Box::new(e)),
  30. (_, _) => return Ok(false),
  31. }
  32. }
  33. }
  34. fn execute(&self) -> Result<(), Box<dyn Error>> {
  35. let mut file = FsFile::create(self.path.as_ref())?;
  36. file.write_all(self.content.as_ref().as_bytes())?;
  37. Ok(())
  38. }
  39. }