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.

67 lines
1.9 KiB

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