refactor: adjust all path methods and reduce unwrap

This commit is contained in:
GyDi
2022-11-18 09:35:05 +08:00
parent be81cd72af
commit 34daffbc96
11 changed files with 204 additions and 181 deletions

View File

@@ -8,7 +8,26 @@ pub struct IClashTemp(pub Mapping);
impl IClashTemp {
pub fn new() -> Self {
Self(config::read_merge_mapping(dirs::clash_path()))
match dirs::clash_path().and_then(|path| config::read_merge_mapping(&path)) {
Ok(map) => Self(map),
Err(err) => {
log::error!(target: "app", "{err}");
Self::template()
}
}
}
pub fn template() -> Self {
let mut map = Mapping::new();
map.insert("mixed-port".into(), 7892.into());
map.insert("log-level".into(), "info".into());
map.insert("allow-lan".into(), false.into());
map.insert("mode".into(), "rule".into());
map.insert("external-controller".into(), "127.0.0.1:9090".into());
map.insert("secret".into(), "".into());
Self(map)
}
pub fn patch_config(&mut self, patch: Mapping) {
@@ -19,7 +38,7 @@ impl IClashTemp {
pub fn save_config(&self) -> Result<()> {
config::save_yaml(
dirs::clash_path(),
dirs::clash_path()?,
&self.0,
Some("# Default Config For ClashN Core\n\n"),
)

View File

@@ -355,7 +355,7 @@ impl PrfItem {
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
let path = dirs::app_profiles_dir()?.join(file);
fs::read_to_string(path).context("failed to read the file")
}
@@ -366,7 +366,7 @@ impl PrfItem {
}
let file = self.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(file);
let path = dirs::app_profiles_dir()?.join(file);
fs::write(path, data.as_bytes()).context("failed to save the file")
}
@@ -375,7 +375,7 @@ impl PrfItem {
let itype = self.itype.as_ref()?.as_str();
let file = self.file.clone()?;
let uid = self.uid.clone().unwrap_or("".into());
let path = dirs::app_profiles_dir().join(file);
let path = dirs::app_profiles_dir().ok()?.join(file);
if !path.exists() {
return None;
@@ -384,11 +384,11 @@ impl PrfItem {
match itype {
"script" => Some(ChainItem {
uid,
data: ChainType::Script(fs::read_to_string(path).unwrap_or("".into())),
data: ChainType::Script(fs::read_to_string(path).ok()?),
}),
"merge" => Some(ChainItem {
uid,
data: ChainType::Merge(config::read_merge_mapping(path)),
data: ChainType::Merge(config::read_merge_mapping(&path).ok()?),
}),
_ => None,
}

View File

@@ -32,30 +32,40 @@ macro_rules! patch {
impl IProfiles {
pub fn new() -> Self {
Self::read_file()
match dirs::profiles_path().and_then(|path| config::read_yaml::<Self>(&path)) {
Ok(mut profiles) => {
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
// compatible with the old old old version
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d"));
}
}
});
profiles
}
Err(err) => {
log::error!(target: "app", "{err}");
Self::template()
}
}
}
/// read the config from the file
pub fn read_file() -> Self {
let mut profiles = config::read_yaml::<Self>(dirs::profiles_path());
if profiles.items.is_none() {
profiles.items = Some(vec![]);
pub fn template() -> Self {
Self {
valid: Some(vec!["dns".into()]),
items: Some(vec![]),
..Self::default()
}
// compatible with the old old old version
profiles.items.as_mut().map(|items| {
for mut item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d"));
}
}
});
profiles
}
/// save the config to the file
pub fn save_file(&self) -> Result<()> {
config::save_yaml(
dirs::profiles_path(),
dirs::profiles_path()?,
self,
Some("# Profiles Config for Clash Verge\n\n"),
)
@@ -131,7 +141,7 @@ impl IProfiles {
}
let file = item.file.clone().unwrap();
let path = dirs::app_profiles_dir().join(&file);
let path = dirs::app_profiles_dir()?.join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
@@ -200,7 +210,7 @@ impl IProfiles {
// the file must exists
each.file = Some(file.clone());
let path = dirs::app_profiles_dir().join(&file);
let path = dirs::app_profiles_dir()?.join(&file);
fs::File::create(path)
.context(format!("failed to create file \"{}\"", file))?
@@ -235,10 +245,12 @@ impl IProfiles {
if let Some(index) = index {
items.remove(index).file.map(|file| {
let path = dirs::app_profiles_dir().join(file);
if path.exists() {
let _ = fs::remove_file(path);
}
let _ = dirs::app_profiles_dir().map(|path| {
let path = path.join(file);
if path.exists() {
let _ = fs::remove_file(path);
}
});
});
}
@@ -263,22 +275,18 @@ impl IProfiles {
return Ok(config);
}
let current = self.current.clone().unwrap();
let current = self.current.as_ref().unwrap();
for item in self.items.as_ref().unwrap().iter() {
if item.uid == Some(current.clone()) {
let file_path = match item.file.clone() {
Some(file) => dirs::app_profiles_dir().join(file),
if item.uid.as_ref() == Some(current) {
let file_path = match item.file.as_ref() {
Some(file) => dirs::app_profiles_dir()?.join(file),
None => bail!("failed to get the file field"),
};
if !file_path.exists() {
bail!("failed to read the file \"{}\"", file_path.display());
}
return Ok(config::read_merge_mapping(file_path.clone()));
return Ok(config::read_merge_mapping(&file_path)?);
}
}
bail!("failed to find current profile \"uid:{current}\"");
bail!("failed to find the current profile \"uid:{current}\"");
}
/// generate the data for activate clash config

View File

@@ -85,13 +85,36 @@ pub struct IVergeTheme {
impl IVerge {
pub fn new() -> Self {
config::read_yaml::<IVerge>(dirs::verge_path())
match dirs::verge_path().and_then(|path| config::read_yaml::<IVerge>(&path)) {
Ok(config) => config,
Err(err) => {
log::error!(target: "app", "{err}");
Self::template()
}
}
}
pub fn template() -> Self {
Self {
clash_core: Some("clash".into()),
language: Some("en".into()),
theme_mode: Some("system".into()),
theme_blur: Some(false),
traffic_graph: Some(true),
enable_auto_launch: Some(false),
enable_silent_start: Some(false),
enable_system_proxy: Some(false),
enable_proxy_guard: Some(false),
proxy_guard_duration: Some(30),
auto_close_connection: Some(true),
..Self::default()
}
}
/// Save IVerge App Config
pub fn save_file(&self) -> Result<()> {
config::save_yaml(
dirs::verge_path(),
dirs::verge_path()?,
&self,
Some("# The Config for Clash IVerge App\n\n"),
)
@@ -133,13 +156,14 @@ impl IVerge {
/// 在初始化前尝试拿到单例端口的值
pub fn get_singleton_port() -> u16 {
let config = config::read_yaml::<IVerge>(dirs::verge_path());
#[cfg(not(feature = "verge-dev"))]
const SERVER_PORT: u16 = 33331;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
config.app_singleton_port.unwrap_or(SERVER_PORT)
match dirs::verge_path().and_then(|path| config::read_yaml::<IVerge>(&path)) {
Ok(config) => config.app_singleton_port.unwrap_or(SERVER_PORT),
Err(_) => SERVER_PORT, // 这里就不log错误了
}
}
}