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.8 KiB

use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use resources::Resource;
use symbols::{Action, OwnedSymbolAction, Symbol, SymbolAction, SymbolRunner};
pub struct Dir<D> where D: AsRef<str> {
path: D
}
impl<D> Dir<D> where D: AsRef<str> {
pub fn new(path: D) -> Self {
Dir { path }
}
}
impl<D> Symbol for Dir<D> where D: AsRef<str> {
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(false)
} else {
Err(Box::new(e))
};
}
if metadata.unwrap().is_dir() {
Ok(true)
} else {
Err(Box::new(io::Error::new(io::ErrorKind::AlreadyExists, "Could not create a directory, non-directory file exists")))
}
}
fn execute(&self) -> Result<(), Box<dyn Error>> {
fs::create_dir(self.path.as_ref()).map_err(|e| Box::new(e) as Box<dyn Error>)
}
fn get_prerequisites(&self) -> Vec<Resource> {
if let Some(parent) = Path::new(self.path.as_ref()).parent() {
vec![ Resource::new("dir", parent.to_string_lossy()) ]
} else {
vec![]
}
}
fn provides(&self) -> Option<Vec<Resource>> {
Some(vec![ Resource::new("dir", self.path.as_ref()) ])
}
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<D> fmt::Display for Dir<D> where D: AsRef<str> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error>{
write!(f, "Dir {}", self.path.as_ref())
}
}