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.

149 lines
3.8 KiB

use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use std::str::FromStr;
use crate::command_runner::CommandRunner;
use crate::resources::Resource;
use crate::storage::Storage;
use crate::symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
#[derive(Debug, PartialEq)]
pub enum StorageDirection {
Load,
Save,
}
pub struct StoredDirectory<'a, P: AsRef<Path>, S: Storage, C: CommandRunner> {
path: P,
storage: S,
dir: StorageDirection,
command_runner: &'a C,
}
impl<'a, P: AsRef<Path>, S: Storage, C: CommandRunner> StoredDirectory<'a, P, S, C> {
pub fn new(path: P, storage: S, dir: StorageDirection, command_runner: &'a C) -> Self {
StoredDirectory {
path,
storage,
dir,
command_runner,
}
}
}
impl<P: AsRef<Path>, S: Storage, C: CommandRunner> fmt::Display for StoredDirectory<'_, P, S, C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Stored directory {} ({:?})",
self.path.as_ref().display(),
self.dir
)
}
}
impl<P: AsRef<Path>, S: Storage, C: CommandRunner> Symbol for StoredDirectory<'_, P, S, C> {
fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
let metadata = fs::metadata(self.path.as_ref());
// Check if dir exists
if let Err(e) = metadata {
return if e.kind() == io::ErrorKind::NotFound {
Ok(self.dir == StorageDirection::Save)
} else {
Err(Box::new(e))
};
}
if !metadata.unwrap().is_dir() {
return Err(Box::new(io::Error::new(
io::ErrorKind::AlreadyExists,
"Could not create a directory, non-directory file exists",
)));
}
let dump_date = self.storage.recent_date()?;
let output = self.command_runner.get_output(
"sh",
args![
"-c",
format!(
"find {} -printf '%T@\\n' | sort -r | head -n1 | grep '^[0-9]\\+' -o",
self.path.as_ref().to_str().unwrap()
),
],
)?;
let modified_date = u64::from_str(String::from_utf8(output)?.trim_end())?;
if if self.dir == StorageDirection::Save {
modified_date > dump_date
} else {
dump_date > modified_date
} {
let output = self.command_runner.run_with_args(
"diff",
args!["-rq", self.storage.read_filename()?, self.path.as_ref()],
)?;
match output.status.code() {
Some(0) => Ok(true),
Some(1) => Ok(false),
_ => Err(String::from_utf8(output.stderr)?.into()),
}
} else {
Ok(true)
}
}
fn execute(&self) -> Result<(), Box<dyn Error>> {
if self.dir == StorageDirection::Load {
self
.command_runner
.run_successfully("rm", args!["-rf", self.path.as_ref()])?;
self.command_runner.run_successfully(
"cp",
args!["-a", self.storage.read_filename()?, self.path.as_ref()],
)
} else {
self.command_runner.run_successfully(
"cp",
args!["-a", self.path.as_ref(), self.storage.write_filename()],
)
}
}
fn get_prerequisites(&self) -> Vec<Resource> {
if self.dir == StorageDirection::Save {
return vec![];
}
if let Some(parent) = self.path.as_ref().parent() {
vec![Resource::new("dir", parent.to_str().unwrap())]
} else {
vec![]
}
}
fn provides(&self) -> Option<Vec<Resource>> {
if self.dir == StorageDirection::Load {
Some(vec![Resource::new(
"dir",
self.path.as_ref().to_str().unwrap(),
)])
} else {
None
}
}
fn as_action<'b>(&'b self, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b> {
Box::new(SymbolAction::new(runner, self))
}
fn into_action<'b>(self: Box<Self>, runner: &'b dyn SymbolRunner) -> Box<dyn Action + 'b>
where
Self: 'b,
{
Box::new(OwnedSymbolAction::new(runner, *self))
}
}
#[cfg(test)]
mod test {}