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.

79 lines
2.0 KiB

  1. use std::error::Error;
  2. use std::fmt;
  3. use std::fs::{metadata, File};
  4. use std::io::copy;
  5. use std::marker::PhantomData;
  6. use std::path::Path;
  7. use crate::resources::Resource;
  8. use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
  9. pub struct Concat<S, D, I> {
  10. target: D,
  11. sources: S,
  12. source_item: PhantomData<I>,
  13. }
  14. impl<S, D, I> Concat<S, D, I> {
  15. pub fn new(sources: S, target: D) -> Self {
  16. Self {
  17. target,
  18. sources,
  19. source_item: PhantomData::default(),
  20. }
  21. }
  22. }
  23. impl<S: AsRef<[I]>, D: AsRef<Path>, I: AsRef<Path>> Symbol for Concat<S, D, I> {
  24. fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
  25. let target = self.target.as_ref();
  26. if !target.exists() {
  27. return Ok(false);
  28. }
  29. let target_date = metadata(target)?.modified()?;
  30. for source in self.sources.as_ref() {
  31. if metadata(source)?.modified()? > target_date {
  32. return Ok(false);
  33. }
  34. }
  35. Ok(true)
  36. }
  37. fn execute(&self) -> Result<(), Box<dyn Error>> {
  38. let mut file = File::create(self.target.as_ref())?;
  39. for source in self.sources.as_ref() {
  40. copy(&mut File::open(source)?, &mut file)?;
  41. }
  42. Ok(())
  43. }
  44. fn get_prerequisites(&self) -> Vec<Resource> {
  45. let mut r: Vec<Resource> = self
  46. .sources
  47. .as_ref()
  48. .iter()
  49. .map(|s| Resource::new("file", s.as_ref().to_str().unwrap()))
  50. .collect();
  51. if let Some(parent) = self.target.as_ref().parent() {
  52. r.push(Resource::new("dir", parent.to_str().unwrap()))
  53. }
  54. r
  55. }
  56. fn as_action<'a>(&'a self, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a> {
  57. Box::new(SymbolAction::new(runner, self))
  58. }
  59. fn into_action<'a>(self: Box<Self>, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a>
  60. where
  61. Self: 'a,
  62. {
  63. Box::new(OwnedSymbolAction::new(runner, *self))
  64. }
  65. }
  66. impl<S, D: AsRef<Path>, I> fmt::Display for Concat<S, D, I> {
  67. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  68. write!(f, "Concat {}", self.target.as_ref().display())
  69. }
  70. }