use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[display("{}", self.as_path().display())]
pub enum ConfigPath {
Default(PathBuf),
Override(PathBuf),
}
impl ConfigPath {
pub fn as_path(&self) -> &Path {
match self {
Self::Default(path) | Self::Override(path) => path,
}
}
pub fn to_path_buf(&self) -> PathBuf {
self.as_path().to_path_buf()
}
pub fn into_path_buf(self) -> PathBuf {
match self {
Self::Default(path) | Self::Override(path) => path,
}
}
pub fn is_override(&self) -> bool {
matches!(self, Self::Override(_))
}
pub fn empty_default() -> Self {
Self::Default(PathBuf::new())
}
}
impl AsRef<Path> for ConfigPath {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
#[derive(Debug, Clone)]
pub struct NushellConfigDirs {
pub config_home: PathBuf,
pub config_file: ConfigPath,
pub env_file: ConfigPath,
pub data_home: PathBuf,
pub cache_home: PathBuf,
pub home_dir: PathBuf,
pub vendor_autoload_dirs: Vec<PathBuf>,
pub user_autoload_dirs: Vec<PathBuf>,
#[cfg(feature = "plugin")]
pub plugin_file: ConfigPath,
}
impl NushellConfigDirs {
pub fn empty() -> Self {
Self {
config_home: PathBuf::new(),
config_file: ConfigPath::empty_default(),
env_file: ConfigPath::empty_default(),
data_home: PathBuf::new(),
cache_home: PathBuf::new(),
home_dir: PathBuf::new(),
vendor_autoload_dirs: Vec::new(),
user_autoload_dirs: Vec::new(),
#[cfg(feature = "plugin")]
plugin_file: ConfigPath::empty_default(),
}
}
pub fn is_resolved(&self) -> bool {
!self.config_home.as_os_str().is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_path_default_is_not_override() {
let path = ConfigPath::Default(PathBuf::from("/cfg/config.nu"));
assert!(!path.is_override());
assert_eq!(path.as_path(), Path::new("/cfg/config.nu"));
assert_eq!(path.to_path_buf(), PathBuf::from("/cfg/config.nu"));
}
#[test]
fn config_path_override_is_override() {
let path = ConfigPath::Override(PathBuf::from("/tmp/x.nu"));
assert!(path.is_override());
assert_eq!(path.to_string(), "/tmp/x.nu");
}
#[test]
fn empty_dirs_are_unresolved() {
assert!(!NushellConfigDirs::empty().is_resolved());
}
#[test]
fn into_path_buf_consumes_either_variant() {
assert_eq!(
ConfigPath::Default(PathBuf::from("a")).into_path_buf(),
PathBuf::from("a")
);
assert_eq!(
ConfigPath::Override(PathBuf::from("b")).into_path_buf(),
PathBuf::from("b")
);
}
}