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.

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