Skip to content

Commit

Permalink
refactor(backend): improve code robustness (#303)
Browse files Browse the repository at this point in the history
* refactor: rm useless unsafe

* fix(lint): clippy

* fix(lint): clippy

* fix(lint): clippy

* refactor: rename same mod name to differnet one

* fix: clippy in linux

* fix(lint): clippy in win

* fix(lint): clippy in macos
  • Loading branch information
greenhat616 authored Jan 21, 2024
1 parent 8620b3a commit ba24602
Show file tree
Hide file tree
Showing 34 changed files with 190 additions and 226 deletions.
10 changes: 5 additions & 5 deletions backend/sysproxy-rs/src/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -97,7 +97,7 @@ impl Sysproxy {
host = String::from("'") + &host;
}
if !host.ends_with('\'') && !host.ends_with('"') {
host = host + "'";
host += "'";
}
host
})
Expand Down Expand Up @@ -168,7 +168,7 @@ fn get_proxy(service: &str) -> Result<Sysproxy> {
})
}

fn strip_str<'a>(text: &'a str) -> &'a str {
fn strip_str(text: &str) -> &str {
text.strip_prefix('\'')
.unwrap_or(text)
.strip_suffix('\'')
Expand Down
13 changes: 8 additions & 5 deletions backend/sysproxy-rs/src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<&str>>()
.join(",");

Expand All @@ -84,7 +84,7 @@ impl Sysproxy {
}

pub fn set_bypass(&self, service: &str) -> Result<()> {
let domains = self.bypass.split(",").collect::<Vec<_>>();
let domains = self.bypass.split(',').collect::<Vec<_>>();
networksetup()
.args([["-setproxybypassdomains", service].to_vec(), domains].concat())
.status()?;
Expand All @@ -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,
}

Expand Down Expand Up @@ -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,
};
Expand All @@ -183,7 +186,7 @@ fn default_network_service() -> Result<String> {
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 {
Expand Down Expand Up @@ -213,7 +216,7 @@ fn get_service_by_device(device: String) -> Result<String> {
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;

Expand Down
6 changes: 4 additions & 2 deletions backend/tauri/src/cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}

Expand Down Expand Up @@ -306,7 +308,7 @@ pub async fn clash_api_get_proxy_delay(
) -> CmdResult<clash_api::DelayRes> {
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()),
}
}

Expand Down
7 changes: 4 additions & 3 deletions backend/tauri/src/config/clash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down Expand Up @@ -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(),
};
Expand All @@ -130,6 +130,7 @@ impl IClashTemp {
}
}

#[allow(unused)]
pub fn get_tun_device_ip(&self) -> String {
let config = &self.0;

Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions backend/tauri/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -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::*};
28 changes: 5 additions & 23 deletions backend/tauri/src/config/prfitem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,

Expand Down Expand Up @@ -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),
}
}
}
Expand Down Expand Up @@ -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}\""),
}
}

Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -231,7 +213,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));

Expand Down
32 changes: 17 additions & 15 deletions backend/tauri/src/config/profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -151,21 +151,23 @@ 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()
}

/// 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;

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);
}
}
Expand All @@ -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()) {
Expand Down Expand Up @@ -254,31 +256,31 @@ 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
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;
}
}

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,
};
Expand All @@ -298,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}\"");
}
Expand Down
1 change: 0 additions & 1 deletion backend/tauri/src/config/verge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ impl IVerge {
patch!(enable_clash_fields);

patch!(auto_log_clean);
patch!(window_size_position);
patch!(window_size_state);
}

Expand Down
Loading

0 comments on commit ba24602

Please sign in to comment.