Skip to content

Commit

Permalink
chore: fix clippy errors & reenable warnings check (#915)
Browse files Browse the repository at this point in the history
  • Loading branch information
miraclx authored Oct 31, 2024
1 parent 70222f4 commit f1ddc4c
Show file tree
Hide file tree
Showing 21 changed files with 66 additions and 67 deletions.
2 changes: 1 addition & 1 deletion .github/actions/style/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ runs:
echo "Rust code is not properly formatted."
exit 1 # Exit with a non-zero status code if formatting fails
fi
if ! cargo clippy; then
if ! cargo clippy -- -D warnings; then
echo "Rust code is not properly linted."
exit 1 # Exit with a non-zero status code if formatting fails
fi
Expand Down
4 changes: 0 additions & 4 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions apps/kv-store/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::len_without_is_empty)]

use std::collections::BTreeMap;

use calimero_sdk::types::Error;
Expand Down
28 changes: 11 additions & 17 deletions contracts/proxy-lib/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use core::str;
use std::collections::HashSet;
use std::usize;

use calimero_context_config::repr::{Repr, ReprTransmute};
use calimero_context_config::types::{ContextId, Signed, SignerId};
Expand Down Expand Up @@ -127,20 +126,20 @@ impl ProxyContract {
num_proposals <= self.active_proposals_limit,
"Account has too many active proposals. Confirm or delete some."
);
return self.perform_action_by_member(MemberAction::Create {
self.perform_action_by_member(MemberAction::Create {
proposal,
num_proposals,
});
})
}

pub fn approve(&mut self, proposal: Signed<ProposalApprovalWithSigner>) -> Promise {
let proposal = proposal
.parse(|i| *i.signer_id)
.expect("failed to parse input");
return self.perform_action_by_member(MemberAction::Approve {
self.perform_action_by_member(MemberAction::Approve {
identity: proposal.signer_id,
proposal_id: proposal.proposal_id,
});
})
}

fn internal_confirm(&mut self, proposal_id: ProposalId, signer_id: SignerId) {
Expand Down Expand Up @@ -199,13 +198,10 @@ impl ProxyContract {
proposal_id: ProposalId,
) -> Option<ProposalWithApprovals> {
let approvals_for_proposal = self.approvals.get(&proposal_id);
match approvals_for_proposal {
Some(approvals) => Some(ProposalWithApprovals {
proposal_id,
num_approvals: approvals.len(),
}),
None => None,
}
approvals_for_proposal.map(|approvals| ProposalWithApprovals {
proposal_id,
num_approvals: approvals.len(),
})
}

#[private]
Expand Down Expand Up @@ -357,9 +353,7 @@ impl ProxyContract {
let author_id: SignerId = proposal.author_id.rt().expect("Invalid signer");
let mut num_proposals = *self.num_proposals_pk.get(&author_id).unwrap_or(&0);

if num_proposals > 0 {
num_proposals = num_proposals - 1;
}
num_proposals = num_proposals.saturating_sub(1);
self.num_proposals_pk.insert(author_id, num_proposals);
proposal
}
Expand All @@ -370,10 +364,10 @@ impl ProxyContract {
key: Box<[u8]>,
value: Box<[u8]>,
) -> Option<Box<[u8]>> {
let val = self.context_storage.insert(key.clone(), value);
val
self.context_storage.insert(key.clone(), value)
}

#[expect(clippy::type_complexity, reason = "Acceptable here")]
pub fn context_storage_entries(
&self,
offset: usize,
Expand Down
13 changes: 9 additions & 4 deletions contracts/test-counter/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#![allow(unused_crate_dependencies, reason = "False positives")]
#![allow(
clippy::use_self,
clippy::must_use_candidate,
unused_crate_dependencies,
reason = "False positives"
)]

use near_sdk::{env, near, PanicOnDefault};

