use crate::ConfigEntry;
use std::path::PathBuf;
use strut_core::AppProfile;
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum ConfigDir {
Generic(PathBuf),
Specific {
path: PathBuf,
profile: String,
},
}
impl ConfigDir {
pub fn at(path: PathBuf) -> Self {
Self::make_with_profile(path, None)
}
pub fn make_with_profile(path: PathBuf, known_profile: Option<&str>) -> Self {
if let Some(known_profile) = known_profile {
return Self::Specific {
path,
profile: known_profile.to_string(),
};
}
Self::Generic(path)
}
pub fn make_capturing_profile(path: PathBuf) -> Self {
match path.file_name().and_then(std::ffi::OsStr::to_str) {
Some(name) => {
let profile = name.to_string();
Self::Specific { path, profile }
}
None => Self::Generic(path),
}
}
}
impl ConfigDir {
pub fn name(&self) -> Option<&str> {
self.path().file_name().and_then(std::ffi::OsStr::to_str)
}
pub fn is_generic(&self) -> bool {
match *self {
Self::Generic(_) => true,
Self::Specific { .. } => false,
}
}
pub fn is_specific(&self) -> bool {
!self.is_generic()
}
pub fn path(&self) -> &PathBuf {
match *self {
Self::Generic(ref path) => path,
Self::Specific { ref path, .. } => path,
}
}
pub fn profile(&self) -> Option<&str> {
match *self {
Self::Generic(_) => None,
Self::Specific { ref profile, .. } => Some(profile),
}
}
pub fn applies_to_active_profile(&self) -> bool {
self.applies_to(AppProfile::active())
}
pub fn applies_to(&self, profile: impl AsRef<AppProfile>) -> bool {
let given_profile = profile.as_ref();
match *self {
Self::Generic(_) => true,
Self::Specific { ref profile, .. } => given_profile.is(profile),
}
}
pub fn expand(&self, profile: Option<&str>) -> Vec<ConfigEntry> {
std::fs::read_dir(self.path())
.into_iter()
.flat_map(|read_dir| {
read_dir
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter_map(|path| ConfigEntry::try_from_with_profile(path, profile))
})
.collect::<Vec<_>>()
}
}
impl From<ConfigDir> for PathBuf {
fn from(file: ConfigDir) -> Self {
match file {
ConfigDir::Generic(path) => path,
ConfigDir::Specific { path, .. } => path,
}
}
}