Unverified Commit cfd55bd6 authored by Andrew Jones's avatar Andrew Jones Committed by GitHub
Browse files

Use rustfmt config from `ink!` 🦑 (#505)

* Copy ink rustfmt config

* inkify

* Add editorconfig

* Fmt

* Fmt

* Fmt
parent bce9301c
Pipeline #188284 passed with stages
in 10 minutes and 50 seconds
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
max_width = 90 # changed
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
use_small_heuristics = "Default"
indent_style = "Block"
wrap_comments = false
format_code_in_doc_comments = false
comment_width = 80
normalize_comments = true # changed
normalize_doc_attributes = false
license_template_path = "FILE_HEADER" # changed
format_strings = false
format_macro_matchers = false
format_macro_bodies = true
empty_item_single_line = true
struct_lit_single_line = true
fn_single_line = false
where_single_line = false
imports_indent = "Block"
imports_layout = "Vertical" # changed
imports_granularity = "Crate" # changed
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
type_punctuation_density = "Wide"
space_before_colon = false
space_after_colon = true
spaces_around_ranges = false
binop_separator = "Front"
remove_nested_parens = true
combine_control_expr = false # changed
overflow_delimited_expr = false
struct_field_align_threshold = 0
enum_discrim_align_threshold = 0
match_arm_blocks = true
force_multiline_blocks = true # changed
fn_args_layout = "Tall"
brace_style = "SameLineWhere"
control_brace_style = "AlwaysSameLine"
trailing_semicolon = false # changed
trailing_comma = "Vertical"
match_block_trailing_comma = false
blank_lines_upper_bound = 1
blank_lines_lower_bound = 0
edition = "2021" # changed
version = "One"
merge_derives = true
use_try_shorthand = true # changed
use_field_init_shorthand = true # changed
force_explicit_abi = true
condense_wildcard_suffixes = false
color = "Auto"
unstable_features = true # changed
disable_all_formatting = false
skip_children = false
hide_parse_errors = false
error_on_line_overflow = false
error_on_unformatted = false
report_todo = "Always"
report_fixme = "Always"
ignore = []
# Below are `rustfmt` internal settings
#
# emit_mode = "Files"
# make_backup = false
......@@ -19,17 +19,31 @@ use std::{
env,
ffi::OsStr,
fs::File,
io::{prelude::*, Write},
io::{
prelude::*,
Write,
},
iter::Iterator,
path::{Path, PathBuf},
path::{
Path,
PathBuf,
},
process::Command,
};
use anyhow::Result;
use walkdir::WalkDir;
use zip::{write::FileOptions, CompressionMethod, ZipWriter};
use zip::{
write::FileOptions,
CompressionMethod,
ZipWriter,
};
use platforms::{TARGET_ARCH, TARGET_ENV, TARGET_OS};
use platforms::{
TARGET_ARCH,
TARGET_ENV,
TARGET_OS,
};
use substrate_build_script_utils::rerun_if_git_head_changed;
const DEFAULT_UNIX_PERMISSIONS: u32 = 0o755;
......@@ -59,7 +73,10 @@ fn main() {
/// * Creates a zip archive of the `new` project template.
/// * Builds the `dylint` driver found in `ink_linting`, the compiled
/// driver is put into a zip archive as well.
fn zip_template_and_build_dylint_driver(manifest_dir: PathBuf, out_dir: PathBuf) -> Result<()> {
fn zip_template_and_build_dylint_driver(
manifest_dir: PathBuf,
out_dir: PathBuf,
) -> Result<()> {
zip_template(&manifest_dir, &out_dir)?;
check_dylint_link_installed()?;
......@@ -108,7 +125,11 @@ fn zip_template_and_build_dylint_driver(manifest_dir: PathBuf, out_dir: PathBuf)
)
})?;
let res = build_and_zip_dylint_driver(ink_dylint_driver_dir, out_dir, dylint_driver_dst_file);
let res = build_and_zip_dylint_driver(
ink_dylint_driver_dir,
out_dir,
dylint_driver_dst_file,
);
// After the build process of `ink_linting` happened we need to name back to the original
// `_Cargo.toml` name, otherwise the directory would be "dirty" and `cargo publish` would
......@@ -295,7 +316,11 @@ fn zip_dir(src_dir: &Path, dst_file: &Path, method: CompressionMethod) -> Result
///
/// `dylint` drivers have a file name of the form `libink_linting@toolchain.[so,dll]`.
#[cfg(not(feature = "cargo-clippy"))]
fn zip_dylint_driver(src_dir: &Path, dst_file: &Path, method: CompressionMethod) -> Result<()> {
fn zip_dylint_driver(
src_dir: &Path,
dst_file: &Path,
method: CompressionMethod,
) -> Result<()> {
if !src_dir.exists() {
anyhow::bail!("src_dir '{}' does not exist", src_dir.display());
}
......@@ -333,7 +358,7 @@ fn zip_dylint_driver(src_dir: &Path, dst_file: &Path, method: CompressionMethod)
zip.finish()?;
lib_found = true;
break;
break
}
}
......
......@@ -23,7 +23,7 @@ where
{
if bytes.is_empty() {
// Return empty string without prepended `0x`.
return serializer.serialize_str("");
return serializer.serialize_str("")
}
serde_hex::serialize(bytes, serializer)
}
......@@ -56,7 +56,9 @@ where
}
/// Deserializes the given hex string with optional `0x` prefix.
pub fn deserialize_from_byte_str_array<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
pub fn deserialize_from_byte_str_array<'de, D>(
deserializer: D,
) -> Result<[u8; 32], D::Error>
where
D: serde::Deserializer<'de>,
{
......
......@@ -55,10 +55,22 @@
mod byte_str;
use semver::Version;
use serde::{de, Deserialize, Serialize, Serializer};
use serde_json::{Map, Value};
use serde::{
de,
Deserialize,
Serialize,
Serializer,
};
use serde_json::{
Map,
Value,
};
use std::{
fmt::{Display, Formatter, Result as DisplayResult},
fmt::{
Display,
Formatter,
Result as DisplayResult,
},
str::FromStr,
};
use url::Url;
......@@ -627,8 +639,10 @@ mod tests {
#[test]
fn json_with_optional_fields() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let compiler = SourceCompiler::new(
Compiler::RustC,
Version::parse("1.46.0-nightly").unwrap(),
);
let wasm = SourceWasm::new(vec![0u8, 1u8, 2u8]);
let source = Source::new(Some(wasm), CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
......@@ -709,8 +723,10 @@ mod tests {
#[test]
fn json_excludes_optional_fields() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let compiler = SourceCompiler::new(
Compiler::RustC,
Version::parse("1.46.0-nightly").unwrap(),
);
let source = Source::new(None, CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
.name("incrementer".to_string())
......@@ -759,8 +775,10 @@ mod tests {
#[test]
fn decoding_works() {
let language = SourceLanguage::new(Language::Ink, Version::new(2, 1, 0));
let compiler =
SourceCompiler::new(Compiler::RustC, Version::parse("1.46.0-nightly").unwrap());
let compiler = SourceCompiler::new(
Compiler::RustC,
Version::parse("1.46.0-nightly").unwrap(),
);
let wasm = SourceWasm::new(vec![0u8, 1u8, 2u8]);
let source = Source::new(Some(wasm), CodeHash([0u8; 32]), language, compiler);
let contract = Contract::builder()
......
......@@ -16,21 +16,49 @@
use crate::{
crate_metadata::CrateMetadata,
maybe_println, util, validate_wasm,
workspace::{Manifest, ManifestPath, Profile, Workspace},
BuildArtifacts, BuildMode, BuildResult, Network, OptimizationPasses, OptimizationResult,
OutputType, UnstableFlags, UnstableOptions, Verbosity, VerbosityFlags,
maybe_println,
util,
validate_wasm,
workspace::{
Manifest,
ManifestPath,
Profile,
Workspace,
},
BuildArtifacts,
BuildMode,
BuildResult,
Network,
OptimizationPasses,
OptimizationResult,
OutputType,
UnstableFlags,
UnstableOptions,
Verbosity,
VerbosityFlags,
};
use anyhow::{
Context,
Result,
};
use anyhow::{Context, Result};
use colored::Colorize;
use parity_wasm::elements::{External, Internal, MemoryType, Module, Section};
use parity_wasm::elements::{
External,
Internal,
MemoryType,
Module,
Section,
};
use regex::Regex;
use semver::Version;
use std::{
convert::TryFrom,
ffi::OsStr,
fs::metadata,
path::{Path, PathBuf},
path::{
Path,
PathBuf,
},
process::Command,
str,
};
......@@ -417,19 +445,23 @@ fn check_dylint_requirements(_working_dir: Option<&Path>) -> Result<()> {
///
/// Iterates over the import section, finds the memory import entry if any and adjusts the maximum
/// limit.
fn ensure_maximum_memory_pages(module: &mut Module, maximum_allowed_pages: u32) -> Result<()> {
fn ensure_maximum_memory_pages(
module: &mut Module,
maximum_allowed_pages: u32,
) -> Result<()> {
let mem_ty = module
.import_section_mut()
.and_then(|section| {
section
.entries_mut()
.iter_mut()
.find_map(|entry| match entry.external_mut() {
section.entries_mut().iter_mut().find_map(|entry| {
match entry.external_mut() {
External::Memory(ref mut mem_ty) => Some(mem_ty),
_ => None,
})
}
})
})
.context("Memory import is not found. Is --import-memory specified in the linker args")?;
.context(
"Memory import is not found. Is --import-memory specified in the linker args",
)?;
if let Some(requested_maximum) = mem_ty.limits().maximum() {
// The module already has maximum, check if it is within the limit bail out.
......@@ -453,10 +485,12 @@ fn ensure_maximum_memory_pages(module: &mut Module, maximum_allowed_pages: u32)
/// Presently all custom sections are not required so they can be stripped safely.
/// The name section is already stripped by `wasm-opt`.
fn strip_custom_sections(module: &mut Module) {
module.sections_mut().retain(|section| match section {
Section::Reloc(_) => false,
Section::Custom(custom) if custom.name() != "name" => false,
_ => true,
module.sections_mut().retain(|section| {
match section {
Section::Reloc(_) => false,
Section::Custom(custom) if custom.name() != "name" => false,
_ => true,
}
})
}
......@@ -484,8 +518,8 @@ fn load_module<P: AsRef<Path>>(path: P) -> Result<Module> {
/// Performs required post-processing steps on the Wasm artifact.
fn post_process_wasm(crate_metadata: &CrateMetadata) -> Result<()> {
// Deserialize Wasm module from a file.
let mut module =
load_module(&crate_metadata.original_wasm).context("Loading of original wasm failed")?;
let mut module = load_module(&crate_metadata.original_wasm)
.context("Loading of original wasm failed")?;
strip_exports(&mut module);
ensure_maximum_memory_pages(&mut module, MAX_MEMORY_PAGES)?;
......@@ -527,7 +561,7 @@ fn optimize_wasm(
return Err(anyhow::anyhow!(
"Optimization failed, optimized wasm output file `{}` not found.",
dest_optimized.display()
));
))
}
let original_size = metadata(&crate_metadata.dest_wasm)?.len() as f64 / 1000.0;
......@@ -899,15 +933,28 @@ pub(crate) fn execute(args: ExecuteArgs) -> Result<BuildResult> {
#[cfg(test)]
mod tests_ci_only {
use super::{
assert_compatible_ink_dependencies, assert_debug_mode_supported,
assert_compatible_ink_dependencies,
assert_debug_mode_supported,
check_wasm_opt_version_compatibility,
};
use crate::{
cmd::{build::load_module, BuildCommand},
util::tests::{with_new_contract_project, with_tmp_dir},
cmd::{
build::load_module,
BuildCommand,
},
util::tests::{
with_new_contract_project,
with_tmp_dir,
},
workspace::Manifest,
BuildArtifacts, BuildMode, ManifestPath, OptimizationPasses, OutputType, UnstableOptions,
Verbosity, VerbosityFlags,
BuildArtifacts,
BuildMode,
ManifestPath,
OptimizationPasses,
OutputType,
UnstableOptions,
Verbosity,
VerbosityFlags,
};
use semver::Version;
#[cfg(unix)]
......@@ -915,15 +962,22 @@ mod tests_ci_only {
use std::{
ffi::OsStr,
io::Write,
path::{Path, PathBuf},
path::{
Path,
PathBuf,
},
};
/// Modifies the `Cargo.toml` under the supplied `cargo_toml_path` by
/// setting `optimization-passes` in `[package.metadata.contract]` to `passes`.
fn write_optimization_passes_into_manifest(cargo_toml_path: &Path, passes: OptimizationPasses) {
fn write_optimization_passes_into_manifest(
cargo_toml_path: &Path,
passes: OptimizationPasses,
) {
let manifest_path =
ManifestPath::new(cargo_toml_path).expect("manifest path creation failed");
let mut manifest = Manifest::new(manifest_path.clone()).expect("manifest creation failed");
let mut manifest =
Manifest::new(manifest_path.clone()).expect("manifest creation failed");
manifest
.set_profile_optimization_passes(passes)
.expect("setting `optimization-passes` in profile failed");
......@@ -1125,7 +1179,8 @@ mod tests_ci_only {
// the manifest path
// when
let res = assert_compatible_ink_dependencies(&manifest_path, Verbosity::Default);
let res =
assert_compatible_ink_dependencies(&manifest_path, Verbosity::Default);
// then
assert!(res.is_ok());
......@@ -1150,7 +1205,8 @@ mod tests_ci_only {
.expect("writing manifest failed");
// when
let res = assert_compatible_ink_dependencies(&manifest_path, Verbosity::Default);
let res =
assert_compatible_ink_dependencies(&manifest_path, Verbosity::Default);
// then
assert!(res.is_err());
......@@ -1214,8 +1270,9 @@ mod tests_ci_only {
// this println is here to debug a spuriously failing CI at the following assert.
eprintln!("error: {:?}", res);
assert!(format!("{:?}", res)
.starts_with("Err(Your wasm-opt version is 98, but we require a version >= 99."));
assert!(format!("{:?}", res).starts_with(
"Err(Your wasm-opt version is 98, but we require a version >= 99."
));
Ok(())
})
......@@ -1283,21 +1340,26 @@ mod tests_ci_only {
#[test]
pub fn debug_mode_must_be_compatible() {
let _ =
assert_debug_mode_supported(&Version::parse("3.0.0-rc4").expect("parsing must work"))
.expect("debug mode must be compatible");
let _ =
assert_debug_mode_supported(&Version::parse("4.0.0-rc1").expect("parsing must work"))
.expect("debug mode must be compatible");
let _ = assert_debug_mode_supported(&Version::parse("5.0.0").expect("parsing must work"))
.expect("debug mode must be compatible");
let _ = assert_debug_mode_supported(
&Version::parse("3.0.0-rc4").expect("parsing must work"),
)
.expect("debug mode must be compatible");
let _ = assert_debug_mode_supported(
&Version::parse("4.0.0-rc1").expect("parsing must work"),
)
.expect("debug mode must be compatible");
let _ = assert_debug_mode_supported(
&Version::parse("5.0.0").expect("parsing must work"),
)
.expect("debug mode must be compatible");
}
#[test]
pub fn debug_mode_must_be_incompatible() {
let res =
assert_debug_mode_supported(&Version::parse("3.0.0-rc3").expect("parsing must work"))
.expect_err("assertion must fail");
let res = assert_debug_mode_supported(
&Version::parse("3.0.0-rc3").expect("parsing must work"),
)
.expect_err("assertion must fail");
assert_eq!(
res.to_string(),
"Building the contract in debug mode requires an ink! version newer than `3.0.0-rc3`!"
......@@ -1353,8 +1415,8 @@ mod tests_ci_only {
std::fs::create_dir_all(new_dir_path).expect("creating dir must work");
std::fs::rename(old_lib_path, new_lib_path).expect("moving file must work");
let mut manifest =
Manifest::new(manifest_path.clone()).expect("creating manifest must work");
let mut manifest = Manifest::new(manifest_path.clone())
.expect("creating manifest must work");
manifest
.set_lib_path("srcfoo/lib.rs")
.expect("setting lib path must work");
......
......@@ -15,11 +15,17 @@
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.
use crate::{
cmd::extrinsics::{load_metadata, ContractMessageTranscoder},
cmd::extrinsics::{
load_metadata,
ContractMessageTranscoder,
},
util::decode_hex,
DEFAULT_KEY_COL_WIDTH,
};
use anyhow::{Context, Result};
use anyhow::{
Context,
Result,
};
use colored::Colorize as _;
#[derive(Debug, Clone, clap::Args)]
......@@ -47,12 +53,21 @@ impl DecodeCommand {
const ERR_MSG: &str = "Failed to decode specified data as a hex value";
let decoded_data = match self.r#type {
DataType::Event => transcoder
.decode_contract_event(&mut &decode_hex(&self.data).context(ERR_MSG)?[..])?,
DataType::Message => transcoder
.decode_contract_message(&mut &decode_hex(&self.data).context(ERR_MSG)?[..])?,
DataType::Constructor => transcoder
.decode_contract_constructor(&mut &decode_hex(&self.data).context(ERR_MSG)?[..])?,
DataType::Event => {
transcoder.decode_contract_event(
&mut &decode_hex(&self.data).context(ERR_MSG)?[..],
)?
}
DataType::Message => {
transcoder.decode_contract_message(
&mut &decode_hex(&self.data).context(ERR_MSG)?[..],
)?
}
DataType::Constructor => {
transcoder.decode_contract_constructor(
&mut &decode_hex(&self.data).context(ERR_MSG)?[..],
)?
}
};
println!(
......
......@@ -15,17 +15,34 @@
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.
use super::{
display_contract_exec_result, display_events, load_metadata, parse_balance,
wait_for_success_and_handle_error, Balance, ContractMessageTranscoder, ExtrinsicOpts,
PairSigner, RuntimeApi, EXEC_RESULT_MAX_KEY_COL_WIDTH,
display_contract_exec_result,
display_events,
load_metadata,
parse_balance,
wait_for_success_and_handle_error,
Balance,
ContractMessageTranscoder,
ExtrinsicOpts,
PairSigner,
RuntimeApi,
EXEC_RESULT_MAX_KEY_COL_WIDTH,
};
use crate::name_value_println;
use anyhow::Result;
use jsonrpsee::{core::client::ClientT, rpc_params, ws_client::WsClientBuilder};
use jsonrpsee::{
core::client::ClientT,
rpc_params,
ws_client::WsClientBuilder,
};
use serde::Serialize;
use sp_core::Bytes;
use std::fmt::Debug;
use subxt::{rpc::NumberOrHex, ClientBuilder, Config, DefaultConfig};
use subxt::{
rpc::NumberOrHex,
ClientBuilder,
Config,
DefaultConfig,
};
type ContractExecResult = pallet_contracts_primitives::ContractExecResult<Balance>;
......@@ -53,7 +70,8 @@ pub struct CallCommand {
impl CallCommand {
pub fn run(&self) -> Result<()> {
let (_, contract_metadata) = load_metadata(self.extrinsic_opts.manifest_path.as_ref())?;
let (_, contract_metadata) =
load_metadata(self.extrinsic_opts.manifest_path.as_ref())?;
let transcoder = ContractMessageTranscoder::new(&contract_metadata);
let call_data = transcoder.encode(&self.message, &self.args)?;
log::debug!("message data: {:?}", hex::encode(&call_data));
......@@ -95,7 +113,8 @@ impl CallCommand {
match result.result {
Ok(ref ret_val) => {
let value = transcoder.decode_return(&self.message, &mut &ret_val.data.0[..])?;
let value =
transcoder.decode_return(&self.message, &mut &ret_val.data.0[..])?;
name_value_println!(
"Result",
String::from("Success!"),
......@@ -106,7 +125,11 @@ impl CallCommand {
format!("{:?}", ret_val.did_revert()),
EXEC_RESULT_MAX_KEY_COL_WIDTH
);