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.

45 lines
1.2 KiB

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