Skip to content

Commit

Permalink
refactor: use anyhow to handle error
Browse files Browse the repository at this point in the history
  • Loading branch information
zzzgydi committed Feb 27, 2022
1 parent ade34f5 commit dbf380a
Show file tree
Hide file tree
Showing 9 changed files with 224 additions and 193 deletions.
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ build = "build.rs"
tauri-build = { version = "1.0.0-rc.3", features = [] }

[dependencies]
anyhow = "1.0"
dirs = "4.0.0"
dunce = "1.0.2"
chrono = "0.4.19"
Expand Down
142 changes: 76 additions & 66 deletions src-tauri/src/cmds.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
use crate::{
core::{ClashInfo, ProfileItem, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState},
utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig},
utils::{dirs, fetch::fetch_profile, sysopt::SysProxyConfig},
};
use anyhow::Result;
use serde_yaml::Mapping;
use std::{path::PathBuf, process::Command};
use tauri::{api, State};

/// wrap the anyhow error
/// transform the error to String
macro_rules! wrap_err {
($stat: expr) => {
match $stat {
Ok(a) => Ok(a),
Err(err) => {
log::error!("{}", err.to_string());
Err(format!("{}", err.to_string()))
}
}
};
}

/// return the string literal error
macro_rules! ret_err {
($str: literal) => {
return Err($str.into())
};
}

/// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock
#[tauri::command]
pub fn get_profiles(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
match profiles_state.0.lock() {
Ok(profiles) => Ok(profiles.clone()),
Err(_) => Err("failed to get profiles lock".into()),
}
let profiles = profiles_state.0.lock().unwrap();
Ok(profiles.clone())
}

/// synchronize data irregularly
#[tauri::command]
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
match profiles_state.0.lock() {
Ok(mut profiles) => profiles.sync_file(),
Err(_) => Err("failed to get profiles lock".into()),
}
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.sync_file())
}

/// import the profile from url
Expand All @@ -36,7 +53,7 @@ pub async fn import_profile(
) -> Result<(), String> {
let result = fetch_profile(&url, with_proxy).await?;
let mut profiles = profiles_state.0.lock().unwrap();
profiles.import_from_url(url, result)
wrap_err!(profiles.import_from_url(url, result))
}

/// new a profile
Expand All @@ -49,7 +66,7 @@ pub async fn new_profile(
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
profiles.append_item(name, desc)?;
wrap_err!(profiles.append_item(name, desc))?;
Ok(())
}

Expand All @@ -66,34 +83,34 @@ pub async fn update_profile(
Ok(mut profile) => {
let items = profile.items.take().unwrap_or(vec![]);
if index >= items.len() {
return Err("the index out of bound".into());
ret_err!("the index out of bound");
}
let url = match &items[index].url {
Some(u) => u.clone(),
None => return Err("failed to update profile for `invalid url`".into()),
None => ret_err!("failed to update profile for `invalid url`"),
};
profile.items = Some(items);
url
}
Err(_) => return Err("failed to get profiles lock".into()),
Err(_) => ret_err!("failed to get profiles lock"),
};

let result = fetch_profile(&url, with_proxy).await?;

match profiles_state.0.lock() {
Ok(mut profiles) => {
profiles.update_item(index, result)?;
wrap_err!(profiles.update_item(index, result))?;

// reactivate the profile
let current = profiles.current.clone().unwrap_or(0);
if current == index {
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
wrap_err!(profiles.activate(&clash))
} else {
Ok(())
}
}
Err(_) => Err("failed to get profiles lock".into()),
Err(_) => ret_err!("failed to get profiles lock"),
}
}

Expand All @@ -105,14 +122,10 @@ pub fn select_profile(
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.put_current(index))?;

match profiles.put_current(index) {
Ok(()) => {
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
}
Err(err) => Err(err),
}
let clash = clash_state.0.lock().unwrap();
wrap_err!(profiles.activate(&clash))
}

