Apply some clippy lints (#11154)

* Apply some clippy hints

* Revert clippy ci changes

* Update client/cli/src/commands/generate.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/cli/src/commands/inspect_key.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/db/src/bench.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/db/src/bench.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/service/src/client/block_rules.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/service/src/client/block_rules.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/network/src/transactions.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/network/src/protocol.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Revert due to missing `or_default` function.

* Fix compilation and simplify code

* Undo change that corrupts benchmark.

* fix clippy

* Update client/service/test/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/state-db/src/noncanonical.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/state-db/src/noncanonical.rs

remove leftovers!

* Update client/tracing/src/logging/directives.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/fork-tree/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* added needed ref

* Update frame/referenda/src/benchmarking.rs

* Simplify byte-vec creation

* let's just not overlap the ranges

* Correction

* cargo fmt

* Update utils/frame/benchmarking-cli/src/shared/stats.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update utils/frame/benchmarking-cli/src/pallet/command.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Giles Cope <gilescope@gmail.com>
This commit is contained in:
Falco Hirschenberger
2022-04-30 23:28:27 +02:00
committed by GitHub
parent a990473cf9
commit b581604aa7
368 changed files with 1927 additions and 2236 deletions
@@ -31,7 +31,7 @@ use crate::{
shared::{Stats, UnderscoreHelper},
};
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static VERSION: &str = env!("CARGO_PKG_VERSION");
static TEMPLATE: &str = include_str!("./weights.hbs");
/// Data consumed by Handlebar to fill out the `weights.hbs` template.
@@ -93,13 +93,13 @@ impl TemplateData {
let mut fd = fs::File::create(&out_path)?;
info!("Writing weights to {:?}", fs::canonicalize(&out_path)?);
handlebars
.render_template_to_write(&TEMPLATE, &self, &mut fd)
.render_template_to_write(TEMPLATE, &self, &mut fd)
.map_err(|e| format!("HBS template write: {:?}", e).into())
}
/// Build a path for the weight file.
fn build_path(&self, weight_out: &Option<PathBuf>) -> Result<PathBuf> {
let mut path = weight_out.clone().unwrap_or(PathBuf::from("."));
let mut path = weight_out.clone().unwrap_or_else(|| PathBuf::from("."));
if !path.is_dir() {
return Err("Need directory as --weight-path".into())
@@ -123,9 +123,9 @@ impl PalletCmd {
let spec = config.chain_spec;
let wasm_method = self.wasm_method.into();
let strategy = self.execution.unwrap_or(ExecutionStrategy::Native);
let pallet = self.pallet.clone().unwrap_or_else(|| String::new());
let pallet = self.pallet.clone().unwrap_or_default();
let pallet = pallet.as_bytes();
let extrinsic = self.extrinsic.clone().unwrap_or_else(|| String::new());
let extrinsic = self.extrinsic.clone().unwrap_or_default();
let extrinsic_split: Vec<&str> = extrinsic.split(',').collect();
let extrinsics: Vec<_> = extrinsic_split.iter().map(|x| x.trim().as_bytes()).collect();
@@ -155,7 +155,7 @@ impl PalletCmd {
extensions.register(OffchainWorkerExt::new(offchain.clone()));
extensions.register(OffchainDbExt::new(offchain));
extensions.register(TransactionPoolExt::new(pool));
return extensions
extensions
};
// Get Benchmark List
@@ -339,7 +339,7 @@ impl PalletCmd {
batches.extend(batch);
// Show progress information
if let Some(elapsed) = timer.elapsed().ok() {
if let Ok(elapsed) = timer.elapsed() {
if elapsed >= time::Duration::from_secs(5) {
timer = time::SystemTime::now();
log::info!(
@@ -401,7 +401,7 @@ impl PalletCmd {
batches: &Vec<BenchmarkBatchSplitResults>,
storage_info: &Vec<StorageInfo>,
) {
for batch in batches.into_iter() {
for batch in batches.iter() {
// Print benchmark metadata
println!(
"Pallet: {:?}, Extrinsic: {:?}, Lowest values: {:?}, Highest values: {:?}, Steps: {:?}, Repeat: {:?}",
@@ -420,12 +420,12 @@ impl PalletCmd {
if !self.no_storage_info {
let mut comments: Vec<String> = Default::default();
writer::add_storage_comments(&mut comments, &batch.db_results, &storage_info);
writer::add_storage_comments(&mut comments, &batch.db_results, storage_info);
println!("Raw Storage Info\n========");
for comment in comments {
println!("{}", comment);
}
println!("");
println!();
}
// Conduct analysis.
@@ -446,7 +446,7 @@ impl PalletCmd {
{
println!("Writes = {:?}", analysis);
}
println!("");
println!();
}
if !self.no_min_squares {
println!("Min Squares Analysis\n========");
@@ -465,7 +465,7 @@ impl PalletCmd {
{
println!("Writes = {:?}", analysis);
}
println!("");
println!();
}
}
}
@@ -35,7 +35,7 @@ use frame_support::traits::StorageInfo;
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::Zero;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const VERSION: &str = env!("CARGO_PKG_VERSION");
const TEMPLATE: &str = include_str!("./template.hbs");
// This is the final structure we will pass to the Handlebars template.
@@ -280,12 +280,12 @@ pub fn write_results(
// Which analysis function should be used when outputting benchmarks
let analysis_choice: AnalysisChoice =
cmd.output_analysis.clone().try_into().map_err(|e| io_error(e))?;
cmd.output_analysis.clone().try_into().map_err(io_error)?;
// Capture individual args
let cmd_data = CmdData {
steps: cmd.steps.clone(),
repeat: cmd.repeat.clone(),
steps: cmd.steps,
repeat: cmd.repeat,
lowest_range_values: cmd.lowest_range_values.clone(),
highest_range_values: cmd.highest_range_values.clone(),
execution: format!("{:?}", cmd.execution),
@@ -374,7 +374,7 @@ pub(crate) fn add_storage_comments(
// This tracks the keys we already identified, so we only generate a single comment.
let mut identified = HashSet::<Vec<u8>>::new();
for result in results.clone() {
for result in results {
for (key, reads, writes, whitelisted) in &result.keys {
// skip keys which are whitelisted
if *whitelisted {
@@ -73,7 +73,7 @@ impl Stats {
if xs.is_empty() {
return Err("Empty input is invalid".into())
}
let (avg, stddev) = Self::avg_and_stddev(&xs);
let (avg, stddev) = Self::avg_and_stddev(xs);
Ok(Self {
sum: xs.iter().sum(),
@@ -112,7 +112,7 @@ impl Stats {
/// Returns the specified percentile for the given data.
/// This is best effort since it ignores the interpolation case.
fn percentile(mut xs: Vec<u64>, p: f64) -> u64 {
xs.sort();
xs.sort_unstable();
let index = (xs.len() as f64 * p).ceil() as usize - 1;
xs[index.clamp(0, xs.len() - 1)]
}
@@ -120,9 +120,9 @@ impl Stats {
impl fmt::Debug for Stats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Total: {}\n", self.sum)?;
write!(f, "Min: {}, Max: {}\n", self.min, self.max)?;
write!(f, "Average: {}, Median: {}, Stddev: {}\n", self.avg, self.median, self.stddev)?;
writeln!(f, "Total: {}", self.sum)?;
writeln!(f, "Min: {}, Max: {}", self.min, self.max)?;
writeln!(f, "Average: {}, Median: {}, Stddev: {}", self.avg, self.median, self.stddev)?;
write!(f, "Percentiles 99th, 95th, 75th: {}, {}, {}", self.p99, self.p95, self.p75)
}
}
@@ -25,7 +25,7 @@ use std::{env, fs, path::PathBuf};
use super::cmd::StorageParams;
use crate::shared::{Stats, UnderscoreHelper};
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
static VERSION: &str = env!("CARGO_PKG_VERSION");
static TEMPLATE: &str = include_str!("./weights.hbs");
/// Data consumed by Handlebar to fill out the `weights.hbs` template.
@@ -64,7 +64,7 @@ impl PalletIdCmd {
R::AccountId: Ss58Codec,
{
if self.id.len() != 8 {
Err("a module id must be a string of 8 characters")?
return Err("a module id must be a string of 8 characters".into())
}
let password = self.keystore_params.read_password()?;
@@ -80,7 +80,7 @@ impl PalletIdCmd {
&account_id.to_ss58check_with_version(unwrap_or_default_ss58_version(self.network)),
password,
self.network,
self.output_scheme.output_type.clone()
self.output_scheme.output_type
)
);
@@ -275,8 +275,8 @@ impl<B: BlockT + DeserializeOwned> Default for Builder<B> {
impl<B: BlockT + DeserializeOwned> Builder<B> {
fn as_online(&self) -> &OnlineConfig<B> {
match &self.mode {
Mode::Online(config) => &config,
Mode::OfflineOrElseOnline(_, config) => &config,
Mode::Online(config) => config,
Mode::OfflineOrElseOnline(_, config) => config,
_ => panic!("Unexpected mode: Online"),
}
}
@@ -380,7 +380,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
log::error!(
target: LOG_TARGET,
"failed to execute batch: {:?}. Error: {:?}",
chunk_keys.iter().map(|k| HexDisplay::from(k)).collect::<Vec<_>>(),
chunk_keys.iter().map(HexDisplay::from).collect::<Vec<_>>(),
e
);
"batch failed."
@@ -388,7 +388,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
assert_eq!(chunk_keys.len(), values.len());
for (idx, key) in chunk_keys.into_iter().enumerate() {
for (idx, key) in chunk_keys.iter().enumerate() {
let maybe_value = values[idx].clone();
let value = maybe_value.unwrap_or_else(|| {
log::warn!(target: LOG_TARGET, "key {:?} had none corresponding value.", &key);
@@ -452,7 +452,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
assert_eq!(batch_child_key.len(), batch_response.len());
for (idx, key) in batch_child_key.into_iter().enumerate() {
for (idx, key) in batch_child_key.iter().enumerate() {
let maybe_value = batch_response[idx].clone();
let value = maybe_value.unwrap_or_else(|| {
log::warn!(target: LOG_TARGET, "key {:?} had none corresponding value.", &key);
@@ -571,7 +571,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
&self,
top_kv: &[KeyValue],
) -> Result<ChildKeyValues, &'static str> {
let child_kv = self.load_child_remote(&top_kv).await?;
let child_kv = self.load_child_remote(top_kv).await?;
if let Some(c) = &self.as_online().state_snapshot {
self.save_child_snapshot(&child_kv, &c.path)?;
}
@@ -612,7 +612,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
},
};
child_kv.push((ChildInfo::new_default(&un_prefixed), child_kv_inner));
child_kv.push((ChildInfo::new_default(un_prefixed), child_kv_inner));
}
Ok(child_kv)
@@ -624,8 +624,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
let at = self
.as_online()
.at
.expect("online config must be initialized by this point; qed.")
.clone();
.expect("online config must be initialized by this point; qed.");
log::info!(target: LOG_TARGET, "scraping key-pairs from remote @ {:?}", at);
let mut keys_and_values = if config.pallets.len() > 0 {
@@ -848,7 +847,7 @@ impl<B: BlockT + DeserializeOwned> Builder<B> {
info!(
target: LOG_TARGET,
"injecting a total of {} child keys",
child_kv.iter().flat_map(|(_, kv)| kv).count(),
child_kv.iter().flat_map(|(_, kv)| kv).count()
);
for (info, key_values) in child_kv {
@@ -73,7 +73,7 @@ where
return Err("No access to trie from backend.".to_string())
};
let essence = trie_backend.essence();
let (nb_to_migrate, trie) = count_migrate(essence, &essence.root())?;
let (nb_to_migrate, trie) = count_migrate(essence, essence.root())?;
let mut nb_to_migrate_child = 0;
let mut child_roots: Vec<(ChildInfo, Vec<u8>)> = Vec::new();
@@ -76,12 +76,12 @@ impl ExecuteBlockCmd {
<Block::Hash as FromStr>::Err: Debug,
{
match (&self.block_at, &self.state) {
(Some(block_at), State::Snap { .. }) => hash_of::<Block>(&block_at),
(Some(block_at), State::Snap { .. }) => hash_of::<Block>(block_at),
(Some(block_at), State::Live { .. }) => {
log::warn!(target: LOG_TARGET, "--block-at is provided while state type is live. the `Live::at` will be ignored");
hash_of::<Block>(&block_at)
hash_of::<Block>(block_at)
},
(None, State::Live { at: Some(at), .. }) => hash_of::<Block>(&at),
(None, State::Live { at: Some(at), .. }) => hash_of::<Block>(at),
_ => {
panic!("either `--block-at` must be provided, or state must be `live with a proper `--at``");
},
@@ -31,8 +31,8 @@ use sp_core::H256;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::{fmt::Debug, str::FromStr};
const SUB: &'static str = "chain_subscribeFinalizedHeads";
const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads";
const SUB: &str = "chain_subscribeFinalizedHeads";
const UN_SUB: &str = "chain_unsubscribeFinalizedHeads";
/// Configurations of the [`Command::FollowChain`].
#[derive(Debug, Clone, clap::Parser)]
@@ -68,7 +68,7 @@ where
log::info!(target: LOG_TARGET, "subscribing to {:?} / {:?}", SUB, UN_SUB);
let mut subscription: Subscription<Block::Header> =
client.subscribe(&SUB, None, &UN_SUB).await.unwrap();
client.subscribe(SUB, None, UN_SUB).await.unwrap();
let (code_key, code) = extract_code(&config.chain_spec)?;
let executor = build_executor::<ExecDispatch>(&shared, &config);
@@ -104,7 +104,7 @@ where
if maybe_state_ext.is_none() {
let builder = Builder::<Block>::new().mode(Mode::Online(OnlineConfig {
transport: command.uri.clone().into(),
at: Some(header.parent_hash().clone()),
at: Some(*header.parent_hash()),
..Default::default()
}));
@@ -136,7 +136,7 @@ where
maybe_state_ext.as_mut().expect("state_ext either existed or was just created");
let (mut changes, encoded_result) = state_machine_call_with_proof::<Block, ExecDispatch>(
&state_ext,
state_ext,
&executor,
execution,
"TryRuntime_execute_block_no_check",
@@ -68,12 +68,12 @@ impl OffchainWorkerCmd {
<Block::Hash as FromStr>::Err: Debug,
{
match (&self.header_at, &self.state) {
(Some(header_at), State::Snap { .. }) => hash_of::<Block>(&header_at),
(Some(header_at), State::Snap { .. }) => hash_of::<Block>(header_at),
(Some(header_at), State::Live { .. }) => {
log::error!(target: LOG_TARGET, "--header-at is provided while state type is live, this will most likely lead to a nonsensical result.");
hash_of::<Block>(&header_at)
hash_of::<Block>(header_at)
},
(None, State::Live { at: Some(at), .. }) => hash_of::<Block>(&at),
(None, State::Live { at: Some(at), .. }) => hash_of::<Block>(at),
_ => {
panic!("either `--header-at` must be provided, or state must be `live` with a proper `--at`");
},
@@ -296,7 +296,7 @@ use std::{fmt::Debug, path::PathBuf, str::FromStr};
mod commands;
pub(crate) mod parse;
pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli";
pub(crate) const LOG_TARGET: &str = "try-runtime::cli";
/// Possible commands of `try-runtime`.
#[derive(Debug, Clone, clap::Subcommand)]
@@ -738,7 +738,7 @@ pub(crate) fn state_machine_call_with_proof<Block: BlockT, D: NativeExecutionDis
let runtime_code_backend = sp_state_machine::backend::BackendRuntimeCode::new(&proving_backend);
let runtime_code = runtime_code_backend.runtime_code()?;
let pre_root = backend.root().clone();
let pre_root = *backend.root();
let encoded_results = StateMachine::new(
&proving_backend,
@@ -801,8 +801,8 @@ pub(crate) fn local_spec<Block: BlockT, D: NativeExecutionDispatch + 'static>(
executor: &NativeElseWasmExecutor<D>,
) -> (String, u32, sp_core::storage::StateVersion) {
let (_, encoded) = state_machine_call::<Block, D>(
&ext,
&executor,
ext,
executor,
sc_cli::ExecutionStrategy::NativeElseWasm,
"Core_version",
&[],