Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+94 -96
View File
@@ -19,15 +19,20 @@
//! Substrate chain configurations.
#![warn(missing_docs)]
use std::{borrow::Cow, fs::File, path::PathBuf, sync::Arc, collections::HashMap};
use serde::{Serialize, Deserialize};
use sp_core::{storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild}, Bytes};
use sp_runtime::BuildStorage;
use serde_json as json;
use crate::{RuntimeGenesis, ChainType, extension::GetExtension, Properties};
use crate::{extension::GetExtension, ChainType, Properties, RuntimeGenesis};
use sc_network::config::MultiaddrWithPeerId;
use sc_telemetry::TelemetryEndpoints;
use sp_runtime::traits::{Block as BlockT, NumberFor};
use serde::{Deserialize, Serialize};
use serde_json as json;
use sp_core::{
storage::{ChildInfo, Storage, StorageChild, StorageData, StorageKey},
Bytes,
};
use sp_runtime::{
traits::{Block as BlockT, NumberFor},
BuildStorage,
};
use std::{borrow::Cow, collections::HashMap, fs::File, path::PathBuf, sync::Arc};
enum GenesisSource<G> {
File(PathBuf),
@@ -56,8 +61,8 @@ impl<G: RuntimeGenesis> GenesisSource<G> {
match self {
Self::File(path) => {
let file = File::open(path)
.map_err(|e| format!("Error opening spec file: {}", e))?;
let file =
File::open(path).map_err(|e| format!("Error opening spec file: {}", e))?;
let genesis: GenesisContainer<G> = json::from_reader(file)
.map_err(|e| format!("Error parsing spec file: {}", e))?;
Ok(genesis.genesis)
@@ -69,22 +74,25 @@ impl<G: RuntimeGenesis> GenesisSource<G> {
},
Self::Factory(f) => Ok(Genesis::Runtime(f())),
Self::Storage(storage) => {
let top = storage.top
let top = storage
.top
.iter()
.map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone())))
.collect();
let children_default = storage.children_default
let children_default = storage
.children_default
.iter()
.map(|(k, child)|
(
StorageKey(k.clone()),
child.data
.map(|(k, child)| {
(
StorageKey(k.clone()),
child
.data
.iter()
.map(|(k, v)| (StorageKey(k.clone()), StorageData(v.clone())))
.collect()
)
)
.collect(),
)
})
.collect();
Ok(Genesis::Raw(RawGenesis { top, children_default }))
@@ -99,24 +107,24 @@ impl<G: RuntimeGenesis, E> BuildStorage for ChainSpec<G, E> {
Genesis::Runtime(gc) => gc.build_storage(),
Genesis::Raw(RawGenesis { top: map, children_default: children_map }) => Ok(Storage {
top: map.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
children_default: children_map.into_iter().map(|(storage_key, child_content)| {
let child_info = ChildInfo::new_default(storage_key.0.as_slice());
(
storage_key.0,
StorageChild {
data: child_content.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
child_info,
},
)
}).collect(),
children_default: children_map
.into_iter()
.map(|(storage_key, child_content)| {
let child_info = ChildInfo::new_default(storage_key.0.as_slice());
(
storage_key.0,
StorageChild {
data: child_content.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
child_info,
},
)
})
.collect(),
}),
}
}
fn assimilate_storage(
&self,
_: &mut Storage,
) -> Result<(), String> {
fn assimilate_storage(&self, _: &mut Storage) -> Result<(), String> {
Err("`assimilate_storage` not implemented for `ChainSpec`.".into())
}
}
@@ -181,10 +189,7 @@ pub struct ChainSpec<G, E = NoExtension> {
impl<G, E: Clone> Clone for ChainSpec<G, E> {
fn clone(&self) -> Self {
ChainSpec {
client_spec: self.client_spec.clone(),
genesis: self.genesis.clone(),
}
ChainSpec { client_spec: self.client_spec.clone(), genesis: self.genesis.clone() }
}
}
@@ -258,10 +263,7 @@ impl<G, E> ChainSpec<G, E> {
code_substitutes: HashMap::new(),
};
ChainSpec {
client_spec,
genesis: GenesisSource::Factory(Arc::new(constructor)),
}
ChainSpec { client_spec, genesis: GenesisSource::Factory(Arc::new(constructor)) }
}
/// Type of the chain.
@@ -281,22 +283,15 @@ impl<G, E: serde::de::DeserializeOwned> ChainSpec<G, E> {
let json = json.into();
let client_spec = json::from_slice(json.as_ref())
.map_err(|e| format!("Error parsing spec file: {}", e))?;
Ok(ChainSpec {
client_spec,
genesis: GenesisSource::Binary(json),
})
Ok(ChainSpec { client_spec, genesis: GenesisSource::Binary(json) })
}
/// Parse json file into a `ChainSpec`
pub fn from_json_file(path: PathBuf) -> Result<Self, String> {
let file = File::open(&path)
.map_err(|e| format!("Error opening spec file: {}", e))?;
let client_spec = json::from_reader(file)
.map_err(|e| format!("Error parsing spec file: {}", e))?;
Ok(ChainSpec {
client_spec,
genesis: GenesisSource::File(path),
})
let file = File::open(&path).map_err(|e| format!("Error opening spec file: {}", e))?;
let client_spec =
json::from_reader(file).map_err(|e| format!("Error parsing spec file: {}", e))?;
Ok(ChainSpec { client_spec, genesis: GenesisSource::File(path) })
}
}
@@ -312,33 +307,34 @@ impl<G: RuntimeGenesis, E: serde::Serialize + Clone + 'static> ChainSpec<G, E> {
let genesis = match (raw, self.genesis.resolve()?) {
(true, Genesis::Runtime(g)) => {
let storage = g.build_storage()?;
let top = storage.top.into_iter()
.map(|(k, v)| (StorageKey(k), StorageData(v)))
.collect();
let children_default = storage.children_default.into_iter()
.map(|(sk, child)| (
StorageKey(sk),
child.data.into_iter()
.map(|(k, v)| (StorageKey(k), StorageData(v)))
.collect(),
))
let top =
storage.top.into_iter().map(|(k, v)| (StorageKey(k), StorageData(v))).collect();
let children_default = storage
.children_default
.into_iter()
.map(|(sk, child)| {
(
StorageKey(sk),
child
.data
.into_iter()
.map(|(k, v)| (StorageKey(k), StorageData(v)))
.collect(),
)
})
.collect();
Genesis::Raw(RawGenesis { top, children_default })
},
(_, genesis) => genesis,
};
Ok(JsonContainer {
client_spec: self.client_spec.clone(),
genesis,
})
Ok(JsonContainer { client_spec: self.client_spec.clone(), genesis })
}
/// Dump to json string.
pub fn as_json(&self, raw: bool) -> Result<String, String> {
let container = self.json_container(raw)?;
json::to_string_pretty(&container)
.map_err(|e| format!("Error generating spec json: {}", e))
json::to_string_pretty(&container).map_err(|e| format!("Error generating spec json: {}", e))
}
}
@@ -404,7 +400,11 @@ where
}
fn code_substitutes(&self) -> std::collections::HashMap<String, Vec<u8>> {
self.client_spec.code_substitutes.iter().map(|(h, c)| (h.clone(), c.0.clone())).collect()
self.client_spec
.code_substitutes
.iter()
.map(|(h, c)| (h.clone(), c.0.clone()))
.collect()
}
}
@@ -417,7 +417,8 @@ pub struct LightSyncState<Block: BlockT> {
/// The babe weight of the finalized block.
pub babe_finalized_block_weight: sp_consensus_babe::BabeBlockWeight,
/// The authority set for grandpa.
pub grandpa_authority_set: sc_finality_grandpa::AuthoritySet<<Block as BlockT>::Hash, NumberFor<Block>>,
pub grandpa_authority_set:
sc_finality_grandpa::AuthoritySet<<Block as BlockT>::Hash, NumberFor<Block>>,
}
impl<Block: BlockT> LightSyncState<Block> {
@@ -427,25 +428,25 @@ impl<Block: BlockT> LightSyncState<Block> {
SerializableLightSyncState {
finalized_block_header: StorageData(self.finalized_block_header.encode()),
babe_epoch_changes:
StorageData(self.babe_epoch_changes.encode()),
babe_finalized_block_weight:
self.babe_finalized_block_weight,
grandpa_authority_set:
StorageData(self.grandpa_authority_set.encode()),
babe_epoch_changes: StorageData(self.babe_epoch_changes.encode()),
babe_finalized_block_weight: self.babe_finalized_block_weight,
grandpa_authority_set: StorageData(self.grandpa_authority_set.encode()),
}
}
/// Convert from a `SerializableLightSyncState`.
pub fn from_serializable(serialized: &SerializableLightSyncState) -> Result<Self, codec::Error> {
pub fn from_serializable(
serialized: &SerializableLightSyncState,
) -> Result<Self, codec::Error> {
Ok(Self {
finalized_block_header: codec::Decode::decode(&mut &serialized.finalized_block_header.0[..])?,
babe_epoch_changes:
codec::Decode::decode(&mut &serialized.babe_epoch_changes.0[..])?,
babe_finalized_block_weight:
serialized.babe_finalized_block_weight,
grandpa_authority_set:
codec::Decode::decode(&mut &serialized.grandpa_authority_set.0[..])?,
finalized_block_header: codec::Decode::decode(
&mut &serialized.finalized_block_header.0[..],
)?,
babe_epoch_changes: codec::Decode::decode(&mut &serialized.babe_epoch_changes.0[..])?,
babe_finalized_block_weight: serialized.babe_finalized_block_weight,
grandpa_authority_set: codec::Decode::decode(
&mut &serialized.grandpa_authority_set.0[..],
)?,
})
}
}
@@ -469,12 +470,9 @@ mod tests {
struct Genesis(HashMap<String, String>);
impl BuildStorage for Genesis {
fn assimilate_storage(
&self,
storage: &mut Storage,
) -> Result<(), String> {
fn assimilate_storage(&self, storage: &mut Storage) -> Result<(), String> {
storage.top.extend(
self.0.iter().map(|(a, b)| (a.clone().into_bytes(), b.clone().into_bytes()))
self.0.iter().map(|(a, b)| (a.clone().into_bytes(), b.clone().into_bytes())),
);
Ok(())
}
@@ -485,11 +483,10 @@ mod tests {
#[test]
fn should_deserialize_example_chain_spec() {
let spec1 = TestSpec::from_json_bytes(Cow::Owned(
include_bytes!("../res/chain_spec.json").to_vec()
)).unwrap();
let spec2 = TestSpec::from_json_file(
PathBuf::from("./res/chain_spec.json")
).unwrap();
include_bytes!("../res/chain_spec.json").to_vec(),
))
.unwrap();
let spec2 = TestSpec::from_json_file(PathBuf::from("./res/chain_spec.json")).unwrap();
assert_eq!(spec1.as_json(false), spec2.as_json(false));
assert_eq!(spec2.chain_type(), ChainType::Live)
@@ -506,8 +503,9 @@ mod tests {
#[test]
fn should_deserialize_chain_spec_with_extensions() {
let spec = TestSpec2::from_json_bytes(Cow::Owned(
include_bytes!("../res/chain_spec2.json").to_vec()
)).unwrap();
include_bytes!("../res/chain_spec2.json").to_vec(),
))
.unwrap();
assert_eq!(spec.extensions().my_property, "Test Extension");
}
+70 -58
View File
@@ -18,19 +18,21 @@
//! Chain Spec extensions helpers.
use std::fmt::Debug;
use std::any::{TypeId, Any};
use std::{
any::{Any, TypeId},
fmt::Debug,
};
use std::collections::BTreeMap;
use serde::{Serialize, Deserialize, de::DeserializeOwned};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
/// A `ChainSpec` extension.
///
/// This trait is implemented automatically by `ChainSpecGroup` macro.
pub trait Group: Clone + Sized {
/// An associated type containing fork definition.
type Fork: Fork<Base=Self>;
type Fork: Fork<Base = Self>;
/// Convert to fork type.
fn to_fork(self) -> Self::Fork;
@@ -45,7 +47,7 @@ pub trait Group: Clone + Sized {
/// a complete set of parameters
pub trait Fork: Serialize + DeserializeOwned + Clone + Sized {
/// A base `Group` type.
type Base: Group<Fork=Self>;
type Base: Group<Fork = Self>;
/// Combine with another struct.
///
@@ -128,7 +130,8 @@ pub trait Extension: Serialize + DeserializeOwned + Clone {
fn get_any(&self, t: TypeId) -> &dyn Any;
/// Get forkable extensions of specific type.
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>>
where
BlockNumber: Ord + Clone + 'static,
T: Group + 'static,
<Self::Forks as IsForks>::Extension: Extension,
@@ -142,8 +145,12 @@ pub trait Extension: Serialize + DeserializeOwned + Clone {
impl Extension for crate::NoExtension {
type Forks = Self;
fn get<T: 'static>(&self) -> Option<&T> { None }
fn get_any(&self, _t: TypeId) -> &dyn Any { self }
fn get<T: 'static>(&self) -> Option<&T> {
None
}
fn get_any(&self, _t: TypeId) -> &dyn Any {
self
}
}
pub trait IsForks {
@@ -166,14 +173,12 @@ pub struct Forks<BlockNumber: Ord, T: Group> {
impl<B: Ord, T: Group + Default> Default for Forks<B, T> {
fn default() -> Self {
Self {
base: Default::default(),
forks: Default::default(),
}
Self { base: Default::default(), forks: Default::default() }
}
}
impl<B: Ord, T: Group> Forks<B, T> where
impl<B: Ord, T: Group> Forks<B, T>
where
T::Fork: Debug,
{
/// Create new fork definition given the base and the forks.
@@ -195,7 +200,8 @@ impl<B: Ord, T: Group> Forks<B, T> where
}
}
impl<B, T> IsForks for Forks<B, T> where
impl<B, T> IsForks for Forks<B, T>
where
B: Ord + 'static,
T: Group + 'static,
{
@@ -203,29 +209,31 @@ impl<B, T> IsForks for Forks<B, T> where
type Extension = T;
}
impl<B: Ord + Clone, T: Group + Extension> Forks<B, T> where
impl<B: Ord + Clone, T: Group + Extension> Forks<B, T>
where
T::Fork: Extension,
{
/// Get forks definition for a subset of this extension.
///
/// Returns the `Forks` struct, but limited to a particular type
/// within the extension.
pub fn for_type<X>(&self) -> Option<Forks<B, X>> where
pub fn for_type<X>(&self) -> Option<Forks<B, X>>
where
X: Group + 'static,
{
let base = self.base.get::<X>()?.clone();
let forks = self.forks.iter().filter_map(|(k, v)| {
Some((k.clone(), v.get::<Option<X::Fork>>()?.clone()?))
}).collect();
let forks = self
.forks
.iter()
.filter_map(|(k, v)| Some((k.clone(), v.get::<Option<X::Fork>>()?.clone()?)))
.collect();
Some(Forks {
base,
forks,
})
Some(Forks { base, forks })
}
}
impl<B, E> Extension for Forks<B, E> where
impl<B, E> Extension for Forks<B, E>
where
B: Serialize + DeserializeOwned + Ord + Clone + 'static,
E: Extension + Group + 'static,
{
@@ -245,7 +253,8 @@ impl<B, E> Extension for Forks<B, E> where
}
}
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>>
where
BlockNumber: Ord + Clone + 'static,
T: Group + 'static,
<Self::Forks as IsForks>::Extension: Extension,
@@ -266,7 +275,7 @@ pub trait GetExtension {
fn get_any(&self, t: TypeId) -> &dyn Any;
}
impl <E: Extension> GetExtension for E {
impl<E: Extension> GetExtension for E {
fn get_any(&self, t: TypeId) -> &dyn Any {
Extension::get_any(self, t)
}
@@ -281,7 +290,7 @@ pub fn get_extension<T: 'static>(e: &dyn GetExtension) -> Option<&T> {
#[cfg(test)]
mod tests {
use super::*;
use sc_chain_spec_derive::{ChainSpecGroup, ChainSpecExtension};
use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
// Make the proc macro work for tests and doc tests.
use crate as sc_chain_spec;
@@ -297,7 +306,9 @@ mod tests {
pub test: u8,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
#[derive(
Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension,
)]
#[serde(deny_unknown_fields)]
pub struct Extensions {
pub ext1: Extension1,
@@ -315,11 +326,12 @@ mod tests {
#[test]
fn forks_should_work_correctly() {
use super::Extension as _ ;
use super::Extension as _;
// We first need to deserialize into a `Value` because of the following bug:
// https://github.com/serde-rs/json/issues/505
let ext_val: serde_json::Value = serde_json::from_str(r#"
let ext_val: serde_json::Value = serde_json::from_str(
r#"
{
"test": 11,
"forkable": {
@@ -342,40 +354,40 @@ mod tests {
}
}
}
"#).unwrap();
"#,
)
.unwrap();
let ext: Ext2 = serde_json::from_value(ext_val).unwrap();
assert_eq!(ext.get::<Extension1>(), Some(&Extension1 {
test: 11
}));
assert_eq!(ext.get::<Extension1>(), Some(&Extension1 { test: 11 }));
// get forks definition
let forks = ext.get::<Forks<u64, Extensions>>().unwrap();
assert_eq!(forks.at_block(0), Extensions {
ext1: Extension1 { test: 15 },
ext2: Extension2 { test: 123 },
});
assert_eq!(forks.at_block(1), Extensions {
ext1: Extension1 { test: 5 },
ext2: Extension2 { test: 123 },
});
assert_eq!(forks.at_block(2), Extensions {
ext1: Extension1 { test: 5 },
ext2: Extension2 { test: 5 },
});
assert_eq!(forks.at_block(4), Extensions {
ext1: Extension1 { test: 5 },
ext2: Extension2 { test: 5 },
});
assert_eq!(forks.at_block(5), Extensions {
ext1: Extension1 { test: 5 },
ext2: Extension2 { test: 1 },
});
assert_eq!(forks.at_block(10), Extensions {
ext1: Extension1 { test: 5 },
ext2: Extension2 { test: 1 },
});
assert_eq!(
forks.at_block(0),
Extensions { ext1: Extension1 { test: 15 }, ext2: Extension2 { test: 123 } }
);
assert_eq!(
forks.at_block(1),
Extensions { ext1: Extension1 { test: 5 }, ext2: Extension2 { test: 123 } }
);
assert_eq!(
forks.at_block(2),
Extensions { ext1: Extension1 { test: 5 }, ext2: Extension2 { test: 5 } }
);
assert_eq!(
forks.at_block(4),
Extensions { ext1: Extension1 { test: 5 }, ext2: Extension2 { test: 5 } }
);
assert_eq!(
forks.at_block(5),
Extensions { ext1: Extension1 { test: 5 }, ext2: Extension2 { test: 1 } }
);
assert_eq!(
forks.at_block(10),
Extensions { ext1: Extension1 { test: 5 }, ext2: Extension2 { test: 1 } }
);
assert!(forks.at_block(10).get::<Extension2>().is_some());
// filter forks for `Extension2`
+16 -16
View File
@@ -35,7 +35,7 @@
//!
//! #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ChainSpecExtension)]
//! pub struct MyExtension {
//! pub known_blocks: HashMap<u64, String>,
//! pub known_blocks: HashMap<u64, String>,
//! }
//!
//! pub type MyChainSpec<G> = GenericChainSpec<G, MyExtension>;
@@ -53,19 +53,19 @@
//!
//! #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ChainSpecGroup)]
//! pub struct ClientParams {
//! max_block_size: usize,
//! max_extrinsic_size: usize,
//! max_block_size: usize,
//! max_extrinsic_size: usize,
//! }
//!
//! #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ChainSpecGroup)]
//! pub struct PoolParams {
//! max_transaction_size: usize,
//! max_transaction_size: usize,
//! }
//!
//! #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ChainSpecGroup, ChainSpecExtension)]
//! pub struct Extension {
//! pub client: ClientParams,
//! pub pool: PoolParams,
//! pub client: ClientParams,
//! pub pool: PoolParams,
//! }
//!
//! pub type BlockNumber = u64;
@@ -88,20 +88,20 @@
//!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
//! pub struct ClientParams {
//! max_block_size: usize,
//! max_extrinsic_size: usize,
//! max_block_size: usize,
//! max_extrinsic_size: usize,
//! }
//!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
//! pub struct PoolParams {
//! max_transaction_size: usize,
//! max_transaction_size: usize,
//! }
//!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecExtension)]
//! pub struct Extension {
//! pub client: ClientParams,
//! #[forks]
//! pub pool: Forks<u64, PoolParams>,
//! pub client: ClientParams,
//! #[forks]
//! pub pool: Forks<u64, PoolParams>,
//! }
//!
//! pub type MyChainSpec<G> = GenericChainSpec<G, Extension>;
@@ -111,16 +111,16 @@ mod chain_spec;
mod extension;
pub use chain_spec::{
ChainSpec as GenericChainSpec, NoExtension, LightSyncState, SerializableLightSyncState,
ChainSpec as GenericChainSpec, LightSyncState, NoExtension, SerializableLightSyncState,
};
pub use extension::{Group, Fork, Forks, Extension, GetExtension, get_extension};
pub use extension::{get_extension, Extension, Fork, Forks, GetExtension, Group};
pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
use serde::{Serialize, de::DeserializeOwned};
use sp_runtime::BuildStorage;
use sc_network::config::MultiaddrWithPeerId;
use sc_telemetry::TelemetryEndpoints;
use serde::{de::DeserializeOwned, Serialize};
use sp_core::storage::Storage;
use sp_runtime::BuildStorage;
/// The type of a chain.
///