Expand All @@ -11,16 +16,16 @@ pub struct CounterContract {
#[near]
impl CounterContract {
#[init]
pub fn new() -> Self {
pub const fn new() -> Self {
Self { counter: 0 }
}

pub fn increment(&mut self) {
self.counter += 1;
self.counter = self.counter.wrapping_add(1);
env::log_str("Counter incremented");
}

pub fn get_count(&self) -> u32 {
pub const fn get_count(&self) -> u32 {
self.counter
}
}
12 changes: 7 additions & 5 deletions crates/context/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![expect(clippy::unwrap_in_result, reason = "Repr transmute")]

use core::error::Error;
use core::str::FromStr;
use std::collections::HashSet;
Expand Down Expand Up @@ -140,7 +142,7 @@ impl ContextManager {
PrivateKey::random(&mut rand::thread_rng())
}

pub async fn create_context(
pub fn create_context(
&self,
seed: Option<[u8; 32]>,
application_id: ApplicationId,
Expand Down Expand Up @@ -178,7 +180,7 @@ impl ContextManager {
bail!("Application is not installed on node.")
};

self.add_context(&context, identity_secret, true).await?;
self.add_context(&context, identity_secret, true)?;

let (tx, rx) = oneshot::channel();

Expand Down Expand Up @@ -249,7 +251,7 @@ impl ContextManager {
Ok(())
}

async fn add_context(
fn add_context(
&self,
context: &Context,
identity_secret: PrivateKey,
Expand Down Expand Up @@ -381,8 +383,7 @@ impl ContextManager {
}
}

self.add_context(&context, identity_secret, !context_exists)
.await?;
self.add_context(&context, identity_secret, !context_exists)?;

self.subscribe(&context.id).await?;

Expand Down Expand Up @@ -568,6 +569,7 @@ impl ContextManager {

drop(iter);

#[expect(clippy::iter_with_drain, reason = "reallocation would be a bad idea")]
for k in keys.drain(..) {
store.delete(&k)?;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/network/src/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ impl EventLoop {
// Finds a new rendezvous peer for registration.
// Prioritizes Discovered peers, falls back to dialing Expired peers if necessary.
// Returns Some(PeerId) if a suitable peer is found, None otherwise.
pub(crate) async fn find_new_rendezvous_peer(&mut self) -> Option<PeerId> {
pub(crate) fn find_new_rendezvous_peer(&self) -> Option<PeerId> {
let mut candidate = None;

for peer_id in self.discovery.state.get_rendezvous_peer_ids() {
Expand Down
2 changes: 1 addition & 1 deletion crates/network/src/events/rendezvous.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl EventHandler<Event> for EventLoop {
RendezvousRegistrationStatus::Expired,
);

if let Some(nominated_peer) = self.find_new_rendezvous_peer().await {
if let Some(nominated_peer) = self.find_new_rendezvous_peer() {
if self.swarm.is_connected(&nominated_peer) {
if let Err(err) = self.rendezvous_register(&nominated_peer) {
error!(%err, "Failed to register with nominated rendezvous peer");
Expand Down
6 changes: 3 additions & 3 deletions crates/node/src/catchup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::types::{
};
use crate::Node;

mod actions;
// mod actions;
mod blobs;

impl Node {
Expand Down Expand Up @@ -170,7 +170,7 @@ impl Node {
}

async fn perform_blob_catchup(
&mut self,
&self,
chosen_peer: PeerId,
latest_application: Application,
) -> EyreResult<()> {
Expand All @@ -189,7 +189,7 @@ impl Node {
}

async fn perform_blob_stream_catchup(
&mut self,
&self,
chosen_peer: PeerId,
latest_application: Application,
) -> EyreResult<()> {
Expand Down
6 changes: 3 additions & 3 deletions crates/node/src/interactive_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ pub async fn handle_line(node: &mut Node, line: String) -> eyre::Result<()> {
SubCommands::Application(application) => application.run(node).await,
SubCommands::Call(call) => call.run(node).await,
SubCommands::Context(context) => context.run(node).await,
SubCommands::Identity(identity) => identity.run(node).await,
SubCommands::Identity(identity) => identity.run(node),
SubCommands::Peers(peers) => peers.run(node.network_client.clone().into()).await,
SubCommands::State(state) => state.run(node).await,
SubCommands::Store(store) => store.run(node).await,
SubCommands::State(state) => state.run(node),
SubCommands::Store(store) => store.run(node),
};

if let Err(err) = result {
Expand Down
19 changes: 9 additions & 10 deletions crates/node/src/interactive_cli/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ enum Commands {

impl ContextCommand {
#[expect(clippy::similar_names, reason = "Acceptable here")]
#[expect(clippy::too_many_lines, reason = "TODO: Will be refactored")]
pub async fn run(self, node: &Node) -> Result<()> {
let ind = ">>".blue();

Expand Down Expand Up @@ -110,7 +111,7 @@ impl ContextCommand {
let application_id = application_id.parse()?;

let (context_seed, params) = 'infer: {
let Some(context_seed) = context_seed.clone() else {
let Some(context_seed) = context_seed else {
break 'infer (None, None);
};
let context_seed_clone = context_seed.clone();
Expand All @@ -132,15 +133,13 @@ impl ContextCommand {

let (tx, rx) = oneshot::channel();

node.ctx_manager
.create_context(
context_seed.map(Into::into),
application_id,
None,
params.map(|x| x.as_bytes().to_owned()).unwrap_or_default(),
tx,
)
.await?;
node.ctx_manager.create_context(
context_seed.map(Into::into),
application_id,
None,
params.map(|x| x.as_bytes().to_owned()).unwrap_or_default(),
tx,
)?;

let _ignored = tokio::spawn(async move {
let err: eyre::Report = match rx.await {
Expand Down
4 changes: 2 additions & 2 deletions crates/node/src/interactive_cli/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ enum IdentitySubcommands {
}

impl IdentityCommand {
pub async fn run(self, node: &Node) -> Result<()> {
pub fn run(self, node: &Node) -> Result<()> {
match &self.subcommand {
IdentitySubcommands::Ls { context_id } => {
match ContextId::from_str(context_id) {
Expand All @@ -44,7 +44,7 @@ impl IdentityCommand {
println!("{:44} | Owned", "Identity");

for (k, v) in first.into_iter().chain(iter.entries()) {
let (k, v) = (k.unwrap(), v.unwrap());
let (k, v) = (k?, v?);

if k.context_id() != context_id {
break;
Expand Down
2 changes: 1 addition & 1 deletion crates/node/src/interactive_cli/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct StateCommand {
context_id: String,
}
impl StateCommand {
pub async fn run(self, node: &Node) -> Result<()> {
pub fn run(self, node: &Node) -> Result<()> {
let ind = ">>".blue();
let handle = node.store.handle();
let mut iter = handle.iter::<ContextStateKey>()?;
Expand Down
2 changes: 1 addition & 1 deletion crates/node/src/interactive_cli/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct StoreCommand;

impl StoreCommand {
// todo! revisit: get specific context state
pub async fn run(self, node: &Node) -> Result<()> {
pub fn run(self, node: &Node) -> Result<()> {
println!("Executing Store command");
let ind = ">>".blue();

Expand Down
4 changes: 2 additions & 2 deletions crates/sdk/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use serde::{Serialize, Serializer};
#[derive(Debug, Serialize)]
pub struct Error(#[serde(serialize_with = "error_string")] Box<dyn CoreError>);

fn error_string<S>(error: &Box<dyn CoreError>, serializer: S) -> Result<S::Ok, S::Error>
fn error_string<S>(error: &impl AsRef<dyn CoreError>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&error.to_string())
serializer.serialize_str(&error.as_ref().to_string())
}

impl Error {
Expand Down
1 change: 0 additions & 1 deletion crates/server/src/admin/handlers/context/create_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ pub async fn handler(
req.initialization_params,
tx,
)
.await
.map_err(parse_api_error);

if let Err(err) = result {
Expand Down
6 changes: 3 additions & 3 deletions crates/server/src/admin/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,13 @@ async fn serve_embedded_file(uri: Uri) -> Result<impl IntoResponse, StatusCode>

// Attempt to serve the requested file
if let Some(file) = NodeUiStaticFiles::get(path) {
return serve_file(file).await;
return serve_file(file);
}

// Fallback to index.html for SPA routing if the file wasn't found and it's not already "index.html"
if path != "index.html" {
if let Some(index_file) = NodeUiStaticFiles::get("index.html") {
return serve_file(index_file).await;
return serve_file(index_file);
}
}

Expand All @@ -285,7 +285,7 @@ async fn serve_embedded_file(uri: Uri) -> Result<impl IntoResponse, StatusCode>
/// - `Result<impl IntoResponse, StatusCode>`: If the response is successfully built, it returns an `Ok`
/// with the response. If there is an error building the response, it returns an `Err` with a
/// 500 INTERNAL_SERVER_ERROR status code.
async fn serve_file(file: EmbeddedFile) -> Result<impl IntoResponse, StatusCode> {
fn serve_file(file: EmbeddedFile) -> Result<impl IntoResponse, StatusCode> {
Response::builder()
.status(StatusCode::OK)
.header("Content-Type", file.metadata.mimetype())
Expand Down
1 change: 0 additions & 1 deletion crates/storage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ indexmap.workspace = true
serde = { workspace = true, features = ["derive"] }
sha2.workspace = true
thiserror.workspace = true
uuid.workspace = true

calimero-sdk = { path = "../sdk" }
calimero-storage-macros = { path = "../storage-macros" }
Expand Down
Loading

0 comments on commit f1ddc4c

Please sign in to comment.