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

use std::error::Error;
use std::fmt;
use std::fs::{metadata, File};
use std::io::copy;
use std::marker::PhantomData;
use std::path::Path;
use crate::resources::Resource;
use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
pub struct Concat<S, D, I> {
target: D,
sources: S,
source_item: PhantomData<I>,
}
impl<S, D, I> Concat<S, D, I> {
pub fn new(sources: S, target: D) -> Self {
Self {
target,
sources,
source_item: PhantomData::default(),
}
}
}
impl<S: AsRef<[I]>, D: AsRef<Path>, I: AsRef<Path>> Symbol for Concat<S, D, I> {
fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
let target = self.target.as_ref();
if !target.exists() {
return Ok(false);
}
let target_date = metadata(target)?.modified()?;
for source in self.sources.as_ref() {
if metadata(source)?.modified()? > target_date {
return Ok(false);
}
}
Ok(true)
}
fn execute(&self) -> Result<(), Box<dyn Error>> {
let mut file = File::create(self.target.as_ref())?;
for source in self.sources.as_ref() {
copy(&mut File::open(source)?, &mut file)?;
}
Ok(())
}
fn get_prerequisites(&self) -> Vec<Resource> {
let mut r: Vec<Resource> = self
.sources
.as_ref()
.iter()
.map(|s| Resource::new("file", s.as_ref().to_str().unwrap()))
.collect();
if let Some(parent) = self.target.as_ref().parent() {
r.push(Resource::new("dir", parent.to_str().unwrap()))
}
r
}
fn as_action<'a>(&'a self, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a> {
Box::new(SymbolAction::new(runner, self))
}
fn into_action<'a>(self: Box<Self>, runner: &'a dyn SymbolRunner) -> Box<dyn Action + 'a>
where
Self: 'a,
{
Box::new(OwnedSymbolAction::new(runner, *self))
}
}
impl<S, D: AsRef<Path>, I> fmt::Display for Concat<S, D, I> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "Concat {}", self.target.as_ref().display())
}
}