From e93985c6084b2f9acb873d0f0358c13590041e97 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 16:19:21 +0800 Subject: [PATCH 1/8] refactor: rm useless unsafe --- backend/tauri/src/config/prfitem.rs | 2 +- backend/tauri/src/core/manager.rs | 4 +- backend/tauri/src/utils/dirs.rs | 61 +++++++++++++---------------- 3 files changed, 31 insertions(+), 36 deletions(-) diff --git a/backend/tauri/src/config/prfitem.rs b/backend/tauri/src/config/prfitem.rs index e3ea8368bc..eadf9d32b6 100644 --- a/backend/tauri/src/config/prfitem.rs +++ b/backend/tauri/src/config/prfitem.rs @@ -231,7 +231,7 @@ impl PrfItem { }; } - let version = unsafe { dirs::APP_VERSION }; + let version = dirs::get_app_version(); let version = format!("clash-verge/v{version}"); builder = builder.user_agent(user_agent.unwrap_or(version)); diff --git a/backend/tauri/src/core/manager.rs b/backend/tauri/src/core/manager.rs index 5503569c42..74ddd7a8ca 100644 --- a/backend/tauri/src/core/manager.rs +++ b/backend/tauri/src/core/manager.rs @@ -75,8 +75,8 @@ pub fn escape<'a>(text: &'a str) -> Cow<'a, str> { } if let Some(owned) = owned { - unsafe { Cow::Owned(String::from_utf8_unchecked(owned)) } + Cow::Owned(String::from_utf8(owned).unwrap()) } else { - unsafe { Cow::Borrowed(std::str::from_utf8_unchecked(bytes)) } + Cow::Borrowed(std::str::from_utf8(bytes).unwrap()) } } diff --git a/backend/tauri/src/utils/dirs.rs b/backend/tauri/src/utils/dirs.rs index 377dd26d27..ee03c16f75 100644 --- a/backend/tauri/src/utils/dirs.rs +++ b/backend/tauri/src/utils/dirs.rs @@ -27,6 +27,14 @@ pub fn get_app_version() -> &'static str { APP_VERSION } +pub fn get_portable_flag() -> bool { + unsafe { PORTABLE_FLAG } +} + +pub fn get_resource_dir() -> Option { + unsafe { RESOURCE_DIR.clone() } +} + /// initialize portable flag #[cfg(target_os = "windows")] pub unsafe fn init_portable_flag() -> Result<()> { @@ -48,22 +56,20 @@ pub unsafe fn init_portable_flag() -> Result<()> { /// get the verge app home dir pub fn app_home_dir() -> Result { #[cfg(target_os = "windows")] - unsafe { - use tauri::utils::platform::current_exe; - - if !PORTABLE_FLAG { - Ok(home_dir() - .ok_or(anyhow::anyhow!("failed to get app home dir"))? - .join(".config") - .join(APP_DIR)) - } else { - let app_exe = current_exe()?; - let app_exe = dunce::canonicalize(app_exe)?; - let app_dir = app_exe - .parent() - .ok_or(anyhow::anyhow!("failed to get the portable app dir"))?; - Ok(PathBuf::from(app_dir).join(".config").join(APP_DIR)) - } + use tauri::utils::platform::current_exe; + + if !get_portable_flag() { + Ok(home_dir() + .ok_or(anyhow::anyhow!("failed to get app home dir"))? + .join(".config") + .join(APP_DIR)) + } else { + let app_exe = current_exe()?; + let app_exe = dunce::canonicalize(app_exe)?; + let app_dir = app_exe + .parent() + .ok_or(anyhow::anyhow!("failed to get the portable app dir"))?; + Ok(PathBuf::from(app_dir).join(".config").join(APP_DIR)) } #[cfg(not(target_os = "windows"))] @@ -114,30 +120,19 @@ pub fn storage_path() -> Result { #[allow(unused)] pub fn app_res_dir() -> Result { - unsafe { - Ok(RESOURCE_DIR - .clone() - .ok_or(anyhow::anyhow!("failed to get the resource dir"))?) - } + get_resource_dir().ok_or(anyhow::anyhow!("failed to get the resource dir")) } pub fn clash_pid_path() -> Result { - unsafe { - Ok(RESOURCE_DIR - .clone() - .ok_or(anyhow::anyhow!("failed to get the resource dir"))? - .join("clash.pid")) - } + Ok(get_resource_dir() + .ok_or(anyhow::anyhow!("failed to get the resource dir"))? + .join("clash.pid")) } #[cfg(windows)] pub fn service_path() -> Result { - unsafe { - let res_dir = RESOURCE_DIR - .clone() - .ok_or(anyhow::anyhow!("failed to get the resource dir"))?; - Ok(res_dir.join("clash-verge-service.exe")) - } + let res_dir = get_resource_dir().ok_or(anyhow::anyhow!("failed to get the resource dir"))?; + Ok(res_dir.join("clash-verge-service.exe")) } #[cfg(windows)] From ee50cd0b8e5edd2cb936a418910c7cb21f28d738 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 16:27:38 +0800 Subject: [PATCH 2/8] fix(lint): clippy --- backend/tauri/src/cmds.rs | 6 ++++-- backend/tauri/src/config/clash.rs | 7 ++++--- backend/tauri/src/config/prfitem.rs | 26 ++++---------------------- backend/tauri/src/config/profiles.rs | 8 +++++--- 4 files changed, 17 insertions(+), 30 deletions(-) diff --git a/backend/tauri/src/cmds.rs b/backend/tauri/src/cmds.rs index f4c92402fd..b36f488805 100644 --- a/backend/tauri/src/cmds.rs +++ b/backend/tauri/src/cmds.rs @@ -227,7 +227,9 @@ pub fn open_app_dir() -> CmdResult<()> { #[tauri::command] pub fn open_core_dir() -> CmdResult<()> { let core_dir = wrap_err!(tauri::utils::platform::current_exe())?; - let core_dir = core_dir.parent().ok_or(format!("failed to get core dir"))?; + let core_dir = core_dir + .parent() + .ok_or("failed to get core dir".to_string())?; wrap_err!(open::that(core_dir)) } @@ -306,7 +308,7 @@ pub async fn clash_api_get_proxy_delay( ) -> CmdResult { match clash_api::get_proxy_delay(name, url).await { Ok(res) => Ok(res), - Err(err) => Err(format!("{}", err.to_string())), + Err(err) => Err(err.to_string()), } } diff --git a/backend/tauri/src/config/clash.rs b/backend/tauri/src/config/clash.rs index 9ccc52b961..8fb00f8740 100644 --- a/backend/tauri/src/config/clash.rs +++ b/backend/tauri/src/config/clash.rs @@ -70,8 +70,8 @@ impl IClashTemp { let config = &self.0; ClashInfo { - port: Self::guard_mixed_port(&config), - server: Self::guard_client_ctrl(&config), + port: Self::guard_mixed_port(config), + server: Self::guard_client_ctrl(config), secret: config.get("secret").and_then(|value| match value { Value::String(val_str) => Some(val_str.clone()), Value::Bool(val_bool) => Some(val_bool.to_string()), @@ -103,7 +103,7 @@ impl IClashTemp { Some(val_str) => { let val_str = val_str.trim(); - let val = match val_str.starts_with(":") { + let val = match val_str.starts_with(':') { true => format!("127.0.0.1{val_str}"), false => val_str.to_owned(), }; @@ -130,6 +130,7 @@ impl IClashTemp { } } + #[allow(unused)] pub fn get_tun_device_ip(&self) -> String { let config = &self.0; diff --git a/backend/tauri/src/config/prfitem.rs b/backend/tauri/src/config/prfitem.rs index eadf9d32b6..83e0eefa16 100644 --- a/backend/tauri/src/config/prfitem.rs +++ b/backend/tauri/src/config/prfitem.rs @@ -8,7 +8,7 @@ use sysproxy::Sysproxy; use super::Config; -#[derive(Debug, Clone, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize, Serialize, Default)] pub struct PrfItem { pub uid: Option, @@ -96,25 +96,7 @@ impl PrfOption { a.update_interval = b.update_interval.or(a.update_interval); Some(a) } - t @ _ => t.0.or(t.1), - } - } -} - -impl Default for PrfItem { - fn default() -> Self { - PrfItem { - uid: None, - itype: None, - name: None, - desc: None, - file: None, - url: None, - selected: None, - extra: None, - updated: None, - option: None, - file_data: None, + t => t.0.or(t.1), } } } @@ -152,7 +134,7 @@ impl PrfItem { let desc = item.desc.unwrap_or("".into()); PrfItem::from_script(name, desc) } - typ @ _ => bail!("invalid profile item type \"{typ}\""), + typ => bail!("invalid profile item type \"{typ}\""), } } @@ -188,7 +170,7 @@ impl PrfItem { let opt_ref = option.as_ref(); let with_proxy = opt_ref.map_or(false, |o| o.with_proxy.unwrap_or(false)); let self_proxy = opt_ref.map_or(false, |o| o.self_proxy.unwrap_or(false)); - let user_agent = opt_ref.map_or(None, |o| o.user_agent.clone()); + let user_agent = opt_ref.and_then(|o| o.user_agent.clone()); let mut builder = reqwest::ClientBuilder::new().use_rustls_tls().no_proxy(); diff --git a/backend/tauri/src/config/profiles.rs b/backend/tauri/src/config/profiles.rs index 417d608940..e61e284af8 100644 --- a/backend/tauri/src/config/profiles.rs +++ b/backend/tauri/src/config/profiles.rs @@ -151,7 +151,9 @@ impl IProfiles { self.items = Some(vec![]); } - self.items.as_mut().map(|items| items.push(item)); + if let Some(items) = self.items.as_mut() { + items.push(item) + } self.save_file() } @@ -181,7 +183,7 @@ impl IProfiles { /// update the item value pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> { - let mut items = self.items.take().unwrap_or(vec![]); + let mut items = self.items.take().unwrap_or_default(); for each in items.iter_mut() { if each.uid == Some(uid.clone()) { @@ -254,7 +256,7 @@ impl IProfiles { let current = self.current.as_ref().unwrap_or(&uid); let current = current.clone(); - let mut items = self.items.take().unwrap_or(vec![]); + let mut items = self.items.take().unwrap_or_default(); let mut index = None; // get the index From 6c83f5335447d5ed5d4978e705e10c9d69e2d2e6 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 16:28:32 +0800 Subject: [PATCH 3/8] fix(lint): clippy --- backend/tauri/src/config/profiles.rs | 10 +++++----- backend/tauri/src/core/core.rs | 6 +++--- backend/tauri/src/core/handle.rs | 2 +- backend/tauri/src/core/manager.rs | 2 +- backend/tauri/src/core/sysopt.rs | 16 ++++++++-------- backend/tauri/src/core/tasks/mod.rs | 2 -- backend/tauri/src/core/tray.rs | 2 +- backend/tauri/src/enhance/field.rs | 16 ++++++---------- backend/tauri/src/enhance/mod.rs | 14 +++++++------- backend/tauri/src/enhance/script.rs | 2 +- backend/tauri/src/feat.rs | 18 ++++++++++-------- backend/tauri/src/utils/help.rs | 8 ++++---- backend/tauri/src/utils/resolve.rs | 4 ++-- backend/tauri/src/utils/server.rs | 2 +- 14 files changed, 50 insertions(+), 54 deletions(-) diff --git a/backend/tauri/src/config/profiles.rs b/backend/tauri/src/config/profiles.rs index e61e284af8..cf30d0feec 100644 --- a/backend/tauri/src/config/profiles.rs +++ b/backend/tauri/src/config/profiles.rs @@ -159,7 +159,7 @@ impl IProfiles { /// reorder items pub fn reorder(&mut self, active_id: String, over_id: String) -> Result<()> { - let mut items = self.items.take().unwrap_or(vec![]); + let mut items = self.items.take().unwrap_or_default(); let mut old_index = None; let mut new_index = None; @@ -268,19 +268,19 @@ impl IProfiles { } if let Some(index) = index { - items.remove(index).file.map(|file| { + if let Some(file) = items.remove(index).file { let _ = dirs::app_profiles_dir().map(|path| { let path = path.join(file); if path.exists() { let _ = fs::remove_file(path); } }); - }); + } } // delete the original uid if current == uid { - self.current = match items.len() > 0 { + self.current = match !items.is_empty() { true => items[0].uid.clone(), false => None, }; @@ -300,7 +300,7 @@ impl IProfiles { Some(file) => dirs::app_profiles_dir()?.join(file), None => bail!("failed to get the file field"), }; - return Ok(help::read_merge_mapping(&file_path)?); + return help::read_merge_mapping(&file_path); } bail!("failed to find the current profile \"uid:{current}\""); } diff --git a/backend/tauri/src/core/core.rs b/backend/tauri/src/core/core.rs index 257d15d960..f8ec8ef8c2 100644 --- a/backend/tauri/src/core/core.rs +++ b/backend/tauri/src/core/core.rs @@ -125,7 +125,7 @@ impl CoreManager { use super::win_service; // 服务模式 - let enable = { Config::verge().latest().enable_service_mode.clone() }; + let enable = { Config::verge().latest().enable_service_mode }; let enable = enable.unwrap_or(false); *self.use_service_mode.lock() = enable; @@ -134,10 +134,10 @@ impl CoreManager { // 服务模式启动失败就直接运行sidecar log::debug!(target: "app", "try to run core in service mode"); - match (|| async { + match async { win_service::check_service().await?; win_service::run_core_by_service(&config_path).await - })() + } .await { Ok(_) => return Ok(()), diff --git a/backend/tauri/src/core/handle.rs b/backend/tauri/src/core/handle.rs index 5b46cea7c2..d12d459114 100644 --- a/backend/tauri/src/core/handle.rs +++ b/backend/tauri/src/core/handle.rs @@ -28,7 +28,7 @@ impl Handle { self.app_handle .lock() .as_ref() - .map_or(None, |a| a.get_window("main")) + .and_then(|a| a.get_window("main")) } pub fn refresh_clash() { diff --git a/backend/tauri/src/core/manager.rs b/backend/tauri/src/core/manager.rs index 74ddd7a8ca..6158a5ba1c 100644 --- a/backend/tauri/src/core/manager.rs +++ b/backend/tauri/src/core/manager.rs @@ -52,7 +52,7 @@ pub fn grant_permission(core: String) -> anyhow::Result<()> { } #[allow(unused)] -pub fn escape<'a>(text: &'a str) -> Cow<'a, str> { +pub fn escape(text: &str) -> Cow<'_, str> { let bytes = text.as_bytes(); let mut owned = None; diff --git a/backend/tauri/src/core/sysopt.rs b/backend/tauri/src/core/sysopt.rs index 22d8ed6bd7..2c19ec4b7b 100644 --- a/backend/tauri/src/core/sysopt.rs +++ b/backend/tauri/src/core/sysopt.rs @@ -53,7 +53,7 @@ impl Sysopt { let verge = Config::verge(); let verge = verge.latest(); ( - verge.enable_system_proxy.clone().unwrap_or(false), + verge.enable_system_proxy.unwrap_or(false), verge.system_proxy_bypass.clone(), ) }; @@ -66,7 +66,7 @@ impl Sysopt { }; if enable { - let old = Sysproxy::get_system_proxy().map_or(None, |p| Some(p)); + let old = Sysproxy::get_system_proxy().ok(); current.set_system_proxy()?; *self.old_sysproxy.lock() = old; @@ -93,7 +93,7 @@ impl Sysopt { let verge = Config::verge(); let verge = verge.latest(); ( - verge.enable_system_proxy.clone().unwrap_or(false), + verge.enable_system_proxy.unwrap_or(false), verge.system_proxy_bypass.clone(), ) }; @@ -142,7 +142,7 @@ impl Sysopt { /// init the auto launch pub fn init_launch(&self) -> Result<()> { - let enable = { Config::verge().latest().enable_auto_launch.clone() }; + let enable = { Config::verge().latest().enable_auto_launch }; let enable = enable.unwrap_or(false); let app_exe = current_exe()?; @@ -233,7 +233,7 @@ impl Sysopt { drop(auto_launch); return self.init_launch(); } - let enable = { Config::verge().latest().enable_auto_launch.clone() }; + let enable = { Config::verge().latest().enable_auto_launch }; let enable = enable.unwrap_or(false); let auto_launch = auto_launch.as_ref().unwrap(); @@ -271,9 +271,9 @@ impl Sysopt { let verge = Config::verge(); let verge = verge.latest(); ( - verge.enable_system_proxy.clone().unwrap_or(false), - verge.enable_proxy_guard.clone().unwrap_or(false), - verge.proxy_guard_duration.clone().unwrap_or(10), + verge.enable_system_proxy.unwrap_or(false), + verge.enable_proxy_guard.unwrap_or(false), + verge.proxy_guard_duration.unwrap_or(10), verge.system_proxy_bypass.clone(), ) }; diff --git a/backend/tauri/src/core/tasks/mod.rs b/backend/tauri/src/core/tasks/mod.rs index c9fa6f7c6b..6676b3fa1b 100644 --- a/backend/tauri/src/core/tasks/mod.rs +++ b/backend/tauri/src/core/tasks/mod.rs @@ -6,5 +6,3 @@ pub mod task; mod utils; pub use jobs::JobsManager; -pub use task::TaskManager; -pub use utils::Error; diff --git a/backend/tauri/src/core/tray.rs b/backend/tauri/src/core/tray.rs index 2a1fe26fd9..c9548a5fb0 100644 --- a/backend/tauri/src/core/tray.rs +++ b/backend/tauri/src/core/tray.rs @@ -10,7 +10,7 @@ use super::storage; pub struct Tray {} impl Tray { - pub fn tray_menu(app_handle: &AppHandle) -> SystemTrayMenu { + pub fn tray_menu(_app_handle: &AppHandle) -> SystemTrayMenu { let zh = { Config::verge().latest().language == Some("zh".into()) }; let version = env!("NYANPASU_VERSION"); diff --git a/backend/tauri/src/enhance/field.rs b/backend/tauri/src/enhance/field.rs index aa3fda8a65..71dde6a8cf 100644 --- a/backend/tauri/src/enhance/field.rs +++ b/backend/tauri/src/enhance/field.rs @@ -114,9 +114,9 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping { .chain(DEFAULT_FIELDS) .for_each(|key| { let key = Value::from(key); - config.get(&key).map(|value| { + if let Some(value) = config.get(&key) { ret.insert(key, value.clone()); - }); + } }); if !enable_filter { @@ -126,17 +126,13 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping { .chain(DEFAULT_FIELDS) .collect(); - let config_keys: HashSet<&str> = config - .keys() - .filter_map(|e| e.as_str()) - .into_iter() - .collect(); + let config_keys: HashSet<&str> = config.keys().filter_map(|e| e.as_str()).collect(); config_keys.difference(&supported_keys).for_each(|&key| { let key = Value::from(key); - config.get(&key).map(|value| { + if let Some(value) = config.get(&key) { ret.insert(key, value.clone()); - }); + } }); } @@ -150,7 +146,7 @@ pub fn use_keys(config: &Mapping) -> Vec { .map(|s| { let mut s = s.to_string(); s.make_ascii_lowercase(); - return s; + s }) .collect() } diff --git a/backend/tauri/src/enhance/mod.rs b/backend/tauri/src/enhance/mod.rs index c3c40841b3..003f2f2a95 100644 --- a/backend/tauri/src/enhance/mod.rs +++ b/backend/tauri/src/enhance/mod.rs @@ -4,7 +4,7 @@ mod merge; mod script; mod tun; -pub(self) use self::field::*; +use self::field::*; use self::{chain::*, merge::*, script::*, tun::*}; use crate::config::Config; @@ -24,9 +24,9 @@ pub fn enhance() -> (Mapping, Vec, HashMap) { let verge = verge.latest(); ( verge.clash_core.clone(), - verge.enable_tun_mode.clone().unwrap_or(false), - verge.enable_builtin_enhanced.clone().unwrap_or(true), - verge.enable_clash_fields.clone().unwrap_or(true), + verge.enable_tun_mode.unwrap_or(false), + verge.enable_builtin_enhanced.unwrap_or(true), + verge.enable_clash_fields.unwrap_or(true), ) }; @@ -35,18 +35,18 @@ pub fn enhance() -> (Mapping, Vec, HashMap) { let profiles = Config::profiles(); let profiles = profiles.latest(); - let current = profiles.current_mapping().unwrap_or(Mapping::new()); + let current = profiles.current_mapping().unwrap_or_default(); let chain = match profiles.chain.as_ref() { Some(chain) => chain .iter() .filter_map(|uid| profiles.get_item(uid).ok()) - .filter_map(|item| >::from(item)) + .filter_map(>::from) .collect::>(), None => vec![], }; - let valid = profiles.valid.clone().unwrap_or(vec![]); + let valid = profiles.valid.clone().unwrap_or_default(); (current, chain, valid) }; diff --git a/backend/tauri/src/enhance/script.rs b/backend/tauri/src/enhance/script.rs index 6c207d921d..30a922f676 100644 --- a/backend/tauri/src/enhance/script.rs +++ b/backend/tauri/src/enhance/script.rs @@ -47,7 +47,7 @@ pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(Stri if result == "\"\"" { anyhow::bail!("main function should return object"); } - return Ok(serde_json::from_str::(result.as_str())?); + Ok(serde_json::from_str::(result.as_str())?) }); let mut out = outputs.lock().unwrap(); diff --git a/backend/tauri/src/feat.rs b/backend/tauri/src/feat.rs index 2b637f49c1..30306c5d5b 100644 --- a/backend/tauri/src/feat.rs +++ b/backend/tauri/src/feat.rs @@ -80,7 +80,7 @@ pub fn change_clash_mode(mode: String) { // 切换系统代理 pub fn toggle_system_proxy() { - let enable = Config::verge().draft().enable_system_proxy.clone(); + let enable = Config::verge().draft().enable_system_proxy; let enable = enable.unwrap_or(false); tauri::async_runtime::spawn(async move { @@ -128,7 +128,7 @@ pub fn disable_system_proxy() { // 切换tun模式 pub fn toggle_tun_mode() { - let enable = Config::verge().data().enable_tun_mode.clone(); + let enable = Config::verge().data().enable_tun_mode; let enable = enable.unwrap_or(false); tauri::async_runtime::spawn(async move { @@ -178,18 +178,18 @@ pub fn disable_tun_mode() { pub async fn patch_clash(patch: Mapping) -> Result<()> { Config::clash().draft().patch_config(patch.clone()); - match { + let res = { let mixed_port = patch.get("mixed-port"); let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false); if mixed_port.is_some() && !enable_random_port { - let changed = mixed_port.clone().unwrap() + let changed = mixed_port.unwrap() != Config::verge() .latest() .verge_mixed_port .unwrap_or(Config::clash().data().get_mixed_port()); // 检查端口占用 if changed { - if let Some(port) = mixed_port.clone().unwrap().as_u64() { + if let Some(port) = mixed_port.unwrap().as_u64() { if !port_scanner::local_port_available(port as u16) { Config::clash().discard(); bail!("port already in use"); @@ -220,7 +220,8 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> { Config::runtime().latest().patch_config(patch); >::Ok(()) - } { + }; + match res { Ok(()) => { Config::clash().apply(); Config::clash().data().save_config()?; @@ -244,7 +245,7 @@ pub async fn patch_verge(patch: IVerge) -> Result<()> { let proxy_bypass = patch.system_proxy_bypass; let language = patch.language; - match { + let res = { #[cfg(target_os = "windows")] { let service_mode = patch.enable_service_mode; @@ -287,7 +288,8 @@ pub async fn patch_verge(patch: IVerge) -> Result<()> { } >::Ok(()) - } { + }; + match res { Ok(()) => { Config::verge().apply(); Config::verge().data().save_file()?; diff --git a/backend/tauri/src/utils/help.rs b/backend/tauri/src/utils/help.rs index 5c2aaaa5d3..ec5bc12f55 100644 --- a/backend/tauri/src/utils/help.rs +++ b/backend/tauri/src/utils/help.rs @@ -13,7 +13,7 @@ pub fn read_yaml(path: &PathBuf) -> Result { bail!("file not found \"{}\"", path.display()); } - let yaml_str = fs::read_to_string(&path) + let yaml_str = fs::read_to_string(path) .with_context(|| format!("failed to read the file \"{}\"", path.display()))?; serde_yaml::from_str::(&yaml_str).with_context(|| { @@ -74,7 +74,7 @@ pub fn parse_str(target: &str, key: &str) -> Option { let idx = idx + key.len(); let value = &target[idx..]; - match value.split(';').nth(0) { + match value.split(';').next() { Some(value) => value.trim().parse(), None => value.trim().parse(), } @@ -91,11 +91,11 @@ pub fn open_file(app: tauri::AppHandle, path: PathBuf) -> Result<()> { let code = "code"; let _ = match Program::from_str(code) { - Ok(code) => open(&app.shell_scope(), &path.to_string_lossy(), Some(code)), + Ok(code) => open(&app.shell_scope(), path.to_string_lossy(), Some(code)), Err(err) => { log::error!(target: "app", "Can't find VScode `{err}`"); // default open - open(&app.shell_scope(), &path.to_string_lossy(), None) + open(&app.shell_scope(), path.to_string_lossy(), None) } }; diff --git a/backend/tauri/src/utils/resolve.rs b/backend/tauri/src/utils/resolve.rs index cc2df3750c..30186fb203 100644 --- a/backend/tauri/src/utils/resolve.rs +++ b/backend/tauri/src/utils/resolve.rs @@ -80,7 +80,7 @@ pub fn resolve_setup(app: &mut App) { log::trace!("init system tray"); log_err!(tray::Tray::update_systray(&app.app_handle())); - let silent_start = { Config::verge().data().enable_silent_start.clone() }; + let silent_start = { Config::verge().data().enable_silent_start }; if !silent_start.unwrap_or(false) { create_window(&app.app_handle()); } @@ -315,7 +315,7 @@ pub fn resolve_core_version(core_type: &ClashCore) -> Result { for item in out { log::debug!(target: "app", "check item: {}", item); if item.starts_with('v') - || item.starts_with("n") + || item.starts_with('n') || item.starts_with("alpha") || Version::parse(item).is_ok() { diff --git a/backend/tauri/src/utils/server.rs b/backend/tauri/src/utils/server.rs index f4e98368ab..09a5974728 100644 --- a/backend/tauri/src/utils/server.rs +++ b/backend/tauri/src/utils/server.rs @@ -36,7 +36,7 @@ pub fn embed_server(app_handle: AppHandle) { tauri::async_runtime::spawn(async move { let commands = warp::path!("commands" / "visible").map(move || { resolve::create_window(&app_handle); - format!("ok") + "ok".to_string() }); warp::serve(commands).bind(([127, 0, 0, 1], port)).await; From 2052acf311a5434a40caa08bd7bc761afa6ba47b Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 16:59:25 +0800 Subject: [PATCH 4/8] fix(lint): clippy --- backend/tauri/src/config/profiles.rs | 14 +++++------ backend/tauri/src/config/verge.rs | 1 - backend/tauri/src/core/core.rs | 18 ++++++-------- backend/tauri/src/core/hotkey.rs | 2 ++ backend/tauri/src/core/tasks/jobs/profiles.rs | 1 + backend/tauri/src/core/tasks/storage.rs | 2 ++ backend/tauri/src/core/tasks/task.rs | 9 +++---- backend/tauri/src/core/tasks/utils.rs | 1 + backend/tauri/src/enhance/chain.rs | 17 +++++++------ backend/tauri/src/enhance/field.rs | 2 +- backend/tauri/src/enhance/merge.rs | 3 ++- backend/tauri/src/enhance/mod.rs | 2 +- backend/tauri/src/feat.rs | 10 ++++---- backend/tauri/src/utils/config.rs | 6 ++--- backend/tauri/src/utils/resolve.rs | 24 ------------------- backend/tauri/src/utils/tmpl.rs | 3 +-- 16 files changed, 48 insertions(+), 67 deletions(-) diff --git a/backend/tauri/src/config/profiles.rs b/backend/tauri/src/config/profiles.rs index cf30d0feec..8f882fc96c 100644 --- a/backend/tauri/src/config/profiles.rs +++ b/backend/tauri/src/config/profiles.rs @@ -37,13 +37,13 @@ impl IProfiles { profiles.items = Some(vec![]); } // compatible with the old old old version - profiles.items.as_mut().map(|items| { + if let Some(items) = profiles.items.as_mut() { for item in items.iter_mut() { if item.uid.is_none() { item.uid = Some(help::get_uid("d")); } } - }); + } profiles } Err(err) => { @@ -163,11 +163,11 @@ impl IProfiles { let mut old_index = None; let mut new_index = None; - for i in 0..items.len() { - if items[i].uid == Some(active_id.clone()) { + for (i, item) in items.iter().enumerate() { + if item.uid == Some(active_id.clone()) { old_index = Some(i); } - if items[i].uid == Some(over_id.clone()) { + if item.uid == Some(over_id.clone()) { new_index = Some(i); } } @@ -260,8 +260,8 @@ impl IProfiles { let mut index = None; // get the index - for i in 0..items.len() { - if items[i].uid == Some(uid.clone()) { + for (i, item) in items.iter().enumerate() { + if item.uid == Some(uid.clone()) { index = Some(i); break; } diff --git a/backend/tauri/src/config/verge.rs b/backend/tauri/src/config/verge.rs index b2aeb4594a..eacf700f64 100644 --- a/backend/tauri/src/config/verge.rs +++ b/backend/tauri/src/config/verge.rs @@ -261,7 +261,6 @@ impl IVerge { patch!(enable_clash_fields); patch!(auto_log_clean); - patch!(window_size_position); patch!(window_size_state); } diff --git a/backend/tauri/src/core/core.rs b/backend/tauri/src/core/core.rs index f8ec8ef8c2..0b8b70c957 100644 --- a/backend/tauri/src/core/core.rs +++ b/backend/tauri/src/core/core.rs @@ -34,12 +34,12 @@ impl CoreManager { .map(|pid| { let mut system = System::new(); system.refresh_all(); - system.process(Pid::from_u32(pid)).map(|proc| { + if let Some(proc) = system.process(Pid::from_u32(pid)) { if proc.name().contains("clash") { log::debug!(target: "app", "kill old clash process"); proc.kill(); } - }); + } }); tauri::async_runtime::spawn(async { @@ -131,15 +131,14 @@ impl CoreManager { *self.use_service_mode.lock() = enable; if enable { - // 服务模式启动失败就直接运行sidecar + // 服务模式启动失败就直接运行 sidecar log::debug!(target: "app", "try to run core in service mode"); - - match async { + let res = async { win_service::check_service().await?; win_service::run_core_by_service(&config_path).await } - .await - { + .await; + match res { Ok(_) => return Ok(()), Err(err) => { // 修改这个值,免得stop出错 @@ -155,10 +154,7 @@ impl CoreManager { let clash_core = { Config::verge().latest().clash_core.clone() }; let clash_core = clash_core.unwrap_or(ClashCore::ClashPremium); - let is_clash = match &clash_core { - ClashCore::ClashPremium => true, - _ => false, - }; + let is_clash = matches!(&clash_core, ClashCore::ClashPremium); let config_path = dirs::path_to_str(&config_path)?; diff --git a/backend/tauri/src/core/hotkey.rs b/backend/tauri/src/core/hotkey.rs index 0db5a0571c..62776cc5c6 100644 --- a/backend/tauri/src/core/hotkey.rs +++ b/backend/tauri/src/core/hotkey.rs @@ -15,7 +15,9 @@ pub struct Hotkey { type HotKeyOp<'a> = (&'a str, HotKeyOpType<'a>); enum HotKeyOpType<'a> { + #[allow(unused)] Unbind(&'a str), + #[allow(unused)] Change(&'a str, &'a str), Bind(&'a str), } diff --git a/backend/tauri/src/core/tasks/jobs/profiles.rs b/backend/tauri/src/core/tasks/jobs/profiles.rs index f68c4e6f8c..5cccc2bb55 100644 --- a/backend/tauri/src/core/tasks/jobs/profiles.rs +++ b/backend/tauri/src/core/tasks/jobs/profiles.rs @@ -22,6 +22,7 @@ type ProfileUID = String; pub struct ProfileUpdater(ProfileUID); impl ProfileUpdater { + #[allow(dead_code)] pub fn new(profile_uid: &str) -> Self { Self(profile_uid.to_string()) } diff --git a/backend/tauri/src/core/tasks/storage.rs b/backend/tauri/src/core/tasks/storage.rs index 2e2e74c09d..1f705f676b 100644 --- a/backend/tauri/src/core/tasks/storage.rs +++ b/backend/tauri/src/core/tasks/storage.rs @@ -36,6 +36,7 @@ impl EventsGuard { } /// get_events get all events of a task + #[allow(dead_code)] pub fn get_events(&self, task_id: TaskID) -> Result>> { let mut value = match self.get_event_ids(task_id)? { Some(value) => value, @@ -91,6 +92,7 @@ impl EventsGuard { } /// remove_event remove a event from the storage + #[allow(dead_code)] pub fn remove_event(&self, event_id: TaskEventID, task_id: TaskID) -> Result<()> { let event_ids: Vec = match self.get_event_ids(task_id)? { Some(value) => value.into_iter().filter(|v| v != &event_id).collect(), diff --git a/backend/tauri/src/core/tasks/task.rs b/backend/tauri/src/core/tasks/task.rs index a5e5dc001c..7ad8036365 100644 --- a/backend/tauri/src/core/tasks/task.rs +++ b/backend/tauri/src/core/tasks/task.rs @@ -15,7 +15,6 @@ use parking_lot::{Mutex, RwLock as RW}; use serde::{Deserialize, Serialize}; use snowflake::SnowflakeIdGenerator; use std::{ - collections::HashMap, sync::{Arc, OnceLock}, time::Duration, }; @@ -41,7 +40,8 @@ pub enum TaskRunResult { pub enum TaskSchedule { Once(Duration), // 一次性执行 Interval(Duration), // 按间隔执行 - Cron(String), // 按 cron 表达式执行 + #[allow(dead_code)] + Cron(String), // 按 cron 表达式执行 } impl Default for TaskSchedule { @@ -155,6 +155,7 @@ fn build_task<'a>(task: Task, len: usize) -> (Task, TimerTaskBuilder<'a>) { // NOTE: 由于 DelayTimer 的设计,因此继续使用弃用的 candy 方法 // NOTE: 请注意一定需要回收内存,否则会造成内存泄漏 let cron = cron.clone(); + #[allow(deprecated)] builder.set_frequency_by_candy(CandyFrequency::Repeated(CandyCronStr(cron))); } TaskSchedule::Interval(duration) => { @@ -289,8 +290,6 @@ impl TaskListOps for TaskList { } } -type TasksEvents = Arc>>; - pub struct TaskManager { /// cron manager timer: Arc>, @@ -400,6 +399,7 @@ impl TaskManager { list.iter().find(|t| t.id == task_id).cloned() } + #[allow(dead_code)] pub fn pick_task(&self, task_id: TaskID) -> Result { let list = self.list.read(); list.iter() @@ -408,6 +408,7 @@ impl TaskManager { .ok_or(Error::CreateTaskFailed(TaskCreationError::NotFound)) } + #[allow(dead_code)] pub fn total(&self) -> usize { let list = self.list.read(); list.len() diff --git a/backend/tauri/src/core/tasks/utils.rs b/backend/tauri/src/core/tasks/utils.rs index 611e94d724..23d5acdcec 100644 --- a/backend/tauri/src/core/tasks/utils.rs +++ b/backend/tauri/src/core/tasks/utils.rs @@ -2,6 +2,7 @@ use thiserror::Error; #[derive(Debug)] pub enum TaskCreationError { + #[allow(unused)] AlreadyExist, NotFound, } diff --git a/backend/tauri/src/enhance/chain.rs b/backend/tauri/src/enhance/chain.rs index 3aa3181a57..99822cec52 100644 --- a/backend/tauri/src/enhance/chain.rs +++ b/backend/tauri/src/enhance/chain.rs @@ -78,13 +78,16 @@ impl ChainItem { impl ChainSupport { pub fn is_support(&self, core: Option<&ClashCore>) -> bool { match core { - Some(core) => match (self, core) { - (ChainSupport::All, _) => true, - (ChainSupport::Clash, ClashCore::ClashPremium) => true, - (ChainSupport::ClashRs, ClashCore::ClashRs) => true, - (ChainSupport::Mihomo, ClashCore::Mihomo | ClashCore::MihomoAlpha) => true, - _ => false, - }, + Some(core) => matches!( + (self, core), + (ChainSupport::All, _) + | (ChainSupport::Clash, ClashCore::ClashPremium) + | (ChainSupport::ClashRs, ClashCore::ClashRs) + | ( + ChainSupport::Mihomo, + ClashCore::Mihomo | ClashCore::MihomoAlpha + ) + ), None => true, } } diff --git a/backend/tauri/src/enhance/field.rs b/backend/tauri/src/enhance/field.rs index 71dde6a8cf..70820fbeb2 100644 --- a/backend/tauri/src/enhance/field.rs +++ b/backend/tauri/src/enhance/field.rs @@ -75,7 +75,7 @@ pub fn use_valid_fields(mut valid: Vec) -> Vec { .collect() } -pub fn use_filter(config: Mapping, filter: &Vec, enable: bool) -> Mapping { +pub fn use_filter(config: Mapping, filter: &[String], enable: bool) -> Mapping { if !enable { return config; } diff --git a/backend/tauri/src/enhance/merge.rs b/backend/tauri/src/enhance/merge.rs index 20342c9898..566cd3e83b 100644 --- a/backend/tauri/src/enhance/merge.rs +++ b/backend/tauri/src/enhance/merge.rs @@ -19,7 +19,8 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping { }); let merge_list = MERGE_FIELDS.iter().map(|s| s.to_string()); - let merge = use_filter(merge, &merge_list.collect(), true); + let merge_list = merge_list.collect::>(); + let merge = use_filter(merge, &merge_list, true); ["rules", "proxies", "proxy-groups"] .iter() diff --git a/backend/tauri/src/enhance/mod.rs b/backend/tauri/src/enhance/mod.rs index 003f2f2a95..63bb45d9d9 100644 --- a/backend/tauri/src/enhance/mod.rs +++ b/backend/tauri/src/enhance/mod.rs @@ -105,7 +105,7 @@ pub fn enhance() -> (Mapping, Vec, HashMap) { log::error!(target: "app", "builtin script error `{err}`"); } }, - _ => {} + ChainType::Merge(_) => todo!(), } }); } diff --git a/backend/tauri/src/feat.rs b/backend/tauri/src/feat.rs index 30306c5d5b..69cc2d237a 100644 --- a/backend/tauri/src/feat.rs +++ b/backend/tauri/src/feat.rs @@ -10,6 +10,7 @@ use serde_yaml::{Mapping, Value}; use wry::application::clipboard::Clipboard; // 打开面板 +#[allow(unused)] pub fn open_dashboard() { let handle = handle::Handle::global(); let app_handle = handle.app_handle.lock(); @@ -19,6 +20,7 @@ pub fn open_dashboard() { } // 关闭面板 +#[allow(unused)] pub fn close_dashboard() { let handle = handle::Handle::global(); let app_handle = handle.app_handle.lock(); @@ -367,12 +369,12 @@ pub fn copy_clash_env(option: &str) { let cmd: String = format!("set http_proxy={http_proxy} \n set https_proxy={http_proxy}"); let ps: String = format!("$env:HTTP_PROXY=\"{http_proxy}\"; $env:HTTPS_PROXY=\"{http_proxy}\""); - let mut cliboard = Clipboard::new(); + let mut clipboard = Clipboard::new(); match option { - "sh" => cliboard.write_text(sh), - "cmd" => cliboard.write_text(cmd), - "ps" => cliboard.write_text(ps), + "sh" => clipboard.write_text(sh), + "cmd" => clipboard.write_text(cmd), + "ps" => clipboard.write_text(ps), _ => log::error!(target: "app", "copy_clash_env: Invalid option! {option}"), } } diff --git a/backend/tauri/src/utils/config.rs b/backend/tauri/src/utils/config.rs index 83557d010d..a97ab53849 100644 --- a/backend/tauri/src/utils/config.rs +++ b/backend/tauri/src/utils/config.rs @@ -50,10 +50,8 @@ impl NyanpasuReqwestProxyExt for reqwest::ClientBuilder { if let Ok(proxy) = get_self_proxy() { builder = builder.swift_set_proxy(&proxy); } - if let Ok(proxy) = get_system_proxy() { - if let Some(proxy) = proxy { - builder = builder.swift_set_proxy(&proxy); - } + if let Ok(Some(proxy)) = get_system_proxy() { + builder = builder.swift_set_proxy(&proxy); } builder } diff --git a/backend/tauri/src/utils/resolve.rs b/backend/tauri/src/utils/resolve.rs index 30186fb203..7606c7fc8c 100644 --- a/backend/tauri/src/utils/resolve.rs +++ b/backend/tauri/src/utils/resolve.rs @@ -229,30 +229,6 @@ pub fn is_window_open(app_handle: &AppHandle) -> bool { app_handle.get_window("main").is_some() } -/// save window size and position -#[deprecated] -pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) -> Result<()> { - let win = app_handle - .get_window("main") - .ok_or(anyhow::anyhow!("failed to get window"))?; - - let scale = win.scale_factor()?; - let size = win.inner_size()?; - let size = size.to_logical::(scale); - let pos = win.outer_position()?; - let pos = pos.to_logical::(scale); - - let verge = Config::verge(); - let mut verge = verge.latest(); - verge.window_size_position = Some(vec![size.width, size.height, pos.x, pos.y]); - - if save_to_file { - verge.save_file()?; - } - - Ok(()) -} - pub fn save_window_state(app_handle: &AppHandle, save_to_file: bool) -> Result<()> { let win = app_handle .get_window("main") diff --git a/backend/tauri/src/utils/tmpl.rs b/backend/tauri/src/utils/tmpl.rs index ec17c336eb..9d2060c512 100644 --- a/backend/tauri/src/utils/tmpl.rs +++ b/backend/tauri/src/utils/tmpl.rs @@ -1,5 +1,4 @@ -///! Some config file template - +//! Some config file template /// template for new a profile item pub const ITEM_LOCAL: &str = "# Profile Template for clash verge From 0007bd079f7c744d09ff9cd04fdce64d3c2fd023 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 17:06:15 +0800 Subject: [PATCH 5/8] refactor: rename same mod name to differnet one --- backend/tauri/src/config/{config.rs => core.rs} | 0 backend/tauri/src/config/mod.rs | 4 ++-- backend/tauri/src/core/{core.rs => clash_core.rs} | 0 backend/tauri/src/core/mod.rs | 4 ++-- 4 files changed, 4 insertions(+), 4 deletions(-) rename backend/tauri/src/config/{config.rs => core.rs} (100%) rename backend/tauri/src/core/{core.rs => clash_core.rs} (100%) diff --git a/backend/tauri/src/config/config.rs b/backend/tauri/src/config/core.rs similarity index 100% rename from backend/tauri/src/config/config.rs rename to backend/tauri/src/config/core.rs diff --git a/backend/tauri/src/config/mod.rs b/backend/tauri/src/config/mod.rs index 5f59f058dc..0d63587d58 100644 --- a/backend/tauri/src/config/mod.rs +++ b/backend/tauri/src/config/mod.rs @@ -1,9 +1,9 @@ mod clash; -mod config; +mod core; mod draft; mod prfitem; mod profiles; mod runtime; mod verge; -pub use self::{clash::*, config::*, draft::*, prfitem::*, profiles::*, runtime::*, verge::*}; +pub use self::{clash::*, core::*, draft::*, prfitem::*, profiles::*, runtime::*, verge::*}; diff --git a/backend/tauri/src/core/core.rs b/backend/tauri/src/core/clash_core.rs similarity index 100% rename from backend/tauri/src/core/core.rs rename to backend/tauri/src/core/clash_core.rs diff --git a/backend/tauri/src/core/mod.rs b/backend/tauri/src/core/mod.rs index e857122ef1..014818bcfd 100644 --- a/backend/tauri/src/core/mod.rs +++ b/backend/tauri/src/core/mod.rs @@ -1,5 +1,5 @@ pub mod clash_api; -mod core; +mod clash_core; pub mod handle; pub mod hotkey; pub mod logger; @@ -11,4 +11,4 @@ pub mod tray; pub mod updater; pub mod win_service; pub mod win_uwp; -pub use self::core::*; +pub use self::clash_core::*; From 7be225cc3553b794495821f3e6730baa6f0d8a27 Mon Sep 17 00:00:00 2001 From: greenhat616 Date: Sun, 21 Jan 2024 09:46:30 +0000 Subject: [PATCH 6/8] fix: clippy in linux --- backend/sysproxy-rs/src/linux.rs | 10 +++---- backend/tauri/src/core/tray.rs | 51 ++++++++++++++++++-------------- backend/tauri/src/utils/dirs.rs | 32 +++++++++++--------- 3 files changed, 51 insertions(+), 42 deletions(-) diff --git a/backend/sysproxy-rs/src/linux.rs b/backend/sysproxy-rs/src/linux.rs index 5c72a21b7f..b66aef1ea6 100644 --- a/backend/sysproxy-rs/src/linux.rs +++ b/backend/sysproxy-rs/src/linux.rs @@ -11,12 +11,12 @@ impl Sysproxy { let https = get_proxy("https")?; let http = get_proxy("http")?; - if socks.host.len() == 0 { - if http.host.len() > 0 { + if socks.host.is_empty() { + if !http.host.is_empty() { socks.host = http.host; socks.port = http.port; } - if https.host.len() > 0 { + if !https.host.is_empty() { socks.host = https.host; socks.port = https.port; } @@ -97,7 +97,7 @@ impl Sysproxy { host = String::from("'") + &host; } if !host.ends_with('\'') && !host.ends_with('"') { - host = host + "'"; + host += "'"; } host }) @@ -168,7 +168,7 @@ fn get_proxy(service: &str) -> Result { }) } -fn strip_str<'a>(text: &'a str) -> &'a str { +fn strip_str(text: &str) -> &str { text.strip_prefix('\'') .unwrap_or(text) .strip_suffix('\'') diff --git a/backend/tauri/src/core/tray.rs b/backend/tauri/src/core/tray.rs index c9548a5fb0..1e9c2ff948 100644 --- a/backend/tauri/src/core/tray.rs +++ b/backend/tauri/src/core/tray.rs @@ -109,15 +109,18 @@ impl Tray { } pub fn update_part(app_handle: &AppHandle) -> Result<()> { - let zh = { Config::verge().latest().language == Some("zh".into()) }; - macro_rules! t { - ($en: expr, $zh: expr) => { - if zh { - $zh - } else { - $en - } - }; + #[cfg(not(target_os = "linux"))] + { + let zh = { Config::verge().latest().language == Some("zh".into()) }; + macro_rules! t { + ($en: expr, $zh: expr) => { + if zh { + $zh + } else { + $en + } + }; + } } let mode = { Config::clash() @@ -157,21 +160,23 @@ impl Tray { let _ = tray.get_item("system_proxy").set_selected(*system_proxy); let _ = tray.get_item("tun_mode").set_selected(*tun_mode); - let switch_map = { - let mut map = std::collections::HashMap::new(); - map.insert(true, t!("On", "开")); - map.insert(false, t!("Off", "关")); - map - }; - #[cfg(not(target_os = "linux"))] - let _ = tray.set_tooltip(&format!( - "{}: {}\n{}: {}", - t!("System Proxy", "系统代理"), - switch_map[system_proxy], - t!("TUN Mode", "Tun 模式"), - switch_map[tun_mode] - )); + { + let switch_map = { + let mut map = std::collections::HashMap::new(); + map.insert(true, t!("On", "开")); + map.insert(false, t!("Off", "关")); + map + }; + + let _ = tray.set_tooltip(&format!( + "{}: {}\n{}: {}", + t!("System Proxy", "系统代理"), + switch_map[system_proxy], + t!("TUN Mode", "Tun 模式"), + switch_map[tun_mode] + )); + } Ok(()) } diff --git a/backend/tauri/src/utils/dirs.rs b/backend/tauri/src/utils/dirs.rs index ee03c16f75..114d8dc70b 100644 --- a/backend/tauri/src/utils/dirs.rs +++ b/backend/tauri/src/utils/dirs.rs @@ -19,6 +19,7 @@ static mut RESOURCE_DIR: Option = None; /// portable flag #[allow(unused)] +#[cfg(target_os = "windows")] static mut PORTABLE_FLAG: bool = false; pub static APP_VERSION: &str = env!("NYANPASU_VERSION"); @@ -27,6 +28,7 @@ pub fn get_app_version() -> &'static str { APP_VERSION } +#[cfg(target_os = "windows")] pub fn get_portable_flag() -> bool { unsafe { PORTABLE_FLAG } } @@ -56,20 +58,22 @@ pub unsafe fn init_portable_flag() -> Result<()> { /// get the verge app home dir pub fn app_home_dir() -> Result { #[cfg(target_os = "windows")] - use tauri::utils::platform::current_exe; - - if !get_portable_flag() { - Ok(home_dir() - .ok_or(anyhow::anyhow!("failed to get app home dir"))? - .join(".config") - .join(APP_DIR)) - } else { - let app_exe = current_exe()?; - let app_exe = dunce::canonicalize(app_exe)?; - let app_dir = app_exe - .parent() - .ok_or(anyhow::anyhow!("failed to get the portable app dir"))?; - Ok(PathBuf::from(app_dir).join(".config").join(APP_DIR)) + { + use tauri::utils::platform::current_exe; + + if !get_portable_flag() { + Ok(home_dir() + .ok_or(anyhow::anyhow!("failed to get app home dir"))? + .join(".config") + .join(APP_DIR)) + } else { + let app_exe = current_exe()?; + let app_exe = dunce::canonicalize(app_exe)?; + let app_dir = app_exe + .parent() + .ok_or(anyhow::anyhow!("failed to get the portable app dir"))?; + Ok(PathBuf::from(app_dir).join(".config").join(APP_DIR)) + } } #[cfg(not(target_os = "windows"))] From 1fd320db07800654a180d411b46b453b70e36c98 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 17:49:54 +0800 Subject: [PATCH 7/8] fix(lint): clippy in win --- backend/tauri/src/core/tray.rs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/backend/tauri/src/core/tray.rs b/backend/tauri/src/core/tray.rs index 1e9c2ff948..ac4ee5d00c 100644 --- a/backend/tauri/src/core/tray.rs +++ b/backend/tauri/src/core/tray.rs @@ -109,19 +109,6 @@ impl Tray { } pub fn update_part(app_handle: &AppHandle) -> Result<()> { - #[cfg(not(target_os = "linux"))] - { - let zh = { Config::verge().latest().language == Some("zh".into()) }; - macro_rules! t { - ($en: expr, $zh: expr) => { - if zh { - $zh - } else { - $en - } - }; - } - } let mode = { Config::clash() .latest() @@ -162,6 +149,17 @@ impl Tray { #[cfg(not(target_os = "linux"))] { + let zh = { Config::verge().latest().language == Some("zh".into()) }; + macro_rules! t { + ($en: expr, $zh: expr) => { + if zh { + $zh + } else { + $en + } + }; + } + let switch_map = { let mut map = std::collections::HashMap::new(); map.insert(true, t!("On", "开")); From 94b5e82ad7a925fc2c2b749843341b675ca95b73 Mon Sep 17 00:00:00 2001 From: Jonson Petard <41122242+greenhat616@users.noreply.github.com> Date: Sun, 21 Jan 2024 19:14:34 +0800 Subject: [PATCH 8/8] fix(lint): clippy in macos --- backend/sysproxy-rs/src/macos.rs | 13 ++++++++----- backend/tauri/src/core/clash_core.rs | 14 ++++++-------- backend/tauri/src/main.rs | 13 +++++-------- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/backend/sysproxy-rs/src/macos.rs b/backend/sysproxy-rs/src/macos.rs index 906f38c927..a27eef4f01 100644 --- a/backend/sysproxy-rs/src/macos.rs +++ b/backend/sysproxy-rs/src/macos.rs @@ -64,7 +64,7 @@ impl Sysproxy { let bypass = from_utf8(&bypass_output.stdout) .or(Err(Error::ParseStr("bypass".into())))? .split('\n') - .filter(|s| s.len() > 0) + .filter(|s| !s.is_empty()) .collect::>() .join(","); @@ -84,7 +84,7 @@ impl Sysproxy { } pub fn set_bypass(&self, service: &str) -> Result<()> { - let domains = self.bypass.split(",").collect::>(); + let domains = self.bypass.split(',').collect::>(); networksetup() .args([["-setproxybypassdomains", service].to_vec(), domains].concat()) .status()?; @@ -94,8 +94,11 @@ impl Sysproxy { #[derive(Debug)] enum ProxyType { + #[allow(clippy::upper_case_acronyms)] HTTP, + #[allow(clippy::upper_case_acronyms)] HTTPS, + #[allow(clippy::upper_case_acronyms)] SOCKS, } @@ -164,7 +167,7 @@ fn parse<'a>(target: &'a str, key: &'a str) -> &'a str { Some(idx) => { let idx = idx + key.len(); let value = &target[idx..]; - let value = match value.find("\n") { + let value = match value.find('\n') { Some(end) => &value[..end], None => value, }; @@ -183,7 +186,7 @@ fn default_network_service() -> Result { let interfaces = interfaces::Interface::get_all().or(Err(Error::NetworkInterface))?; let interface = interfaces .into_iter() - .find(|i| i.addresses.iter().find(|a| a.addr == Some(addr)).is_some()) + .find(|i| i.addresses.iter().any(|a| a.addr == Some(addr))) .map(|i| i.name.to_owned()); match interface { @@ -213,7 +216,7 @@ fn get_service_by_device(device: String) -> Result { let stdout = from_utf8(&output.stdout).or(Err(Error::ParseStr("output".into())))?; let hardware = stdout.split("Ethernet Address:").find_map(|s| { - let lines = s.split("\n"); + let lines = s.split('\n'); let mut hardware = None; let mut device_ = None; diff --git a/backend/tauri/src/core/clash_core.rs b/backend/tauri/src/core/clash_core.rs index 0b8b70c957..da511907e4 100644 --- a/backend/tauri/src/core/clash_core.rs +++ b/backend/tauri/src/core/clash_core.rs @@ -105,7 +105,7 @@ impl CoreManager { } #[cfg(target_os = "macos")] { - let enable_tun = Config::verge().latest().enable_tun_mode.clone(); + let enable_tun = Config::verge().latest().enable_tun_mode; let enable_tun = enable_tun.unwrap_or(false); if enable_tun { @@ -266,18 +266,16 @@ impl CoreManager { #[cfg(target_os = "macos")] { - let enable_tun = Config::verge().latest().enable_tun_mode.clone(); + let enable_tun = Config::verge().latest().enable_tun_mode; let enable_tun = enable_tun.unwrap_or(false); if enable_tun { log::debug!(target: "app", "try to set system dns"); - match (|| { - // 执行 networksetup -setdnsservers Wi-Fi "Empty" - Command::new("networksetup") - .args(["-setdnsservers", "Wi-Fi", "Empty"]) - .output() - })() { + match Command::new("networksetup") + .args(["-setdnsservers", "Wi-Fi", "Empty"]) + .output() + { Ok(_) => return Ok(()), Err(err) => { // 修改这个值,免得stop出错 diff --git a/backend/tauri/src/main.rs b/backend/tauri/src/main.rs index 246dc041b9..137a126ace 100644 --- a/backend/tauri/src/main.rs +++ b/backend/tauri/src/main.rs @@ -127,16 +127,13 @@ fn main() -> std::io::Result<()> { use tauri::Manager; if label == "main" { - match event { - tauri::WindowEvent::CloseRequested { api, .. } => { - api.prevent_close(); - let _ = resolve::save_window_state(app_handle, true); + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + let _ = resolve::save_window_state(app_handle, true); - app_handle.get_window("main").map(|win| { - let _ = win.hide(); - }); + if let Some(win) = app_handle.get_window("main") { + let _ = win.hide(); } - _ => {} } } }