clippy all codes (#1214)

1. clippy code
2. add fmt and clippy check in ci
This commit is contained in:
Sijie.Sun
2025-08-10 22:56:41 +08:00
committed by GitHub
parent 0087ac3ffc
commit e43537939a
144 changed files with 1475 additions and 1531 deletions

View File

@@ -1,7 +1,10 @@
fn main() {
// enable thunk-rs when target os is windows and arch is x86_64 or i686
#[cfg(target_os = "windows")]
if !std::env::var("TARGET").unwrap_or_default().contains("aarch64"){
thunk::thunk();
}
}
fn main() {
// enable thunk-rs when target os is windows and arch is x86_64 or i686
#[cfg(target_os = "windows")]
if !std::env::var("TARGET")
.unwrap_or_default()
.contains("aarch64")
{
thunk::thunk();
}
}

View File

@@ -25,7 +25,7 @@ fn load_geoip_db(geoip_db: Option<String>) -> Option<maxminddb::Reader<Vec<u8>>>
match maxminddb::Reader::open_readfile(&path) {
Ok(reader) => {
tracing::info!("Successfully loaded GeoIP2 database from {}", path);
return Some(reader);
Some(reader)
}
Err(err) => {
tracing::debug!("Failed to load GeoIP2 database from {}: {}", path, err);
@@ -207,10 +207,8 @@ impl ClientManager {
let region = city.subdivisions.map(|r| {
r.iter()
.map(|x| x.names.as_ref())
.flatten()
.map(|x| x.get("zh-CN").or_else(|| x.get("en")))
.flatten()
.filter_map(|x| x.names.as_ref())
.filter_map(|x| x.get("zh-CN").or_else(|| x.get("en")))
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")

View File

@@ -94,14 +94,10 @@ impl SessionRpcService {
return Ok(HeartbeatResponse {});
};
let machine_id: uuid::Uuid =
let machine_id: uuid::Uuid = req.machine_id.map(Into::into).ok_or(anyhow::anyhow!(
"Machine id is not set correctly, expect uuid but got: {:?}",
req.machine_id
.clone()
.map(Into::into)
.ok_or(anyhow::anyhow!(
"Machine id is not set correctly, expect uuid but got: {:?}",
req.machine_id
))?;
))?;
let user_id = storage
.db()
@@ -121,7 +117,7 @@ impl SessionRpcService {
if data.req.replace(req.clone()).is_none() {
assert!(data.storage_token.is_none());
data.storage_token = Some(StorageToken {
token: req.user_token.clone().into(),
token: req.user_token.clone(),
client_url: data.client_url.clone(),
machine_id,
user_id,

View File

@@ -34,7 +34,7 @@ impl TryFrom<WeakRefStorage> for Storage {
type Error = ();
fn try_from(weak: Weak<StorageInner>) -> Result<Self, Self::Error> {
weak.upgrade().map(|inner| Storage(inner)).ok_or(())
weak.upgrade().map(Storage).ok_or(())
}
}
@@ -51,9 +51,7 @@ impl Storage {
machine_id: &uuid::Uuid,
client_url: &url::Url,
) {
map.remove_if(&machine_id, |_, v| {
v.storage_token.client_url == *client_url
});
map.remove_if(machine_id, |_, v| v.storage_token.client_url == *client_url);
}
fn update_mid_to_client_info_map(
@@ -74,11 +72,7 @@ impl Storage {
}
pub fn update_client(&self, stoken: StorageToken, report_time: i64) {
let inner = self
.0
.user_clients_map
.entry(stoken.user_id)
.or_insert_with(DashMap::new);
let inner = self.0.user_clients_map.entry(stoken.user_id).or_default();
let client_info = ClientInfo {
storage_token: stoken.clone(),

View File

@@ -151,7 +151,7 @@ async fn get_dual_stack_listener(
} else {
None
};
let v4_listener = if let Ok(_) = local_ipv4().await {
let v4_listener = if local_ipv4().await.is_ok() {
get_listener_by_url(&format!("{}://0.0.0.0:{}", protocol, port).parse().unwrap()).ok()
} else {
None

View File

@@ -137,7 +137,7 @@ mod post {
mod get {
use crate::restful::{
captcha::{
captcha::spec::SpecCaptcha,
builder::spec::SpecCaptcha,
extension::{axum_tower_sessions::CaptchaAxumTowerSessionExt as _, CaptchaUtil},
NewCaptcha as _,
},

View File

@@ -46,22 +46,22 @@ pub(crate) struct Captcha {
/// 验证码文本类型 The character type of the captcha
pub enum CaptchaType {
/// 字母数字混合
TypeDefault = 1,
Default = 1,
/// 纯数字
TypeOnlyNumber,
OnlyNumber,
/// 纯字母
TypeOnlyChar,
OnlyChar,
/// 纯大写字母
TypeOnlyUpper,
OnlyUpper,
/// 纯小写字母
TypeOnlyLower,
OnlyLower,
/// 数字大写字母
TypeNumAndUpper,
NumAndUpper,
}
/// 内置字体 Fonts shipped with the library
@@ -92,29 +92,29 @@ impl Captcha {
/// 生成随机验证码
pub fn alphas(&mut self) -> Vec<char> {
let mut cs = vec!['\0'; self.len];
for i in 0..self.len {
for cs_i in cs.iter_mut() {
match self.char_type {
CaptchaType::TypeDefault => cs[i] = self.randoms.alpha(),
CaptchaType::TypeOnlyNumber => {
cs[i] = self.randoms.alpha_under(self.randoms.num_max_index)
CaptchaType::Default => *cs_i = self.randoms.alpha(),
CaptchaType::OnlyNumber => {
*cs_i = self.randoms.alpha_under(self.randoms.num_max_index)
}
CaptchaType::TypeOnlyChar => {
cs[i] = self
CaptchaType::OnlyChar => {
*cs_i = self
.randoms
.alpha_between(self.randoms.char_min_index, self.randoms.char_max_index)
}
CaptchaType::TypeOnlyUpper => {
cs[i] = self
CaptchaType::OnlyUpper => {
*cs_i = self
.randoms
.alpha_between(self.randoms.upper_min_index, self.randoms.upper_max_index)
}
CaptchaType::TypeOnlyLower => {
cs[i] = self
CaptchaType::OnlyLower => {
*cs_i = self
.randoms
.alpha_between(self.randoms.lower_min_index, self.randoms.lower_max_index)
}
CaptchaType::TypeNumAndUpper => {
cs[i] = self.randoms.alpha_under(self.randoms.upper_max_index)
CaptchaType::NumAndUpper => {
*cs_i = self.randoms.alpha_under(self.randoms.upper_max_index)
}
}
}
@@ -142,7 +142,7 @@ impl Captcha {
}
}
pub fn get_font(&mut self) -> Arc<Font> {
pub fn get_font(&'_ mut self) -> Arc<Font<'_>> {
if let Some(font) = font::get_font(&self.font_name) {
font
} else {
@@ -185,6 +185,7 @@ where
/// 特别地/In particular:
///
/// - 对算术验证码[ArithmeticCaptcha](crate::captcha::arithmetic::ArithmeticCaptcha)而言,这里的`len`是验证码中数字的数量。
///
/// For [ArithmeticCaptcha](crate::captcha::arithmetic::ArithmeticCaptcha), the `len` presents the count of the digits
/// in the Captcha.
fn with_size_and_len(width: i32, height: i32, len: usize) -> Self;
@@ -226,7 +227,7 @@ impl NewCaptcha for Captcha {
let len = 5;
let width = 130;
let height = 48;
let char_type = CaptchaType::TypeDefault;
let char_type = CaptchaType::Default;
let chars = None;
Self {

View File

@@ -1,6 +1,4 @@
use rand::{random};
use rand::random;
/// 随机数工具类
pub(crate) struct Randoms {

View File

@@ -10,7 +10,7 @@ use axum::response::Response;
use std::fmt::Debug;
use tower_sessions::Session;
const CAPTCHA_KEY: &'static str = "ez-captcha";
const CAPTCHA_KEY: &str = "ez-captcha";
/// Axum & Tower_Sessions
#[async_trait]
@@ -32,7 +32,7 @@ pub trait CaptchaAxumTowerSessionStaticExt {
/// Verify the Captcha code, and return whether user's code is correct.
async fn ver(code: &str, session: &Session) -> bool {
match session.get::<String>(CAPTCHA_KEY).await {
Ok(Some(ans)) => ans.to_ascii_lowercase() == code.to_ascii_lowercase(),
Ok(Some(ans)) => ans.eq_ignore_ascii_case(code),
_ => false,
}
}

View File

@@ -1,7 +1,7 @@
pub mod axum_tower_sessions;
use super::base::captcha::AbstractCaptcha;
use super::captcha::spec::SpecCaptcha;
use super::builder::spec::SpecCaptcha;
use super::{CaptchaFont, NewCaptcha};
/// 验证码工具类 - Captcha Utils

View File

@@ -117,7 +117,7 @@
#![allow(dead_code)]
pub(crate) mod base;
pub mod captcha;
pub mod builder;
pub mod extension;
mod utils;

View File

@@ -32,21 +32,24 @@ impl From<(u8, u8, u8)> for Color {
}
}
impl Into<(u8, u8, u8, u8)> for Color {
fn into(self) -> (u8, u8, u8, u8) {
impl From<Color> for (u8, u8, u8, u8) {
fn from(val: Color) -> Self {
(
(self.0 * 255.0) as u8,
(self.1 * 255.0) as u8,
(self.2 * 255.0) as u8,
(self.3 * 255.0) as u8,
(val.0 * 255.0) as u8,
(val.1 * 255.0) as u8,
(val.2 * 255.0) as u8,
(val.3 * 255.0) as u8,
)
}
}
impl Into<u32> for Color {
fn into(self) -> u32 {
let color: (u8, u8, u8, u8) = self.into();
(color.0 as u32) << 24 + (color.1 as u32) << 16 + (color.2 as u32) << 8 + (color.3 as u32)
impl From<Color> for u32 {
fn from(val: Color) -> Self {
let color: (u8, u8, u8, u8) = val.into();
(color.0 as u32)
<< (24 + (color.1 as u32))
<< (16 + (color.2 as u32))
<< (8 + (color.3 as u32))
}
}

View File

@@ -11,7 +11,7 @@ struct FontAssets;
// pub(crate) static ref FONTS: RwLock<HashMap<String, Arc<Font>>> = Default::default();
// }
pub fn get_font(font_name: &str) -> Option<Arc<Font>> {
pub fn get_font(font_name: &'_ str) -> Option<Arc<Font<'_>>> {
// let fonts_cell = FONTS.get_or_init(|| Default::default());
// let guard = fonts_cell.read();
//
@@ -31,7 +31,7 @@ pub fn get_font(font_name: &str) -> Option<Arc<Font>> {
// }
}
pub fn load_font(font_name: &str) -> Result<Option<Font>, Box<dyn Error>> {
pub fn load_font(font_name: &'_ str) -> Result<Option<Font<'_>>, Box<dyn Error>> {
match FontAssets::get(font_name) {
Some(assets) => {
let font = Font::try_from_vec(Vec::from(assets.data)).unwrap();

View File

@@ -143,7 +143,7 @@ impl RestfulServer {
return Err((StatusCode::UNAUTHORIZED, other_error("No such user").into()));
};
let machines = client_mgr.list_machine_by_user_id(user.id().clone()).await;
let machines = client_mgr.list_machine_by_user_id(user.id()).await;
Ok(GetSummaryJsonResp {
device_count: machines.len() as u32,

View File

@@ -8,7 +8,7 @@ use axum_login::AuthUser;
use easytier::launcher::NetworkConfig;
use easytier::proto::common::Void;
use easytier::proto::rpc_types::controller::BaseController;
use easytier::proto::web::*;
use easytier::proto::{self, web::*};
use crate::client_manager::session::{Location, Session};
use crate::client_manager::ClientManager;
@@ -85,7 +85,7 @@ impl NetworkApi {
let Some(user_id) = auth_session.user.as_ref().map(|x| x.id()) else {
return Err((
StatusCode::UNAUTHORIZED,
other_error(format!("No user id found")).into(),
other_error("No user id found".to_string()).into(),
));
};
Ok(user_id)
@@ -108,7 +108,7 @@ impl NetworkApi {
let Some(token) = result.get_token().await else {
return Err((
StatusCode::UNAUTHORIZED,
other_error(format!("No token reported")).into(),
other_error("No token reported".to_string()).into(),
));
};
@@ -120,7 +120,7 @@ impl NetworkApi {
{
return Err((
StatusCode::FORBIDDEN,
other_error(format!("Token mismatch")).into(),
other_error("Token mismatch".to_string()).into(),
));
}
@@ -177,7 +177,7 @@ impl NetworkApi {
.insert_or_update_user_network_config(
auth_session.user.as_ref().unwrap().id(),
machine_id,
resp.inst_id.clone().unwrap_or_default().into(),
resp.inst_id.unwrap_or_default().into(),
serde_json::to_string(&config).unwrap(),
)
.await
@@ -248,7 +248,7 @@ impl NetworkApi {
.await
.map_err(convert_rpc_error)?;
let running_inst_ids = ret.inst_ids.clone().into_iter().map(Into::into).collect();
let running_inst_ids = ret.inst_ids.clone().into_iter().collect();
// collect networks that are disabled
let disabled_inst_ids = client_mgr
@@ -261,7 +261,7 @@ impl NetworkApi {
.await
.map_err(convert_db_error)?
.iter()
.filter_map(|x| x.network_instance_id.clone().try_into().ok())
.map(|x| Into::<proto::common::Uuid>::into(x.network_instance_id.clone()))
.collect::<Vec<_>>();
Ok(ListNetworkInstanceIdsJsonResp {
@@ -330,9 +330,8 @@ impl NetworkApi {
// not implement disable all
return Err((
StatusCode::NOT_IMPLEMENTED,
other_error(format!("Not implemented")).into(),
))
.into();
other_error("Not implemented".to_string()).into(),
));
};
let sess = Self::get_session_by_machine_id(&auth_session, &client_mgr, &machine_id).await?;

View File

@@ -76,32 +76,32 @@ impl Backend {
pub async fn register_new_user(&self, new_user: &RegisterNewUser) -> anyhow::Result<()> {
let hashed_password = password_auth::generate_hash(new_user.credentials.password.as_str());
let mut txn = self.db.orm_db().begin().await?;
let txn = self.db.orm_db().begin().await?;
entity::users::ActiveModel {
username: Set(new_user.credentials.username.clone()),
password: Set(hashed_password.clone()),
..Default::default()
}
.save(&mut txn)
.save(&txn)
.await?;
entity::users_groups::ActiveModel {
user_id: Set(entity::users::Entity::find()
.filter(entity::users::Column::Username.eq(new_user.credentials.username.as_str()))
.one(&mut txn)
.one(&txn)
.await?
.unwrap()
.id),
group_id: Set(entity::groups::Entity::find()
.filter(entity::groups::Column::Name.eq("users"))
.one(&mut txn)
.one(&txn)
.await?
.unwrap()
.id),
..Default::default()
}
.save(&mut txn)
.save(&txn)
.await?;
txn.commit().await?;

View File

@@ -52,9 +52,7 @@ pub fn build_router(api_host: Option<url::Url>) -> Router {
router
};
let router = router.fallback_service(service);
router
router.fallback_service(service)
}
pub struct WebServer {