/// delete profile item
Expand All @@ -123,16 +136,13 @@ pub fn delete_profile(
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
match profiles.delete_item(index) {
Ok(change) => match change {
true => {
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
}
false => Ok(()),
},
Err(err) => Err(err),

if wrap_err!(profiles.delete_item(index))? {
let clash = clash_state.0.lock().unwrap();
wrap_err!(profiles.activate(&clash))?;
}

Ok(())
}

/// patch the profile config
Expand All @@ -142,10 +152,8 @@ pub fn patch_profile(
profile: ProfileItem,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
match profiles_state.0.lock() {
Ok(mut profiles) => profiles.patch_item(index, profile),
Err(_) => Err("can not get profiles lock".into()),
}
let mut profiles = profiles_state.0.lock().unwrap();
wrap_err!(profiles.patch_item(index, profile))
}

/// run vscode command to edit the profile
Expand All @@ -156,19 +164,34 @@ pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> R

if index >= items.len() {
profiles.items = Some(items);
return Err("the index out of bound".into());
ret_err!("the index out of bound");
}

let file = items[index].file.clone().unwrap_or("".into());
profiles.items = Some(items);

let path = app_home_dir().join("profiles").join(file);
let path = dirs::app_profiles_dir().join(file);
if !path.exists() {
return Err("the file not found".into());
ret_err!("the file not found");
}

// use vscode first
if let Ok(code) = which::which("code") {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;

return match Command::new(code)
.creation_flags(0x08000000)
.arg(path)
.spawn()
{
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()),
};
}

#[cfg(not(target_os = "windows"))]
return match Command::new(code).arg(path).spawn() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()),
Expand All @@ -187,23 +210,15 @@ pub fn restart_sidecar(
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();

match clash.restart_sidecar(&mut profiles) {
Ok(_) => Ok(()),
Err(err) => {
log::error!("{}", err);
Err(err)
}
}
wrap_err!(clash.restart_sidecar(&mut profiles))
}

/// get the clash core info from the state
/// the caller can also get the infomation by clash's api
#[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
match clash_state.0.lock() {
Ok(clash) => Ok(clash.info.clone()),
Err(_) => Err("failed to get clash lock".into()),
}
let clash = clash_state.0.lock().unwrap();
Ok(clash.info.clone())
}

/// update the clash core config
Expand All @@ -219,26 +234,21 @@ pub fn patch_clash_config(
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
clash.patch_config(payload, &mut verge, &mut profiles)
wrap_err!(clash.patch_config(payload, &mut verge, &mut profiles))
}

/// get the system proxy
#[tauri::command]
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
match SysProxyConfig::get_sys() {
Ok(value) => Ok(value),
Err(err) => Err(err.to_string()),
}
wrap_err!(SysProxyConfig::get_sys())
}

/// get the current proxy config
/// which may not the same as system proxy
#[tauri::command]
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
match verge_state.0.lock() {
Ok(verge) => Ok(verge.cur_sysproxy.clone()),
Err(_) => Err("failed to get verge lock".into()),
}
let verge = verge_state.0.lock().unwrap();
Ok(verge.cur_sysproxy.clone())
}

/// get the verge config
Expand Down Expand Up @@ -266,16 +276,16 @@ pub fn patch_verge_config(
let tun_mode = payload.enable_tun_mode.clone();

let mut verge = verge_state.0.lock().unwrap();
verge.patch_config(payload)?;
wrap_err!(verge.patch_config(payload))?;

// change tun mode
if tun_mode.is_some() {
let mut clash = clash_state.0.lock().unwrap();
let profiles = profiles_state.0.lock().unwrap();

clash.tun_mode(tun_mode.unwrap())?;
wrap_err!(clash.tun_mode(tun_mode.unwrap()))?;
clash.update_config();
profiles.activate(&clash)?;
wrap_err!(profiles.activate(&clash))?;
}

Ok(())
Expand All @@ -290,14 +300,14 @@ pub fn kill_sidecars() {
/// open app config dir
#[tauri::command]
pub fn open_app_dir() -> Result<(), String> {
let app_dir = app_home_dir();
let app_dir = dirs::app_home_dir();
open_path_cmd(app_dir, "failed to open app dir")
}

/// open logs dir
#[tauri::command]
pub fn open_logs_dir() -> Result<(), String> {
let log_dir = app_home_dir().join("logs");
let log_dir = dirs::app_logs_dir();
open_path_cmd(log_dir, "failed to open logs dir")
}

Expand Down
Loading

0 comments on commit dbf380a

Please sign in to comment.