From 7828a4c7cb0b3d485c33903184bdb1691239c5ab Mon Sep 17 00:00:00 2001 From: Michael Mueller Date: Fri, 29 Jan 2021 07:32:11 +0100 Subject: [PATCH 1/3] Print warning to stderr --- src/workspace/manifest.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/workspace/manifest.rs b/src/workspace/manifest.rs index 948437c3..70ac9366 100644 --- a/src/workspace/manifest.rs +++ b/src/workspace/manifest.rs @@ -229,7 +229,7 @@ impl Manifest { if members.contains(&LEGACY_METADATA_PACKAGE_PATH.into()) { // warn user if they have legacy metadata generation artifacts use colored::Colorize; - println!( + eprintln!( "{} {} {} {}", "warning:".yellow().bold(), "please remove".bold(), -- GitLab From d6fbdff479d973362a8a866ef7dbc1abdf9e072e Mon Sep 17 00:00:00 2001 From: Michael Mueller Date: Fri, 29 Jan 2021 07:32:24 +0100 Subject: [PATCH 2/3] Suppress output on `--quiet` --- src/cmd/build.rs | 39 +++++++++++++++++++++++---------------- src/cmd/metadata.rs | 15 +++++++++------ src/cmd/new.rs | 4 ++-- src/main.rs | 35 ++++++++++++++++++++++++++++------- src/util.rs | 9 +++++++++ 5 files changed, 71 insertions(+), 31 deletions(-) diff --git a/src/cmd/build.rs b/src/cmd/build.rs index 95401341..faaad93c 100644 --- a/src/cmd/build.rs +++ b/src/cmd/build.rs @@ -157,7 +157,7 @@ fn build_cargo_project( Ok(()) }; - if unstable_flags.original_manifest { + if unstable_flags.original_manifest && util::is_verbose(&verbosity) { println!( "{} {}", "warning:".yellow().bold(), @@ -318,6 +318,7 @@ fn execute( target_directory: crate_metadata.target_directory, optimization_result: maybe_optimization_result, build_artifact, + verbosity, }; return Ok(res); } @@ -342,26 +343,32 @@ pub(crate) fn execute_with_crate_metadata( build_artifact: BuildArtifacts, unstable_flags: UnstableFlags, ) -> Result<(Option, Option)> { - println!( - " {} {}", - format!("[1/{}]", build_artifact.steps()).bold(), - "Building cargo project".bright_green().bold() - ); + if util::is_verbose(&verbosity) { + println!( + " {} {}", + format!("[1/{}]", build_artifact.steps()).bold(), + "Building cargo project".bright_green().bold() + ); + } build_cargo_project(&crate_metadata, build_artifact, verbosity, unstable_flags)?; - println!( - " {} {}", - format!("[2/{}]", build_artifact.steps()).bold(), - "Post processing wasm file".bright_green().bold() - ); + if util::is_verbose(&verbosity) { + println!( + " {} {}", + format!("[2/{}]", build_artifact.steps()).bold(), + "Post processing wasm file".bright_green().bold() + ); + } post_process_wasm(&crate_metadata)?; if !optimize_contract { return Ok((None, None)); } - println!( - " {} {}", - format!("[3/{}]", build_artifact.steps()).bold(), - "Optimizing wasm file".bright_green().bold() - ); + if util::is_verbose(&verbosity) { + println!( + " {} {}", + format!("[3/{}]", build_artifact.steps()).bold(), + "Optimizing wasm file".bright_green().bold() + ); + } let optimization_result = optimize_wasm(&crate_metadata)?; Ok(( Some(crate_metadata.dest_wasm.clone()), diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 595d05bb..276af777 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -72,11 +72,13 @@ impl GenerateMetadataCommand { let generate_metadata = |manifest_path: &ManifestPath| -> Result<()> { let mut current_progress = 4; - println!( - " {} {}", - format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), - "Generating metadata".bright_green().bold() - ); + if util::is_verbose(&self.verbosity) { + println!( + " {} {}", + format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), + "Generating metadata".bright_green().bold() + ); + } let target_dir_arg = format!("--target-dir={}", target_directory.to_string_lossy()); let stdout = util::invoke_cargo( "run", @@ -102,7 +104,7 @@ impl GenerateMetadataCommand { current_progress += 1; } - if self.build_artifact == BuildArtifacts::All { + if self.build_artifact == BuildArtifacts::All && util::is_verbose(&self.verbosity) { println!( " {} {}", format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), @@ -144,6 +146,7 @@ impl GenerateMetadataCommand { optimization_result, target_directory, build_artifact: self.build_artifact, + verbosity: self.verbosity, }) } diff --git a/src/cmd/new.rs b/src/cmd/new.rs index 84689404..f294e3cf 100644 --- a/src/cmd/new.rs +++ b/src/cmd/new.rs @@ -23,7 +23,7 @@ use std::{ use anyhow::Result; use heck::CamelCase as _; -pub(crate) fn execute

(name: &str, dir: Option

) -> Result +pub(crate) fn execute

(name: &str, dir: Option

) -> Result> where P: AsRef, { @@ -93,7 +93,7 @@ where } } - Ok(format!("Created contract {}", name)) + Ok(Some(format!("Created contract {}", name))) } #[cfg(test)] diff --git a/src/main.rs b/src/main.rs index 27ff3fdd..860928dc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -94,15 +94,20 @@ impl ExtrinsicOpts { #[derive(Clone, Debug, StructOpt)] pub struct VerbosityFlags { + /// No output printed to stdout #[structopt(long)] quiet: bool, + /// Use verbose output #[structopt(long)] verbose: bool, } +/// Denotes if output should be printed to stdout. #[derive(Clone, Copy)] -enum Verbosity { +pub enum Verbosity { + /// No output printed to stdout Quiet, + /// Use verbose output Verbose, } @@ -200,6 +205,8 @@ pub struct BuildResult { pub optimization_result: Option, /// Which build artifacts were generated. pub build_artifact: BuildArtifacts, + /// The verbosity flags. + pub verbosity: Option, } /// Result of the optimization process. @@ -344,7 +351,11 @@ fn main() { let Opts::Contract(args) = Opts::from_args(); match exec(args.cmd) { - Ok(msg) => println!("\t{}", msg), + Ok(maybe_msg) => { + if let Some(msg) = maybe_msg { + println!("\t{}", msg) + } + } Err(err) => { eprintln!( "{} {}", @@ -356,12 +367,16 @@ fn main() { } } -fn exec(cmd: Command) -> Result { +fn exec(cmd: Command) -> Result> { match &cmd { Command::New { name, target_dir } => cmd::new::execute(name, target_dir.as_ref()), Command::Build(build) => { let result = build.exec()?; - Ok(result.display()) + if util::is_verbose(&result.verbosity) { + Ok(Some(result.display())) + } else { + Ok(None) + } } Command::Check(check) => { let res = check.exec()?; @@ -369,7 +384,13 @@ fn exec(cmd: Command) -> Result { res.dest_wasm.is_none(), "no dest_wasm must be on the generation result" ); - Ok("\nYour contract's code was built successfully.".to_string()) + if util::is_verbose(&res.verbosity) { + Ok(Some( + "\nYour contract's code was built successfully.".to_string(), + )) + } else { + Ok(None) + } } Command::GenerateMetadata {} => Err(anyhow::anyhow!( "Command deprecated, use `cargo contract build` instead" @@ -381,7 +402,7 @@ fn exec(cmd: Command) -> Result { wasm_path, } => { let code_hash = cmd::execute_deploy(extrinsic_opts, wasm_path.as_ref())?; - Ok(format!("Code hash: {:?}", code_hash)) + Ok(Some(format!("Code hash: {:?}", code_hash))) } #[cfg(feature = "extrinsics")] Command::Instantiate { @@ -398,7 +419,7 @@ fn exec(cmd: Command) -> Result { *code_hash, data.clone(), )?; - Ok(format!("Contract account: {:?}", contract_account)) + Ok(Some(format!("Contract account: {:?}", contract_account))) } } } diff --git a/src/util.rs b/src/util.rs index 17eb31b8..71949830 100644 --- a/src/util.rs +++ b/src/util.rs @@ -93,6 +93,15 @@ pub(crate) fn base_name(path: &PathBuf) -> &str { .expect("must be valid utf-8") } +/// Returns `true` if output should be printed (i.e. verbose output is set). +pub(crate) fn is_verbose(verbosity: &Option) -> bool { + if let Some(Verbosity::Verbose) = verbosity { + true + } else { + false + } +} + #[cfg(test)] pub mod tests { use std::path::Path; -- GitLab From 45f787d71b3c8ff5c759acfa1a1e58f67c85471d Mon Sep 17 00:00:00 2001 From: Michael Mueller Date: Wed, 3 Feb 2021 10:40:04 +0100 Subject: [PATCH 3/3] Refactor conditional printing --- src/cmd/build.rs | 56 ++++++++++++++++++++++----------------------- src/cmd/metadata.rs | 24 +++++++++---------- src/main.rs | 26 +++++++++++++++------ src/util.rs | 23 ++++++++++--------- 4 files changed, 70 insertions(+), 59 deletions(-) diff --git a/src/cmd/build.rs b/src/cmd/build.rs index faaad93c..6708e601 100644 --- a/src/cmd/build.rs +++ b/src/cmd/build.rs @@ -23,7 +23,7 @@ use std::{ use crate::{ crate_metadata::CrateMetadata, - util, + maybe_println, util, workspace::{ManifestPath, Profile, Workspace}, BuildArtifacts, BuildResult, UnstableFlags, UnstableOptions, VerbosityFlags, }; @@ -69,7 +69,7 @@ impl BuildCommand { let manifest_path = ManifestPath::try_from(self.manifest_path.as_ref())?; let unstable_flags: UnstableFlags = TryFrom::<&UnstableOptions>::try_from(&self.unstable_options)?; - let verbosity: Option = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?; + let verbosity = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?; execute( &manifest_path, verbosity, @@ -97,7 +97,7 @@ impl CheckCommand { let manifest_path = ManifestPath::try_from(self.manifest_path.as_ref())?; let unstable_flags: UnstableFlags = TryFrom::<&UnstableOptions>::try_from(&self.unstable_options)?; - let verbosity: Option = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?; + let verbosity: Verbosity = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?; execute( &manifest_path, verbosity, @@ -126,7 +126,7 @@ impl CheckCommand { fn build_cargo_project( crate_metadata: &CrateMetadata, build_artifact: BuildArtifacts, - verbosity: Option, + verbosity: Verbosity, unstable_flags: UnstableFlags, ) -> Result<()> { util::assert_channel()?; @@ -157,8 +157,9 @@ fn build_cargo_project( Ok(()) }; - if unstable_flags.original_manifest && util::is_verbose(&verbosity) { - println!( + if unstable_flags.original_manifest { + maybe_println!( + verbosity, "{} {}", "warning:".yellow().bold(), "with 'original-manifest' enabled, the contract binary may not be of optimal size." @@ -297,7 +298,7 @@ fn optimize_wasm(crate_metadata: &CrateMetadata) -> Result { /// It does so by invoking `cargo build` and then post processing the final binary. fn execute( manifest_path: &ManifestPath, - verbosity: Option, + verbosity: Verbosity, optimize_contract: bool, build_artifact: BuildArtifacts, unstable_flags: UnstableFlags, @@ -338,37 +339,34 @@ fn execute( /// Returns a tuple of `(maybe_optimized_wasm_path, maybe_optimization_result)`. pub(crate) fn execute_with_crate_metadata( crate_metadata: &CrateMetadata, - verbosity: Option, + verbosity: Verbosity, optimize_contract: bool, build_artifact: BuildArtifacts, unstable_flags: UnstableFlags, ) -> Result<(Option, Option)> { - if util::is_verbose(&verbosity) { - println!( - " {} {}", - format!("[1/{}]", build_artifact.steps()).bold(), - "Building cargo project".bright_green().bold() - ); - } + maybe_println!( + verbosity, + " {} {}", + format!("[1/{}]", build_artifact.steps()).bold(), + "Building cargo project".bright_green().bold() + ); build_cargo_project(&crate_metadata, build_artifact, verbosity, unstable_flags)?; - if util::is_verbose(&verbosity) { - println!( - " {} {}", - format!("[2/{}]", build_artifact.steps()).bold(), - "Post processing wasm file".bright_green().bold() - ); - } + maybe_println!( + verbosity, + " {} {}", + format!("[2/{}]", build_artifact.steps()).bold(), + "Post processing wasm file".bright_green().bold() + ); post_process_wasm(&crate_metadata)?; if !optimize_contract { return Ok((None, None)); } - if util::is_verbose(&verbosity) { - println!( - " {} {}", - format!("[3/{}]", build_artifact.steps()).bold(), - "Optimizing wasm file".bright_green().bold() - ); - } + maybe_println!( + verbosity, + " {} {}", + format!("[3/{}]", build_artifact.steps()).bold(), + "Optimizing wasm file".bright_green().bold() + ); let optimization_result = optimize_wasm(&crate_metadata)?; Ok(( Some(crate_metadata.dest_wasm.clone()), diff --git a/src/cmd/metadata.rs b/src/cmd/metadata.rs index 276af777..0197c2f1 100644 --- a/src/cmd/metadata.rs +++ b/src/cmd/metadata.rs @@ -16,7 +16,7 @@ use crate::{ crate_metadata::CrateMetadata, - util, + maybe_println, util, workspace::{ManifestPath, Workspace}, BuildArtifacts, BuildResult, OptimizationResult, UnstableFlags, Verbosity, }; @@ -37,7 +37,7 @@ const METADATA_FILE: &str = "metadata.json"; /// Executes the metadata generation process struct GenerateMetadataCommand { crate_metadata: CrateMetadata, - verbosity: Option, + verbosity: Verbosity, build_artifact: BuildArtifacts, unstable_options: UnstableFlags, } @@ -72,13 +72,12 @@ impl GenerateMetadataCommand { let generate_metadata = |manifest_path: &ManifestPath| -> Result<()> { let mut current_progress = 4; - if util::is_verbose(&self.verbosity) { - println!( - " {} {}", - format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), - "Generating metadata".bright_green().bold() - ); - } + maybe_println!( + self.verbosity, + " {} {}", + format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), + "Generating metadata".bright_green().bold() + ); let target_dir_arg = format!("--target-dir={}", target_directory.to_string_lossy()); let stdout = util::invoke_cargo( "run", @@ -104,8 +103,9 @@ impl GenerateMetadataCommand { current_progress += 1; } - if self.build_artifact == BuildArtifacts::All && util::is_verbose(&self.verbosity) { - println!( + if self.build_artifact == BuildArtifacts::All { + maybe_println!( + self.verbosity, " {} {}", format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(), "Generating bundle".bright_green().bold() @@ -262,7 +262,7 @@ fn blake2_hash(code: &[u8]) -> CodeHash { /// It does so by generating and invoking a temporary workspace member. pub(crate) fn execute( manifest_path: &ManifestPath, - verbosity: Option, + verbosity: Verbosity, build_artifact: BuildArtifacts, unstable_options: UnstableFlags, ) -> Result { diff --git a/src/main.rs b/src/main.rs index 860928dc..cd3295db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -105,20 +105,32 @@ pub struct VerbosityFlags { /// Denotes if output should be printed to stdout. #[derive(Clone, Copy)] pub enum Verbosity { + /// Use default output + Default, /// No output printed to stdout Quiet, /// Use verbose output Verbose, } -impl TryFrom<&VerbosityFlags> for Option { +impl Verbosity { + /// Returns `true` if output should be printed (i.e. verbose output is set). + pub(crate) fn is_verbose(&self) -> bool { + match self { + Verbosity::Quiet => false, + Verbosity::Default | Verbosity::Verbose => true, + } + } +} + +impl TryFrom<&VerbosityFlags> for Verbosity { type Error = Error; fn try_from(value: &VerbosityFlags) -> Result { match (value.quiet, value.verbose) { - (false, false) => Ok(None), - (true, false) => Ok(Some(Verbosity::Quiet)), - (false, true) => Ok(Some(Verbosity::Verbose)), + (false, false) => Ok(Verbosity::Default), + (true, false) => Ok(Verbosity::Quiet), + (false, true) => Ok(Verbosity::Verbose), (true, true) => anyhow::bail!("Cannot pass both --quiet and --verbose flags"), } } @@ -206,7 +218,7 @@ pub struct BuildResult { /// Which build artifacts were generated. pub build_artifact: BuildArtifacts, /// The verbosity flags. - pub verbosity: Option, + pub verbosity: Verbosity, } /// Result of the optimization process. @@ -372,7 +384,7 @@ fn exec(cmd: Command) -> Result> { Command::New { name, target_dir } => cmd::new::execute(name, target_dir.as_ref()), Command::Build(build) => { let result = build.exec()?; - if util::is_verbose(&result.verbosity) { + if result.verbosity.is_verbose() { Ok(Some(result.display())) } else { Ok(None) @@ -384,7 +396,7 @@ fn exec(cmd: Command) -> Result> { res.dest_wasm.is_none(), "no dest_wasm must be on the generation result" ); - if util::is_verbose(&res.verbosity) { + if res.verbosity.is_verbose() { Ok(Some( "\nYour contract's code was built successfully.".to_string(), )) diff --git a/src/util.rs b/src/util.rs index 71949830..04edfde4 100644 --- a/src/util.rs +++ b/src/util.rs @@ -43,7 +43,7 @@ pub(crate) fn invoke_cargo( command: &str, args: I, working_dir: Option

, - verbosity: Option, + verbosity: Verbosity, ) -> Result> where I: IntoIterator + std::fmt::Debug, @@ -60,9 +60,9 @@ where cmd.arg(command); cmd.args(args); match verbosity { - Some(Verbosity::Quiet) => cmd.arg("--quiet"), - Some(Verbosity::Verbose) => cmd.arg("--verbose"), - None => &mut cmd, + Verbosity::Quiet => cmd.arg("--quiet"), + Verbosity::Verbose => cmd.arg("--verbose"), + Verbosity::Default => &mut cmd, }; log::info!("invoking cargo: {:?}", cmd); @@ -93,13 +93,14 @@ pub(crate) fn base_name(path: &PathBuf) -> &str { .expect("must be valid utf-8") } -/// Returns `true` if output should be printed (i.e. verbose output is set). -pub(crate) fn is_verbose(verbosity: &Option) -> bool { - if let Some(Verbosity::Verbose) = verbosity { - true - } else { - false - } +/// Prints to stdout if `verbosity.is_verbose()` is `true`. +#[macro_export] +macro_rules! maybe_println { + ($verbosity:expr, $($msg:tt)*) => { + if $verbosity.is_verbose() { + println!($($msg)*); + } + }; } #[cfg(test)] -- GitLab