Skip to content

Commit

Permalink
Merge pull request #694 from Pauan/quiet
Browse files Browse the repository at this point in the history
Adding in `--quiet` and `--log-level` flags
  • Loading branch information
Pauan authored Jan 22, 2020
2 parents b4a4585 + d04ee6c commit 846b989
Show file tree
Hide file tree
Showing 9 changed files with 240 additions and 20 deletions.
20 changes: 20 additions & 0 deletions docs/src/commands/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,23 @@ a Rust-generated WebAssembly project.
[new]: ./new.html
[build]: ./build.html
[pack-pub]: ./pack-and-publish.html

### Log levels

By default `wasm-pack` displays a lot of useful information.

You can cause it to display even *more* information by using `--verbose`, or you can silence *all* stdout by using `--quiet`.

You can also use `--log-level` to have fine-grained control over wasm-pack's log output:

* `--log-level info` is the default, it causes all messages to be logged.
* `--log-level warn` causes warnings and errors to be displayed, but not info.
* `--log-level error` causes only errors to be displayed.

These flags are global flags, so they can be used with every command, and they must come *before* the command:

```sh
wasm-pack --log-level error build
wasm-pack --quiet build
wasm-pack --verbose build
```
15 changes: 15 additions & 0 deletions src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,14 @@ pub fn cargo_build_wasm(
) -> Result<(), Error> {
let msg = format!("{}Compiling to Wasm...", emoji::CYCLONE);
PBAR.info(&msg);

let mut cmd = Command::new("cargo");
cmd.current_dir(path).arg("build").arg("--lib");

if PBAR.quiet() {
cmd.arg("--quiet");
}

match profile {
BuildProfile::Profiling => {
// Once there are DWARF debug info consumers, force enable debug
Expand All @@ -99,6 +105,7 @@ pub fn cargo_build_wasm(
// debug info by default.
}
}

cmd.arg("--target").arg("wasm32-unknown-unknown");
cmd.args(extra_options);
child::run(cmd, "cargo build").context("Compiling your crate to WebAssembly failed")?;
Expand All @@ -111,11 +118,19 @@ pub fn cargo_build_wasm(
/// wasm-bindgen-cli to use when running tests.
pub fn cargo_build_wasm_tests(path: &Path, debug: bool) -> Result<(), Error> {
let mut cmd = Command::new("cargo");

cmd.current_dir(path).arg("build").arg("--tests");

if PBAR.quiet() {
cmd.arg("--quiet");
}

if !debug {
cmd.arg("--release");
}

cmd.arg("--target").arg("wasm32-unknown-unknown");

child::run(cmd, "cargo build").context("Compilation of your program failed")?;
Ok(())
}
4 changes: 4 additions & 0 deletions src/install/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,10 @@ pub fn cargo_install(
.arg("--root")
.arg(&tmp);

if PBAR.quiet() {
cmd.arg("--quiet");
}

let context = format!("Installing {} with cargo", tool);
child::run(cmd, "cargo install").context(context)?;

Expand Down
12 changes: 10 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ pub mod target;
pub mod test;
pub mod wasm_opt;

use progressbar::ProgressOutput;
use progressbar::{LogLevel, ProgressOutput};

/// The global progress bar and user-facing message output.
pub static PBAR: ProgressOutput = ProgressOutput;
pub static PBAR: ProgressOutput = ProgressOutput::new();

/// 📦 ✨ pack and publish your wasm!
#[derive(Debug, StructOpt)]
Expand All @@ -60,4 +60,12 @@ pub struct Cli {
/// Log verbosity is based off the number of v used
#[structopt(long = "verbose", short = "v", parse(from_occurrences))]
pub verbosity: u8,

#[structopt(long = "quiet", short = "q")]
/// No output printed to stdout
pub quiet: bool,

#[structopt(long = "log-level", default_value = "info")]
/// The maximum level of messages that should be logged by wasm-pack. [possible values: info, warn, error]
pub log_level: LogLevel,
}
7 changes: 7 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ fn run() -> Result<(), failure::Error> {
}

let args = Cli::from_args();

PBAR.set_log_level(args.log_level);

if args.quiet {
PBAR.set_quiet(true);
}

run_wasm_pack(args.cmd)?;

if let Ok(wasm_pack_version) = wasm_pack_version.try_recv() {
Expand Down
100 changes: 82 additions & 18 deletions src/progressbar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,111 @@

use console::style;
use emoji;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};

#[repr(u8)]
#[derive(Debug, Clone, Copy)]
/// The maximum log level for wasm-pack
// The ordering is important: the least verbose must be at
// the top and the most verbose at the bottom
pub enum LogLevel {
/// Logs only error
Error,
/// Logs only warn and error
Warn,
/// Logs everything
Info,
}

impl std::str::FromStr for LogLevel {
type Err = failure::Error;
fn from_str(s: &str) -> Result<Self, failure::Error> {
match s {
"error" => Ok(LogLevel::Error),
"warn" => Ok(LogLevel::Warn),
"info" => Ok(LogLevel::Info),
_ => bail!("Unknown log-level: {}", s),
}
}
}

/// Synchronized progress bar and status message printing.
pub struct ProgressOutput;
pub struct ProgressOutput {
quiet: AtomicBool,
log_level: AtomicU8,
}

impl ProgressOutput {
/// Returns a new ProgressOutput
pub const fn new() -> Self {
Self {
quiet: AtomicBool::new(false),
log_level: AtomicU8::new(LogLevel::Info as u8),
}
}

/// Print the given message.
fn message(&self, message: &str) {
eprintln!("{}", message);
}

/// Returns whether it should silence stdout or not
pub fn quiet(&self) -> bool {
self.quiet.load(Ordering::SeqCst)
}

/// Causes it to silence stdout
pub fn set_quiet(&self, quiet: bool) {
self.quiet.store(quiet, Ordering::SeqCst);
}

/// Returns whether the specified log level is enabled or not
pub fn is_log_enabled(&self, level: LogLevel) -> bool {
(level as u8) <= self.log_level.load(Ordering::SeqCst)
}

/// Sets the log level for wasm-pack
pub fn set_log_level(&self, log_level: LogLevel) {
self.log_level.store(log_level as u8, Ordering::SeqCst);
}

/// Add an informational message.
pub fn info(&self, message: &str) {
let info = format!("{}: {}", style("[INFO]").bold().dim(), message,);
self.message(&info);
if !self.quiet() && self.is_log_enabled(LogLevel::Info) {
let info = format!("{}: {}", style("[INFO]").bold().dim(), message,);
self.message(&info);
}
}

/// Add a warning message.
pub fn warn(&self, message: &str) {
let warn = format!(
"{} {}: {}",
emoji::WARN,
style("[WARN]").bold().dim(),
message
);
self.message(&warn);
if !self.quiet() && self.is_log_enabled(LogLevel::Warn) {
let warn = format!(
"{} {}: {}",
emoji::WARN,
style("[WARN]").bold().dim(),
message
);
self.message(&warn);
}
}

/// Add an error message.
pub fn error(&self, message: &str) {
let err = format!(
"{} {}: {}",
emoji::ERROR,
style("[ERR]").bold().dim(),
message
);
self.message(&err);
if self.is_log_enabled(LogLevel::Error) {
let err = format!(
"{} {}: {}",
emoji::ERROR,
style("[ERR]").bold().dim(),
message
);
self.message(&err);
}
}
}

impl Default for ProgressOutput {
fn default() -> Self {
ProgressOutput
ProgressOutput::new()
}
}
10 changes: 10 additions & 0 deletions src/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub mod webdriver;

use crate::PBAR;
use child;
use failure::{self, ResultExt};
use std::ffi::OsStr;
Expand All @@ -22,13 +23,22 @@ where
V: AsRef<OsStr>,
{
let mut cmd = Command::new("cargo");

cmd.envs(envs);
cmd.current_dir(path).arg("test");

if PBAR.quiet() {
cmd.arg("--quiet");
}

if release {
cmd.arg("--release");
}

cmd.arg("--target").arg("wasm32-unknown-unknown");

cmd.args(extra_options);

child::run(cmd, "cargo test").context("Running Wasm tests with wasm-bindgen-test failed")?;

// NB: `child::run` took care of ensuring that test output gets printed.
Expand Down
91 changes: 91 additions & 0 deletions tests/all/log_level.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use assert_cmd::prelude::*;
use predicates::boolean::PredicateBooleanExt;
use predicates::prelude::predicate::str::contains;
use predicates::reflection::PredicateReflection;
use predicates::Predicate;
use utils;

fn matches_info() -> impl Predicate<str> + PredicateReflection {
contains("[INFO]: Checking for the Wasm target...")
.and(contains("[INFO]: Compiling to Wasm..."))
.and(contains("[INFO]: License key is set in Cargo.toml but no LICENSE file(s) were found; Please add the LICENSE file(s) to your project directory"))
.and(contains("[INFO]: Installing wasm-bindgen..."))
.and(contains("[INFO]: Optimizing wasm binaries with `wasm-opt`..."))
.and(contains("[INFO]: :-) Done in "))
.and(contains("[INFO]: :-) Your wasm pkg is ready to publish at "))
}

fn matches_warn() -> impl Predicate<str> + PredicateReflection {
contains(":-) [WARN]: origin crate has no README")
}

fn matches_cargo() -> impl Predicate<str> + PredicateReflection {
contains("Finished release [optimized] target(s) in ")
}

#[test]
fn quiet() {
utils::fixture::Fixture::new()
.cargo_toml("js-hello-world")
.hello_world_src_lib()
.wasm_pack()
.arg("--quiet")
.arg("build")
.assert()
.success()
.stdout("")
.stderr("");
}

#[test]
fn log_level_info() {
utils::fixture::Fixture::new()
.cargo_toml("js-hello-world")
.hello_world_src_lib()
.wasm_pack()
.arg("--log-level")
.arg("info")
.arg("build")
.assert()
.success()
.stdout("")
.stderr(matches_cargo().and(matches_warn()).and(matches_info()));
}

#[test]
fn log_level_warn() {
utils::fixture::Fixture::new()
.cargo_toml("js-hello-world")
.hello_world_src_lib()
.wasm_pack()
.arg("--log-level")
.arg("warn")
.arg("build")
.assert()
.success()
.stdout("")
.stderr(
matches_cargo()
.and(matches_warn())
.and(matches_info().not()),
);
}

#[test]
fn log_level_error() {
utils::fixture::Fixture::new()
.cargo_toml("js-hello-world")
.hello_world_src_lib()
.wasm_pack()
.arg("--log-level")
.arg("error")
.arg("build")
.assert()
.success()
.stdout("")
.stderr(
matches_cargo()
.and(matches_warn().not())
.and(matches_info().not()),
);
}
1 change: 1 addition & 0 deletions tests/all/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod download;
mod generate;
mod license;
mod lockfile;
mod log_level;
mod manifest;
mod readme;
mod stamps;
Expand Down

0 comments on commit 846b989

Please sign in to comment.