refactor: replace type references with Self in various structs and methods for consistency

This commit is contained in:
Tunglies
2025-11-06 01:15:59 +08:00
Unverified
parent 70236f781c
commit 671ac2ebed
15 changed files with 102 additions and 103 deletions

View File

@@ -227,3 +227,4 @@ needless_raw_string_hashes = "deny" # Too many in existing code
or_fun_call = "deny"
cognitive_complexity = "deny"
useless_let_if_seq = "deny"
use_self = "deny"

View File

@@ -22,11 +22,11 @@ pub struct Config {
}
impl Config {
pub async fn global() -> &'static Config {
pub async fn global() -> &'static Self {
static CONFIG: OnceCell<Config> = OnceCell::const_new();
CONFIG
.get_or_init(|| async {
Config {
Self {
clash_config: Draft::new(IClashTemp::new().await),
verge_config: Draft::new(IVerge::new().await),
profiles_config: Draft::new(IProfiles::new().await),
@@ -60,7 +60,7 @@ impl Config {
if !cmd::system::is_admin().unwrap_or_default()
&& service::is_service_available().await.is_err()
{
let verge = Config::verge().await;
let verge = Self::verge().await;
verge.edit_draft(|d| {
d.enable_tun_mode = Some(false);
});
@@ -68,7 +68,7 @@ impl Config {
let _ = tray::Tray::global().update_menu().await;
// 分离数据获取和异步调用避免Send问题
let verge_data = Config::verge().await.latest_arc();
let verge_data = Self::verge().await.latest_arc();
logging_error!(Type::Core, verge_data.save_file().await);
}
@@ -154,7 +154,7 @@ impl Config {
ConfigType::Check => dirs::app_home_dir()?.join(files::CHECK_CONFIG),
};
let runtime = Config::runtime().await;
let runtime = Self::runtime().await;
let runtime_arc = runtime.latest_arc();
let config = runtime_arc
.config
@@ -168,7 +168,7 @@ impl Config {
pub async fn generate() -> Result<()> {
let (config, exists_keys, logs) = enhance::enhance().await;
Config::runtime().await.edit_draft(|d| {
Self::runtime().await.edit_draft(|d| {
*d = IRuntime {
config: Some(config),
exists_keys,
@@ -189,11 +189,11 @@ impl Config {
};
let operation = || async {
if Config::runtime().await.latest_arc().config.is_some() {
if Self::runtime().await.latest_arc().config.is_some() {
return Ok::<(), BackoffError<anyhow::Error>>(());
}
Config::generate().await.map_err(BackoffError::transient)
Self::generate().await.map_err(BackoffError::transient)
};
if let Err(e) = backoff::future::retry(backoff_strategy, operation).await {

View File

@@ -152,7 +152,7 @@ impl PrfOption {
impl PrfItem {
/// From partial item
/// must contain `itype`
pub async fn from(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> {
pub async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
if item.itype.is_none() {
bail!("type should not be null");
}
@@ -170,13 +170,13 @@ impl PrfItem {
let name = item.name.as_ref();
let desc = item.desc.as_ref();
let option = item.option.as_ref();
PrfItem::from_url(url, name, desc, option).await
Self::from_url(url, name, desc, option).await
}
"local" => {
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
let desc = item.desc.clone().unwrap_or_else(|| "".into());
let option = item.option.as_ref();
PrfItem::from_local(name, desc, file_data, option).await
Self::from_local(name, desc, file_data, option).await
}
typ => bail!("invalid profile item type \"{typ}\""),
}
@@ -189,7 +189,7 @@ impl PrfItem {
desc: String,
file_data: Option<String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
) -> Result<Self> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let opt_ref = option.as_ref();
@@ -201,31 +201,31 @@ impl PrfItem {
let mut groups = opt_ref.and_then(|o| o.groups.clone());
if merge.is_none() {
let merge_item = &mut PrfItem::from_merge(None)?;
let merge_item = &mut Self::from_merge(None)?;
profiles::profiles_append_item_safe(merge_item).await?;
merge = merge_item.uid.clone();
}
if script.is_none() {
let script_item = &mut PrfItem::from_script(None)?;
let script_item = &mut Self::from_script(None)?;
profiles::profiles_append_item_safe(script_item).await?;
script = script_item.uid.clone();
}
if rules.is_none() {
let rules_item = &mut PrfItem::from_rules()?;
let rules_item = &mut Self::from_rules()?;
profiles::profiles_append_item_safe(rules_item).await?;
rules = rules_item.uid.clone();
}
if proxies.is_none() {
let proxies_item = &mut PrfItem::from_proxies()?;
let proxies_item = &mut Self::from_proxies()?;
profiles::profiles_append_item_safe(proxies_item).await?;
proxies = proxies_item.uid.clone();
}
if groups.is_none() {
let groups_item = &mut PrfItem::from_groups()?;
let groups_item = &mut Self::from_groups()?;
profiles::profiles_append_item_safe(groups_item).await?;
groups = groups_item.uid.clone();
}
Ok(PrfItem {
Ok(Self {
uid: Some(uid),
itype: Some("local".into()),
name: Some(name),
@@ -256,7 +256,7 @@ impl PrfItem {
name: Option<&String>,
desc: Option<&String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
) -> Result<Self> {
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
let accept_invalid_certs =
@@ -393,32 +393,32 @@ impl PrfItem {
}
if merge.is_none() {
let merge_item = &mut PrfItem::from_merge(None)?;
let merge_item = &mut Self::from_merge(None)?;
profiles::profiles_append_item_safe(merge_item).await?;
merge = merge_item.uid.clone();
}
if script.is_none() {
let script_item = &mut PrfItem::from_script(None)?;
let script_item = &mut Self::from_script(None)?;
profiles::profiles_append_item_safe(script_item).await?;
script = script_item.uid.clone();
}
if rules.is_none() {
let rules_item = &mut PrfItem::from_rules()?;
let rules_item = &mut Self::from_rules()?;
profiles::profiles_append_item_safe(rules_item).await?;
rules = rules_item.uid.clone();
}
if proxies.is_none() {
let proxies_item = &mut PrfItem::from_proxies()?;
let proxies_item = &mut Self::from_proxies()?;
profiles::profiles_append_item_safe(proxies_item).await?;
proxies = proxies_item.uid.clone();
}
if groups.is_none() {
let groups_item = &mut PrfItem::from_groups()?;
let groups_item = &mut Self::from_groups()?;
profiles::profiles_append_item_safe(groups_item).await?;
groups = groups_item.uid.clone();
}
Ok(PrfItem {
Ok(Self {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
@@ -445,7 +445,7 @@ impl PrfItem {
/// ## Merge type (enhance)
/// create the enhanced item by using `merge` rule
pub fn from_merge(uid: Option<String>) -> Result<PrfItem> {
pub fn from_merge(uid: Option<String>) -> Result<Self> {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
} else {
@@ -453,7 +453,7 @@ impl PrfItem {
};
let file = format!("{id}.yaml").into();
Ok(PrfItem {
Ok(Self {
uid: Some(id),
itype: Some("merge".into()),
name: None,
@@ -471,14 +471,14 @@ impl PrfItem {
/// ## Script type (enhance)
/// create the enhanced item by using javascript quick.js
pub fn from_script(uid: Option<String>) -> Result<PrfItem> {
pub fn from_script(uid: Option<String>) -> Result<Self> {
let id = if let Some(uid) = uid {
uid
} else {
help::get_uid("s").into()
};
let file = format!("{id}.js").into(); // js ext
Ok(PrfItem {
Ok(Self {
uid: Some(id),
itype: Some("script".into()),
name: None,
@@ -495,11 +495,11 @@ impl PrfItem {
}
/// ## Rules type (enhance)
pub fn from_rules() -> Result<PrfItem> {
pub fn from_rules() -> Result<Self> {
let uid = help::get_uid("r").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(PrfItem {
Ok(Self {
uid: Some(uid),
itype: Some("rules".into()),
name: None,
@@ -516,11 +516,11 @@ impl PrfItem {
}
/// ## Proxies type (enhance)
pub fn from_proxies() -> Result<PrfItem> {
pub fn from_proxies() -> Result<Self> {
let uid = help::get_uid("p").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(PrfItem {
Ok(Self {
uid: Some(uid),
itype: Some("proxies".into()),
name: None,
@@ -537,11 +537,11 @@ impl PrfItem {
}
/// ## Groups type (enhance)
pub fn from_groups() -> Result<PrfItem> {
pub fn from_groups() -> Result<Self> {
let uid = help::get_uid("g").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(PrfItem {
Ok(Self {
uid: Some(uid),
itype: Some("groups".into()),
name: None,

View File

@@ -87,7 +87,7 @@ impl IProfiles {
}
/// 只修改currentvalid和chain
pub fn patch_config(&mut self, patch: &IProfiles) {
pub fn patch_config(&mut self, patch: &Self) {
if self.items.is_none() {
self.items = Some(vec![]);
}

View File

@@ -262,7 +262,7 @@ impl IVerge {
/// 验证并修正配置文件中的clash_core值
pub async fn validate_and_fix_config() -> Result<()> {
let config_path = dirs::verge_path()?;
let mut config = match help::read_yaml::<IVerge>(&config_path).await {
let mut config = match help::read_yaml::<Self>(&config_path).await {
Ok(config) => config,
Err(_) => Self::template(),
};
@@ -311,7 +311,7 @@ impl IVerge {
}
/// 配置修正后重新加载配置
async fn reload_config_after_fix(updated_config: IVerge) -> Result<()> {
async fn reload_config_after_fix(updated_config: Self) -> Result<()> {
logging!(
info,
Type::Config,
@@ -351,7 +351,7 @@ impl IVerge {
pub async fn new() -> Self {
match dirs::verge_path() {
Ok(path) => match help::read_yaml::<IVerge>(&path).await {
Ok(path) => match help::read_yaml::<Self>(&path).await {
Ok(mut config) => {
// compatibility
if let Some(start_page) = config.start_page.clone()
@@ -446,7 +446,7 @@ impl IVerge {
/// patch verge config
/// only save to file
#[allow(clippy::cognitive_complexity)]
pub fn patch_config(&mut self, patch: &IVerge) {
pub fn patch_config(&mut self, patch: &Self) {
macro_rules! patch {
($key: tt) => {
if patch.$key.is_some() {

View File

@@ -47,10 +47,10 @@ enum Operation {
impl Operation {
fn timeout(&self) -> u64 {
match self {
Operation::Upload => TIMEOUT_UPLOAD,
Operation::Download => TIMEOUT_DOWNLOAD,
Operation::List => TIMEOUT_LIST,
Operation::Delete => TIMEOUT_DELETE,
Self::Upload => TIMEOUT_UPLOAD,
Self::Download => TIMEOUT_DOWNLOAD,
Self::List => TIMEOUT_LIST,
Self::Delete => TIMEOUT_DELETE,
}
}
}
@@ -61,9 +61,9 @@ pub struct WebDavClient {
}
impl WebDavClient {
pub fn global() -> &'static WebDavClient {
pub fn global() -> &'static Self {
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new();
WEBDAV_CLIENT.get_or_init(|| WebDavClient {
WEBDAV_CLIENT.get_or_init(|| Self {
config: Arc::new(ArcSwapOption::new(None)),
clients: Arc::new(ArcSwap::new(Arc::new(HashMap::new()))),
})

View File

@@ -75,7 +75,7 @@ struct ProxyConfig {
static PROXY_MANAGER: Lazy<EventDrivenProxyManager> = Lazy::new(EventDrivenProxyManager::new);
impl EventDrivenProxyManager {
pub fn global() -> &'static EventDrivenProxyManager {
pub fn global() -> &'static Self {
&PROXY_MANAGER
}

View File

@@ -159,7 +159,7 @@ impl Handle {
.spawn(move || {
thread::sleep(timing::STARTUP_ERROR_DELAY);
let handle = Handle::global();
let handle = Self::global();
if handle.is_exiting() {
return;
}

View File

@@ -28,16 +28,16 @@ pub enum HotkeyFunction {
impl fmt::Display for HotkeyFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
HotkeyFunction::OpenOrCloseDashboard => "open_or_close_dashboard",
HotkeyFunction::ClashModeRule => "clash_mode_rule",
HotkeyFunction::ClashModeGlobal => "clash_mode_global",
HotkeyFunction::ClashModeDirect => "clash_mode_direct",
HotkeyFunction::ToggleSystemProxy => "toggle_system_proxy",
HotkeyFunction::ToggleTunMode => "toggle_tun_mode",
HotkeyFunction::EntryLightweightMode => "entry_lightweight_mode",
HotkeyFunction::Quit => "quit",
Self::OpenOrCloseDashboard => "open_or_close_dashboard",
Self::ClashModeRule => "clash_mode_rule",
Self::ClashModeGlobal => "clash_mode_global",
Self::ClashModeDirect => "clash_mode_direct",
Self::ToggleSystemProxy => "toggle_system_proxy",
Self::ToggleTunMode => "toggle_tun_mode",
Self::EntryLightweightMode => "entry_lightweight_mode",
Self::Quit => "quit",
#[cfg(target_os = "macos")]
HotkeyFunction::Hide => "hide",
Self::Hide => "hide",
};
write!(f, "{s}")
}
@@ -48,16 +48,16 @@ impl FromStr for HotkeyFunction {
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
"open_or_close_dashboard" => Ok(HotkeyFunction::OpenOrCloseDashboard),
"clash_mode_rule" => Ok(HotkeyFunction::ClashModeRule),
"clash_mode_global" => Ok(HotkeyFunction::ClashModeGlobal),
"clash_mode_direct" => Ok(HotkeyFunction::ClashModeDirect),
"toggle_system_proxy" => Ok(HotkeyFunction::ToggleSystemProxy),
"toggle_tun_mode" => Ok(HotkeyFunction::ToggleTunMode),
"entry_lightweight_mode" => Ok(HotkeyFunction::EntryLightweightMode),
"quit" => Ok(HotkeyFunction::Quit),
"open_or_close_dashboard" => Ok(Self::OpenOrCloseDashboard),
"clash_mode_rule" => Ok(Self::ClashModeRule),
"clash_mode_global" => Ok(Self::ClashModeGlobal),
"clash_mode_direct" => Ok(Self::ClashModeDirect),
"toggle_system_proxy" => Ok(Self::ToggleSystemProxy),
"toggle_tun_mode" => Ok(Self::ToggleTunMode),
"entry_lightweight_mode" => Ok(Self::EntryLightweightMode),
"quit" => Ok(Self::Quit),
#[cfg(target_os = "macos")]
"hide" => Ok(HotkeyFunction::Hide),
"hide" => Ok(Self::Hide),
_ => bail!("invalid hotkey function: {}", s),
}
}
@@ -75,8 +75,8 @@ pub enum SystemHotkey {
impl fmt::Display for SystemHotkey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
SystemHotkey::CmdQ => "CMD+Q",
SystemHotkey::CmdW => "CMD+W",
Self::CmdQ => "CMD+Q",
Self::CmdW => "CMD+W",
};
write!(f, "{s}")
}
@@ -86,8 +86,8 @@ impl fmt::Display for SystemHotkey {
impl SystemHotkey {
pub fn function(self) -> HotkeyFunction {
match self {
SystemHotkey::CmdQ => HotkeyFunction::Quit,
SystemHotkey::CmdW => HotkeyFunction::Hide,
Self::CmdQ => HotkeyFunction::Quit,
Self::CmdW => HotkeyFunction::Hide,
}
}
}

View File

@@ -84,7 +84,7 @@ async fn execute_sysproxy_command(args: Vec<std::string::String>) -> Result<()>
impl Default for Sysopt {
fn default() -> Self {
Sysopt {
Self {
initialed: AtomicBool::new(false),
update_sysproxy: AtomicBool::new(false),
reset_sysproxy: AtomicBool::new(false),

View File

@@ -46,7 +46,7 @@ singleton!(Timer, TIMER_INSTANCE);
impl Timer {
fn new() -> Self {
Timer {
Self {
delay_timer: Arc::new(RwLock::new(DelayTimerBuilder::default().build())),
timer_map: Arc::new(RwLock::new(HashMap::new())),
timer_count: AtomicU64::new(1),

View File

@@ -199,7 +199,7 @@ impl TrayState {
impl Default for Tray {
fn default() -> Self {
Tray {
Self {
last_menu_update: Mutex::new(None),
menu_updating: AtomicBool::new(false),
}

View File

@@ -70,7 +70,7 @@ pub trait AsyncChainItemFrom {
}
impl AsyncChainItemFrom for Option<ChainItem> {
async fn from_async(item: &PrfItem) -> Option<ChainItem> {
async fn from_async(item: &PrfItem) -> Self {
let itype = item.itype.as_ref()?.as_str();
let file = item.file.clone()?;
let uid = item.uid.clone().unwrap_or_else(|| "".into());
@@ -116,22 +116,21 @@ impl AsyncChainItemFrom for Option<ChainItem> {
}
impl ChainItem {
/// 内建支持一些脚本
pub fn builtin() -> Vec<(ChainSupport, ChainItem)> {
pub fn builtin() -> Vec<(ChainSupport, Self)> {
// meta 的一些处理
let meta_guard =
ChainItem::to_script("verge_meta_guard", include_str!("./builtin/meta_guard.js"));
Self::to_script("verge_meta_guard", include_str!("./builtin/meta_guard.js"));
// meta 1.13.2 alpn string 转 数组
let hy_alpn =
ChainItem::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
let hy_alpn = Self::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
// meta 的一些处理
let meta_guard_alpha =
ChainItem::to_script("verge_meta_guard", include_str!("./builtin/meta_guard.js"));
Self::to_script("verge_meta_guard", include_str!("./builtin/meta_guard.js"));
// meta 1.13.2 alpn string 转 数组
let hy_alpn_alpha =
ChainItem::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
Self::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
vec![
(ChainSupport::ClashMeta, hy_alpn),
@@ -154,8 +153,7 @@ impl ChainSupport {
match core {
Some(core) => matches!(
(self, core.as_str()),
(ChainSupport::ClashMeta, "verge-mihomo")
| (ChainSupport::ClashMetaAlpha, "verge-mihomo-alpha")
(Self::ClashMeta, "verge-mihomo") | (Self::ClashMetaAlpha, "verge-mihomo-alpha")
),
None => true,
}

View File

@@ -28,9 +28,9 @@ enum LightweightState {
impl From<u8> for LightweightState {
fn from(v: u8) -> Self {
match v {
1 => LightweightState::In,
2 => LightweightState::Exiting,
_ => LightweightState::Normal,
1 => Self::In,
2 => Self::Exiting,
_ => Self::Normal,
}
}
}

View File

@@ -36,24 +36,24 @@ pub enum Type {
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Type::Cmd => write!(f, "[Cmd]"),
Type::Core => write!(f, "[Core]"),
Type::Config => write!(f, "[Config]"),
Type::Setup => write!(f, "[Setup]"),
Type::System => write!(f, "[System]"),
Type::Service => write!(f, "[Service]"),
Type::Hotkey => write!(f, "[Hotkey]"),
Type::Window => write!(f, "[Window]"),
Type::Tray => write!(f, "[Tray]"),
Type::Timer => write!(f, "[Timer]"),
Type::Frontend => write!(f, "[Frontend]"),
Type::Backup => write!(f, "[Backup]"),
Type::File => write!(f, "[File]"),
Type::Lightweight => write!(f, "[Lightweight]"),
Type::Network => write!(f, "[Network]"),
Type::ProxyMode => write!(f, "[ProxMode]"),
Type::Validate => write!(f, "[Validate]"),
Type::ClashVergeRev => write!(f, "[ClashVergeRev]"),
Self::Cmd => write!(f, "[Cmd]"),
Self::Core => write!(f, "[Core]"),
Self::Config => write!(f, "[Config]"),
Self::Setup => write!(f, "[Setup]"),
Self::System => write!(f, "[System]"),
Self::Service => write!(f, "[Service]"),
Self::Hotkey => write!(f, "[Hotkey]"),
Self::Window => write!(f, "[Window]"),
Self::Tray => write!(f, "[Tray]"),
Self::Timer => write!(f, "[Timer]"),
Self::Frontend => write!(f, "[Frontend]"),
Self::Backup => write!(f, "[Backup]"),
Self::File => write!(f, "[File]"),
Self::Lightweight => write!(f, "[Lightweight]"),
Self::Network => write!(f, "[Network]"),
Self::ProxyMode => write!(f, "[ProxMode]"),
Self::Validate => write!(f, "[Validate]"),
Self::ClashVergeRev => write!(f, "[ClashVergeRev]"),
}
}
}