Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suppress output on --quiet #165

Merged
merged 3 commits into from
Feb 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions src/cmd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::{

use crate::{
crate_metadata::CrateMetadata,
util,
maybe_println, util,
workspace::{ManifestPath, Profile, Workspace},
BuildArtifacts, BuildResult, UnstableFlags, UnstableOptions, VerbosityFlags,
};
Expand Down Expand Up @@ -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<Verbosity> = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?;
let verbosity = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?;
execute(
&manifest_path,
verbosity,
Expand Down Expand Up @@ -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<Verbosity> = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?;
let verbosity: Verbosity = TryFrom::<&VerbosityFlags>::try_from(&self.verbosity)?;
execute(
&manifest_path,
verbosity,
Expand Down Expand Up @@ -126,7 +126,7 @@ impl CheckCommand {
fn build_cargo_project(
crate_metadata: &CrateMetadata,
build_artifact: BuildArtifacts,
verbosity: Option<Verbosity>,
verbosity: Verbosity,
unstable_flags: UnstableFlags,
) -> Result<()> {
util::assert_channel()?;
Expand Down Expand Up @@ -158,7 +158,8 @@ fn build_cargo_project(
};

if unstable_flags.original_manifest {
println!(
maybe_println!(
verbosity,
"{} {}",
"warning:".yellow().bold(),
"with 'original-manifest' enabled, the contract binary may not be of optimal size."
Expand Down Expand Up @@ -297,7 +298,7 @@ fn optimize_wasm(crate_metadata: &CrateMetadata) -> Result<OptimizationResult> {
/// It does so by invoking `cargo build` and then post processing the final binary.
fn execute(
manifest_path: &ManifestPath,
verbosity: Option<Verbosity>,
verbosity: Verbosity,
optimize_contract: bool,
build_artifact: BuildArtifacts,
unstable_flags: UnstableFlags,
Expand All @@ -318,6 +319,7 @@ fn execute(
target_directory: crate_metadata.target_directory,
optimization_result: maybe_optimization_result,
build_artifact,
verbosity,
};
return Ok(res);
}
Expand All @@ -337,18 +339,20 @@ 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: Verbosity,
optimize_contract: bool,
build_artifact: BuildArtifacts,
unstable_flags: UnstableFlags,
) -> Result<(Option<PathBuf>, Option<OptimizationResult>)> {
println!(
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)?;
println!(
maybe_println!(
verbosity,
" {} {}",
format!("[2/{}]", build_artifact.steps()).bold(),
"Post processing wasm file".bright_green().bold()
Expand All @@ -357,7 +361,8 @@ pub(crate) fn execute_with_crate_metadata(
if !optimize_contract {
return Ok((None, None));
}
println!(
maybe_println!(
verbosity,
" {} {}",
format!("[3/{}]", build_artifact.steps()).bold(),
"Optimizing wasm file".bright_green().bold()
Expand Down
13 changes: 8 additions & 5 deletions src/cmd/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

use crate::{
crate_metadata::CrateMetadata,
util,
maybe_println, util,
workspace::{ManifestPath, Workspace},
BuildArtifacts, BuildResult, OptimizationResult, UnstableFlags, Verbosity,
};
Expand All @@ -37,7 +37,7 @@ const METADATA_FILE: &str = "metadata.json";
/// Executes the metadata generation process
struct GenerateMetadataCommand {
crate_metadata: CrateMetadata,
verbosity: Option<Verbosity>,
verbosity: Verbosity,
build_artifact: BuildArtifacts,
unstable_options: UnstableFlags,
}
Expand Down Expand Up @@ -72,7 +72,8 @@ impl GenerateMetadataCommand {

let generate_metadata = |manifest_path: &ManifestPath| -> Result<()> {
let mut current_progress = 4;
println!(
maybe_println!(
self.verbosity,
" {} {}",
format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(),
"Generating metadata".bright_green().bold()
Expand Down Expand Up @@ -103,7 +104,8 @@ impl GenerateMetadataCommand {
}

if self.build_artifact == BuildArtifacts::All {
println!(
maybe_println!(
self.verbosity,
" {} {}",
format!("[{}/{}]", current_progress, self.build_artifact.steps()).bold(),
"Generating bundle".bright_green().bold()
Expand Down Expand Up @@ -144,6 +146,7 @@ impl GenerateMetadataCommand {
optimization_result,
target_directory,
build_artifact: self.build_artifact,
verbosity: self.verbosity,
})
}

Expand Down Expand Up @@ -259,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: Verbosity,
build_artifact: BuildArtifacts,
unstable_options: UnstableFlags,
) -> Result<BuildResult> {
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::{
use anyhow::Result;
use heck::CamelCase as _;

pub(crate) fn execute<P>(name: &str, dir: Option<P>) -> Result<String>
pub(crate) fn execute<P>(name: &str, dir: Option<P>) -> Result<Option<String>>
where
P: AsRef<Path>,
{
Expand Down Expand Up @@ -93,7 +93,7 @@ where
}
}

Ok(format!("Created contract {}", name))
Ok(Some(format!("Created contract {}", name)))
}

#[cfg(test)]
Expand Down
55 changes: 44 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,26 +94,43 @@ 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 {
/// Use default output
Default,
/// No output printed to stdout
Quiet,
/// Use verbose output
Verbose,
}

impl TryFrom<&VerbosityFlags> for Option<Verbosity> {
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<Self, Self::Error> {
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"),
}
}
Expand Down Expand Up @@ -200,6 +217,8 @@ pub struct BuildResult {
pub optimization_result: Option<OptimizationResult>,
/// Which build artifacts were generated.
pub build_artifact: BuildArtifacts,
/// The verbosity flags.
pub verbosity: Verbosity,
}

/// Result of the optimization process.
Expand Down Expand Up @@ -344,7 +363,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!(
"{} {}",
Expand All @@ -356,20 +379,30 @@ fn main() {
}
}

fn exec(cmd: Command) -> Result<String> {
fn exec(cmd: Command) -> Result<Option<String>> {
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 result.verbosity.is_verbose() {
Ok(Some(result.display()))
} else {
Ok(None)
}
}
Command::Check(check) => {
let res = check.exec()?;
assert!(
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 res.verbosity.is_verbose() {
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"
Expand All @@ -381,7 +414,7 @@ fn exec(cmd: Command) -> Result<String> {
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 {
Expand All @@ -398,7 +431,7 @@ fn exec(cmd: Command) -> Result<String> {
*code_hash,
data.clone(),
)?;
Ok(format!("Contract account: {:?}", contract_account))
Ok(Some(format!("Contract account: {:?}", contract_account)))
}
}
}
18 changes: 14 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub(crate) fn invoke_cargo<I, S, P>(
command: &str,
args: I,
working_dir: Option<P>,
verbosity: Option<Verbosity>,
verbosity: Verbosity,
) -> Result<Vec<u8>>
where
I: IntoIterator<Item = S> + std::fmt::Debug,
Expand All @@ -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);
Expand Down Expand Up @@ -93,6 +93,16 @@ pub(crate) fn base_name(path: &PathBuf) -> &str {
.expect("must be valid utf-8")
}

/// 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)]
pub mod tests {
use std::path::Path;
Expand Down
2 changes: 1 addition & 1 deletion src/workspace/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down