use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct Hierarchy {
root: PathBuf,
}
impl Hierarchy {
pub fn new<P: AsRef<Path>>(path: P) -> Hierarchy {
Hierarchy {
root: path.as_ref().to_owned(),
}
}
pub fn root(&self) -> HierarchyNode {
HierarchyNode {
path: self.root.clone(),
}
}
pub fn create<P: AsRef<Path>>(&mut self, name: P) -> io::Result<HierarchyNode> {
self.root().new_sub(name)
}
pub fn get_child<P: AsRef<Path>>(&self, name: P) -> Option<HierarchyNode> {
let child_hierarchy = self.root.join(name);
if child_hierarchy.exists() {
let child = HierarchyNode {
path: child_hierarchy,
};
Some(child)
} else {
None
}
}
}
#[derive(Debug)]
pub struct HierarchyNode {
path: PathBuf,
}
impl HierarchyNode {
pub fn as_path(&self) -> &Path {
self.path.as_path()
}
pub fn new_sub<P: AsRef<Path>>(&mut self, name: P) -> io::Result<HierarchyNode> {
use io::ErrorKind::AlreadyExists;
let name = PathBuf::from(name.as_ref());
let sub_controller = self.path.join(&name);
match fs::create_dir(&sub_controller) {
Ok(()) => {}
Err(e) if e.kind() == AlreadyExists => {}
Err(e) => return Err(e),
}
Ok(HierarchyNode {
path: sub_controller,
})
}
}
impl AsRef<Path> for HierarchyNode {
fn as_ref(&self) -> &Path {
self.as_path()
}
}