diff --git a/ceres/src/api_service/mono_api_service.rs b/ceres/src/api_service/mono_api_service.rs index 8e210ee79..f171dda77 100644 --- a/ceres/src/api_service/mono_api_service.rs +++ b/ceres/src/api_service/mono_api_service.rs @@ -232,7 +232,7 @@ impl ApiHandler for MonoApiService { } impl MonoApiService { - pub async fn merge_mr(&self, user_id: String, mr: mega_mr::Model) -> Result<(), MegaError> { + pub async fn merge_mr(&self, username: &str, mr: mega_mr::Model) -> Result<(), MegaError> { let storage = self.storage.services.mono_storage.clone(); let refs = storage.get_ref(&mr.path).await.unwrap().unwrap(); @@ -261,7 +261,7 @@ impl MonoApiService { // add conversation self.storage .issue_storage() - .add_conversation(&mr.link, &user_id, None, ConvTypeEnum::Merged) + .add_conversation(&mr.link, username, None, ConvTypeEnum::Merged) .await .unwrap(); // update mr status last @@ -434,7 +434,7 @@ mod test { let cloned_path = full_path.clone(); // Clone full_path let name = cloned_path.file_name().unwrap().to_str().unwrap(); full_path.pop(); - println!("name: {}, path: {:?}", name, full_path); + println!("name: {name}, path: {full_path:?}"); } } } diff --git a/ceres/src/pack/import_repo.rs b/ceres/src/pack/import_repo.rs index 9e1037ed3..d7d8f0bf7 100644 --- a/ceres/src/pack/import_repo.rs +++ b/ceres/src/pack/import_repo.rs @@ -122,7 +122,7 @@ impl PackHandler for ImportRepo { let entry = c.into(); entry_tx.send(entry).await.unwrap(); } - Err(err) => eprintln!("Error: {:?}", err), + Err(err) => eprintln!("Error: {err:?}"), } } tracing::info!("send commits end"); @@ -135,7 +135,7 @@ impl PackHandler for ImportRepo { let entry = t.into(); entry_tx.send(entry).await.unwrap(); } - Err(err) => eprintln!("Error: {:?}", err), + Err(err) => eprintln!("Error: {err:?}"), } } tracing::info!("send trees end"); @@ -145,7 +145,7 @@ impl PackHandler for ImportRepo { while let Some(model) = bid_stream.next().await { match model { Ok(m) => bids.push(m.blob_id), - Err(err) => eprintln!("Error: {:?}", err), + Err(err) => eprintln!("Error: {err:?}"), } } @@ -164,7 +164,7 @@ impl PackHandler for ImportRepo { let entry: Entry = b.into(); sender_clone.send(entry).await.unwrap(); } - Err(err) => eprintln!("Error: {:?}", err), + Err(err) => eprintln!("Error: {err:?}"), } } // }); @@ -383,7 +383,7 @@ impl ImportRepo { let new_commit = Commit::from_tree_id( save_trees.back().unwrap().id, vec![SHA1::from_str(&root_ref.ref_commit_hash).unwrap()], - &format!("\n{}", commit_msg), + &format!("\n{commit_msg}"), ); let save_trees: Vec = save_trees @@ -415,7 +415,7 @@ mod test { let path = PathBuf::from("/third-party/crates/tokio/tokio-console"); let ancestors: Vec<_> = path.ancestors().collect(); for path in ancestors.into_iter() { - println!("{:?}", path); + println!("{path:?}"); } } } diff --git a/ceres/src/protocol/smart.rs b/ceres/src/protocol/smart.rs index 996bf77db..d15add8c1 100644 --- a/ceres/src/protocol/smart.rs +++ b/ceres/src/protocol/smart.rs @@ -70,10 +70,10 @@ impl SmartProtocol { "HEAD" }; let cap_list = match service_type { - ServiceType::UploadPack => format!("{}{}", UPLOAD_CAP_LIST, COMMON_CAP_LIST), - ServiceType::ReceivePack => format!("{}{}", RECEIVE_CAP_LIST, COMMON_CAP_LIST), + ServiceType::UploadPack => format!("{UPLOAD_CAP_LIST}{COMMON_CAP_LIST}"), + ServiceType::ReceivePack => format!("{RECEIVE_CAP_LIST}{COMMON_CAP_LIST}"), }; - let pkt_line = format!("{}{}{}{}{}{}", head_hash, SP, name, NUL, cap_list, LF); + let pkt_line = format!("{head_hash}{SP}{name}{NUL}{cap_list}{LF}"); let mut ref_list = vec![pkt_line]; for git_ref in git_refs { @@ -152,7 +152,7 @@ impl SmartProtocol { for hash in &have { if pack_handler.check_commit_exist(hash).await { - add_pkt_line_string(&mut protocol_buf, format!("ACK {} common\n", hash)); + add_pkt_line_string(&mut protocol_buf, format!("ACK {hash} common\n")); if last_common_commit.is_empty() { last_common_commit = hash.to_string(); } @@ -174,7 +174,7 @@ impl SmartProtocol { if self.capabilities.contains(&Capability::NoDone) { // If multi_ack_detailed and no-done are both present, then the sender is free to immediately send a pack // following its first "ACK obj-id ready" message. - add_pkt_line_string(&mut protocol_buf, format!("ACK {} ready\n", hash)); + add_pkt_line_string(&mut protocol_buf, format!("ACK {hash} ready\n")); } } } else { @@ -183,7 +183,7 @@ impl SmartProtocol { let (_, rx) = tokio::sync::mpsc::channel::>(1); pack_data = ReceiverStream::new(rx); } - add_pkt_line_string(&mut protocol_buf, format!("ACK {} \n", last_common_commit)); + add_pkt_line_string(&mut protocol_buf, format!("ACK {last_common_commit} \n")); } Ok((pack_data, protocol_buf)) } @@ -299,7 +299,7 @@ impl SmartProtocol { pub fn build_smart_reply(&self, ref_list: &Vec, service: String) -> BytesMut { let mut pkt_line_stream = BytesMut::new(); if self.transport_protocol == TransportProtocol::Http { - add_pkt_line_string(&mut pkt_line_stream, format!("# service={}\n", service)); + add_pkt_line_string(&mut pkt_line_stream, format!("# service={service}\n")); pkt_line_stream.put(&PKT_LINE_END_MARKER[..]); } @@ -385,7 +385,7 @@ pub fn read_pkt_line(bytes: &mut Bytes) -> (usize, Bytes) { } let pkt_length = bytes.copy_to_bytes(4); let pkt_length = usize::from_str_radix(core::str::from_utf8(&pkt_length).unwrap(), 16) - .unwrap_or_else(|_| panic!("{:?} is not a valid digit?", pkt_length)); + .unwrap_or_else(|_| panic!("{pkt_length:?} is not a valid digit?")); if pkt_length == 0 { return (0, Bytes::new()); } diff --git a/common/src/config.rs b/common/src/config.rs index e6f151a71..c4ee14f0a 100644 --- a/common/src/config.rs +++ b/common/src/config.rs @@ -171,7 +171,7 @@ impl Default for Config { .lines() .map(|line| { if line.starts_with("base_dir ") { - format!("base_dir = {:?}", base_dir) + format!("base_dir = {base_dir:?}") } else { line.to_string() } @@ -257,7 +257,7 @@ fn traverse_config(key: &str, value: &c::Value, f: &impl Fn(&str, &c::Value)) { let new_key = if key.is_empty() { k.clone() } else { - format!("{}.{}", key, k) + format!("{key}.{k}") }; traverse_config(&new_key, v, f); } @@ -424,7 +424,7 @@ impl PackConfig { let percentage: f64 = size_str .trim_end_matches('%') .parse() - .map_err(|_| format!("Invalid percentage: {}", size_str))?; + .map_err(|_| format!("Invalid percentage: {size_str}"))?; let total_mem = fn_get_total_capacity()?; return Ok((total_mem as f64 * percentage / 100.0) as usize); @@ -457,7 +457,7 @@ impl PackConfig { let value: f64 = number .parse() - .map_err(|_| format!("Invalid size: {}", size_str))?; + .map_err(|_| format!("Invalid size: {size_str}"))?; let unit = chars.collect::().to_uppercase(); // For compatibility, @@ -476,7 +476,7 @@ impl PackConfig { "MIB" | "M" => value * 1_024.0 * 1_024.0, "GIB" | "G" => value * 1_024.0 * 1_024.0 * 1_024.0, "TIB" | "T" => value * 1_099_511_627_776.0, - _ => Err(format!("Invalid unit: {}", unit))?, + _ => Err(format!("Invalid unit: {unit}"))?, }; Ok(bytes as usize) diff --git a/common/src/enums.rs b/common/src/enums.rs index 640389c00..78ca64cd3 100644 --- a/common/src/enums.rs +++ b/common/src/enums.rs @@ -21,7 +21,7 @@ impl FromStr for SupportOauthType { fn from_str(s: &str) -> Result { match s { "github" => Ok(Self::GitHub), - _ => Err(format!("'{}' is not a valid oauth type", s)), + _ => Err(format!("'{s}' is not a valid oauth type")), } } } diff --git a/common/src/utils.rs b/common/src/utils.rs index 989266eba..1487cd326 100644 --- a/common/src/utils.rs +++ b/common/src/utils.rs @@ -44,7 +44,7 @@ pub fn generate_rich_text(content: &str) -> String { } pub fn mr_ref_name(mr_link: &str) -> String { - format!("refs/mr/{}", mr_link) + format!("refs/mr/{mr_link}") } /// Format commit message with GPG signature
@@ -54,10 +54,10 @@ pub fn mr_ref_name(mr_link: &str) -> String { pub fn format_commit_msg(msg: &str, gpg_sig: Option<&str>) -> String { match gpg_sig { None => { - format!("\n{}", msg) + format!("\n{msg}") } Some(gpg) => { - format!("{}\n\n{}", gpg, msg) + format!("{gpg}\n\n{msg}") } } } @@ -96,8 +96,7 @@ pub fn check_conventional_commits_message(msg: &str) -> bool { let unicode_pattern = r"\p{L}\p{N}\p{P}\p{S}\p{Z}"; // type only support characters&numbers, others fields support all unicode characters let regex_str = format!( - r"^(?P[\p{{L}}\p{{N}}_-]+)(?:\((?P[{unicode}]+)\))?!?: (?P[{unicode}]+)$", - unicode = unicode_pattern + r"^(?P[\p{{L}}\p{{N}}_-]+)(?:\((?P[{unicode_pattern}]+)\))?!?: (?P[{unicode_pattern}]+)$", ); let re = Regex::new(®ex_str).unwrap(); @@ -116,7 +115,7 @@ pub fn check_conventional_commits_message(msg: &str) -> bool { let commit_type = commit_type.unwrap(); if !RECOMMENDED_TYPES.contains(&commit_type.to_lowercase().as_str()) { - println!("`{}` is not a recommended commit type, refer to https://www.conventionalcommits.org/en/v1.0.0/ for more information", commit_type); + println!("`{commit_type}` is not a recommended commit type, refer to https://www.conventionalcommits.org/en/v1.0.0/ for more information"); } // println!("{}({}): {}\n{}", commit_type, scope.unwrap_or("None".to_string()), description.unwrap(), body_footer); diff --git a/gateway/src/api/github_router.rs b/gateway/src/api/github_router.rs index c93173916..84be461da 100644 --- a/gateway/src/api/github_router.rs +++ b/gateway/src/api/github_router.rs @@ -32,12 +32,12 @@ async fn webhook( /// GitHub API: Get the files change of a pull request.
/// For read-only operation of public repos, no authentication is required. pub async fn get_pr_files(pr_url: &str) -> Value { - get_request(&format!("{}/files", pr_url)).await + get_request(&format!("{pr_url}/files")).await } /// GitHub API: Get the commits of a pull request. pub async fn get_pr_commits(pr_url: &str) -> Value { - get_request(&format!("{}/commits", pr_url)).await + get_request(&format!("{pr_url}/commits")).await } /// Send a GET request to the given URL and return the JSON response. async fn get_request(url: &str) -> Value { diff --git a/gateway/src/https_server.rs b/gateway/src/https_server.rs index 3af238f4c..bcc098618 100644 --- a/gateway/src/https_server.rs +++ b/gateway/src/https_server.rs @@ -42,7 +42,7 @@ pub async fn http_server(context: AppContext, options: HttpOptions) { let app = app(context.storage, host.clone(), port, p2p.clone()).await; - let server_url = format!("{}:{}", host, port); + let server_url = format!("{host}:{port}"); let listener = tokio::net::TcpListener::bind(server_url).await.unwrap(); axum::serve(listener, app.into_make_service()) @@ -61,7 +61,7 @@ pub async fn app(storage: Storage, host: String, port: u16, p2p: P2pOptions) -> storage: storage.clone(), oauth_client: None, store: None, - listen_addr: format!("http://{}:{}", host, port), + listen_addr: format!("http://{host}:{port}"), }; let mega_api_state = MegaApiServiceState { diff --git a/gemini/src/ca/server.rs b/gemini/src/ca/server.rs index f7a76cf24..30a63e92c 100644 --- a/gemini/src/ca/server.rs +++ b/gemini/src/ca/server.rs @@ -90,7 +90,7 @@ fn _is_reserved_key(name: String) -> bool { } fn add_user_key_pre(name: String) -> String { - format!("{}{}", USER_KEY_PRE, name) + format!("{USER_KEY_PRE}{name}") } pub fn get_cert_name_from_path(path: &str) -> Option { diff --git a/gemini/src/lfs/mod.rs b/gemini/src/lfs/mod.rs index b9bafedda..674cf5a34 100644 --- a/gemini/src/lfs/mod.rs +++ b/gemini/src/lfs/mod.rs @@ -45,7 +45,7 @@ pub async fn share_lfs( let json = serde_json::to_string(&lfs).unwrap(); let client = Client::new(); - let url = format!("{}/api/v1/lfs_share", bootstrap_node); + let url = format!("{bootstrap_node}/api/v1/lfs_share"); let response = client .post(url) .header("content-type", "application/json") @@ -79,13 +79,12 @@ pub async fn share_lfs( /// pub async fn get_lfs_chunks_info(bootstrap_node: String, file_hash: String) -> Option { let url = format!( - "{}/api/v1/lfs_chunk?file_hash={}", - bootstrap_node, file_hash + "{bootstrap_node}/api/v1/lfs_chunk?file_hash={file_hash}" ); let lfs_info: LFSInfoRes = match get(url.clone()).await { Ok(response) => { if !response.status().is_success() { - println!("Get lfs chuncks info failed {}", url); + println!("Get lfs chuncks info failed {url}"); return None; } let body = response.text().await.unwrap(); @@ -93,7 +92,7 @@ pub async fn get_lfs_chunks_info(bootstrap_node: String, file_hash: String) -> O lfs_info } Err(_) => { - println!("Get lfs chuncks info failed {}", url); + println!("Get lfs chuncks info failed {url}"); return None; } }; diff --git a/gemini/src/p2p/relay.rs b/gemini/src/p2p/relay.rs index eb1e4df49..3530dbb1d 100644 --- a/gemini/src/p2p/relay.rs +++ b/gemini/src/p2p/relay.rs @@ -61,7 +61,7 @@ impl P2PRelay { pub async fn run(&self, host: String, port: u16) -> Result<()> { let server_config = self.get_server_config().await?; - let addr = format!("{}:{}", host, port); + let addr = format!("{host}:{port}"); let endpoint = quinn::Endpoint::server(server_config, SocketAddr::from_str(addr.as_str()).unwrap())?; info!("Quic server listening on udp {}", endpoint.local_addr()?); @@ -670,7 +670,7 @@ impl P2PRelay { "File handle receive, target_id:{}, from:{}, file_path:{}", target_id, from, git_path ); - let key = format!("git-clone-{}-{}", target_id, from); + let key = format!("git-clone-{target_id}-{from}"); if let Some(target_conn) = self.git_objects_connection_map.get(&key) { info!("Find target connection to {}", target_id); @@ -708,11 +708,8 @@ impl P2PRelay { let header = String::from_utf8_lossy(&header_buf[..len]); let header: LFSHeader = serde_json::from_str(&header)?; let (target_id, from, oid, size) = (header.target, header.from, header.oid, header.size); - info!( - "LFS handle receive, target_id:{}, from:{}, oid:{}: size:{}", - target_id, from, oid, size - ); - let key = format!("lfs-{}-{}", target_id, from); + info!("LFS handle receive, target_id:{target_id}, from:{from}, oid:{oid}: size:{size}"); + let key = format!("lfs-{target_id}-{from}"); if let Some(target_conn) = self.lfs_connection_map.get(&key) { info!("Find target connection to {}", target_id); diff --git a/gemini/src/util.rs b/gemini/src/util.rs index 3292ebecd..0a874aa96 100644 --- a/gemini/src/util.rs +++ b/gemini/src/util.rs @@ -20,7 +20,7 @@ pub fn get_available_port() -> Result { let port = listener.local_addr().unwrap().port(); Ok(port) } - Err(e) => Err(format!("Failed to bind to a port: {}", e)), + Err(e) => Err(format!("Failed to bind to a port: {e}")), } } @@ -101,12 +101,12 @@ pub fn parse_pointer_data(data: &[u8]) -> Option<(String, u64)> { } // Start with format `version ...` if let Some(data) = - data.strip_prefix(format!("version {}\noid {}:", LFS_VERSION, LFS_HASH_ALGO).as_bytes()) + data.strip_prefix(format!("version {LFS_VERSION}\noid {LFS_HASH_ALGO}:").as_bytes()) { if data.len() > LFS_OID_LEN && data[LFS_OID_LEN] == b'\n' { // check `oid` length let oid = String::from_utf8(data[..LFS_OID_LEN].to_vec()).unwrap(); - if let Some(data) = data.strip_prefix(format!("{}\nsize ", oid).as_bytes()) { + if let Some(data) = data.strip_prefix(format!("{oid}\nsize ").as_bytes()) { let data = String::from_utf8(data[..].to_vec()).unwrap(); if let Ok(size) = data.trim_end().parse::() { return Some((oid, size)); diff --git a/jupiter/README.md b/jupiter/README.md index 56f830156..80a886ae3 100644 --- a/jupiter/README.md +++ b/jupiter/README.md @@ -1,18 +1,26 @@ ## Jupiter Module - Monorepo and Mega Database Storage Engine ### Migration Guideline -1. Generate entity files +1. Generate new migration + +```bash + +cd mega/jupiter/src + sea-orm-cli migrate generate +``` + +2. Generate entity files ```bash -cd mega/jupiter/src/migration +cd mega/jupiter/src sea-orm-cli generate entity -u postgres://postgres:postgres@localhost:5432/mono -o ../callisto/src --with-serde both ``` -2. Running Migrator CLI +3. Running Migrator CLI - Generate a new migration file ```sh diff --git a/jupiter/callisto/src/access_token.rs b/jupiter/callisto/src/access_token.rs index a2f8e46bb..4e6e520a6 100644 --- a/jupiter/callisto/src/access_token.rs +++ b/jupiter/callisto/src/access_token.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/builds.rs b/jupiter/callisto/src/builds.rs index 3e011c55c..579485d52 100644 --- a/jupiter/callisto/src/builds.rs +++ b/jupiter/callisto/src/builds.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/entity_ext/item_labels.rs b/jupiter/callisto/src/entity_ext/item_labels.rs new file mode 100644 index 000000000..10db07e17 --- /dev/null +++ b/jupiter/callisto/src/entity_ext/item_labels.rs @@ -0,0 +1,47 @@ +use sea_orm::entity::prelude::*; + +use crate::{item_labels::Column, item_labels::Entity}; + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation { + MegaIssue, + MegaMr, + Label, +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + match self { + Self::MegaIssue => Entity::belongs_to(crate::mega_issue::Entity) + .from(Column::ItemId) + .to(crate::mega_issue::Column::Id) + .into(), + Self::MegaMr => Entity::belongs_to(crate::mega_mr::Entity) + .from(Column::ItemId) + .to(crate::mega_mr::Column::Id) + .into(), + Self::Label => Entity::belongs_to(crate::label::Entity) + .from(Column::LabelId) + .to(crate::label::Column::Id) + .into(), + } + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::Label.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::MegaIssue.def() + } +} + +impl Related for Entity { + fn to() -> RelationDef { + Relation::MegaMr.def() + } +} diff --git a/jupiter/callisto/src/entity_ext/label.rs b/jupiter/callisto/src/entity_ext/label.rs new file mode 100644 index 000000000..e791ec9df --- /dev/null +++ b/jupiter/callisto/src/entity_ext/label.rs @@ -0,0 +1,17 @@ +use sea_orm::entity::prelude::*; + +use crate::label::Entity; + + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation { + ItemLabels, +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + match self { + Self::ItemLabels => Entity::has_many(crate::item_labels::Entity).into(), + } + } +} \ No newline at end of file diff --git a/jupiter/callisto/src/entity_ext/mega_issue.rs b/jupiter/callisto/src/entity_ext/mega_issue.rs new file mode 100644 index 000000000..9cf738629 --- /dev/null +++ b/jupiter/callisto/src/entity_ext/mega_issue.rs @@ -0,0 +1,26 @@ +use sea_orm::entity::prelude::*; + +use crate::mega_issue::Entity; + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation { + Label, +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + match self { + Self::Label => Entity::has_many(crate::item_labels::Entity).into(), + } + } +} + +impl Related for Entity { + fn to() -> RelationDef { + crate::entity_ext::item_labels::Relation::Label.def() + } + + fn via() -> Option { + Some(crate::entity_ext::item_labels::Relation::MegaIssue.def().rev()) + } +} \ No newline at end of file diff --git a/jupiter/callisto/src/entity_ext/mega_mr.rs b/jupiter/callisto/src/entity_ext/mega_mr.rs new file mode 100644 index 000000000..03b3cb6c4 --- /dev/null +++ b/jupiter/callisto/src/entity_ext/mega_mr.rs @@ -0,0 +1,26 @@ +use sea_orm::entity::prelude::*; + +use crate::mega_mr::Entity; + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation { + Label, +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + match self { + Self::Label => Entity::has_many(crate::item_labels::Entity).into(), + } + } +} + +impl Related for Entity { + fn to() -> RelationDef { + crate::entity_ext::item_labels::Relation::Label.def() + } + + fn via() -> Option { + Some(crate::entity_ext::item_labels::Relation::MegaMr.def().rev()) + } +} diff --git a/jupiter/callisto/src/entity_ext/mod.rs b/jupiter/callisto/src/entity_ext/mod.rs new file mode 100644 index 000000000..1c6c17f11 --- /dev/null +++ b/jupiter/callisto/src/entity_ext/mod.rs @@ -0,0 +1,4 @@ +pub mod mega_issue; +pub mod mega_mr; +pub mod item_labels; +pub mod label; \ No newline at end of file diff --git a/jupiter/callisto/src/git_blob.rs b/jupiter/callisto/src/git_blob.rs index 17474b4f4..fad61529a 100644 --- a/jupiter/callisto/src/git_blob.rs +++ b/jupiter/callisto/src/git_blob.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_commit.rs b/jupiter/callisto/src/git_commit.rs index 8d322bffa..229963d0e 100644 --- a/jupiter/callisto/src/git_commit.rs +++ b/jupiter/callisto/src/git_commit.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_issue.rs b/jupiter/callisto/src/git_issue.rs index 6de29f369..fe6d0661f 100644 --- a/jupiter/callisto/src/git_issue.rs +++ b/jupiter/callisto/src/git_issue.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_pr.rs b/jupiter/callisto/src/git_pr.rs index 9d4dab417..0f48d952b 100644 --- a/jupiter/callisto/src/git_pr.rs +++ b/jupiter/callisto/src/git_pr.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_repo.rs b/jupiter/callisto/src/git_repo.rs index d22f24697..1badcf8b5 100644 --- a/jupiter/callisto/src/git_repo.rs +++ b/jupiter/callisto/src/git_repo.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_tag.rs b/jupiter/callisto/src/git_tag.rs index 34ad5a6b9..292611b08 100644 --- a/jupiter/callisto/src/git_tag.rs +++ b/jupiter/callisto/src/git_tag.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/git_tree.rs b/jupiter/callisto/src/git_tree.rs index 8e7de0b37..ade3e06a4 100644 --- a/jupiter/callisto/src/git_tree.rs +++ b/jupiter/callisto/src/git_tree.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/import_refs.rs b/jupiter/callisto/src/import_refs.rs index 1aba9d572..e9a038eb7 100644 --- a/jupiter/callisto/src/import_refs.rs +++ b/jupiter/callisto/src/import_refs.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use super::sea_orm_active_enums::RefTypeEnum; use sea_orm::entity::prelude::*; diff --git a/jupiter/callisto/src/item_labels.rs b/jupiter/callisto/src/item_labels.rs index 39b06e84b..db989bdbe 100644 --- a/jupiter/callisto/src/item_labels.rs +++ b/jupiter/callisto/src/item_labels.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; @@ -15,48 +15,7 @@ pub struct Model { pub item_type: String, } -#[derive(Copy, Clone, Debug, EnumIter)] -pub enum Relation { - MegaIssue, - MegaMr, - Label -} - -impl RelationTrait for Relation { - fn def(&self) -> RelationDef { - match self { - Self::MegaIssue => Entity::belongs_to(super::mega_issue::Entity) - .from(Column::ItemId) - .to(super::mega_issue::Column::Id) - .into(), - Self::MegaMr => Entity::belongs_to(super::mega_mr::Entity) - .from(Column::ItemId) - .to(super::mega_mr::Column::Id) - .into(), - Self::Label => Entity::belongs_to(super::label::Entity) - .from(Column::LabelId) - .to(super::label::Column::Id) - .into(), - } - } -} - -impl Related for Entity { - fn to() -> RelationDef { - Relation::Label.def() - } -} - -impl Related for Entity { - fn to() -> RelationDef { - Relation::MegaIssue.def() - } -} - -impl Related for Entity { - fn to() -> RelationDef { - Relation::MegaMr.def() - } -} +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} impl ActiveModelBehavior for ActiveModel {} diff --git a/jupiter/callisto/src/label.rs b/jupiter/callisto/src/label.rs index 89e33202d..024de4764 100644 --- a/jupiter/callisto/src/label.rs +++ b/jupiter/callisto/src/label.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; @@ -15,17 +15,7 @@ pub struct Model { pub description: String, } -#[derive(Copy, Clone, Debug, EnumIter)] -pub enum Relation { - ItemLabels, -} - -impl RelationTrait for Relation { - fn def(&self) -> RelationDef { - match self { - Self::ItemLabels => Entity::has_many(super::item_labels::Entity).into(), - } - } -} +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} impl ActiveModelBehavior for ActiveModel {} diff --git a/jupiter/callisto/src/lfs_locks.rs b/jupiter/callisto/src/lfs_locks.rs index 276c66921..fbf171d88 100644 --- a/jupiter/callisto/src/lfs_locks.rs +++ b/jupiter/callisto/src/lfs_locks.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/lfs_objects.rs b/jupiter/callisto/src/lfs_objects.rs index 02f7b6ecd..c77eb598c 100644 --- a/jupiter/callisto/src/lfs_objects.rs +++ b/jupiter/callisto/src/lfs_objects.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/lfs_split_relations.rs b/jupiter/callisto/src/lfs_split_relations.rs index 625502a79..5cafc3bca 100644 --- a/jupiter/callisto/src/lfs_split_relations.rs +++ b/jupiter/callisto/src/lfs_split_relations.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mega_blob.rs b/jupiter/callisto/src/mega_blob.rs index b99de3f4d..4718c32c5 100644 --- a/jupiter/callisto/src/mega_blob.rs +++ b/jupiter/callisto/src/mega_blob.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mega_commit.rs b/jupiter/callisto/src/mega_commit.rs index 2e055a0ac..1899a91aa 100644 --- a/jupiter/callisto/src/mega_commit.rs +++ b/jupiter/callisto/src/mega_commit.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mega_conversation.rs b/jupiter/callisto/src/mega_conversation.rs index a1f189cac..bda49f196 100644 --- a/jupiter/callisto/src/mega_conversation.rs +++ b/jupiter/callisto/src/mega_conversation.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use super::sea_orm_active_enums::ConvTypeEnum; use sea_orm::entity::prelude::*; @@ -10,12 +10,12 @@ pub struct Model { #[sea_orm(primary_key, auto_increment = false)] pub id: i64, pub link: String, - pub user_id: String, pub conv_type: ConvTypeEnum, #[sea_orm(column_type = "Text", nullable)] pub comment: Option, pub created_at: DateTime, pub updated_at: DateTime, + pub username: String, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] diff --git a/jupiter/callisto/src/mega_issue.rs b/jupiter/callisto/src/mega_issue.rs index 0e0a61214..56d9f26b6 100644 --- a/jupiter/callisto/src/mega_issue.rs +++ b/jupiter/callisto/src/mega_issue.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; @@ -18,27 +18,7 @@ pub struct Model { pub user_id: String, } -#[derive(Copy, Clone, Debug, EnumIter)] -pub enum Relation { - Label, -} - -impl RelationTrait for Relation { - fn def(&self) -> RelationDef { - match self { - Self::Label => Entity::has_many(super::item_labels::Entity).into(), - } - } -} - -impl Related for Entity { - fn to() -> RelationDef { - super::item_labels::Relation::Label.def() - } - - fn via() -> Option { - Some(super::item_labels::Relation::MegaIssue.def().rev()) - } -} +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} impl ActiveModelBehavior for ActiveModel {} diff --git a/jupiter/callisto/src/mega_mr.rs b/jupiter/callisto/src/mega_mr.rs index 9a1e50ca1..7f61068f0 100644 --- a/jupiter/callisto/src/mega_mr.rs +++ b/jupiter/callisto/src/mega_mr.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use super::sea_orm_active_enums::MergeStatusEnum; use sea_orm::entity::prelude::*; @@ -22,27 +22,7 @@ pub struct Model { pub updated_at: DateTime, } -#[derive(Copy, Clone, Debug, EnumIter)] -pub enum Relation { - Label, -} - -impl RelationTrait for Relation { - fn def(&self) -> RelationDef { - match self { - Self::Label => Entity::has_many(super::item_labels::Entity).into(), - } - } -} - -impl Related for Entity { - fn to() -> RelationDef { - super::item_labels::Relation::Label.def() - } - - fn via() -> Option { - Some(super::item_labels::Relation::MegaMr.def().rev()) - } -} +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} impl ActiveModelBehavior for ActiveModel {} diff --git a/jupiter/callisto/src/mega_refs.rs b/jupiter/callisto/src/mega_refs.rs index 1c6a30c7f..776c83935 100644 --- a/jupiter/callisto/src/mega_refs.rs +++ b/jupiter/callisto/src/mega_refs.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mega_tag.rs b/jupiter/callisto/src/mega_tag.rs index d8a3ed50c..e5e448168 100644 --- a/jupiter/callisto/src/mega_tag.rs +++ b/jupiter/callisto/src/mega_tag.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mega_tree.rs b/jupiter/callisto/src/mega_tree.rs index 9b93d7ad2..b584ab60e 100644 --- a/jupiter/callisto/src/mega_tree.rs +++ b/jupiter/callisto/src/mega_tree.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/mod.rs b/jupiter/callisto/src/mod.rs index c8879dc0c..0284fe6c7 100644 --- a/jupiter/callisto/src/mod.rs +++ b/jupiter/callisto/src/mod.rs @@ -1,6 +1,7 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 pub mod prelude; +pub mod entity_ext; pub mod access_token; pub mod builds; diff --git a/jupiter/callisto/src/mq_storage.rs b/jupiter/callisto/src/mq_storage.rs index 0cb743898..dbbc6890e 100644 --- a/jupiter/callisto/src/mq_storage.rs +++ b/jupiter/callisto/src/mq_storage.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/prelude.rs b/jupiter/callisto/src/prelude.rs index 30d5559be..6959f4cba 100644 --- a/jupiter/callisto/src/prelude.rs +++ b/jupiter/callisto/src/prelude.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 pub use super::access_token::Entity as AccessToken; pub use super::builds::Entity as Builds; @@ -33,3 +33,4 @@ pub use super::relay_path_mapping::Entity as RelayPathMapping; pub use super::relay_repo_info::Entity as RelayRepoInfo; pub use super::ssh_keys::Entity as SshKeys; pub use super::user::Entity as User; +pub use super::vault::Entity as Vault; diff --git a/jupiter/callisto/src/raw_blob.rs b/jupiter/callisto/src/raw_blob.rs index 8ab042ef2..efced10a6 100644 --- a/jupiter/callisto/src/raw_blob.rs +++ b/jupiter/callisto/src/raw_blob.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use super::sea_orm_active_enums::StorageTypeEnum; use sea_orm::entity::prelude::*; diff --git a/jupiter/callisto/src/relay_lfs_info.rs b/jupiter/callisto/src/relay_lfs_info.rs index d88d5063c..283f21224 100644 --- a/jupiter/callisto/src/relay_lfs_info.rs +++ b/jupiter/callisto/src/relay_lfs_info.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/relay_node.rs b/jupiter/callisto/src/relay_node.rs index 9517f46a1..f0ef82fae 100644 --- a/jupiter/callisto/src/relay_node.rs +++ b/jupiter/callisto/src/relay_node.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/relay_nostr_event.rs b/jupiter/callisto/src/relay_nostr_event.rs index 7476ff6f2..8a76e1db0 100644 --- a/jupiter/callisto/src/relay_nostr_event.rs +++ b/jupiter/callisto/src/relay_nostr_event.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/relay_nostr_req.rs b/jupiter/callisto/src/relay_nostr_req.rs index 855a68ce2..61447fcb5 100644 --- a/jupiter/callisto/src/relay_nostr_req.rs +++ b/jupiter/callisto/src/relay_nostr_req.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/relay_path_mapping.rs b/jupiter/callisto/src/relay_path_mapping.rs index 382477e74..20d777025 100644 --- a/jupiter/callisto/src/relay_path_mapping.rs +++ b/jupiter/callisto/src/relay_path_mapping.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/relay_repo_info.rs b/jupiter/callisto/src/relay_repo_info.rs index 60573422d..669cc992a 100644 --- a/jupiter/callisto/src/relay_repo_info.rs +++ b/jupiter/callisto/src/relay_repo_info.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/sea_orm_active_enums.rs b/jupiter/callisto/src/sea_orm_active_enums.rs index 6096fc0cb..92f27feb5 100644 --- a/jupiter/callisto/src/sea_orm_active_enums.rs +++ b/jupiter/callisto/src/sea_orm_active_enums.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/ssh_keys.rs b/jupiter/callisto/src/ssh_keys.rs index f2e48e101..7c5080652 100644 --- a/jupiter/callisto/src/ssh_keys.rs +++ b/jupiter/callisto/src/ssh_keys.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/user.rs b/jupiter/callisto/src/user.rs index 322e48110..4148da7b0 100644 --- a/jupiter/callisto/src/user.rs +++ b/jupiter/callisto/src/user.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; diff --git a/jupiter/callisto/src/vault.rs b/jupiter/callisto/src/vault.rs index 8e548c248..fa11a7753 100644 --- a/jupiter/callisto/src/vault.rs +++ b/jupiter/callisto/src/vault.rs @@ -1,4 +1,4 @@ -//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.10 +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12 use sea_orm::entity::prelude::*; use serde::{Deserialize, Serialize}; @@ -6,9 +6,9 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] #[sea_orm(table_name = "vault")] pub struct Model { - #[sea_orm(primary_key, auto_increment = true)] + #[sea_orm(primary_key)] pub id: i64, - #[sea_orm(unique, indexed)] + #[sea_orm(unique)] pub key: String, #[sea_orm(column_type = "VarBinary(StringLen::None)")] pub value: Vec, diff --git a/jupiter/src/lfs_storage/local_storage.rs b/jupiter/src/lfs_storage/local_storage.rs index 597c62c50..2b9f00b95 100644 --- a/jupiter/src/lfs_storage/local_storage.rs +++ b/jupiter/src/lfs_storage/local_storage.rs @@ -42,7 +42,7 @@ impl LfsFileStorage for LocalStorage { .join("objects") .join(transform_path(object_id)); let mut file = - fs::File::open(&path).unwrap_or_else(|_| panic!("Open file:{:?} failed!", path)); + fs::File::open(&path).unwrap_or_else(|_| panic!("Open file:{path:?} failed!")); let mut buffer = Vec::new(); file.read_to_end(&mut buffer).unwrap(); Ok(Bytes::from(buffer)) diff --git a/jupiter/src/lib.rs b/jupiter/src/lib.rs index c4786d412..d6100852f 100644 --- a/jupiter/src/lib.rs +++ b/jupiter/src/lib.rs @@ -1,5 +1,5 @@ pub mod lfs_storage; -pub mod migrator; +pub mod migration; pub mod storage; pub mod utils; diff --git a/jupiter/src/migrator/m20250314_025943_init.rs b/jupiter/src/migration/m20250314_025943_init.rs similarity index 99% rename from jupiter/src/migrator/m20250314_025943_init.rs rename to jupiter/src/migration/m20250314_025943_init.rs index 7b6480f96..676ecb6b6 100644 --- a/jupiter/src/migrator/m20250314_025943_init.rs +++ b/jupiter/src/migration/m20250314_025943_init.rs @@ -5,7 +5,7 @@ use sea_orm_migration::{ sea_orm::{DatabaseBackend, EnumIter, Iterable}, }; -use crate::migrator::pk_bigint; +use crate::migration::pk_bigint; #[derive(DeriveMigrationName)] pub struct Migration; diff --git a/jupiter/src/migrator/m20250427_031332_add_mr_refs_tag.rs b/jupiter/src/migration/m20250427_031332_add_mr_refs_tag.rs similarity index 100% rename from jupiter/src/migrator/m20250427_031332_add_mr_refs_tag.rs rename to jupiter/src/migration/m20250427_031332_add_mr_refs_tag.rs diff --git a/jupiter/src/migrator/m20250605_013340_alter_mega_mr_index.rs b/jupiter/src/migration/m20250605_013340_alter_mega_mr_index.rs similarity index 100% rename from jupiter/src/migrator/m20250605_013340_alter_mega_mr_index.rs rename to jupiter/src/migration/m20250605_013340_alter_mega_mr_index.rs diff --git a/jupiter/src/migrator/m20250610_000001_add_vault_storage.rs b/jupiter/src/migration/m20250610_000001_add_vault_storage.rs similarity index 100% rename from jupiter/src/migrator/m20250610_000001_add_vault_storage.rs rename to jupiter/src/migration/m20250610_000001_add_vault_storage.rs diff --git a/jupiter/src/migrator/m20250613_033821_alter_user_id.rs b/jupiter/src/migration/m20250613_033821_alter_user_id.rs similarity index 100% rename from jupiter/src/migrator/m20250613_033821_alter_user_id.rs rename to jupiter/src/migration/m20250613_033821_alter_user_id.rs diff --git a/jupiter/src/migrator/m20250618_065050_add_label.rs b/jupiter/src/migration/m20250618_065050_add_label.rs similarity index 98% rename from jupiter/src/migrator/m20250618_065050_add_label.rs rename to jupiter/src/migration/m20250618_065050_add_label.rs index b63accc10..48ebf403d 100644 --- a/jupiter/src/migrator/m20250618_065050_add_label.rs +++ b/jupiter/src/migration/m20250618_065050_add_label.rs @@ -1,6 +1,6 @@ use sea_orm_migration::{prelude::*, schema::*, sea_orm::DatabaseBackend}; -use crate::migrator::pk_bigint; +use crate::migration::pk_bigint; #[derive(DeriveMigrationName)] pub struct Migration; diff --git a/jupiter/src/migration/m20250628_025312_add_username_in_conversation.rs b/jupiter/src/migration/m20250628_025312_add_username_in_conversation.rs new file mode 100644 index 000000000..1d5164d23 --- /dev/null +++ b/jupiter/src/migration/m20250628_025312_add_username_in_conversation.rs @@ -0,0 +1,42 @@ +use sea_orm_migration::prelude::*; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .alter_table( + Table::alter() + .table(MegaConversation::Table) + .drop_column("user_id") + .to_owned(), + ) + .await?; + + manager + .alter_table( + Table::alter() + .table(MegaConversation::Table) + .add_column_if_not_exists( + ColumnDef::new(Alias::new("username")) + .string() + .not_null() + .default(""), + ) + .to_owned(), + ) + .await?; + Ok(()) + } + + async fn down(&self, _: &SchemaManager) -> Result<(), DbErr> { + Ok(()) + } +} + +#[derive(DeriveIden)] +enum MegaConversation { + Table, +} diff --git a/jupiter/src/migrator/mod.rs b/jupiter/src/migration/mod.rs similarity index 95% rename from jupiter/src/migrator/mod.rs rename to jupiter/src/migration/mod.rs index 22e47b5bf..c92d857db 100644 --- a/jupiter/src/migrator/mod.rs +++ b/jupiter/src/migration/mod.rs @@ -41,6 +41,7 @@ mod m20250605_013340_alter_mega_mr_index; mod m20250610_000001_add_vault_storage; mod m20250613_033821_alter_user_id; mod m20250618_065050_add_label; +mod m20250628_025312_add_username_in_conversation; /// Creates a primary key column definition with big integer type. /// @@ -70,6 +71,7 @@ impl MigratorTrait for Migrator { Box::new(m20250610_000001_add_vault_storage::Migration), Box::new(m20250613_033821_alter_user_id::Migration), Box::new(m20250618_065050_add_label::Migration), + Box::new(m20250628_025312_add_username_in_conversation::Migration), ] } } @@ -98,7 +100,7 @@ pub async fn apply_migrations(db: &DatabaseConnection, refresh: bool) -> Result< false => Migrator::up(db, None).await, } .map_err(|e| { - log::error!("Failed to apply migrations: {}", e); + log::error!("Failed to apply migrations: {e}"); e.into() }) } diff --git a/jupiter/src/storage/git_db_storage.rs b/jupiter/src/storage/git_db_storage.rs index f9bfaae2b..b75a5b57c 100644 --- a/jupiter/src/storage/git_db_storage.rs +++ b/jupiter/src/storage/git_db_storage.rs @@ -206,7 +206,7 @@ impl GitDbStorage { repo_path: &str, ) -> Result, MegaError> { let query = git_repo::Entity::find() - .filter(Expr::cust(format!("'{}' LIKE repo_path || '%'", repo_path))) + .filter(Expr::cust(format!("'{repo_path}' LIKE repo_path || '%'"))) .order_by_desc(Expr::cust("LENGTH(repo_path)")); tracing::debug!("{}", query.build(DbBackend::Postgres).to_string()); let result = query.one(self.get_connection()).await?; diff --git a/jupiter/src/storage/init.rs b/jupiter/src/storage/init.rs index eed5faae7..16f41f52b 100644 --- a/jupiter/src/storage/init.rs +++ b/jupiter/src/storage/init.rs @@ -4,7 +4,7 @@ use sea_orm::{ConnectOptions, Database, DatabaseConnection}; use std::{path::Path, time::Duration}; use tracing::log; -use crate::migrator::apply_migrations; +use crate::migration::apply_migrations; use crate::utils::id_generator; @@ -17,7 +17,7 @@ pub async fn database_connection(db_config: &DbConfig) -> DatabaseConnection { match postgres_connection(db_config).await { Ok(conn) => conn, Err(e) => { - log::error!("Failed to connect to postgres: {}", e); + log::error!("Failed to connect to postgres: {e}"); log::info!("Falling back to sqlite"); sqlite_connection(db_config) .await @@ -36,7 +36,7 @@ pub async fn database_connection(db_config: &DbConfig) -> DatabaseConnection { async fn postgres_connection(db_config: &DbConfig) -> Result { let db_url = db_config.db_url.to_owned(); - log::info!("Connecting to database: {}", db_url); + log::info!("Connecting to database: {db_url}"); let opt = setup_option(db_url); Database::connect(opt).await.map_err(|e| e.into()) @@ -49,7 +49,7 @@ async fn sqlite_connection(db_config: &DbConfig) -> Result>()), ) - .find_with_related(label::Entity) .order_by_desc(mega_issue::Column::CreatedAt) + .find_with_related(label::Entity) .all(self.get_connection()) .await?; @@ -137,18 +137,18 @@ impl IssueStorage { pub async fn add_conversation( &self, link: &str, - user_id: &str, + username: &str, comment: Option, conv_type: ConvTypeEnum, ) -> Result { let conversation = mega_conversation::Model { id: generate_id(), link: link.to_owned(), - user_id: user_id.to_owned(), conv_type, comment, created_at: chrono::Utc::now().naive_utc(), updated_at: chrono::Utc::now().naive_utc(), + username: username.to_owned(), }; let conversation = conversation.into_active_model(); let res = conversation.insert(self.get_connection()).await.unwrap(); @@ -201,7 +201,7 @@ impl IssueStorage { pub async fn modify_labels( &self, - user_id: &str, + username: &str, item_id: i64, link: &str, to_add: Vec, @@ -218,8 +218,8 @@ impl IssueStorage { self.add_conversation( link, - user_id, - Some(format!("{} removed {:?}", user_id, to_remove)), + username, + Some(format!("{username} removed {to_remove:?}")), ConvTypeEnum::Label, ) .await?; @@ -245,8 +245,8 @@ impl IssueStorage { .await?; self.add_conversation( link, - user_id, - Some(format!("{} added {:?}", user_id, to_add)), + username, + Some(format!("{username} added {to_add:?}")), ConvTypeEnum::Label, ) .await?; diff --git a/jupiter/src/storage/mr_storage.rs b/jupiter/src/storage/mr_storage.rs index f96f3e18d..8977c734c 100644 --- a/jupiter/src/storage/mr_storage.rs +++ b/jupiter/src/storage/mr_storage.rs @@ -6,8 +6,8 @@ use sea_orm::{ PaginatorTrait, QueryFilter, QueryOrder, Set, }; -use callisto::{label, mega_mr}; use callisto::sea_orm_active_enums::MergeStatusEnum; +use callisto::{label, mega_mr}; use common::errors::MegaError; use common::utils::generate_id; @@ -60,15 +60,12 @@ impl MrStorage { .await .map(|m| (m, num_pages))?; - let mr_with_label: Vec<(mega_mr::Model, Vec)> = - mega_mr::Entity::find() - .filter( - mega_mr::Column::Id.is_in(mr_list.iter().map(|i| i.id).collect::>()), - ) - .find_with_related(label::Entity) - .order_by_desc(mega_mr::Column::CreatedAt) - .all(self.get_connection()) - .await?; + let mr_with_label: Vec<(mega_mr::Model, Vec)> = mega_mr::Entity::find() + .filter(mega_mr::Column::Id.is_in(mr_list.iter().map(|i| i.id).collect::>())) + .order_by_desc(mega_mr::Column::CreatedAt) + .find_with_related(label::Entity) + .all(self.get_connection()) + .await?; Ok((mr_with_label, page)) } diff --git a/jupiter/src/tests.rs b/jupiter/src/tests.rs index a45a176e5..59f58d1a3 100644 --- a/jupiter/src/tests.rs +++ b/jupiter/src/tests.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, LazyLock}; use common::config::Config; use crate::lfs_storage::local_storage::LocalStorage; -use crate::migrator::apply_migrations; +use crate::migration::apply_migrations; use crate::storage::{ git_db_storage::GitDbStorage, issue_storage::IssueStorage, lfs_db_storage::LfsDbStorage, mono_storage::MonoStorage, mq_storage::MQStorage, mr_storage::MrStorage, diff --git a/jupiter/src/utils/converter.rs b/jupiter/src/utils/converter.rs index 89536aa2d..235dd54f7 100644 --- a/jupiter/src/utils/converter.rs +++ b/jupiter/src/utils/converter.rs @@ -28,7 +28,7 @@ pub fn init_trees(mono_config: &MonoConfig) -> (HashMap, HashMap {} Err(e) => { - println!("{}", e); + println!("{e}"); if !args.ignore_errors { // if `--ignore-errors` is not set, stop on first error return; @@ -147,7 +147,7 @@ async fn add_a_file(file: &Path, index: &mut Index, verbose: bool) -> Result<(), FileStatus::Deleted => { index.remove(file_str, 0); if verbose { - println!("removed: {}", file_str); + println!("removed: {file_str}"); } } FileStatus::NotFound => { diff --git a/libra/src/command/branch.rs b/libra/src/command/branch.rs index 14b0ca4ee..3ad0b9d58 100644 --- a/libra/src/command/branch.rs +++ b/libra/src/command/branch.rs @@ -67,7 +67,7 @@ pub async fn set_upstream(branch: &str, upstream: &str) { let (remote, remote_branch) = match upstream.split_once('/') { Some((remote, branch)) => (remote, branch), None => { - eprintln!("fatal: invalid upstream '{}'", upstream); + eprintln!("fatal: invalid upstream '{upstream}'"); return; } }; @@ -77,13 +77,12 @@ pub async fn set_upstream(branch: &str, upstream: &str) { "branch", Some(branch), "merge", - &format!("refs/heads/{}", remote_branch), + &format!("refs/heads/{remote_branch}"), ) .await; } println!( - "Branch '{}' set up to track remote branch '{}'", - branch, upstream + "Branch '{branch}' set up to track remote branch '{upstream}'" ); } @@ -91,14 +90,14 @@ pub async fn create_branch(new_branch: String, branch_or_commit: Option) tracing::debug!("create branch: {} from {:?}", new_branch, branch_or_commit); if !is_valid_git_branch_name(&new_branch) { - eprintln!("fatal: invalid branch name: {}", new_branch); + eprintln!("fatal: invalid branch name: {new_branch}"); return; } // check if branch exists let branch = Branch::find_branch(&new_branch, None).await; if branch.is_some() { - panic!("fatal: A branch named '{}' already exists.", new_branch); + panic!("fatal: A branch named '{new_branch}' already exists."); } let commit_id = match branch_or_commit { @@ -107,7 +106,7 @@ pub async fn create_branch(new_branch: String, branch_or_commit: Option) match commit { Ok(commit) => commit, Err(e) => { - eprintln!("fatal: {}", e); + eprintln!("fatal: {e}"); return; } } @@ -118,7 +117,7 @@ pub async fn create_branch(new_branch: String, branch_or_commit: Option) // check if commit_hash exists let _ = load_object::(&commit_id) - .unwrap_or_else(|_| panic!("fatal: not a valid object name: '{}'", commit_id)); + .unwrap_or_else(|_| panic!("fatal: not a valid object name: '{commit_id}'")); // create branch Branch::update_branch(&new_branch, &commit_id.to_string(), None).await; @@ -127,14 +126,13 @@ pub async fn create_branch(new_branch: String, branch_or_commit: Option) async fn delete_branch(branch_name: String) { let _ = Branch::find_branch(&branch_name, None) .await - .unwrap_or_else(|| panic!("fatal: branch '{}' not found", branch_name)); + .unwrap_or_else(|| panic!("fatal: branch '{branch_name}' not found")); let head = Head::current().await; if let Head::Branch(name) = head { if name == branch_name { panic!( - "fatal: Cannot delete the branch '{}' which you are currently on", - branch_name + "fatal: Cannot delete the branch '{branch_name}' which you are currently on" ); } } @@ -150,7 +148,7 @@ async fn show_current_branch() { println!("HEAD detached at {}", &commit_hash.to_string()[..8]); } Head::Branch(name) => { - println!("{}", name); + println!("{name}"); } } } @@ -174,7 +172,7 @@ pub async fn list_branches(remotes: bool) { if let Head::Detached(commit) = head { let s = "HEAD detached at ".to_string() + &commit.to_string()[..8]; let s = s.green(); - println!("{}", s); + println!("{s}"); }; let head_name = match head { Head::Branch(name) => name, @@ -189,7 +187,7 @@ pub async fn list_branches(remotes: bool) { if head_name == name { println!("* {}", name.green()); } else { - println!(" {}", name); + println!(" {name}"); }; } } diff --git a/libra/src/command/checkout.rs b/libra/src/command/checkout.rs index 7b434f061..b82dcc7d1 100644 --- a/libra/src/command/checkout.rs +++ b/libra/src/command/checkout.rs @@ -63,7 +63,7 @@ async fn create_and_switch_new_branch(new_branch: &str) { } async fn get_remote(branch_name: &str) { - let remote_branch_name: String = format!("origin/{}", branch_name); + let remote_branch_name: String = format!("origin/{branch_name}"); create_and_switch_new_branch(branch_name).await; // Set branch upstream @@ -81,7 +81,7 @@ pub async fn check_branch(branch_name: &str) -> Option { let target_branch: Option = Branch::find_branch(branch_name, None).await; if target_branch.is_none() { - let remote_branch_name: String = format!("origin/{}", branch_name); + let remote_branch_name: String = format!("origin/{branch_name}"); if !Branch::search_branch(&remote_branch_name).await.is_empty() { println!("branch '{branch_name}' set up to track '{remote_branch_name}'."); diff --git a/libra/src/command/clone.rs b/libra/src/command/clone.rs index 8bacf3d6a..d81147b7b 100644 --- a/libra/src/command/clone.rs +++ b/libra/src/command/clone.rs @@ -61,7 +61,7 @@ pub async fn execute(args: CloneArgs) { return; } let repo_name = local_path.file_name().unwrap().to_str().unwrap(); - println!("Cloning into '{}'", repo_name); + println!("Cloning into '{repo_name}'"); } let is_success = Cell::new(false); @@ -76,7 +76,7 @@ pub async fn execute(args: CloneArgs) { //check if the branch name is valid if let Some(branch) = args.branch.clone() { if !branch::is_valid_git_branch_name(&branch) { - eprintln!("invalid branch name: '{}'.\n\nBranch names must:\n- Not contain spaces, control characters, or any of these characters: \\ : \" ? * [\n- Not start or end with a slash ('/'), or end with a dot ('.')\n- Not contain consecutive slashes ('//') or dots ('..')\n- Not be reserved names like 'HEAD' or contain '@{{'\n- Not be empty or just a dot ('.')\n\nPlease choose a valid branch name.", branch); + eprintln!("invalid branch name: '{branch}'.\n\nBranch names must:\n- Not contain spaces, control characters, or any of these characters: \\ : \" ? * [\n- Not start or end with a slash ('/'), or end with a dot ('.')\n- Not contain consecutive slashes ('//') or dots ('..')\n- Not be reserved names like 'HEAD' or contain '@{{'\n- Not be empty or just a dot ('.')\n\nPlease choose a valid branch name."); return; } } diff --git a/libra/src/command/config.rs b/libra/src/command/config.rs index 211cc258b..7ee023c7e 100644 --- a/libra/src/command/config.rs +++ b/libra/src/command/config.rs @@ -52,7 +52,7 @@ pub struct Key { pub async fn execute(args: ConfigArgs) { if let Err(e) = args.validate() { - eprintln!("error: {}", e); + eprintln!("error: {e}"); return; } if args.list { @@ -88,7 +88,7 @@ async fn parse_key(mut origin_key: String) -> Key { (configuration, origin_key) = match origin_key.split_once(".") { Some((first_part, remainer)) => (first_part.to_string(), remainer.to_string()), None => { - panic!("error: key does not contain a section: {}", origin_key); + panic!("error: key does not contain a section: {origin_key}"); } }; (name, origin_key) = match origin_key.rsplit_once(".") { @@ -138,15 +138,15 @@ async fn get_config(key: &Key, default: Option<&str>, valuepattern: Option<&str> if let Some(vp) = valuepattern { // if value pattern is present, check it if v.contains(vp) { - println!("{}", v); + println!("{v}"); } } else { // if value pattern is not present, just print it - println!("{}", v); + println!("{v}"); } } else if let Some(default_value) = default { // if value is not exits just return the default value if it's present - println!("{}", default_value); + println!("{default_value}"); } } @@ -159,19 +159,19 @@ async fn get_all_config(key: &Key, default: Option<&str>, valuepattern: Option<& if let Some(vp) = valuepattern { // for each value, check if it matches the pattern if value.contains(vp) { - println!("{}", value); + println!("{value}"); matched_any = true; } } else { // print all if value pattern is not present matched_any = true; - println!("{}", value); + println!("{value}"); } } if !matched_any { if let Some(default_value) = default { // if no value matches the pattern, print the default value if it's present - println!("{}", default_value); + println!("{default_value}"); } } } @@ -204,6 +204,6 @@ async fn unset_all_config(key: &Key, valuepattern: Option<&str>) { async fn list_config() { let configurations = config::Config::list_all().await; for (key, value) in configurations { - println!("{}={}", key, value); + println!("{key}={value}"); } } diff --git a/libra/src/command/diff.rs b/libra/src/command/diff.rs index b81e47f8b..2be20af32 100644 --- a/libra/src/command/diff.rs +++ b/libra/src/command/diff.rs @@ -72,8 +72,7 @@ pub async fn execute(args: DiffArgs) { let file = std::fs::File::create(path) .map_err(|e| { eprintln!( - "fatal: could not open to file '{}' for writing: {}", - path, e + "fatal: could not open to file '{path}' for writing: {e}" ); }) .unwrap(); @@ -86,7 +85,7 @@ pub async fn execute(args: DiffArgs) { Some(ref source) => match get_target_commit(source).await { Ok(commit_hash) => get_commit_blobs(&commit_hash).await, Err(e) => { - eprintln!("fatal: {}, can't use as diff old source", e); + eprintln!("fatal: {e}, can't use as diff old source"); return; } }, @@ -107,7 +106,7 @@ pub async fn execute(args: DiffArgs) { Some(ref source) => match get_target_commit(source).await { Ok(commit_hash) => get_commit_blobs(&commit_hash).await, Err(e) => { - eprintln!("fatal: {}, can't use as diff new source", e); + eprintln!("fatal: {e}, can't use as diff new source"); return; } }, @@ -235,7 +234,7 @@ pub async fn diff( let old_index = old_hash.map_or("0000000".to_string(), |h| h.to_string()[0..8].to_string()); let new_index = new_hash.map_or("0000000".to_string(), |h| h.to_string()[0..8].to_string()); - writeln!(w, "index {}..{}", old_index, new_index).unwrap(); + writeln!(w, "index {old_index}..{new_index}").unwrap(); // check is the content is valid utf-8 or maybe binary let old_type = infer::get(&old_content); let new_type = infer::get(&new_content); @@ -263,8 +262,8 @@ pub async fn diff( format!("b/{}", file_display(&file, new_hash, new_type)), ) }; - writeln!(w, "--- {}", old_prefix).unwrap(); - writeln!(w, "+++ {}", new_prefix).unwrap(); + writeln!(w, "--- {old_prefix}").unwrap(); + writeln!(w, "+++ {new_prefix}").unwrap(); imara_diff_result(&old_text, &new_text, algorithm.as_str(), w); } _ => { @@ -389,7 +388,7 @@ fn imara_diff_result(old: &str, new: &str, algorithm: &str, w: &mut dyn io::Writ ) .to_string(); - write!(w, "{}", result).unwrap(); + write!(w, "{result}").unwrap(); } #[cfg(test)] @@ -468,7 +467,7 @@ mod test { let mut buf = Vec::new(); similar_diff_result(old, new, &mut buf); let result = String::from_utf8(buf).unwrap(); - println!("{}", result); + println!("{result}"); } #[tokio::test] @@ -529,16 +528,14 @@ mod test { let elapse = start.elapsed(); let ouput = String::from_utf8(buf).expect("Invalid UTF-8 in diff ouput"); - println!("libra diff algorithm: {:?} Spend Time: {:?}", algo, elapse); + println!("libra diff algorithm: {algo:?} Spend Time: {elapse:?}"); assert!( !ouput.is_empty(), - "libra diff algorithm: {} produce a empty output", - algo + "libra diff algorithm: {algo} produce a empty output" ); assert!( ouput.contains("@@"), - "libra diff algorithm: {}, ouput missing diff markers", - algo + "libra diff algorithm: {algo}, ouput missing diff markers" ); outputs.push((algo, ouput)); @@ -550,13 +547,11 @@ mod test { let minus_line = output.lines().filter(|line| line.starts_with("-")).count(); assert_eq!( plus_line, 6, - "libra diff algorithm {}, expect plus_line: 6, got {} ", - algo, plus_line + "libra diff algorithm {algo}, expect plus_line: 6, got {plus_line} " ); assert_eq!( minus_line, 1, - "libra diff algorithm {}, expect minus_line: 1, got {} ", - algo, minus_line + "libra diff algorithm {algo}, expect minus_line: 1, got {minus_line} " ); } } diff --git a/libra/src/command/fetch.rs b/libra/src/command/fetch.rs index 10cd8524b..5461a8dce 100644 --- a/libra/src/command/fetch.rs +++ b/libra/src/command/fetch.rs @@ -69,8 +69,7 @@ pub async fn execute(args: FetchArgs) { None => { tracing::error!("remote config '{}' not found", remote); eprintln!( - "fatal: '{}' does not appear to be a libra repository", - remote + "fatal: '{remote}' does not appear to be a libra repository" ); } } @@ -84,7 +83,7 @@ pub async fn fetch_repository(remote_config: &RemoteConfig, branch: Option refs, Err(e) => { - eprintln!("fatal: {}", e); + eprintln!("fatal: {e}"); return; } }; @@ -124,14 +123,14 @@ pub async fn fetch_repository(remote_config: &RemoteConfig, branch: Option { - eprintln!("unknown side-band-64k code: {}", code); + eprintln!("unknown side-band-64k code: {code}"); } } } else if &data != b"NAK\n" { @@ -198,13 +197,13 @@ pub async fn fetch_repository(remote_config: &RemoteConfig, branch: Option 32 { // 12 header + 20 hash let pack_file = utils::path::objects() .join("pack") - .join(format!("pack-{}.pack", checksum)); + .join(format!("pack-{checksum}.pack")); let mut file = fs::File::create(pack_file.clone()).unwrap(); file.write_all(&pack_data).expect("write failed"); @@ -231,7 +230,7 @@ pub async fn fetch_repository(remote_config: &RemoteConfig, branch: Option {} Err(e) => { - eprintln!("Error: {}", e); + eprintln!("Error: {e}"); std::process::exit(1); } } @@ -114,7 +114,7 @@ pub async fn init(args: InitArgs) -> io::Result<()> { if !branch::is_valid_git_branch_name(branch_name) { return Err(io::Error::new( io::ErrorKind::InvalidInput, - format!("invalid branch name: '{}'.\n\nBranch names must:\n- Not contain spaces, control characters, or any of these characters: \\ : \" ? * [\n- Not start or end with a slash ('/'), or end with a dot ('.')\n- Not contain consecutive slashes ('//') or dots ('..')\n- Not be reserved names like 'HEAD' or contain '@{{'\n- Not be empty or just a dot ('.')\n\nPlease choose a valid branch name.", branch_name), + format!("invalid branch name: '{branch_name}'.\n\nBranch names must:\n- Not contain spaces, control characters, or any of these characters: \\ : \" ? * [\n- Not start or end with a slash ('/'), or end with a dot ('.')\n- Not contain consecutive slashes ('//') or dots ('..')\n- Not be reserved names like 'HEAD' or contain '@{{'\n- Not be empty or just a dot ('.')\n\nPlease choose a valid branch name."), )); } } diff --git a/libra/src/command/lfs.rs b/libra/src/command/lfs.rs index a5b1195e2..3ef8a8f34 100644 --- a/libra/src/command/lfs.rs +++ b/libra/src/command/lfs.rs @@ -108,7 +108,7 @@ pub async fn execute(cmd: LfsCmds) { LfsCmds::Lock { path } => { // Only check existence if !Path::new(&path).exists() { - eprintln!("fatal: pathspec '{}' did not match any files", path); + eprintln!("fatal: pathspec '{path}' did not match any files"); return; } @@ -118,7 +118,7 @@ pub async fn execute(cmd: LfsCmds) { .lock(path.clone(), refspec.clone()) .await; if code.is_success() { - println!("Locked {}", path); + println!("Locked {path}"); } else if code == StatusCode::FORBIDDEN { eprintln!("Forbidden: You must have push access to create a lock"); } else if code == StatusCode::CONFLICT { @@ -128,7 +128,7 @@ pub async fn execute(cmd: LfsCmds) { LfsCmds::Unlock { path, force, id } => { if !force { if !Path::new(&path).exists() { - eprintln!("fatal: pathspec '{}' did not match any files", path); + eprintln!("fatal: pathspec '{path}' did not match any files"); return; } if !status::is_clean().await { @@ -152,7 +152,7 @@ pub async fn execute(cmd: LfsCmds) { .await .locks; if locks.is_empty() { - eprintln!("fatal: no lock found for path '{}'", path); + eprintln!("fatal: no lock found for path '{path}'"); return; } locks[0].id.clone() @@ -164,7 +164,7 @@ pub async fn execute(cmd: LfsCmds) { .unlock(id.clone(), refspec.clone(), force) .await; if code.is_success() { - println!("Unlocked {}", path); + println!("Unlocked {path}"); } else if code == StatusCode::FORBIDDEN { eprintln!("Forbidden: You must have push access to unlock"); } @@ -212,7 +212,7 @@ pub async fn execute(cmd: LfsCmds) { pub(crate) async fn current_refspec() -> Option { match Head::current().await { - Head::Branch(name) => Some(format!("refs/heads/{}", name)), + Head::Branch(name) => Some(format!("refs/heads/{name}")), Head::Detached(_) => { println!("fatal: HEAD is detached"); None @@ -252,7 +252,7 @@ fn add_lfs_patterns(file_path: &str, patterns: Vec) -> io::Result<()> { if lfs_patterns.contains(&pattern) { continue; } - println!("Tracking \"{}\"", pattern); + println!("Tracking \"{pattern}\""); let pattern = format!( "{} filter=lfs diff=lfs merge=lfs -text\n", pattern.replace(" ", r"\ ") @@ -283,7 +283,7 @@ fn untrack_lfs_patterns(file_path: &str, patterns: Vec) -> io::Result<() } } match matched_pattern { - Some(pattern) => println!("Untracking \"{}\"", pattern), + Some(pattern) => println!("Untracking \"{pattern}\""), None => lines.push(line), } } diff --git a/libra/src/command/log.rs b/libra/src/command/log.rs index 7c03025b2..5323c73b4 100644 --- a/libra/src/command/log.rs +++ b/libra/src/command/log.rs @@ -67,8 +67,7 @@ pub async fn execute(args: LogArgs) { let branch = Branch::find_branch(&branch_name, None).await; if branch.is_none() { panic!( - "fatal: your current branch '{}' does not have any commits yet ", - branch_name + "fatal: your current branch '{branch_name}' does not have any commits yet " ); } } @@ -103,12 +102,12 @@ pub async fn execute(args: LogArgs) { }; message.push_str(&format!("\nAuthor: {}", commit.author)); let (msg, _) = parse_commit_msg(&commit.message); - message.push_str(&format!("\n{}\n", msg)); + message.push_str(&format!("\n{msg}\n")); #[cfg(unix)] { if let Some(ref mut stdin) = process.stdin { - writeln!(stdin, "{}", message).unwrap(); + writeln!(stdin, "{message}").unwrap(); } else { eprintln!("Failed to capture stdin"); } diff --git a/libra/src/command/mod.rs b/libra/src/command/mod.rs index 0cba9d97f..c20d6ed81 100644 --- a/libra/src/command/mod.rs +++ b/libra/src/command/mod.rs @@ -116,10 +116,10 @@ pub async fn get_target_commit(branch_or_commit: &str) -> Result 1 { - return Err(format!("Ambiguous commit hash '{}'", branch_or_commit).into()); + return Err(format!("Ambiguous commit hash '{branch_or_commit}'").into()); } if possible_commits.is_empty() { - return Err(format!("No such branch or commit: '{}'", branch_or_commit).into()); + return Err(format!("No such branch or commit: '{branch_or_commit}'").into()); } Ok(possible_commits[0]) } else { diff --git a/libra/src/command/push.rs b/libra/src/command/push.rs index a6994b673..fa95f9dd1 100644 --- a/libra/src/command/push.rs +++ b/libra/src/command/push.rs @@ -61,7 +61,7 @@ pub async fn execute(args: PushArgs) { if let Some(remote) = remote { remote } else { - eprintln!("fatal: no remote configured for branch '{}'", branch); + eprintln!("fatal: no remote configured for branch '{branch}'"); return; } } @@ -76,8 +76,7 @@ pub async fn execute(args: PushArgs) { .to_string(); println!( - "pushing {}({}) to {}({})", - branch, commit_hash, repository, repo_url + "pushing {branch}({commit_hash}) to {repository}({repo_url})" ); let url = Url::parse(&repo_url).unwrap(); @@ -85,14 +84,14 @@ pub async fn execute(args: PushArgs) { let refs = match client.discovery_reference(ReceivePack).await { Ok(refs) => refs, Err(e) => { - eprintln!("fatal: {}", e); + eprintln!("fatal: {e}"); return; } }; let tracked_branch = Config::get("branch", Some(&branch), "merge") .await // New branch may not have tracking branch - .unwrap_or_else(|| format!("refs/heads/{}", branch)); + .unwrap_or_else(|| format!("refs/heads/{branch}")); let tracked_ref = refs.iter().find(|r| r._ref == tracked_branch); // [0; 20] if new branch @@ -108,8 +107,7 @@ pub async fn execute(args: PushArgs) { add_pkt_line_string( &mut data, format!( - "{} {} {}\0report-status\n", - remote_hash, commit_hash, tracked_branch + "{remote_hash} {commit_hash} {tracked_branch}\0report-status\n" ), ); data.extend_from_slice(b"0000"); @@ -165,7 +163,7 @@ pub async fn execute(args: PushArgs) { } let (_, pkt_line) = read_pkt_line(&mut data); if !pkt_line.starts_with("ok".as_ref()) { - eprintln!("fatal: ref update failed [{:?}]", pkt_line); + eprintln!("fatal: ref update failed [{pkt_line:?}]"); return; } let (len, _) = read_pkt_line(&mut data); @@ -175,7 +173,7 @@ pub async fn execute(args: PushArgs) { // set after push success if args.set_upstream { - branch::set_upstream(&branch, &format!("{}/{}", repository, branch)).await; + branch::set_upstream(&branch, &format!("{repository}/{branch}")).await; } } diff --git a/libra/src/command/remote.rs b/libra/src/command/remote.rs index 06c4f7c92..918590fe1 100644 --- a/libra/src/command/remote.rs +++ b/libra/src/command/remote.rs @@ -29,7 +29,7 @@ pub async fn execute(command: RemoteCmds) { } RemoteCmds::Remove { name } => { if let Err(e) = Config::remove_remote(&name).await { - eprintln!("{}", e); + eprintln!("{e}"); } } RemoteCmds::List => { @@ -52,13 +52,13 @@ async fn show_remote_verbose(remote: &str) { let urls = Config::get_all("remote", Some(remote), "url").await; match urls.first() { Some(url) => { - println!("{} {} (fetch)", remote, url); + println!("{remote} {url} (fetch)"); } None => { - eprintln!("fatal: no URL configured for remote '{}'", remote); + eprintln!("fatal: no URL configured for remote '{remote}'"); } } for url in urls { - println!("{} {} (push)", remote, url); + println!("{remote} {url} (push)"); } } diff --git a/libra/src/command/remove.rs b/libra/src/command/remove.rs index a5aa186ae..fea07ccd7 100644 --- a/libra/src/command/remove.rs +++ b/libra/src/command/remove.rs @@ -81,7 +81,7 @@ fn validate_pathspec(pathspec: &[String], index: &Index) -> bool { // not tracked, but path may be a directory // check if any tracked file in the directory if !index.contains_dir_file(&path_wd) { - println!("fatal: pathspec '{}' did not match any files", path_str); + println!("fatal: pathspec '{path_str}' did not match any files"); return false; } } diff --git a/libra/src/command/restore.rs b/libra/src/command/restore.rs index 6ac3287b0..c89acfa50 100644 --- a/libra/src/command/restore.rs +++ b/libra/src/command/restore.rs @@ -100,9 +100,9 @@ pub async fn execute(args: RestoreArgs) { } else { let src = source.unwrap(); if storage.search(&src).await.len() != 1 { - eprintln!("fatal: could not resolve {}", src); + eprintln!("fatal: could not resolve {src}"); } else { - eprintln!("fatal: reference is not a commit: {}", src); + eprintln!("fatal: reference is not a commit: {src}"); } return; } @@ -159,7 +159,7 @@ async fn restore_to_file(hash: &SHA1, path: &PathBuf) -> io::Result<()> { .download_object(&oid, size, &path_abs, None) .await { - eprintln!("fatal: {}", e); + eprintln!("fatal: {e}"); } } } diff --git a/libra/src/command/status.rs b/libra/src/command/status.rs index 6a7d2937b..2553a7901 100644 --- a/libra/src/command/status.rs +++ b/libra/src/command/status.rs @@ -50,7 +50,7 @@ pub async fn execute() { println!("HEAD detached at {}", &commit_hash.to_string()[..8]); } Head::Branch(branch) => { - println!("On branch {}", branch); + println!("On branch {branch}"); } } diff --git a/libra/src/command/switch.rs b/libra/src/command/switch.rs index b16dfa0e0..9193cb297 100644 --- a/libra/src/command/switch.rs +++ b/libra/src/command/switch.rs @@ -90,8 +90,7 @@ async fn switch_to_branch(branch_name: String) { if target_branch.is_none() { if !Branch::search_branch(&branch_name).await.is_empty() { eprintln!( - "fatal: a branch is expected, got remote branch {}", - branch_name + "fatal: a branch is expected, got remote branch {branch_name}" ); } else { eprintln!("fatal: branch '{}' not found", &branch_name); @@ -133,6 +132,6 @@ mod tests { &commit_id.to_string(), "./", ]); - println!("{:?}", restore_args); + println!("{restore_args:?}"); } } diff --git a/libra/src/internal/config.rs b/libra/src/internal/config.rs index 0d473ffed..e0992663b 100644 --- a/libra/src/internal/config.rs +++ b/libra/src/internal/config.rs @@ -99,7 +99,7 @@ impl Config { pub async fn get_remote_url(remote: &str) -> String { match Config::get("remote", Some(remote), "url").await { Some(url) => url, - None => panic!("fatal: No URL configured for remote '{}'.", remote), + None => panic!("fatal: No URL configured for remote '{remote}'."), } } @@ -181,7 +181,7 @@ impl Config { .await .unwrap(); if remote.is_empty() { - return Err(format!("fatal: No such remote: {}", name)); + return Err(format!("fatal: No such remote: {name}")); } for r in remote { let r: ActiveModel = r.into(); diff --git a/libra/src/internal/db.rs b/libra/src/internal/db.rs index ef028651e..b4d9b7e3b 100644 --- a/libra/src/internal/db.rs +++ b/libra/src/internal/db.rs @@ -24,11 +24,11 @@ pub async fn establish_connection(db_path: &str) -> Result = OnceCell::const_new(); @@ -149,13 +149,13 @@ pub async fn create_database(db_path: &str) -> io::Result { } std::fs::File::create(db_path) - .map_err(|err| IOError::other(format!("Failed to create database file: {:?}", err)))?; + .map_err(|err| IOError::other(format!("Failed to create database file: {err:?}")))?; // Connect to the new database and set up the schema. if let Ok(conn) = establish_connection(db_path).await { setup_database_sql(&conn) .await - .map_err(|err| IOError::other(format!("Failed to setup database: {:?}", err)))?; + .map_err(|err| IOError::other(format!("Failed to setup database: {err:?}")))?; Ok(conn) } else { Err(IOError::other("Failed to connect to new database.")) @@ -206,7 +206,7 @@ mod tests { fs::remove_file(db_path).unwrap(); } let result = create_database(db_path).await; - assert!(result.is_ok(), "create_database failed: {:?}", result); + assert!(result.is_ok(), "create_database failed: {result:?}"); assert!(Path::new(db_path).exists()); let result = create_database(db_path).await; assert!(result.is_err()); diff --git a/libra/src/internal/protocol/https_client.rs b/libra/src/internal/protocol/https_client.rs index 767843f35..c1ee5610e 100644 --- a/libra/src/internal/protocol/https_client.rs +++ b/libra/src/internal/protocol/https_client.rs @@ -73,7 +73,7 @@ impl BasicAuth { } // 401 (Unauthorized): username or password is incorrect if try_cnt >= MAX_TRY { - eprintln!("Failed to authenticate after {} attempts", MAX_TRY); + eprintln!("Failed to authenticate after {MAX_TRY} attempts"); break; } eprintln!("Authentication required, retrying..."); @@ -108,7 +108,7 @@ impl HttpsClient { let service: &str = &service.to_string(); let url = self .url - .join(&format!("info/refs?service={}", service)) + .join(&format!("info/refs?service={service}")) .unwrap(); let res = BasicAuth::send(|| async { self.client.get(url.clone()) }) .await @@ -130,10 +130,9 @@ impl HttpsClient { // check Content-Type MUST be application/x-$servicename-advertisement let content_type = res.headers().get("Content-Type").unwrap().to_str().unwrap(); - if content_type != format!("application/x-{}-advertisement", service) { + if content_type != format!("application/x-{service}-advertisement") { return Err(GitError::NetworkError(format!( - "Content-type must be `application/x-{}-advertisement`, but got: {}", - service, content_type + "Content-type must be `application/x-{service}-advertisement`, but got: {content_type}" ))); } @@ -143,10 +142,9 @@ impl HttpsClient { // the first five bytes of the response entity matches the regex ^[0-9a-f]{4}#. // verify the first pkt-line is # service=$servicename, and ignore LF let (_, first_line) = read_pkt_line(&mut response_content); - if first_line[..].ne(format!("# service={}\n", service).as_bytes()) { + if first_line[..].ne(format!("# service={service}\n").as_bytes()) { return Err(GitError::NetworkError(format!( - "Error Response format, didn't start with `# service={}`", - service + "Error Response format, didn't start with `# service={service}`" ))); } @@ -256,16 +254,16 @@ async fn generate_upload_pack_content(have: &Vec, want: &Vec) -> if !write_first_line { add_pkt_line_string( &mut buf, - format!("want {} {} agent=libra/0.1.0\n", w, capability).to_string(), + format!("want {w} {capability} agent=libra/0.1.0\n").to_string(), ); write_first_line = true; } else { - add_pkt_line_string(&mut buf, format!("want {}\n", w).to_string()); + add_pkt_line_string(&mut buf, format!("want {w}\n").to_string()); } } buf.extend(b"0000"); // split pkt-lines with a flush-pkt for h in have { - add_pkt_line_string(&mut buf, format!("have {}\n", h).to_string()); + add_pkt_line_string(&mut buf, format!("have {h}\n").to_string()); } add_pkt_line_string(&mut buf, "done\n".to_string()); diff --git a/libra/src/internal/protocol/lfs_client.rs b/libra/src/internal/protocol/lfs_client.rs index af403d2aa..f6a19011c 100644 --- a/libra/src/internal/protocol/lfs_client.rs +++ b/libra/src/internal/protocol/lfs_client.rs @@ -111,7 +111,7 @@ impl LFSClient { for (oid, _) in &lfs_oids { let path = lfs::lfs_object_path(oid); if !path.exists() { - eprintln!("fatal: LFS object not found: {}", oid); + eprintln!("fatal: LFS object not found: {oid}"); continue; } let size = path.metadata().unwrap().len() as i64; @@ -145,7 +145,7 @@ impl LFSClient { // By default, an LFS server that doesn't implement any locking endpoints should return 404. // This response will not halt any Git pushes. } else if !code.is_success() { - eprintln!("fatal: LFS verify locks failed. Status: {}", code); + eprintln!("fatal: LFS verify locks failed. Status: {code}"); return Err(()); } else { // success @@ -433,7 +433,7 @@ impl LFSClient { file }; - println!("Downloading LFS file: {}", oid); + println!("Downloading LFS file: {oid}"); let parts = links.len(); let mut downloaded: u64 = file.metadata().await?.len(); let mut last_progress = 0.0; @@ -441,7 +441,7 @@ impl LFSClient { for link in links.iter().skip(start_part) { got_parts += 1; if is_chunked { - println!("- part: {}/{}", got_parts, parts); + println!("- part: {got_parts}/{parts}"); } let response = BasicAuth::send(|| async { @@ -495,7 +495,7 @@ impl LFSClient { println!("Downloaded."); Ok(()) } else { - eprintln!("fatal: LFS download failed. Checksum mismatch: {} != {}. Fallback to pointer file.", checksum, oid); + eprintln!("fatal: LFS download failed. Checksum mismatch: {checksum} != {oid}. Fallback to pointer file."); let pointer = lfs::format_pointer_string(oid, size); file.set_len(0).await?; // clear file.seek(tokio::io::SeekFrom::Start(0)).await?; // ensure @@ -628,7 +628,7 @@ impl LFSClient { match data { Ok(data) => break data, Err(e) => { - eprintln!("fatal: LFS download failed. Error: {}. Retry", e); + eprintln!("fatal: LFS download failed. Error: {e}. Retry"); retry += 1; if retry > 5 { eprintln!("fatal: LFS download failed. Retry limit exceeded."); @@ -645,7 +645,7 @@ impl LFSClient { println!("Downloaded(p2p)."); Ok(()) } else { - eprintln!("fatal: LFS download failed. Checksum mismatch: {} != {}. Fallback to pointer file.", checksum, hash); + eprintln!("fatal: LFS download failed. Checksum mismatch: {checksum} != {hash}. Fallback to pointer file."); file.set_len(0).await?; // clear file.rewind().await?; // == seek(0) let pointer = lfs::format_pointer_string(&hash, lfs_info.size as u64); @@ -690,8 +690,7 @@ impl LFSClient { let checksum = hex::encode(checksum.finish().as_ref()); if checksum != hash { eprintln!( - "fatal: chunk download failed. Chunk checksum mismatch: {} != {}", - checksum, hash + "fatal: chunk download failed. Chunk checksum mismatch: {checksum} != {hash}" ); return Err(anyhow!("Chunk checksum mismatch.")); } @@ -754,7 +753,7 @@ impl LFSClient { } pub async fn unlock(&self, id: String, refspec: String, force: bool) -> StatusCode { - let url = self.lfs_url.join(&format!("locks/{}/unlock", id)).unwrap(); + let url = self.lfs_url.join(&format!("locks/{id}/unlock")).unwrap(); let resp = BasicAuth::send(|| async { self.client.post(url.clone()).json(&UnlockRequest { force: Some(force), @@ -844,10 +843,10 @@ mod tests { .post(lfs_client.batch_url.clone()) .json(&batch_request) .headers(lfs::LFS_HEADERS.clone()); - println!("Request {:?}", request); + println!("Request {request:?}"); let response = request.send().await.unwrap(); let text = response.text().await.unwrap(); - println!("Text {:?}", text); + println!("Text {text:?}"); let _resp = serde_json::from_str::(&text).unwrap(); } @@ -863,7 +862,7 @@ mod tests { match client.push_object(&oid, file).await { Ok(_) => println!("Pushed successfully."), - Err(err) => eprintln!("Push failed: {:?}", err), + Err(err) => eprintln!("Push failed: {err:?}"), } } @@ -879,7 +878,7 @@ mod tests { let oid = utils::lfs::calc_lfs_file_hash(file).unwrap(); let sub_oid = "ee225720cc31599c749fbe9b18f6c8346fa3246839f0dea7ffd3224dbb067952".to_string(); // offset 83886080 size 20971520 - let url = format!("http://localhost:8000/objects/{}/{}", oid, sub_oid); + let url = format!("http://localhost:8000/objects/{oid}/{sub_oid}"); let size = 20971520; let offset = 83886080; let data = client diff --git a/libra/src/lib.rs b/libra/src/lib.rs index 5baeb79ef..b83417c14 100644 --- a/libra/src/lib.rs +++ b/libra/src/lib.rs @@ -45,9 +45,9 @@ mod tests { use url::Url; let client = LFSClient::from_url(&Url::parse("https://git.gitmono.org").unwrap()); - println!("{:?}", client); + println!("{client:?}"); let mut report_fn = |progress: f64| { - println!("progress: {:.2}%", progress); + println!("progress: {progress:.2}%"); Ok(()) }; client diff --git a/libra/src/main.rs b/libra/src/main.rs index 26f55d2a9..c14eae154 100644 --- a/libra/src/main.rs +++ b/libra/src/main.rs @@ -19,7 +19,7 @@ fn main() { Ok(_) => {} Err(e) => { if !matches!(e, GitError::RepoNotFound) { - eprintln!("Error: {:?}", e); + eprintln!("Error: {e:?}"); } } } diff --git a/libra/src/utils/client_storage.rs b/libra/src/utils/client_storage.rs index 0497bc9e5..26ad54b54 100644 --- a/libra/src/utils/client_storage.rs +++ b/libra/src/utils/client_storage.rs @@ -152,8 +152,7 @@ impl ClientStorage { if !re.is_match(path) { return Err(GitError::InvalidArgument(format!( - "Invalid reference path: {}", - path + "Invalid reference path: {path}" ))); } for cap in re.captures_iter(path) { @@ -218,8 +217,7 @@ impl ClientStorage { // the index starts from 0 if n == 0 || n > commit.parent_commit_ids.len() { return Err(GitError::ObjectNotFound(format!( - "Parent {} does not exist", - n + "Parent {n} does not exist" ))); } @@ -572,7 +570,7 @@ mod tests { let client_storage = ClientStorage::init(source); let objs = client_storage.list_objects_loose(); for obj in objs { - println!("{}", obj); + println!("{obj}"); } } diff --git a/libra/src/utils/lfs.rs b/libra/src/utils/lfs.rs index 91ab3bfcd..05380bc62 100644 --- a/libra/src/utils/lfs.rs +++ b/libra/src/utils/lfs.rs @@ -75,8 +75,7 @@ pub fn generate_pointer_file(path: impl AsRef) -> (String, String) { pub fn format_pointer_string(oid: &str, size: u64) -> String { format!( - "version {}\noid {}:{}\nsize {}\n", - LFS_VERSION, LFS_HASH_ALGO, oid, size + "version {LFS_VERSION}\noid {LFS_HASH_ALGO}:{oid}\nsize {size}\n" ) } @@ -212,12 +211,12 @@ pub fn parse_pointer_data(data: &[u8]) -> Option<(String, u64)> { } // Start with format `version ...` if let Some(data) = - data.strip_prefix(format!("version {}\noid {}:", LFS_VERSION, LFS_HASH_ALGO).as_bytes()) + data.strip_prefix(format!("version {LFS_VERSION}\noid {LFS_HASH_ALGO}:").as_bytes()) { if data[LFS_OID_LEN] == b'\n' { // check `oid` length let oid = String::from_utf8(data[..LFS_OID_LEN].to_vec()).unwrap(); - if let Some(data) = data.strip_prefix(format!("{}\nsize ", oid).as_bytes()) { + if let Some(data) = data.strip_prefix(format!("{oid}\nsize ").as_bytes()) { let data = String::from_utf8(data[..].to_vec()).unwrap(); if let Ok(size) = data.trim_end().parse::() { return Some((oid, size)); @@ -289,7 +288,7 @@ mod tests { .unwrap(); let (pointer, _oid) = generate_pointer_file(path); - print!("{}", pointer); + print!("{pointer}"); } #[test] @@ -340,7 +339,7 @@ oid sha256:4859402c258b836d02e955d1090e29f586e58b2040504d68afec3d8d43757bba size 10 "#; let res = parse_pointer_data(data.as_bytes()).unwrap(); - println!("{:?}", res); + println!("{res:?}"); assert_eq!( res.0, "4859402c258b836d02e955d1090e29f586e58b2040504d68afec3d8d43757bba" diff --git a/libra/src/utils/test.rs b/libra/src/utils/test.rs index 1662fdb0d..d951d99a7 100644 --- a/libra/src/utils/test.rs +++ b/libra/src/utils/test.rs @@ -127,7 +127,7 @@ pub fn ensure_file(path: impl AsRef, content: Option<&str>) { let path = path.as_ref(); fs::create_dir_all(path.parent().unwrap()).unwrap(); // ensure父目录 let mut file = fs::File::create(util::working_dir().join(path)) - .unwrap_or_else(|_| panic!("Cannot create file:{:?}", path)); + .unwrap_or_else(|_| panic!("Cannot create file:{path:?}")); if let Some(content) = content { file.write_all(content.as_bytes()).unwrap(); } else { diff --git a/libra/src/utils/util.rs b/libra/src/utils/util.rs index fe8d5adec..9a78a2dac 100644 --- a/libra/src/utils/util.rs +++ b/libra/src/utils/util.rs @@ -44,7 +44,7 @@ pub fn try_get_storage_path(path: Option) -> Result if !path.pop() { return Err(io::Error::new( io::ErrorKind::NotFound, - format!("{:?} is not a libra repository", orig), + format!("{orig:?} is not a libra repository"), )); } } @@ -298,9 +298,9 @@ pub async fn get_commit_base(commit_base: &str) -> Result { let commits = storage.search(commit_base).await; if commits.is_empty() { - return Err(format!("fatal: invalid reference: {}", commit_base)); + return Err(format!("fatal: invalid reference: {commit_base}")); } else if commits.len() > 1 { - return Err(format!("fatal: ambiguous argument: {}", commit_base)); + return Err(format!("fatal: ambiguous argument: {commit_base}")); } if !storage.is_object_type(&commits[0], ObjectType::Commit) { Err(format!( @@ -360,8 +360,7 @@ pub fn check_gitignore(work_dir: &PathBuf, target_file: &PathBuf) -> bool { let (ignore, err) = Gitignore::new(&cur_file); if let Some(e) = err { println!( - "warning: There are some invalid globs in libraignore file {:#?}:\n{}\n", - cur_file, e + "warning: There are some invalid globs in libraignore file {cur_file:#?}:\n{e}\n" ); } if let Match::Ignore(_) = ignore.matched(target_file, false) { diff --git a/libra/tests/command/init_test.rs b/libra/tests/command/init_test.rs index 2ee208cd8..93c704414 100644 --- a/libra/tests/command/init_test.rs +++ b/libra/tests/command/init_test.rs @@ -9,7 +9,7 @@ pub fn verify_init(base_dir: &Path) { // Loop through the directories and verify they exist for dir in dirs { let dir_path = base_dir.join(dir); - assert!(dir_path.exists(), "Directory {} does not exist", dir); + assert!(dir_path.exists(), "Directory {dir} does not exist"); } // Additional file verification @@ -17,7 +17,7 @@ pub fn verify_init(base_dir: &Path) { for file in files { let file_path = base_dir.join(file); - assert!(file_path.exists(), "File {} does not exist", file); + assert!(file_path.exists(), "File {file} does not exist"); } } #[tokio::test] diff --git a/libra/tests/command/log_test.rs b/libra/tests/command/log_test.rs index ef7bc3057..f675c7287 100644 --- a/libra/tests/command/log_test.rs +++ b/libra/tests/command/log_test.rs @@ -31,8 +31,7 @@ async fn test_execute_log() { let branch = Branch::find_branch(&branch_name, None).await; if branch.is_none() { panic!( - "fatal: your current branch '{}' does not have any commits yet ", - branch_name + "fatal: your current branch '{branch_name}' does not have any commits yet " ); } } @@ -46,7 +45,7 @@ async fn test_execute_log() { let max_output_number = min(6, reachable_commits.len()); let mut output_number = 6; for commit in reachable_commits.iter().take(max_output_number) { - assert_eq!(commit.message, format!("\nCommit_{}", output_number)); + assert_eq!(commit.message, format!("\nCommit_{output_number}")); output_number -= 1; } } diff --git a/libra/tests/command/switch_test.rs b/libra/tests/command/switch_test.rs index b6dfee604..26b868dd2 100644 --- a/libra/tests/command/switch_test.rs +++ b/libra/tests/command/switch_test.rs @@ -97,7 +97,7 @@ async fn test_switch_function() { _ => panic!("head not detached,unreachable"), // Head::Detached(name) => name.to_string(), }; - println!("detach {:?}", ref_name); + println!("detach {ref_name:?}"); assert_eq!( ref_name, commit_id_str, "detach the head to a commit failed!" @@ -130,7 +130,7 @@ async fn test_parts_of_switch_module_function() { let temp_path = tempdir().unwrap(); test::setup_with_new_libra_in(temp_path.path()).await; let _guard = ChangeDirGuard::new(temp_path.path()); - println!("temp_path {:?}", temp_path); + println!("temp_path {temp_path:?}"); //Test check the branch test_switch_function().await; @@ -149,11 +149,11 @@ async fn test_detach_head_basic() { let temp_path = tempdir().unwrap(); test::setup_with_new_libra_in(temp_path.path()).await; let _guard = ChangeDirGuard::new(temp_path.path()); - println!("temp_path {:?}", temp_path); + println!("temp_path {temp_path:?}"); for i in 0..6 { let args = CommitArgs { - message: format!("commit_{}", i), + message: format!("commit_{i}"), allow_empty: true, conventional: false, amend: false, @@ -191,7 +191,7 @@ async fn test_detach_head_basic() { for i in 6..12 { let args = CommitArgs { - message: format!("commit_{}", i), + message: format!("commit_{i}"), allow_empty: true, conventional: false, amend: false, @@ -247,28 +247,28 @@ async fn test_detach_head_basic() { //detach use commit's ref { switch_to_branch("master".to_string()).await; - let commit_message = switch_to_detach(format!("{}~11", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}~11")).await; assert_eq!(&commit_message, "commit_0"); } { switch_to_branch("master".to_string()).await; - let commit_message = switch_to_detach(format!("{}~11", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}~11")).await; assert_eq!(&commit_message, "commit_0"); } { switch_to_branch("master".to_string()).await; - let commit_message = switch_to_detach(format!("{}~~~~~~~~~~~", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}~~~~~~~~~~~")).await; assert_eq!(&commit_message, "commit_0"); } { switch_to_branch("master".to_string()).await; - let commit_message = switch_to_detach(format!("{}^^^^^^^^^^^", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}^^^^^^^^^^^")).await; assert_eq!(&commit_message, "commit_0"); } { switch_to_branch("master".to_string()).await; - let commit_message = switch_to_detach(format!("{}^~^~^~^~^~^", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}^~^~^~^~^~^")).await; assert_eq!(&commit_message, "commit_0"); } } @@ -291,7 +291,7 @@ async fn create_commit_tree() { let mut commit = Commit::from_tree_id( tree.id, vec![commit_1.id], - &format_commit_msg(&format!("commit_{}", i), None), + &format_commit_msg(&format!("commit_{i}"), None), ); commit.committer.timestamp = (i + 1) as usize; save_object(&commit, &commit.id).unwrap(); @@ -320,7 +320,7 @@ async fn test_detach_head_extra() { let temp_path = tempdir().unwrap(); test::setup_with_new_libra_in(temp_path.path()).await; let _guard = ChangeDirGuard::new(temp_path.path()); - println!("temp_path {:?}", temp_path); + println!("temp_path {temp_path:?}"); create_commit_tree().await; //detach to head @@ -330,16 +330,16 @@ async fn test_detach_head_extra() { } for i in 1..12 { - let commit_message = switch_to_detach(format!("HEAD^{}", i)).await; - assert_eq!(commit_message, format!("commit_{}", i)); + let commit_message = switch_to_detach(format!("HEAD^{i}")).await; + assert_eq!(commit_message, format!("commit_{i}")); //back to the last commit switch_to_branch("master".to_string()).await; } //detach use the branch's ref for i in 1..12 { - let commit_message = switch_to_detach(format!("master^{}", i)).await; - assert_eq!(commit_message, format!("commit_{}", i)); + let commit_message = switch_to_detach(format!("master^{i}")).await; + assert_eq!(commit_message, format!("commit_{i}")); //back to the last commit switch_to_branch("master".to_string()).await; @@ -359,7 +359,7 @@ async fn test_detach_head_extra() { let master_commit_id = Branch::find_branch("master", None).await.unwrap().commit; //detach use commit's ref { - let commit_message = switch_to_detach(format!("{}^11~", master_commit_id)).await; + let commit_message = switch_to_detach(format!("{master_commit_id}^11~")).await; assert_eq!(commit_message, "commit_0".to_string()); switch_to_branch("master".to_string()).await; } diff --git a/libra/tests/mega_test.rs b/libra/tests/mega_test.rs index 8593c9797..b38d824e3 100644 --- a/libra/tests/mega_test.rs +++ b/libra/tests/mega_test.rs @@ -50,7 +50,7 @@ lazy_static! { fn is_port_in_use(port: u16) -> bool { TcpStream::connect_timeout( - &format!("127.0.0.1:{}", port).parse().unwrap(), + &format!("127.0.0.1:{port}").parse().unwrap(), Duration::from_millis(1000), ) .is_ok() @@ -63,7 +63,7 @@ async fn mega_container(mapping_port: u16) -> ContainerAsync { panic!("mega binary not found in \"target/debug/\", skip lfs test"); } if is_port_in_use(mapping_port) { - panic!("port {} is already in use", mapping_port); + panic!("port {mapping_port} is already in use"); } let port_str = mapping_port.to_string(); let cmd = vec![ @@ -103,7 +103,7 @@ pub async fn mega_bootstrap_servers(mapping_port: u16) -> (ContainerAsync (ContainerAsync println!("Pushed successfully."), - Err(err) => eprintln!("Push failed: {:?}", err), + Err(err) => eprintln!("Push failed: {err:?}"), } #[cfg(feature = "p2p")] test_download_chunk_mega(&mega_server_url).await; @@ -136,7 +136,7 @@ async fn test_download_chunk_mega(mega_server_url: &str) { let client = LFSClient::from_url(&Url::parse(mega_server_url).unwrap()); let oid = lfs::calc_lfs_file_hash(file).unwrap(); let sub_oid = "ee225720cc31599c749fbe9b18f6c8346fa3246839f0dea7ffd3224dbb067952".to_string(); // offset 83886080 size 20971520 - let url = format!("{}/objects/{}/{}", mega_server_url, oid, sub_oid); + let url = format!("{mega_server_url}/objects/{oid}/{sub_oid}"); let size = 20971520; let offset = 83886080; let data = client diff --git a/mega/tests/lfs_test.rs b/mega/tests/lfs_test.rs index 07e5ab3bd..9abc5ab25 100644 --- a/mega/tests/lfs_test.rs +++ b/mega/tests/lfs_test.rs @@ -109,7 +109,7 @@ fn run_libra_cmd_with_stdin(args: &[&str], stdin: Option<&str>, envs: Option bool { TcpStream::connect_timeout( - &format!("127.0.0.1:{}", port).parse().unwrap(), + &format!("127.0.0.1:{port}").parse().unwrap(), Duration::from_millis(1000), ) .is_ok() @@ -121,14 +121,14 @@ fn run_mega_server(data_dir: &Path, http_port: u16) -> ChildGuard { panic!("mega binary not found in \"target/debug/\", skip lfs test"); } if is_port_in_use(http_port) { - panic!("port {} is already in use", http_port); + panic!("port {http_port} is already in use"); } // env var can be shared between parent and child process env::set_var("MEGA_BASE_DIR", data_dir); let server = Command::new(MEGA.to_str().unwrap()) - .args(["service", "multi", "http", "-p", &format!("{}", http_port)]) + .args(["service", "multi", "http", "-p", &format!("{http_port}")]) .current_dir(env!("CARGO_MANIFEST_DIR")) .spawn() .expect("Failed to start mega server"); @@ -140,7 +140,7 @@ fn run_mega_server(data_dir: &Path, http_port: u16) -> ChildGuard { i += 1; } assert!(is_port_in_use(http_port), "mega server not started"); - println!("mega server started in {} secs", i); + println!("mega server started in {i} secs"); thread::sleep(Duration::from_secs(1)); // server @@ -165,7 +165,7 @@ fn generate_large_file(path: &str, size_mb: usize) -> io::Result<()> { fn git_lfs_push(url: &str, lfs_url: &str) -> io::Result<()> { let temp_dir = TempDir::new()?; let repo_path = temp_dir.path().to_str().unwrap(); - println!("repo_path: {}", repo_path); + println!("repo_path: {repo_path}"); // git init run_git_cmd(&["init", repo_path]); @@ -193,7 +193,7 @@ fn git_lfs_push(url: &str, lfs_url: &str) -> io::Result<()> { fn libra_lfs_push(url: &str) -> io::Result<()> { let temp_dir = TempDir::new()?; let repo_path = temp_dir.path().to_str().unwrap(); - println!("repo_path: {}", repo_path); + println!("repo_path: {repo_path}"); env::set_current_dir(repo_path)?; @@ -228,7 +228,7 @@ fn git_lfs_clone(url: &str, lfs_url: &str) -> io::Result<()> { env::set_current_dir(temp_dir.path())?; // git clone url // `--config`: temporary set lfs.url - run_git_cmd(&["clone", url, "--config", &format!("lfs.url={}", lfs_url)]); + run_git_cmd(&["clone", url, "--config", &format!("lfs.url={lfs_url}")]); let file = Path::new("lfs/large_file.bin"); assert!(file.exists(), "Failed to clone large file"); @@ -267,8 +267,8 @@ fn lfs_split_with_git() { // start mega server at background (new process) let mega = run_mega_server(mega_dir.path(), 58001); let mega_start_port = 58001; - let url = &format!("http://localhost:{}/third-party/lfs.git", mega_start_port); - let lfs_url = format!("http://localhost:{}", mega_start_port); + let url = &format!("http://localhost:{mega_start_port}/third-party/lfs.git"); + let lfs_url = format!("http://localhost:{mega_start_port}"); let push_result = git_lfs_push(url, &lfs_url); let clone_result = git_lfs_clone(url, &lfs_url); @@ -315,7 +315,7 @@ async fn mega_container(mapping_port: u16) -> ContainerAsync { panic!("mega binary not found in \"target/debug/\", skip lfs test"); } if is_port_in_use(mapping_port) { - panic!("port {} is already in use", mapping_port); + panic!("port {mapping_port} is already in use"); } let port_str = mapping_port.to_string(); let cmd = vec![ @@ -357,7 +357,7 @@ pub async fn mega_bootstrap_servers(mapping_port: u16) -> (ContainerAsync (ContainerAsync std::fmt::Result { writeln!(f, "tree: {}", self.tree_id)?; for parent in self.parent_commit_ids.iter() { - writeln!(f, "parent: {}", parent)?; + writeln!(f, "parent: {parent}")?; } writeln!(f, "author {}", self.author)?; writeln!(f, "committer {}", self.committer)?; diff --git a/mercury/src/internal/object/mod.rs b/mercury/src/internal/object/mod.rs index e79d51175..f6b708eb6 100644 --- a/mercury/src/internal/object/mod.rs +++ b/mercury/src/internal/object/mod.rs @@ -42,7 +42,7 @@ pub trait ObjectTrait: Send + Sync + Display { let hash_str = h.finalize(); Self::from_bytes( &content, - SHA1::from_str(&format!("{:x}", hash_str)).unwrap(), + SHA1::from_str(&format!("{hash_str:x}")).unwrap(), ) .unwrap() } diff --git a/mercury/src/internal/object/signature.rs b/mercury/src/internal/object/signature.rs index 391c0afbb..f53d541e8 100644 --- a/mercury/src/internal/object/signature.rs +++ b/mercury/src/internal/object/signature.rs @@ -193,7 +193,7 @@ impl Signature { let minutes = offset / 60 % 60; // Format the offset as a string (e.g., "+0800", "-0300", etc.) - let offset_str = format!("{:+03}{:02}", hours, minutes); + let offset_str = format!("{hours:+03}{minutes:02}"); // Return the Signature struct with the provided information Signature { diff --git a/mercury/src/internal/object/tree.rs b/mercury/src/internal/object/tree.rs index ec8bdcdca..4940c3798 100644 --- a/mercury/src/internal/object/tree.rs +++ b/mercury/src/internal/object/tree.rs @@ -174,8 +174,7 @@ impl TreeItem { let (decoded, _, had_errors) = GBK.decode(raw_name); if had_errors { return Err(GitError::InvalidTreeItem(format!( - "Unsupported raw format: {:?}", - raw_name + "Unsupported raw format: {raw_name:?}" ))); } else { decoded.to_string() @@ -237,7 +236,7 @@ impl Display for Tree { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!(f, "Tree: {}", self.id.to_string().blue())?; for item in &self.tree_items { - writeln!(f, "{}", item)?; + writeln!(f, "{item}")?; } Ok(()) } diff --git a/mercury/src/internal/object/types.rs b/mercury/src/internal/object/types.rs index 62f13d308..7d272df8d 100644 --- a/mercury/src/internal/object/types.rs +++ b/mercury/src/internal/object/types.rs @@ -111,8 +111,7 @@ impl ObjectType { 6 => Ok(ObjectType::OffsetDelta), 7 => Ok(ObjectType::HashDelta), _ => Err(GitError::InvalidObjectType(format!( - "Invalid object type number: {}", - number + "Invalid object type number: {number}" ))), } } diff --git a/mercury/src/internal/pack/cache_object.rs b/mercury/src/internal/pack/cache_object.rs index 94ed7c602..0f3d9e1a2 100644 --- a/mercury/src/internal/pack/cache_object.rs +++ b/mercury/src/internal/pack/cache_object.rs @@ -318,7 +318,7 @@ impl Drop for ArcWrapper { if !complete_signal.load(Ordering::Acquire) { let res = data_copy.f_save(&path_copy); if let Err(e) = res { - println!("[f_save] {:?} error: {:?}", path_copy, e); + println!("[f_save] {path_copy:?} error: {e:?}"); } } }); @@ -326,7 +326,7 @@ impl Drop for ArcWrapper { None => { let res = self.data.f_save(path); if let Err(e) = res { - println!("[f_save] {:?} error: {:?}", path, e); + println!("[f_save] {path:?} error: {e:?}"); } } } diff --git a/mercury/src/internal/pack/decode.rs b/mercury/src/internal/pack/decode.rs index 6cf703280..0db2f2053 100644 --- a/mercury/src/internal/pack/decode.rs +++ b/mercury/src/internal/pack/decode.rs @@ -134,8 +134,7 @@ impl Pack { Err(e) => { // If there is an error in reading, return a GitError return Err(GitError::InvalidPackFile(format!( - "Error reading magic identifier: {}", - e + "Error reading magic identifier: {e}" ))); } } @@ -153,16 +152,14 @@ impl Pack { if version != 2 { // Git currently supports version 2, so error if not version 2 return Err(GitError::InvalidPackFile(format!( - "Version Number is {}, not 2", - version + "Version Number is {version}, not 2" ))); } } Err(e) => { // If there is an error in reading, return a GitError return Err(GitError::InvalidPackFile(format!( - "Error reading version number: {}", - e + "Error reading version number: {e}" ))); } } @@ -183,8 +180,7 @@ impl Pack { Err(e) => { // If there is an error in reading, return a GitError Err(GitError::InvalidPackFile(format!( - "Error reading object number: {}", - e + "Error reading object number: {e}" ))) } } @@ -230,8 +226,7 @@ impl Pack { Err(e) => { // If there is an error in reading, return a GitError Err(GitError::InvalidPackFile(format!( - "Decompression error: {}", - e + "Decompression error: {e}" ))) } } @@ -261,7 +256,7 @@ impl Pack { Err(e) => { // Handle the error e.g., by logging it or converting it to GitError // and then return from the function - return Err(GitError::InvalidPackFile(format!("Read error: {}", e))); + return Err(GitError::InvalidPackFile(format!("Read error: {e}"))); } }; @@ -489,7 +484,7 @@ impl Pack { thread::spawn(move || { self.decode(&mut pack, move |entry, _| { if let Err(e) = sender.send(entry) { - eprintln!("Channel full, failed to send entry: {:?}", e); + eprintln!("Channel full, failed to send entry: {e:?}"); } }) .unwrap(); @@ -509,7 +504,7 @@ impl Pack { while let Some(chunk) = stream.next().await { let data = chunk.unwrap().to_vec(); if let Err(e) = tx.send(data) { - eprintln!("Sending Error: {:?}", e); + eprintln!("Sending Error: {e:?}"); break; } } @@ -520,7 +515,7 @@ impl Pack { self.decode(&mut reader, move |entry: Entry, _| { // as we used unbound channel here, it will never full so can be send with synchronous if let Err(e) = sender.send(entry) { - eprintln!("unbound channel Sending Error: {:?}", e); + eprintln!("unbound channel Sending Error: {e:?}"); } }) .unwrap(); @@ -613,7 +608,7 @@ impl Pack { Err(err) => { panic!( "{}", - GitError::DeltaObjectError(format!("Wrong instruction in delta :{}", err)) + GitError::DeltaObjectError(format!("Wrong instruction in delta :{err}")) ); } }; diff --git a/mercury/src/lib.rs b/mercury/src/lib.rs index 54f9f557f..0001ecdec 100644 --- a/mercury/src/lib.rs +++ b/mercury/src/lib.rs @@ -82,9 +82,8 @@ pub mod test_utils { async fn download_lfs_file_if_not_exist(file_name: &str, output_path: &PathBuf, sha256: &str) { let url = format!( - "https://gitmono.s3.ap-southeast-2.amazonaws.com/packs/{}", + "https://gitmono.s3.ap-southeast-2.amazonaws.com/packs/{file_name}", // "https://gitmono.oss-cn-beijing.aliyuncs.com/{}", - file_name ); if !check_file_hash(output_path, sha256).await { download_file(&url, output_path).await.unwrap(); diff --git a/mono/src/api/api_router.rs b/mono/src/api/api_router.rs index bdb80a94b..e93e4206d 100644 --- a/mono/src/api/api_router.rs +++ b/mono/src/api/api_router.rs @@ -143,18 +143,18 @@ async fn get_tree_info( state: State, ) -> Result>, ApiError> { let mut parts = Vec::new(); + + let normalized_path = PathBuf::from(query.path.clone()); + let mut segments = normalized_path.components().peekable(); let mut current = String::new(); - let mut segments = query.path.split('/').peekable(); while let Some(segment) = segments.next() { - if segment.is_empty() { - current = "/".to_string(); - parts.push(current.clone()); - } else if segments.peek().is_some() { - if current != "/" { + let part = segment.as_os_str().to_string_lossy().to_string(); + if segments.peek().is_some() { + if current != "/" && part != "/" { current.push('/'); } - current.push_str(segment); + current.push_str(&part); parts.push(current.clone()); } } @@ -273,7 +273,7 @@ pub async fn get_blob_file( let api_handler = state.monorepo(); let result = api_handler.get_raw_blob_by_hash(&oid).await.unwrap(); - let file_name = format!("inline; filename=\"{}\"", oid); + let file_name = format!("inline; filename=\"{oid}\""); match result { Some(model) => Ok(Response::builder() .header("Content-Type", "application/octet-stream") diff --git a/mono/src/api/issue/issue_router.rs b/mono/src/api/issue/issue_router.rs index e9d797032..6ff00628a 100644 --- a/mono/src/api/issue/issue_router.rs +++ b/mono/src/api/issue/issue_router.rs @@ -108,13 +108,13 @@ async fn new_issue( ) -> Result>, ApiError> { let stg = state.issue_stg().clone(); let res = stg - .save_issue(&user.campsite_user_id, &json.title) + .save_issue(&user.username, &json.title) .await .unwrap(); let _ = stg .add_conversation( &res.link, - &user.campsite_user_id, + &user.username, Some(json.description), ConvTypeEnum::Comment, ) @@ -187,7 +187,7 @@ async fn save_comment( .issue_stg() .add_conversation( &link, - &user.campsite_user_id, + &user.username, Some(payload.content), ConvTypeEnum::Comment, ) @@ -259,7 +259,7 @@ pub async fn common_label_update( let to_remove: Vec = old_ids.difference(&new_ids).copied().collect(); issue_storage - .modify_labels(&user.campsite_user_id, item_id, &link, to_add, to_remove) + .modify_labels(&user.username, item_id, &link, to_add, to_remove) .await?; Ok(Json(CommonResult::success(None))) } diff --git a/mono/src/api/lfs/lfs_router.rs b/mono/src/api/lfs/lfs_router.rs index 61191beee..9f828168c 100644 --- a/mono/src/api/lfs/lfs_router.rs +++ b/mono/src/api/lfs/lfs_router.rs @@ -116,7 +116,7 @@ pub async fn list_locks_for_verification( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -143,7 +143,7 @@ pub async fn create_lock( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -171,7 +171,7 @@ pub async fn delete_lock( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -196,7 +196,7 @@ pub async fn lfs_process_batch( Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -225,7 +225,7 @@ pub async fn lfs_fetch_chunk_ids( tracing::error!("Error: {}", err); Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -244,7 +244,7 @@ pub async fn lfs_download_object( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -283,7 +283,7 @@ pub async fn lfs_download_chunk( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } @@ -319,7 +319,7 @@ pub async fn lfs_upload_object( Err(err) => Ok({ Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::from(format!("Error: {}", err))) + .body(Body::from(format!("Error: {err}"))) .unwrap() }), } diff --git a/mono/src/api/mod.rs b/mono/src/api/mod.rs index 9ecbd6149..40a17d115 100644 --- a/mono/src/api/mod.rs +++ b/mono/src/api/mod.rs @@ -169,14 +169,14 @@ pub mod util { let entities = get_entitystore(path.into(), state).await; let cedar_context = CedarContext::new(entities).unwrap(); cedar_context.is_authorized( - format!(r#"User::"{}""#, username) + format!(r#"User::"{username}""#) .to_owned() .parse::() .unwrap(), - format!(r#"Action::"{}""#, operation) + format!(r#"Action::"{operation}""#) .parse::() .unwrap(), - format!(r#"Repository::"{}""#, path) + format!(r#"Repository::"{path}""#) .parse::() .unwrap(), Context::empty(), diff --git a/mono/src/api/mr/mod.rs b/mono/src/api/mr/mod.rs index 6009670ab..cb9a60469 100644 --- a/mono/src/api/mr/mod.rs +++ b/mono/src/api/mr/mod.rs @@ -69,7 +69,7 @@ impl From for MRDetail { #[derive(Serialize, Deserialize, ToSchema)] pub struct MegaConversation { pub id: i64, - pub user_id: String, + pub username: String, pub conv_type: ConvTypeEnum, pub comment: Option, pub created_at: i64, @@ -80,7 +80,7 @@ impl From for MegaConversation { fn from(value: mega_conversation::Model) -> Self { Self { id: value.id, - user_id: value.user_id, + username: value.username, conv_type: value.conv_type, comment: value.comment, created_at: value.created_at.and_utc().timestamp(), diff --git a/mono/src/api/mr/mr_router.rs b/mono/src/api/mr/mr_router.rs index 0135ef254..968f368c3 100644 --- a/mono/src/api/mr/mr_router.rs +++ b/mono/src/api/mr/mr_router.rs @@ -76,8 +76,8 @@ async fn reopen_mr( .issue_stg() .add_conversation( &link, - &user.campsite_user_id, - Some(format!("{} reopen this", user.name)), + &user.username, + Some(format!("{} reopen this", user.username)), ConvTypeEnum::Reopen, ) .await @@ -121,8 +121,8 @@ async fn close_mr( .issue_stg() .add_conversation( &link, - &user.campsite_user_id, - Some(format!("{} closed this", user.name)), + &user.username, + Some(format!("{} closed this", user.username)), ConvTypeEnum::Closed, ) .await?; @@ -153,7 +153,7 @@ async fn merge( if model.status == MergeStatusEnum::Open { let path = model.path.clone(); util::check_permissions( - &user.name, + &user.username, &path, ActionEnum::ApproveMergeRequest, state.clone(), @@ -162,7 +162,7 @@ async fn merge( .unwrap(); state .monorepo() - .merge_mr(user.campsite_user_id, model) + .merge_mr(&user.username, model) .await?; } Ok(Json(CommonResult::success(None))) @@ -287,7 +287,7 @@ async fn save_comment( .issue_stg() .add_conversation( &model.link, - &user.campsite_user_id, + &user.username, Some(payload.content), ConvTypeEnum::Comment, ) @@ -402,7 +402,7 @@ mod test { let files_with_status = extract_files_with_status(diff_output); println!("Files with status:"); for (file, status) in &files_with_status { - println!("{} ({})", file, status); + println!("{file} ({status})"); } let mut expected = HashMap::new(); diff --git a/mono/src/api/oauth/campsite_store.rs b/mono/src/api/oauth/campsite_store.rs index 4bd2ce42c..655c04e9e 100644 --- a/mono/src/api/oauth/campsite_store.rs +++ b/mono/src/api/oauth/campsite_store.rs @@ -28,7 +28,7 @@ impl SessionStore for CampsiteApiStore { let resp = self .client .get(url) - .header(COOKIE, format!("{}={}", CAMPSITE_API_COOKIE, cookie_value)) + .header(COOKIE, format!("{CAMPSITE_API_COOKIE}={cookie_value}")) .send() .await?; diff --git a/mono/src/api/oauth/mod.rs b/mono/src/api/oauth/mod.rs index 2dee46792..3a23d98f9 100644 --- a/mono/src/api/oauth/mod.rs +++ b/mono/src/api/oauth/mod.rs @@ -176,7 +176,7 @@ pub fn oauth_client(oauth_config: OauthConfig) -> Result let client_secret = oauth_config.github_client_secret; let ui_domain = oauth_config.ui_domain; - let redirect_url = format!("{}/auth/authorized", ui_domain); + let redirect_url = format!("{ui_domain}/auth/authorized"); let auth_url = "https://github.com/login/oauth/authorize".to_string(); diff --git a/mono/src/api/oauth/model.rs b/mono/src/api/oauth/model.rs index ce9db36c1..a933ca0e6 100644 --- a/mono/src/api/oauth/model.rs +++ b/mono/src/api/oauth/model.rs @@ -52,7 +52,7 @@ pub struct CampsiteUserJson { impl From for LoginUser { fn from(value: CampsiteUserJson) -> Self { Self { - name: value.username, + username: value.username, email: value.email.unwrap_or_default(), avatar_url: value.avatar_url, campsite_user_id: value.id, @@ -64,7 +64,7 @@ impl From for LoginUser { #[derive(Serialize, Deserialize, Clone, Debug)] pub struct LoginUser { pub campsite_user_id: String, - pub name: String, + pub username: String, pub avatar_url: String, pub email: String, pub created_at: NaiveDateTime, @@ -73,11 +73,11 @@ pub struct LoginUser { impl From for LoginUser { fn from(value: user::Model) -> Self { Self { - name: value.name, avatar_url: value.avatar_url, email: value.email, created_at: value.created_at, campsite_user_id: String::new(), + username: String::new() } } } diff --git a/mono/src/git_protocol/http.rs b/mono/src/git_protocol/http.rs index 2a55c52ee..dce06bfbe 100644 --- a/mono/src/git_protocol/http.rs +++ b/mono/src/git_protocol/http.rs @@ -31,7 +31,7 @@ pub async fn git_info_refs( let pkt_line_stream = pack_protocol.git_info_refs().await?; - let content_type = format!("application/x-{}-advertisement", service_name); + let content_type = format!("application/x-{service_name}-advertisement"); let response = add_default_header( content_type, Response::builder() diff --git a/mono/src/server/https_server.rs b/mono/src/server/https_server.rs index a0852ff49..b19ffb2b2 100644 --- a/mono/src/server/https_server.rs +++ b/mono/src/server/https_server.rs @@ -48,7 +48,7 @@ pub async fn start_http(ctx: AppContext, options: CommonHttpOptions) { let app = app(ctx.storage, host.clone(), port).await; - let server_url = format!("{}:{}", host, port); + let server_url = format!("{host}:{port}"); let addr = SocketAddr::from_str(&server_url).unwrap(); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); @@ -99,7 +99,7 @@ pub async fn app(storage: Storage, host: String, port: u16) -> Router { storage: storage.clone(), oauth_client: Some(oauth_client(oauth_config.clone()).unwrap()), store: Some(CampsiteApiStore::new(oauth_config.campsite_api_domain)), - listen_addr: format!("http://{}:{}", host, port), + listen_addr: format!("http://{host}:{port}"), }; let origins: Vec = oauth_config @@ -227,6 +227,6 @@ mod test { let mut file = fs::File::create(temp_path).unwrap(); let json = ApiDoc::openapi().to_pretty_json().unwrap(); file.write_all(json.as_bytes()).unwrap(); - println!("{}", json); + println!("{json}"); } } diff --git a/mono/src/server/ssh_server.rs b/mono/src/server/ssh_server.rs index 2773323a3..d590e88fa 100644 --- a/mono/src/server/ssh_server.rs +++ b/mono/src/server/ssh_server.rs @@ -63,7 +63,7 @@ pub async fn start_server(ctx: AppContext, command: &SshOptions) { smart_protocol: None, data_combined: BytesMut::new(), }; - let server_url = format!("{}:{}", host, ssh_port); + let server_url = format!("{host}:{ssh_port}"); let addr = SocketAddr::from_str(&server_url).unwrap(); ssh_server.run_on_address(ru_config, addr).await.unwrap(); } @@ -87,7 +87,7 @@ pub fn load_key(ctx: AppContext) -> PrivateKey { match ctx.vault.write_secret("ssh_server_key", Some(secret)) { Ok(_) => keys, Err(e) => { - panic!("Failed to write SSH server key to vault: {}", e); + panic!("Failed to write SSH server key to vault: {e}"); } } } diff --git a/moon/packages/types/generated.ts b/moon/packages/types/generated.ts index 0f16fdfc7..dd036d03c 100644 --- a/moon/packages/types/generated.ts +++ b/moon/packages/types/generated.ts @@ -3269,7 +3269,7 @@ export type MegaConversation = { id: number /** @format int64 */ updated_at: number - user_id: string + username: string } export enum MergeStatusEnum { diff --git a/orion-server/src/server.rs b/orion-server/src/server.rs index bade5a53d..ef8e18567 100644 --- a/orion-server/src/server.rs +++ b/orion-server/src/server.rs @@ -30,7 +30,7 @@ pub async fn start_server(port: u16) { tracing::info!("Listening on port {}", port); - let addr = tokio::net::TcpListener::bind(&format!("0.0.0.0:{}", port)) + let addr = tokio::net::TcpListener::bind(&format!("0.0.0.0:{port}")) .await .unwrap(); axum::serve( diff --git a/saturn/src/entitystore.rs b/saturn/src/entitystore.rs index 09f558574..313d7f55f 100644 --- a/saturn/src/entitystore.rs +++ b/saturn/src/entitystore.rs @@ -86,9 +86,9 @@ pub fn generate_entity(user: &str, repo: &str) -> Result Result "deleteIssue", ActionEnum::DeleteMergeRequest => "deleteMergeRequest", }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/vault/src/integration/jupiter_backend.rs b/vault/src/integration/jupiter_backend.rs index 06b39f85a..f8789cd9d 100644 --- a/vault/src/integration/jupiter_backend.rs +++ b/vault/src/integration/jupiter_backend.rs @@ -23,7 +23,7 @@ impl Backend for JupiterBackend { match service.list_keys(prefix).await { Ok(keys) => Ok(keys), Err(e) => { - println!("list {:?}", e); + println!("list {e:?}"); Err(rusty_vault::errors::RvError::ErrAuthModuleDisabled) } } @@ -53,7 +53,7 @@ impl Backend for JupiterBackend { } Ok(None) => Ok(None), Err(e) => { - println!("get {:?}", e); + println!("get {e:?}"); Err(rusty_vault::errors::RvError::ErrAuthModuleDisabled) } } @@ -61,7 +61,7 @@ impl Backend for JupiterBackend { }) .join() .inspect_err(|e| { - eprintln!("Error in JupiterBackend::get: {:?}", e); + eprintln!("Error in JupiterBackend::get: {e:?}"); }) .unwrap() } @@ -79,7 +79,7 @@ impl Backend for JupiterBackend { match service.save(entry_clone.key, entry_clone.value).await { Ok(_) => Ok(()), Err(e) => { - println!("put {:?}", e); + println!("put {e:?}"); Err(rusty_vault::errors::RvError::ErrAuthModuleDisabled) } } @@ -99,7 +99,7 @@ impl Backend for JupiterBackend { match service.delete(key).await { Ok(_) => Ok(()), Err(e) => { - println!("delete {:?}", e); + println!("delete {e:?}"); Err(rusty_vault::errors::RvError::ErrAuthModuleDisabled) } } diff --git a/vault/src/integration/vault_core.rs b/vault/src/integration/vault_core.rs index c4dd33345..ee07f5651 100644 --- a/vault/src/integration/vault_core.rs +++ b/vault/src/integration/vault_core.rs @@ -127,7 +127,7 @@ impl VaultCoreInterface for VaultCore { let guard = self.core.read().unwrap(); guard .handle_request(&mut req) - .map_err(|e| MegaError::with_message(format!("Failed to read from vault API: {}", e))) + .map_err(|e| MegaError::with_message(format!("Failed to read from vault API: {e}"))) } fn write_api( @@ -156,22 +156,22 @@ impl VaultCoreInterface for VaultCore { } fn write_secret(&self, name: &str, data: Option>) -> Result<(), MegaError> { - self.write_api(format!("secret/{}", name), data) - .map_err(|_| MegaError::with_message(format!("Failed to write secret: {}", name)))?; + self.write_api(format!("secret/{name}"), data) + .map_err(|_| MegaError::with_message(format!("Failed to write secret: {name}")))?; Ok(()) } fn read_secret(&self, name: &str) -> Result>, MegaError> { let resp = self - .read_api(format!("secret/{}", name)) - .map_err(|_| MegaError::with_message(format!("Failed to read secret: {}", name)))?; + .read_api(format!("secret/{name}")) + .map_err(|_| MegaError::with_message(format!("Failed to read secret: {name}")))?; Ok(resp.and_then(|r| r.data)) } fn delete_secret(&self, name: &str) -> Result<(), MegaError> { - self.delete_api(format!("secret/{}", name)) - .map_err(|_| MegaError::with_message(format!("Failed to delete secret: {}", name)))?; + self.delete_api(format!("secret/{name}")) + .map_err(|_| MegaError::with_message(format!("Failed to delete secret: {name}")))?; Ok(()) } } @@ -245,8 +245,7 @@ mod tests { .expect("Secret should exist"); assert_eq!( read_value, *value, - "Read value does not match written value for {}", - name + "Read value does not match written value for {name}" ); } @@ -260,8 +259,7 @@ mod tests { assert!(read_value.is_ok()); assert!( read_value.unwrap().is_none(), - "Secret {} should be deleted but still exists", - name + "Secret {name} should be deleted but still exists" ); } } diff --git a/vault/src/nostr.rs b/vault/src/nostr.rs index 9213170af..86e62abd1 100644 --- a/vault/src/nostr.rs +++ b/vault/src/nostr.rs @@ -82,8 +82,8 @@ mod tests { #[test] fn test_generate_nostr_id() { let (nostr, keypair) = generate_nostr_id(); - println!("nostr: {:?}", nostr); - println!("keypair: {:?}", keypair); + println!("nostr: {nostr:?}"); + println!("keypair: {keypair:?}"); let secret_key = keypair.0; let public_key = keypair.1; diff --git a/vault/src/pgp.rs b/vault/src/pgp.rs index 4631caeb7..851bd1443 100644 --- a/vault/src/pgp.rs +++ b/vault/src/pgp.rs @@ -115,14 +115,14 @@ impl VaultCore { .clone(); self.write_secret(VAULT_KEY, Some(data)) .unwrap_or_else(|e| { - panic!("Failed to write PGP keys: {:?}", e); + panic!("Failed to write PGP keys: {e:?}"); }); } /// Deletes the key pair from the vault. pub fn delete_keys(&self) { self.delete_secret(VAULT_KEY).unwrap_or_else(|e| { - panic!("Failed to delete PGP keys: {:?}", e); + panic!("Failed to delete PGP keys: {e:?}"); }); } diff --git a/vault/src/pki.rs b/vault/src/pki.rs index 7ca94082d..37cba8966 100644 --- a/vault/src/pki.rs +++ b/vault/src/pki.rs @@ -101,7 +101,7 @@ impl VaultCore { .clone(); // config role - self.write_api(format!("pki/roles/{}", ROLE), Some(role_data)) + self.write_api(format!("pki/roles/{ROLE}"), Some(role_data)) .expect("Failed to configure role"); } @@ -116,7 +116,7 @@ impl VaultCore { .clone(); // issue cert - let resp = self.write_api(format!("pki/issue/{}", ROLE), Some(issue_data)); + let resp = self.write_api(format!("pki/issue/{ROLE}"), Some(issue_data)); let resp_body = resp.unwrap(); let cert_data = resp_body.unwrap().data.unwrap(); @@ -293,7 +293,7 @@ mod tests_raw { let data = resp.unwrap().data; assert!(data.is_some()); let role_data = data.unwrap(); - println!("role_data: {:?}", role_data); + println!("role_data: {role_data:?}"); assert_eq!(role_data["ttl"].as_u64().unwrap(), 60 * 24 * 60 * 60); assert_eq!(role_data["max_ttl"].as_u64().unwrap(), 365 * 24 * 60 * 60); assert_eq!(role_data["not_before_duration"].as_u64().unwrap(), 30); @@ -499,7 +499,7 @@ mod tests_raw { ); let mut root_token = String::new(); - println!("root_token: {:?}", root_token); + println!("root_token: {root_token:?}"); let mut conf: HashMap = HashMap::new(); conf.insert( @@ -528,7 +528,7 @@ mod tests_raw { let result = core.init(&seal_config); assert!(result.is_ok()); let init_result = result.unwrap(); - println!("init_result: {:?}", init_result); + println!("init_result: {init_result:?}"); let mut unsealed = false; for i in 0..seal_config.secret_threshold { @@ -544,7 +544,7 @@ mod tests_raw { } { - println!("root_token: {:?}", root_token); + println!("root_token: {root_token:?}"); test_pki_config_ca(Arc::clone(&c), &root_token).await; test_pki_generate_root(Arc::clone(&c), &root_token, false, true).await; test_pki_config_role(Arc::clone(&c), &root_token).await;