Skip to content

Commit

Permalink
don't confuse it (#122)
Browse files Browse the repository at this point in the history
  • Loading branch information
ibigbug authored Oct 16, 2023
1 parent 19dec04 commit 20c740f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 29 deletions.
46 changes: 18 additions & 28 deletions clash_lib/src/config/def.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -378,35 +376,27 @@ pub struct Config {
pub tun: Option<HashMap<String, Value>>,
}

impl TryFrom<PathBuf> for Config {
type Error = Error;

fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
let content = std::fs::read_to_string(value)?;
let config = content.parse::<Config>()?;
Ok(config)
}
}

impl FromStr for Config {
type Err = Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
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()
))
})?)
}
}

Expand Down
3 changes: 2 additions & 1 deletion clash_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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::<def::Config>()?.try_into()?,
Config::File(file) => TryInto::<def::Config>::try_into(PathBuf::from(file))?.try_into()?,
Config::Str(s) => s.parse::<def::Config>()?.try_into()?,
};

Expand Down

0 comments on commit 20c740f

Please sign in to comment.