summaryrefslogtreecommitdiffstats
path: root/src/theme.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/theme.rs')
-rw-r--r--src/theme.rs58
1 files changed, 28 insertions, 30 deletions
diff --git a/src/theme.rs b/src/theme.rs
index 82daeb4..b644023 100644
--- a/src/theme.rs
+++ b/src/theme.rs
@@ -27,14 +27,12 @@ pub struct Theme {
#[derive(Error, Debug)]
pub enum Error {
- #[error("Theme file not existed")]
- NotExisted(#[from] io::Error),
+ #[error("Can not read the theme file")]
+ ReadFailed(#[from] io::Error),
#[error("Theme file format invalid")]
InvalidFormat(#[from] serde_yaml::Error),
#[error("Theme file path invalid {0}")]
InvalidPath(String),
- #[error("Unknown Theme error")]
- Unknown(),
}
impl Theme {
@@ -45,43 +43,43 @@ impl Theme {
where
D: DeserializeOwned + Default,
{
- let real = if let Some(path) = config_file::Config::expand_home(file) {
+ let real = if let Some(path) = config_file::expand_home(file) {
path
} else {
print_error!("Not a valid theme file path: {}.", &file);
return Err(Error::InvalidPath(file.to_string()));
};
- let path = if Path::new(&real).is_absolute() {
- real
+
+ let mut paths = if Path::new(&real).is_absolute() {
+ vec![real].into_iter()
} else {
- let path = config_file::Config::config_paths()
+ config_file::Config::config_paths()
.map(|p| p.join(real.clone()))
- .find(|p| p.is_file());
- match path {
- Some(p) => p,
- None => {
- return Err(Error::InvalidPath(
- "Did not find theme file in config folders".into(),
- ))
- }
- }
+ .collect::<Vec<_>>()
+ .into_iter()
};
- // try `yml` if `yaml` extension file not found or error
- let mut err: Error = Error::Unknown();
- for ext in ["yaml", "yml"] {
- match fs::read(&path.with_extension(ext)) {
- Ok(f) => match Self::with_yaml(&String::from_utf8_lossy(&f)) {
- Ok(t) => return Ok(t),
- Err(e) => {
- err = Error::from(e);
- }
- },
- Err(e) => err = Error::from(e),
+ let Some(valid) = paths.find_map(|p| {
+ let yaml = p.with_extension("yaml");
+ let yml = p.with_extension("yml");
+ if yaml.is_file() {
+ Some(yaml)
+ } else if yml.is_file() {
+ Some(yml)
+ } else {
+ None
}
- }
+ }) else {
+ return Err(Error::InvalidPath("No valid theme file found".to_string()));
+ };
- Err(err)
+ match fs::read_to_string(valid) {
+ Ok(yaml) => match Self::with_yaml(&yaml) {
+ Ok(t) => Ok(t),
+ Err(e) => Err(Error::InvalidFormat(e)),
+ },
+ Err(e) => Err(Error::ReadFailed(e)),
+ }
}
/// This constructs a Theme struct with a passed [Yaml] str.