Skip to content

Commit

Permalink
Disable coloured logs (#1450)
Browse files Browse the repository at this point in the history
* feat(forge/cast): NO_COLOR env support

refactor: replace ansi_term with yansi

* style: simplify env check

Co-authored-by: zk-tarts <=>
  • Loading branch information
zk-tarts authored Apr 29, 2022
1 parent 2c1cdc9 commit e6d1bdb
Show file tree
Hide file tree
Showing 15 changed files with 59 additions and 48 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ clap = { version = "3.0.10", features = [
"wrap_help",
] }
clap_complete = "3.0.4"
ansi_term = "0.12.1"
yansi = "0.5.1"
tracing-error = "0.2.0"
tracing-subscriber = { version = "0.3", features = ["registry", "env-filter", "fmt"] }
tracing = "0.1.26"
Expand Down
1 change: 1 addition & 0 deletions cli/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use eyre::WrapErr;
async fn main() -> eyre::Result<()> {
color_eyre::install()?;
utils::subscriber();
utils::enable_paint();

let opts = Opts::parse();
match opts.sub {
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/cast/run.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::{cmd::Cmd, utils};
use ansi_term::Colour;
use cast::trace::CallTraceDecoder;
use clap::Parser;
use ethers::{
Expand All @@ -20,6 +19,7 @@ use std::{
time::Duration,
};
use ui::{TUIExitReason, Tui, Ui};
use yansi::Paint;

#[derive(Debug, Clone, Parser)]
pub struct RunArgs {
Expand Down Expand Up @@ -193,9 +193,9 @@ fn print_traces(result: &mut RunResult, decoder: CallTraceDecoder) -> eyre::Resu
println!();

if result.success {
println!("{}", Colour::Green.paint("Script ran successfully."));
println!("{}", Paint::green("Script ran successfully."));
} else {
println!("{}", Colour::Red.paint("Script failed."));
println!("{}", Paint::red("Script failed."));
}

println!("Gas used: {}", result.gas);
Expand Down
6 changes: 3 additions & 3 deletions cli/src/cmd/forge/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use clap::{Parser, ValueHint};
use foundry_config::Config;

use crate::cmd::forge::{install::DependencyInstallOpts, remappings};
use ansi_term::Colour;
use yansi::Paint;

use std::{
path::{Path, PathBuf},
Expand Down Expand Up @@ -88,7 +88,7 @@ impl Cmd for InitArgs {
r#"{}: `forge init` cannot be run on a non-empty directory.
run `forge init --force` to initialize regardless."#,
Colour::Red.paint("error")
Paint::red("error")
);
std::process::exit(1);
}
Expand Down Expand Up @@ -138,7 +138,7 @@ impl Cmd for InitArgs {
}
}

p_println!(!quiet => " {} forge project.", Colour::Green.paint("Initialized"));
p_println!(!quiet => " {} forge project.", Paint::green("Initialized"));
Ok(())
}
}
Expand Down
4 changes: 2 additions & 2 deletions cli/src/cmd/forge/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
use std::{path::PathBuf, str};

use crate::{cmd::Cmd, opts::forge::Dependency, utils::p_println};
use ansi_term::Colour;
use clap::{Parser, ValueHint};
use foundry_config::find_project_root_path;
use yansi::Paint;

use std::{
path::Path,
Expand Down Expand Up @@ -97,7 +97,7 @@ pub(crate) fn install(
install_as_submodule(&dep, &libs, no_commit)?;
}

p_println!(!quiet => " {} {}", Colour::Green.paint("Installed"), dep.name);
p_println!(!quiet => " {} {}", Paint::green("Installed"), dep.name);
}
Ok(())
}
Expand Down
8 changes: 4 additions & 4 deletions cli/src/cmd/forge/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::{
cmd::{forge::build::CoreBuildArgs, Cmd},
compile, utils,
};
use ansi_term::Colour;
use clap::{Parser, ValueHint};
use ethers::{
abi::{Abi, RawLog},
Expand All @@ -28,6 +27,7 @@ use foundry_config::{figment::Figment, Config};
use foundry_utils::{encode_args, IntoFunction, PostLinkInput, RuntimeOrHandle};
use std::{collections::BTreeMap, path::PathBuf};
use ui::{TUIExitReason, Tui, Ui};
use yansi::Paint;

// Loads project's figment and merges the build cli arguments into it
foundry_config::impl_figment_convert!(RunArgs, opts, evm_opts);
Expand Down Expand Up @@ -104,7 +104,7 @@ impl Cmd for RunArgs {
if setup_fn.name != "setUp" {
println!(
"{} Found invalid setup function \"{}\" did you mean \"setUp()\"?",
Colour::Yellow.bold().paint("Warning:"),
Paint::yellow("Warning:").bold(),
setup_fn.signature()
);
}
Expand Down Expand Up @@ -230,9 +230,9 @@ impl Cmd for RunArgs {
}

if result.success {
println!("{}", Colour::Green.paint("Script ran successfully."));
println!("{}", Paint::green("Script ran successfully."));
} else {
println!("{}", Colour::Red.paint("Script failed."));
println!("{}", Paint::red("Script failed."));
}

println!("Gas used: {}", result.gas);
Expand Down
10 changes: 5 additions & 5 deletions cli/src/cmd/forge/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::cmd::{
},
Cmd,
};
use ansi_term::Colour;
use clap::{Parser, ValueHint};
use eyre::Context;
use forge::TestKindGas;
Expand All @@ -23,6 +22,7 @@ use std::{
str::FromStr,
};
use watchexec::config::{InitConfig, RuntimeConfig};
use yansi::Paint;

/// A regex that matches a basic snapshot entry like
/// `Test:testDeposit() (gas: 58804)`
Expand Down Expand Up @@ -382,21 +382,21 @@ fn diff(tests: Vec<Test>, snaps: Vec<SnapshotEntry>) -> eyre::Result<()> {

fn fmt_pct_change(change: f64) -> String {
match change.partial_cmp(&0.0).unwrap_or(Ordering::Equal) {
Ordering::Less => Colour::Green.paint(format!("{:.3}%", change)).to_string(),
Ordering::Less => Paint::green(format!("{:.3}%", change)).to_string(),
Ordering::Equal => {
format!("{:.3}%", change)
}
Ordering::Greater => Colour::Red.paint(format!("{:.3}%", change)).to_string(),
Ordering::Greater => Paint::red(format!("{:.3}%", change)).to_string(),
}
}

fn fmt_change(change: i128) -> String {
match change.cmp(&0) {
Ordering::Less => Colour::Green.paint(format!("{change}")).to_string(),
Ordering::Less => Paint::green(format!("{change}")).to_string(),
Ordering::Equal => {
format!("{change}")
}
Ordering::Greater => Colour::Red.paint(format!("{change}")).to_string(),
Ordering::Greater => Paint::red(format!("{change}")).to_string(),
}
}

Expand Down
15 changes: 7 additions & 8 deletions cli/src/cmd/forge/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::{
utils,
utils::FoundryPathExt,
};
use ansi_term::Colour;
use clap::{AppSettings, Parser};
use ethers::solc::FileFilter;
use forge::{
Expand All @@ -32,6 +31,7 @@ use std::{
time::Duration,
};
use watchexec::config::{InitConfig, RuntimeConfig};
use yansi::Paint;

#[derive(Debug, Clone, Parser)]
pub struct Filter {
Expand Down Expand Up @@ -342,8 +342,8 @@ impl TestOutcome {
let successes = self.successes().count();
println!(
"Encountered a total of {} failing tests, {} tests succeeded",
Colour::Red.paint(failures.to_string()),
Colour::Green.paint(successes.to_string())
Paint::red(failures.to_string()),
Paint::green(successes.to_string())
);
std::process::exit(1);
}
Expand All @@ -359,8 +359,7 @@ impl TestOutcome {

pub fn summary(&self) -> String {
let failed = self.failures().count();
let result =
if failed == 0 { Colour::Green.paint("ok") } else { Colour::Red.paint("FAILED") };
let result = if failed == 0 { Paint::green("ok") } else { Paint::red("FAILED") };
format!(
"Test result: {}. {} passed; {} failed; finished in {:.2?}",
result,
Expand All @@ -373,7 +372,7 @@ impl TestOutcome {

fn short_test_result(name: &str, result: &forge::TestResult) {
let status = if result.success {
Colour::Green.paint("[PASS]")
Paint::green("[PASS]".to_string())
} else {
let txt = match (&result.reason, &result.counterexample) {
(Some(ref reason), Some(ref counterexample)) => {
Expand All @@ -388,7 +387,7 @@ fn short_test_result(name: &str, result: &forge::TestResult) {
(None, None) => "[FAIL]".to_string(),
};

Colour::Red.paint(txt)
Paint::red(txt)
};

println!("{} {} {}", status, name, result.kind.gas_used());
Expand Down Expand Up @@ -538,7 +537,7 @@ fn test(
let mut tests = suite_result.test_results.clone();
println!();
for warning in suite_result.warnings.iter() {
eprintln!("{} {}", Colour::Yellow.bold().paint("Warning:"), warning);
eprintln!("{} {}", Paint::yellow("Warning:").bold(), warning);
}
if !tests.is_empty() {
let term = if tests.len() > 1 { "tests" } else { "test" };
Expand Down
1 change: 1 addition & 0 deletions cli/src/forge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use clap_complete::generate;
fn main() -> eyre::Result<()> {
color_eyre::install()?;
utils::subscriber();
utils::enable_paint();

let opts = Opts::parse();
match opts.sub {
Expand Down
6 changes: 2 additions & 4 deletions cli/src/term.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! terminal utils

use ansi_term::Colour;
use atty::{self, Stream};
use ethers::solc::{
remappings::Remapping,
Expand All @@ -19,6 +18,7 @@ use std::{
},
time::Duration,
};
use yansi::Paint;

/// Some spinners
// https://github.com/gernest/wow/blob/master/spin/spinners.go
Expand Down Expand Up @@ -251,9 +251,7 @@ impl Reporter for SpinnerReporter {
}

fn on_solc_installation_error(&self, version: &Version, error: &str) {
self.send_msg(
Colour::Red.paint(format!("Failed to install solc {version}: {error}")).to_string(),
);
self.send_msg(Paint::red(format!("Failed to install solc {version}: {error}")).to_string());
}

fn on_unresolved_import(&self, import: &Path, remappings: &[Remapping]) {
Expand Down
12 changes: 12 additions & 0 deletions cli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use std::{
};
use tracing_error::ErrorLayer;
use tracing_subscriber::prelude::*;
use yansi::Paint;

// reexport all `foundry_config::utils`
#[doc(hidden)]
Expand Down Expand Up @@ -248,6 +249,17 @@ macro_rules! p_println {
}
pub(crate) use p_println;

/// Disables terminal colours if either:
/// - Running windows and the terminal does not support colour codes.
/// - Colour has been disabled by some environment variable.
pub fn enable_paint() {
let is_windows = cfg!(windows) && !Paint::enable_windows_ascii();
let env_colour_disabled = std::env::var("NO_COLOR").is_ok();
if is_windows || env_colour_disabled {
Paint::disable();
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
8 changes: 4 additions & 4 deletions cli/tests/it/cmd.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! Contains various tests for checking forge's commands
use ansi_term::Colour;
use ethers::solc::{
artifacts::{BytecodeHash, Metadata},
ConfigurableContractArtifact,
Expand All @@ -11,6 +10,7 @@ use foundry_cli_test_utils::{
};
use foundry_config::{parse_with_profile, BasicConfig, Config, SolidityErrorCode};
use std::{env, fs};
use yansi::Paint;

// import forge utils as mod
#[allow(unused)]
Expand Down Expand Up @@ -293,7 +293,7 @@ Gas used: 1751
== Logs ==
script ran
",
Colour::Green.paint("Script ran successfully.")
Paint::green("Script ran successfully.")
),));
});

Expand Down Expand Up @@ -325,7 +325,7 @@ Gas used: 1751
== Logs ==
script ran
",
Colour::Green.paint("Script ran successfully.")
Paint::green("Script ran successfully.")
),));
});

Expand Down Expand Up @@ -362,7 +362,7 @@ Gas used: 3957
1
2
",
Colour::Green.paint("Script ran successfully.")
Paint::green("Script ran successfully.")
),));
});

Expand Down
2 changes: 1 addition & 1 deletion evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ revm = { package = "revm", git = "https://github.com/bluealloy/revm", default-fe
proptest = "1.0.0"

# Display
ansi_term = "0.12.1"
yansi = "0.5.1"
url = "2.2.2"

[dev-dependencies]
Expand Down
Loading

0 comments on commit e6d1bdb

Please sign in to comment.