diff --git a/clash_lib/src/config/def.rs b/clash_lib/src/config/def.rs index 2b1d619f5..c04044e39 100644 --- a/clash_lib/src/config/def.rs +++ b/clash_lib/src/config/def.rs @@ -1,7 +1,5 @@ use crate::Error; -use std::fs::File; -use std::io::BufReader; -use std::path::Path; +use std::path::PathBuf; use std::str::FromStr; use std::{collections::HashMap, fmt::Display}; @@ -378,35 +376,27 @@ pub struct Config { pub tun: Option>, } +impl TryFrom for Config { + type Error = Error; + + fn try_from(value: PathBuf) -> Result { + let content = std::fs::read_to_string(value)?; + let config = content.parse::()?; + Ok(config) + } +} + impl FromStr for Config { type Err = Error; fn from_str(s: &str) -> Result { - let path = Path::new(s); - match path.try_exists() { - Ok(exists) => { - if exists { - let fd = File::open(path)?; - let reader = BufReader::new(fd); - Ok(serde_yaml::from_reader(reader).map_err(|x| { - Error::InvalidConfig(format!( - "cound not parse config content {}: {}", - s, - x.to_string() - )) - })?) - } else { - Ok(serde_yaml::from_str(s).map_err(|x| { - Error::InvalidConfig(format!( - "cound not parse config content {}: {}", - s, - x.to_string() - )) - })?) - } - } - Err(err) => Err(err.into()), - } + Ok(serde_yaml::from_str(s).map_err(|x| { + Error::InvalidConfig(format!( + "cound not parse config content {}: {}", + s, + x.to_string() + )) + })?) } } diff --git a/clash_lib/src/lib.rs b/clash_lib/src/lib.rs index b8cadefb6..9274d3385 100644 --- a/clash_lib/src/lib.rs +++ b/clash_lib/src/lib.rs @@ -20,6 +20,7 @@ use config::def::LogLevel; use proxy::tun::get_tun_runner; use state::Storage; use std::io; +use std::path::PathBuf; use tokio::task::JoinHandle; use std::sync::Arc; @@ -124,7 +125,7 @@ async fn start_async(opts: Options) -> Result<(), Error> { let config: InternalConfig = match opts.config { Config::Def(c) => c.try_into()?, Config::Internal(c) => c, - Config::File(file) => file.parse::()?.try_into()?, + Config::File(file) => TryInto::::try_into(PathBuf::from(file))?.try_into()?, Config::Str(s) => s.parse::()?.try_into()?, };