Apply cargo fmt (#1146)

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
This commit is contained in:
Alexandru Vasile
2023-08-28 16:03:29 +03:00
committed by GitHub
parent b413e5e84e
commit 91a56fd580
18 changed files with 157 additions and 74 deletions
+8 -2
View File
@@ -44,10 +44,16 @@ pub fn explore_calls(
};
// if specified call is wrong, show user the calls to choose from (but this time as an error):
let Some(call) = calls_enum_type_def.variants.iter().find(|variant| variant.name.to_lowercase() == call_name.to_lowercase()) else {
let Some(call) = calls_enum_type_def
.variants
.iter()
.find(|variant| variant.name.to_lowercase() == call_name.to_lowercase())
else {
let available_calls = print_available_calls(calls_enum_type_def, pallet_name);
let description = format!("Usage:\n subxt explore {pallet_name} calls <CALL>\n explore a specific call within this pallet\n\n{available_calls}", );
return Err(eyre!("\"{call_name}\" call not found in \"{pallet_name}\" pallet!\n\n{description}"));
return Err(eyre!(
"\"{call_name}\" call not found in \"{pallet_name}\" pallet!\n\n{description}"
));
};
// collect all the trailing arguments into a single string that is later into a scale_value::Value
+23 -6
View File
@@ -22,18 +22,35 @@ pub fn explore_constants(
let Some(constant_name) = command.constant else {
let available_constants = print_available_constants(pallet_metadata, pallet_name);
writeln!(output, "Usage:")?;
writeln!(output, " subxt explore {pallet_name} constants <CONSTANT>")?;
writeln!(output, " explore a specific call within this pallet\n\n{available_constants}")?;
writeln!(
output,
" subxt explore {pallet_name} constants <CONSTANT>"
)?;
writeln!(
output,
" explore a specific call within this pallet\n\n{available_constants}"
)?;
return Ok(());
};
// if specified constant is wrong, show user the constants to choose from (but this time as an error):
let Some(constant) = pallet_metadata.constants().find(|constant| constant.name().to_lowercase() == constant_name.to_lowercase()) else {
let Some(constant) = pallet_metadata
.constants()
.find(|constant| constant.name().to_lowercase() == constant_name.to_lowercase())
else {
let available_constants = print_available_constants(pallet_metadata, pallet_name);
let mut description = "Usage:".to_string();
writeln!(description, " subxt explore {pallet_name} constants <CONSTANT>")?;
writeln!(description, " explore a specific call within this pallet\n\n{available_constants}")?;
let err = eyre!("constant \"{constant_name}\" not found in \"{pallet_name}\" pallet!\n\n{description}");
writeln!(
description,
" subxt explore {pallet_name} constants <CONSTANT>"
)?;
writeln!(
description,
" explore a specific call within this pallet\n\n{available_constants}"
)?;
let err = eyre!(
"constant \"{constant_name}\" not found in \"{pallet_name}\" pallet!\n\n{description}"
);
return Err(err);
};
+21 -8
View File
@@ -88,16 +88,23 @@ pub async fn run(opts: Opts, output: &mut impl std::io::Write) -> color_eyre::Re
// if no pallet specified, show user the pallets to choose from:
let Some(pallet_name) = opts.pallet else {
let available_pallets = print_available_pallets(&metadata);
writeln!(output, "Usage:", )?;
writeln!(output, " subxt explore <PALLET>", )?;
writeln!(output, " explore a specific pallet", )?;
writeln!(output, "\n{available_pallets}", )?;
writeln!(output, "Usage:",)?;
writeln!(output, " subxt explore <PALLET>",)?;
writeln!(output, " explore a specific pallet",)?;
writeln!(output, "\n{available_pallets}",)?;
return Ok(());
};
// if specified pallet is wrong, show user the pallets to choose from (but this time as an error):
let Some(pallet_metadata) = metadata.pallets().find(|pallet| pallet.name().to_lowercase() == pallet_name.to_lowercase()) else {
return Err(eyre!("pallet \"{}\" not found in metadata!\n{}", pallet_name, print_available_pallets(&metadata)));
let Some(pallet_metadata) = metadata
.pallets()
.find(|pallet| pallet.name().to_lowercase() == pallet_name.to_lowercase())
else {
return Err(eyre!(
"pallet \"{}\" not found in metadata!\n{}",
pallet_name,
print_available_pallets(&metadata)
));
};
// if correct pallet was specified but no subcommand, instruct the user how to proceed:
@@ -108,11 +115,17 @@ pub async fn run(opts: Opts, output: &mut impl std::io::Write) -> color_eyre::Re
}
writeln!(output, "Usage:")?;
writeln!(output, " subxt explore {pallet_name} calls")?;
writeln!(output, " explore the calls that can be made into this pallet")?;
writeln!(
output,
" explore the calls that can be made into this pallet"
)?;
writeln!(output, " subxt explore {pallet_name} constants")?;
writeln!(output, " explore the constants held in this pallet")?;
writeln!(output, " subxt explore {pallet_name} storage")?;
writeln!(output, " explore the storage values held in this pallet")?;
writeln!(
output,
" explore the storage values held in this pallet"
)?;
return Ok(());
};
+9 -2
View File
@@ -35,7 +35,10 @@ pub async fn explore_storage(
let trailing_args = trailing_args.trim();
let Some(storage_metadata) = pallet_metadata.storage() else {
writeln!(output, "The \"{pallet_name}\" pallet has no storage entries.")?;
writeln!(
output,
"The \"{pallet_name}\" pallet has no storage entries."
)?;
return Ok(());
};
@@ -47,7 +50,11 @@ pub async fn explore_storage(
};
// if specified call storage entry wrong, show user the storage entries to choose from (but this time as an error):
let Some(storage) = storage_metadata.entries().iter().find(|entry| entry.name().to_lowercase() == entry_name.to_lowercase()) else {
let Some(storage) = storage_metadata
.entries()
.iter()
.find(|entry| entry.name().to_lowercase() == entry_name.to_lowercase())
else {
let storage_entries = print_available_storage_entries(storage_metadata, pallet_name);
let description = format!("Usage:\n subxt explore {pallet_name} storage <STORAGE_ENTRY>\n view details for a specific storage entry\n\n{storage_entries}");
return Err(eyre!("Storage entry \"{entry_name}\" not found in \"{pallet_name}\" pallet!\n\n{description}"));
+1 -1
View File
@@ -70,7 +70,7 @@ pub fn generate_calls(
return Err(CodegenError::MissingCallMetadata(
pallet_name.into(),
call_name.to_string(),
))
));
};
let fn_name = format_ident!("{}", variant_name.to_snake_case());
// Propagate the documentation just to `TransactionApi` methods, while
+28 -22
View File
@@ -45,31 +45,37 @@ pub fn generate_constants(
return Ok(quote!());
}
let constant_fns = pallet.constants().map(|constant| {
let fn_name = format_ident!("{}", constant.name().to_snake_case());
let pallet_name = pallet.name();
let constant_name = constant.name();
let Some(constant_hash) = pallet.constant_hash(constant_name) else {
return Err(CodegenError::MissingConstantMetadata(constant_name.into(), pallet_name.into()));
};
let constant_fns = pallet
.constants()
.map(|constant| {
let fn_name = format_ident!("{}", constant.name().to_snake_case());
let pallet_name = pallet.name();
let constant_name = constant.name();
let Some(constant_hash) = pallet.constant_hash(constant_name) else {
return Err(CodegenError::MissingConstantMetadata(
constant_name.into(),
pallet_name.into(),
));
};
let return_ty = type_gen.resolve_type_path(constant.ty());
let docs = constant.docs();
let docs = should_gen_docs
.then_some(quote! { #( #[doc = #docs ] )* })
.unwrap_or_default();
let return_ty = type_gen.resolve_type_path(constant.ty());
let docs = constant.docs();
let docs = should_gen_docs
.then_some(quote! { #( #[doc = #docs ] )* })
.unwrap_or_default();
Ok(quote! {
#docs
pub fn #fn_name(&self) -> #crate_path::constants::Address<#return_ty> {
#crate_path::constants::Address::new_static(
#pallet_name,
#constant_name,
[#(#constant_hash,)*]
)
}
Ok(quote! {
#docs
pub fn #fn_name(&self) -> #crate_path::constants::Address<#return_ty> {
#crate_path::constants::Address::new_static(
#pallet_name,
#constant_name,
[#(#constant_hash,)*]
)
}
})
})
}).collect::<Result<Vec<_>, _>>()?;
.collect::<Result<Vec<_>, _>>()?;
Ok(quote! {
pub mod constants {
+1 -1
View File
@@ -47,7 +47,7 @@ pub fn generate_events(
) -> Result<TokenStream2, CodegenError> {
// Early return if the pallet has no events.
let Some(event_ty) = pallet.event_ty_id() else {
return Ok(quote!())
return Ok(quote!());
};
let struct_defs = super::generate_structs_from_variants(
+4 -1
View File
@@ -89,7 +89,10 @@ fn generate_storage_entry_fns(
let pallet_name = pallet.name();
let storage_name = storage_entry.name();
let Some(storage_hash) = pallet.storage_hash(storage_name) else {
return Err(CodegenError::MissingStorageMetadata(pallet_name.into(), storage_name.into()));
return Err(CodegenError::MissingStorageMetadata(
pallet_name.into(),
storage_name.into(),
));
};
let snake_case_name = storage_entry.name().to_snake_case();
+13 -3
View File
@@ -187,11 +187,21 @@ impl TypeSubstitutes {
src_path: &syn::Path,
target_path: &syn::Path,
) -> Result<TypeParamMapping, TypeSubstitutionError> {
let Some(syn::PathSegment { arguments: src_path_args, .. }) = src_path.segments.last() else {
let Some(syn::PathSegment {
arguments: src_path_args,
..
}) = src_path.segments.last()
else {
return Err(TypeSubstitutionError::EmptySubstitutePath(src_path.span()));
};
let Some(syn::PathSegment { arguments: target_path_args, .. }) = target_path.segments.last() else {
return Err(TypeSubstitutionError::EmptySubstitutePath(target_path.span()));
let Some(syn::PathSegment {
arguments: target_path_args,
..
}) = target_path.segments.last()
else {
return Err(TypeSubstitutionError::EmptySubstitutePath(
target_path.span(),
));
};
// Get hold of the generic args for the "from" type, erroring if they aren't valid.
+10 -9
View File
@@ -187,7 +187,7 @@ impl BackgroundTask {
Ok(RpcResponse::Error { id, error }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send error. Id={id} is not a valid number");
return
return;
};
if let Some(sender) = self.requests.remove(&id) {
@@ -216,7 +216,7 @@ impl BackgroundTask {
Ok(RpcResponse::Method { id, result }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send response. Id={id} is not a valid number");
return
return;
};
// Send the response back.
@@ -232,12 +232,13 @@ impl BackgroundTask {
.get()
.trim_start_matches('"')
.trim_end_matches('"')
.parse::<usize>() else {
tracing::warn!(
target: LOG_TARGET,
"Subscription id={result} is not a valid number",
);
return;
.parse::<usize>()
else {
tracing::warn!(
target: LOG_TARGET,
"Subscription id={result} is not a valid number",
);
return;
};
tracing::trace!(target: LOG_TARGET, "Received subscription id={sub_id}");
@@ -256,7 +257,7 @@ impl BackgroundTask {
Ok(RpcResponse::Subscription { method, id, result }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send subscription. Id={id} is not a valid number");
return
return;
};
if let Some(sender) = self.subscriptions.get_mut(&id) {
+20 -7
View File
@@ -114,7 +114,9 @@ impl PlatformRef for SubxtPlatform {
Box::pin(future::poll_fn(|cx| {
// The `connect` is expected to be called before this method and would populate
// the buffers properly. When the buffers are empty, this future is shortly dropped.
let Some((read_buffer, write_buffer)) = stream.buffers.as_mut() else { return Poll::Pending };
let Some((read_buffer, write_buffer)) = stream.buffers.as_mut() else {
return Poll::Pending;
};
// Whether the future returned by `update_stream` should return `Ready` or `Pending`.
let mut update_stream_future_ready = false;
@@ -246,7 +248,7 @@ impl PlatformRef for SubxtPlatform {
stream.buffers.as_mut().map(|(r, _)| r)
else {
assert_eq!(extra_bytes, 0);
return
return;
};
assert!(cursor.start + extra_bytes <= cursor.end);
@@ -254,8 +256,14 @@ impl PlatformRef for SubxtPlatform {
}
fn writable_bytes(&self, stream: &mut Self::Stream) -> usize {
let Some(StreamWriteBuffer::Open { ref mut buffer, must_close: false, ..}) =
stream.buffers.as_mut().map(|(_, w)| w) else { return 0 };
let Some(StreamWriteBuffer::Open {
ref mut buffer,
must_close: false,
..
}) = stream.buffers.as_mut().map(|(_, w)| w)
else {
return 0;
};
buffer.capacity() - buffer.len()
}
@@ -265,15 +273,20 @@ impl PlatformRef for SubxtPlatform {
// Because `writable_bytes` returns 0 if the writing side is closed, and because `data`
// must always have a size inferior or equal to `writable_bytes`, we know for sure that
// the writing side isn't closed.
let Some(StreamWriteBuffer::Open { ref mut buffer, .. } )=
stream.buffers.as_mut().map(|(_, w)| w) else { panic!() };
let Some(StreamWriteBuffer::Open { ref mut buffer, .. }) =
stream.buffers.as_mut().map(|(_, w)| w)
else {
panic!()
};
buffer.reserve(data.len());
buffer.extend(data.iter().copied());
}
fn close_send(&self, stream: &mut Self::Stream) {
// It is not illegal to call this on an already-reset stream.
let Some((_, write_buffer)) = stream.buffers.as_mut() else { return };
let Some((_, write_buffer)) = stream.buffers.as_mut() else {
return;
};
match write_buffer {
StreamWriteBuffer::Open {
+10 -4
View File
@@ -268,7 +268,7 @@ impl ExtrinsicPartTypeIds {
let extrinsic_id = metadata.extrinsic.ty.id;
let Some(extrinsic_ty) = metadata.types.resolve(extrinsic_id) else {
return Err("Missing extrinsic type".into())
return Err("Missing extrinsic type".into());
};
let params: HashMap<_, _> = extrinsic_ty
@@ -313,7 +313,9 @@ fn generate_outer_enums(
.types
.iter()
.find(|ty| {
let Some(ident) = ty.ty.path.ident() else { return false };
let Some(ident) = ty.ty.path.ident() else {
return false;
};
ident == "RuntimeCall"
})
.expect("RuntimeCall exists in V14; qed");
@@ -323,7 +325,9 @@ fn generate_outer_enums(
.types
.iter()
.find(|ty| {
let Some(ident) = ty.ty.path.ident() else { return false };
let Some(ident) = ty.ty.path.ident() else {
return false;
};
ident == "RuntimeEvent"
})
.expect("RuntimeEvent exists in V14; qed");
@@ -357,7 +361,9 @@ fn generate_runtime_error_type(
.pallets
.iter()
.filter_map(|pallet| {
let Some(pallet_error) = &pallet.error else { return None };
let Some(pallet_error) = &pallet.error else {
return None;
};
let path = format!("{}Error", pallet.name);
Some(scale_info::Variant {
+2 -2
View File
@@ -176,10 +176,10 @@ impl Keypair {
/// ```
pub fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &PublicKey) -> bool {
let Ok(signature) = schnorrkel::Signature::from_bytes(&sig.0) else {
return false
return false;
};
let Ok(public) = schnorrkel::PublicKey::from_bytes(&pubkey.0) else {
return false
return false;
};
public
.verify_simple(SIGNING_CTX, message.as_ref(), &signature)
+2 -2
View File
@@ -114,7 +114,7 @@ impl<T: Config + Send + Sync + 'static> Backend<T> for LegacyBackend<T> {
async fn block_body(&self, at: T::Hash) -> Result<Option<Vec<Vec<u8>>>, Error> {
let Some(details) = self.methods.chain_get_block(Some(at)).await? else {
return Ok(None)
return Ok(None);
};
Ok(Some(
details.block.extrinsics.into_iter().map(|b| b.0).collect(),
@@ -364,7 +364,7 @@ impl<T: Config> Stream for StorageFetchDescendantKeysStream<T> {
if let Some(mut keys_fut) = this.keys_fut.take() {
let Poll::Ready(keys) = keys_fut.poll_unpin(cx) else {
this.keys_fut = Some(keys_fut);
return Poll::Pending
return Poll::Pending;
};
match keys {
+1 -1
View File
@@ -435,7 +435,7 @@ const _: () = {
fn is_type_empty(type_id: u32, types: &scale_info::PortableRegistry) -> bool {
let Some(ty) = types.resolve(type_id) else {
// Can't resolve; type may not be empty. Not expected to hit this.
return false
return false;
};
use scale_info::TypeDef;
+2 -1
View File
@@ -145,7 +145,8 @@ impl Eq for ModuleError {}
impl std::fmt::Display for ModuleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Ok(details) = self.details() else {
return f.write_str("Unknown pallet error (pallet and error details cannot be retrieved)");
return f
.write_str("Unknown pallet error (pallet and error details cannot be retrieved)");
};
let pallet = details.pallet.name();
+1 -1
View File
@@ -325,7 +325,7 @@ impl<T: Config, C: OnlineClientT<T>> TxInBlock<T, C> {
.iter()
.position(|ext| {
use crate::config::Hasher;
let Ok((_,stripped)) = strip_compact_prefix(ext) else {
let Ok((_, stripped)) = strip_compact_prefix(ext) else {
return false;
};
let hash = T::Hasher::hash_of(&stripped);
+1 -1
View File
@@ -86,7 +86,7 @@ async fn run() {
for substrate_node_path in substrate_bins_vec {
let Ok(full_path) = which::which(substrate_node_path) else {
continue
continue;
};
// Re-build if the substrate binary we're pointed to changes (mtime):