From c72560dba031f57bd4c50827f44fa50336a53e22 Mon Sep 17 00:00:00 2001 From: Chengbin Du Date: Sat, 20 Apr 2024 10:08:15 +0800 Subject: [PATCH] chore(deps): update yansi to v1.0 --- Cargo.lock | 24 ++++----- Cargo.toml | 2 +- crates/anvil/Cargo.toml | 2 +- crates/anvil/src/config.rs | 28 +++++----- crates/cast/Cargo.toml | 2 +- crates/cast/bin/cmd/wallet/mod.rs | 4 +- crates/chisel/Cargo.toml | 2 +- crates/chisel/bin/main.rs | 29 +++++----- crates/chisel/src/dispatcher.rs | 32 +++++------ crates/chisel/src/executor.rs | 80 ++++++++++++++-------------- crates/chisel/src/session_source.rs | 13 ++--- crates/chisel/src/solidity_helper.rs | 32 ++++++----- crates/cli/Cargo.toml | 2 +- crates/cli/src/handler.rs | 2 +- crates/cli/src/utils/cmd.rs | 6 +-- crates/cli/src/utils/mod.rs | 7 +-- crates/common/Cargo.toml | 2 +- crates/common/src/fmt/mod.rs | 8 +-- crates/common/src/term.rs | 8 +-- crates/evm/traces/Cargo.toml | 2 +- crates/evm/traces/src/lib.rs | 20 +++---- crates/forge/Cargo.toml | 2 +- crates/forge/bin/cmd/coverage.rs | 4 +- crates/forge/bin/cmd/fmt.rs | 16 +++--- crates/forge/bin/cmd/geiger/find.rs | 13 ++--- crates/forge/bin/cmd/geiger/mod.rs | 2 +- crates/forge/bin/cmd/generate/mod.rs | 2 +- crates/forge/bin/cmd/init.rs | 2 +- crates/forge/bin/cmd/install.rs | 6 +-- crates/forge/bin/cmd/snapshot.rs | 8 +-- crates/forge/bin/cmd/test/mod.rs | 2 +- crates/forge/src/gas_report.rs | 3 +- crates/forge/src/result.rs | 24 ++++----- crates/script/Cargo.toml | 2 +- crates/script/src/execute.rs | 8 ++- crates/script/src/lib.rs | 4 +- crates/script/src/runner.rs | 3 +- crates/script/src/sequence.rs | 5 +- crates/verify/Cargo.toml | 2 +- crates/verify/src/bytecode.rs | 17 +++--- 40 files changed, 207 insertions(+), 225 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6f2fe9630e8b..f3a2d625eec4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -725,7 +725,7 @@ dependencies = [ "tracing", "tracing-subscriber", "vergen", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -1821,7 +1821,7 @@ dependencies = [ "tokio", "tracing", "vergen", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -1897,7 +1897,7 @@ dependencies = [ "tracing", "tracing-subscriber", "vergen", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -3534,7 +3534,7 @@ dependencies = [ "tracing-subscriber", "vergen", "watchexec", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -3618,7 +3618,7 @@ dependencies = [ "serde_json", "tempfile", "tracing", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -3651,7 +3651,7 @@ dependencies = [ "tempfile", "tokio", "tracing", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -3764,7 +3764,7 @@ dependencies = [ "tracing", "tracing-error", "tracing-subscriber", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -3820,14 +3820,14 @@ dependencies = [ "tracing", "url", "walkdir", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] name = "foundry-compilers" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8caca67f174741b05c2f4188d3ee93420342130eb2a768abb9b885bb8b918df2" +checksum = "10a73252c7753488cf7779e2788e05088b3b3d9198fbbc5d4da94b5afd0f751d" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -3857,7 +3857,7 @@ dependencies = [ "tokio", "tracing", "walkdir", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] @@ -4042,7 +4042,7 @@ dependencies = [ "tempfile", "tokio", "tracing", - "yansi 0.5.1", + "yansi 1.0.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 2859b9349afe..1b4a5771ab6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,7 +138,7 @@ foundry-linking = { path = "crates/linking" } # solc & compilation utilities foundry-block-explorers = { version = "0.2.6", default-features = false } -foundry-compilers = { version = "0.3.17", default-features = false } +foundry-compilers = { version = "0.3.18", default-features = false } ## revm # no default features to avoid c-kzg diff --git a/crates/anvil/Cargo.toml b/crates/anvil/Cargo.toml index 7930d437a0ea..b02316e7d358 100644 --- a/crates/anvil/Cargo.toml +++ b/crates/anvil/Cargo.toml @@ -70,7 +70,7 @@ serde_repr = "0.1" serde_json.workspace = true serde.workspace = true thiserror = "1" -yansi = "0.5" +yansi = "1.0" tempfile = "3" itertools.workspace = true rand = "0.8" diff --git a/crates/anvil/src/config.rs b/crates/anvil/src/config.rs index 7c35f0c9d7c9..5670128f43ad 100644 --- a/crates/anvil/src/config.rs +++ b/crates/anvil/src/config.rs @@ -182,13 +182,9 @@ pub struct NodeConfig { impl NodeConfig { fn as_string(&self, fork: Option<&ClientFork>) -> String { let mut config_string: String = String::new(); - let _ = write!(config_string, "\n{}", Paint::green(BANNER)); + let _ = write!(config_string, "\n{}", BANNER.green()); let _ = write!(config_string, "\n {VERSION_MESSAGE}"); - let _ = write!( - config_string, - "\n {}", - Paint::green("https://github.com/foundry-rs/foundry") - ); + let _ = write!(config_string, "\n {}", "https://github.com/foundry-rs/foundry".green()); let _ = write!( config_string, @@ -256,9 +252,9 @@ Chain ID: {} Chain ID ================== -{} +\n{} "#, - Paint::green(format!("\n{}", self.get_chain_id())) + self.get_chain_id().green() ); } @@ -268,9 +264,9 @@ Chain ID r#" Gas Price ================== -{} +\n{} "#, - Paint::green(format!("\n{}", self.get_gas_price())) + self.get_gas_price().green() ); } else { let _ = write!( @@ -278,9 +274,9 @@ Gas Price r#" Base Fee ================== -{} +\n{} "#, - Paint::green(format!("\n{}", self.get_base_fee())) + self.get_base_fee().green() ); } @@ -289,9 +285,9 @@ Base Fee r#" Gas Limit ================== -{} +\n{} "#, - Paint::green(format!("\n{}", self.gas_limit)) + self.gas_limit.green() ); let _ = write!( @@ -299,9 +295,9 @@ Gas Limit r#" Genesis Timestamp ================== -{} +\n{} "#, - Paint::green(format!("\n{}", self.get_genesis_timestamp())) + self.get_genesis_timestamp().green() ); config_string diff --git a/crates/cast/Cargo.toml b/crates/cast/Cargo.toml index 04160fa3ffeb..4bcc1498e273 100644 --- a/crates/cast/Cargo.toml +++ b/crates/cast/Cargo.toml @@ -78,7 +78,7 @@ semver = "1" tempfile = "3" tokio = { version = "1", features = ["macros", "signal"] } tracing.workspace = true -yansi = "0.5" +yansi = "1.0" evmole = "0.3.1" [target.'cfg(unix)'.dependencies] diff --git a/crates/cast/bin/cmd/wallet/mod.rs b/crates/cast/bin/cmd/wallet/mod.rs index 60e21a2fb732..1ac943204e11 100644 --- a/crates/cast/bin/cmd/wallet/mod.rs +++ b/crates/cast/bin/cmd/wallet/mod.rs @@ -236,7 +236,7 @@ impl WalletSubcommands { let wallets = wallets.into_iter().map(|b| b.build()).collect::, _>>()?; - println!("{}", Paint::green("Successfully generated a new mnemonic.")); + println!("{}", "Successfully generated a new mnemonic.".green()); println!("Phrase:\n{phrase}"); println!("\nAccounts:"); for (i, wallet) in wallets.iter().enumerate() { @@ -347,7 +347,7 @@ flag to set your key via: "`{}` keystore was saved successfully. Address: {:?}", &account_name, address, ); - println!("{}", Paint::green(success_message)); + println!("{}", success_message.green()); } WalletSubcommands::List(cmd) => { cmd.run().await?; diff --git a/crates/chisel/Cargo.toml b/crates/chisel/Cargo.toml index 9d07ae80019a..3ff8c6e7c646 100644 --- a/crates/chisel/Cargo.toml +++ b/crates/chisel/Cargo.toml @@ -47,7 +47,7 @@ solang-parser.workspace = true strum = { workspace = true, features = ["derive"] } time = { version = "0.3", features = ["formatting"] } tokio = { version = "1", features = ["full"] } -yansi = "0.5" +yansi = "1.0" tracing.workspace = true [target.'cfg(unix)'.dependencies] diff --git a/crates/chisel/bin/main.rs b/crates/chisel/bin/main.rs index 0cca09bf9873..706c6af99e08 100644 --- a/crates/chisel/bin/main.rs +++ b/crates/chisel/bin/main.rs @@ -98,11 +98,6 @@ pub enum ChiselSubcommand { async fn main() -> eyre::Result<()> { handler::install(); utils::subscriber(); - #[cfg(windows)] - if !Paint::enable_windows_ascii() { - Paint::disable() - } - utils::load_dotenv(); // Parse command args @@ -165,7 +160,7 @@ async fn main() -> eyre::Result<()> { } Some(ChiselSubcommand::ClearCache) => { match dispatcher.dispatch_command(ChiselCommand::ClearCache, &[]).await { - DispatchResult::CommandSuccess(Some(msg)) => println!("{}", Paint::green(msg)), + DispatchResult::CommandSuccess(Some(msg)) => println!("{}", msg.green()), DispatchResult::CommandFailed(e) => eprintln!("{e}"), _ => panic!("Unexpected result! Please report this bug."), } @@ -187,7 +182,7 @@ async fn main() -> eyre::Result<()> { } // Print welcome header - println!("Welcome to Chisel! Type `{}` to show available commands.", Paint::green("!help")); + println!("Welcome to Chisel! Type `{}` to show available commands.", "!help".green()); // Begin Rustyline loop loop { @@ -250,17 +245,17 @@ async fn dispatch_repl_line(dispatcher: &mut ChiselDispatcher, line: &str) -> bo DispatchResult::Success(msg) | DispatchResult::CommandSuccess(msg) => { debug!(%line, ?msg, "dispatch success"); if let Some(msg) = msg { - println!("{}", Paint::green(msg)); + println!("{}", msg.green()); } }, DispatchResult::UnrecognizedCommand(e) => eprintln!("{e}"), DispatchResult::SolangParserFailed(e) => { - eprintln!("{}", Paint::red("Compilation error")); - eprintln!("{}", Paint::red(format!("{e:?}"))); + eprintln!("{}", "Compilation error".red()); + eprintln!("{}", format!("{e:?}").red()); } - DispatchResult::FileIoError(e) => eprintln!("{}", Paint::red(format!("⚒️ Chisel File IO Error - {e}"))), - DispatchResult::CommandFailed(msg) | DispatchResult::Failure(Some(msg)) => eprintln!("{}", Paint::red(msg)), - DispatchResult::Failure(None) => eprintln!("{}\nPlease Report this bug as a github issue if it persists: https://github.com/foundry-rs/foundry/issues/new/choose", Paint::red("⚒️ Unknown Chisel Error ⚒️")), + DispatchResult::FileIoError(e) => eprintln!("{}", format!("⚒️ Chisel File IO Error - {e}").red()), + DispatchResult::CommandFailed(msg) | DispatchResult::Failure(Some(msg)) => eprintln!("{}", msg.red()), + DispatchResult::Failure(None) => eprintln!("{}\nPlease Report this bug as a github issue if it persists: https://github.com/foundry-rs/foundry/issues/new/choose", "⚒️ Unknown Chisel Error ⚒️".red()), } r.is_error() } @@ -273,19 +268,19 @@ async fn evaluate_prelude( ) -> eyre::Result<()> { let Some(prelude_dir) = maybe_prelude else { return Ok(()) }; if prelude_dir.is_file() { - println!("{} {}", Paint::yellow("Loading prelude source file:"), prelude_dir.display(),); + println!("{} {}", "Loading prelude source file:".yellow(), prelude_dir.display(),); load_prelude_file(dispatcher, prelude_dir).await?; - println!("{}\n", Paint::green("Prelude source file loaded successfully!")); + println!("{}\n", "Prelude source file loaded successfully!".green()); } else { let prelude_sources = fs::files_with_ext(prelude_dir, "sol"); let print_success_msg = !prelude_sources.is_empty(); for source_file in prelude_sources { - println!("{} {}", Paint::yellow("Loading prelude source file:"), source_file.display(),); + println!("{} {}", "Loading prelude source file:".yellow(), source_file.display(),); load_prelude_file(dispatcher, source_file).await?; } if print_success_msg { - println!("{}\n", Paint::green("All prelude source files loaded successfully!")); + println!("{}\n", "All prelude source files loaded successfully!".green()); } } Ok(()) diff --git a/crates/chisel/src/dispatcher.rs b/crates/chisel/src/dispatcher.rs index cba66f7aa4f7..ebf4aeb3765e 100644 --- a/crates/chisel/src/dispatcher.rs +++ b/crates/chisel/src/dispatcher.rs @@ -195,7 +195,7 @@ impl ChiselDispatcher { ChiselCommand::iter().map(CmdDescriptor::from).collect::>(); DispatchResult::CommandSuccess(Some(format!( "{}\n{}", - Paint::cyan(format!("{CHISEL_CHAR} Chisel help\n=============")), + format!("{CHISEL_CHAR} Chisel help\n=============").cyan(), CmdCategory::iter() .map(|cat| { // Get commands in the current category @@ -209,13 +209,13 @@ impl ChiselDispatcher { // Format the help menu for the current category format!( "{}\n{}\n", - Paint::magenta(cat), + cat.magenta(), cat_cmds .iter() .map(|(cmds, desc, _)| format!( "\t{} - {}", cmds.iter() - .map(|cmd| format!("!{}", Paint::green(cmd))) + .map(|cmd| format!("!{}", cmd.green())) .collect::>() .join(" | "), desc @@ -274,7 +274,7 @@ impl ChiselDispatcher { if let Err(e) = self.session.write() { return DispatchResult::FileIoError(e.into()) } - println!("{}", Paint::green("Saved current session!")); + println!("{}", "Saved current session!".green()); } // Parse the arguments @@ -304,11 +304,11 @@ impl ChiselDispatcher { ChiselCommand::ListSessions => match ChiselSession::list_sessions() { Ok(sessions) => DispatchResult::CommandSuccess(Some(format!( "{}\n{}", - Paint::cyan(format!("{CHISEL_CHAR} Chisel Sessions")), + format!("{CHISEL_CHAR} Chisel Sessions").cyan(), sessions .iter() .map(|(time, name)| { - format!("{} - {}", Paint::blue(format!("{time:?}")), name) + format!("{} - {}", format!("{time:?}").blue(), name) }) .collect::>() .join("\n") @@ -372,7 +372,7 @@ impl ChiselDispatcher { } // Create success message before moving the fork_url - let success_msg = format!("Set fork URL to {}", Paint::yellow(&fork_url)); + let success_msg = format!("Set fork URL to {}", &fork_url.yellow()); // Update the fork_url inside of the [SessionSourceConfig]'s [EvmOpts] // field @@ -410,7 +410,7 @@ impl ChiselDispatcher { self.source_mut().config.calldata = Some(calldata); DispatchResult::CommandSuccess(Some(format!( "Set calldata to '{}'", - Paint::yellow(arg) + arg.yellow() ))) } Err(e) => DispatchResult::CommandFailed(Self::make_error(format!( @@ -428,8 +428,8 @@ impl ChiselDispatcher { (0..mem.len()).step_by(32).for_each(|i| { println!( "{}: {}", - Paint::yellow(format!("[0x{:02x}:0x{:02x}]", i, i + 32)), - Paint::cyan(hex::encode_prefixed(&mem[i..i + 32])) + format!("[0x{:02x}:0x{:02x}]", i, i + 32).yellow(), + hex::encode_prefixed(&mem[i..i + 32]).cyan() ); }); } else { @@ -437,8 +437,8 @@ impl ChiselDispatcher { (0..stack.len()).rev().for_each(|i| { println!( "{}: {}", - Paint::yellow(format!("[{}]", stack.len() - i - 1)), - Paint::cyan(format!("0x{:02x}", stack[i])) + format!("[{}]", stack.len() - i - 1).yellow(), + format!("0x{:02x}", stack[i]).cyan() ); }); } @@ -698,7 +698,7 @@ impl ChiselDispatcher { // Show console logs, if there are any let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", Paint::green("Logs:")); + println!("{}", "Logs:".green()); for log in decoded_logs { println!(" {log}"); } @@ -842,7 +842,7 @@ impl ChiselDispatcher { // Show console logs, if there are any let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", Paint::green("Logs:")); + println!("{}", "Logs:".green()); for log in decoded_logs { println!(" {log}"); } @@ -931,7 +931,7 @@ impl ChiselDispatcher { eyre::bail!("Unexpected error: No traces gathered. Please report this as a bug: https://github.com/foundry-rs/foundry/issues/new?assignees=&labels=T-bug&template=BUG-FORM.yml"); } - println!("{}", Paint::green("Traces:")); + println!("{}", "Traces:".green()); for (kind, trace) in &result.traces { // Display all Setup + Execution traces. if matches!(kind, TraceKind::Setup | TraceKind::Execution) { @@ -952,7 +952,7 @@ impl ChiselDispatcher { /// /// A formatted error [String]. pub fn make_error(msg: T) -> String { - format!("{} {}", Paint::red(format!("{CHISEL_CHAR} Chisel Error:")), Paint::red(msg)) + format!("{} {}", format!("{CHISEL_CHAR} Chisel Error:").red(), msg.red()) } } diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index 6343013b18ba..424bcda901d7 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -194,7 +194,7 @@ impl SessionSource { } let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", Paint::green("Logs:")); + println!("{}", "Logs:".green()); for log in decoded_logs { println!(" {log}"); } @@ -337,20 +337,20 @@ impl SessionSource { fn format_token(token: DynSolValue) -> String { match token { DynSolValue::Address(a) => { - format!("Type: {}\n└ Data: {}", Paint::red("address"), Paint::cyan(a.to_string())) + format!("Type: {}\n└ Data: {}", "address".red(), a.cyan()) } DynSolValue::FixedBytes(b, byte_len) => { format!( "Type: {}\n└ Data: {}", - Paint::red(format!("bytes{byte_len}")), - Paint::cyan(hex::encode_prefixed(b)) + format!("bytes{byte_len}").red(), + hex::encode_prefixed(b).cyan() ) } DynSolValue::Int(i, bit_len) => { format!( "Type: {}\n├ Hex: {}\n├ Hex (full word): {}\n└ Decimal: {}", - Paint::red(format!("int{}", bit_len)), - Paint::cyan(format!( + format!("int{}", bit_len).red(), + format!( "0x{}", format!("{i:x}") .char_indices() @@ -358,16 +358,17 @@ fn format_token(token: DynSolValue) -> String { .take(bit_len / 4) .map(|(_, c)| c) .collect::() - )), - Paint::cyan(format!("{i:#x}")), - Paint::cyan(i) + ) + .cyan(), + format!("{i:#x}").cyan(), + i.cyan() ) } DynSolValue::Uint(i, bit_len) => { format!( "Type: {}\n├ Hex: {}\n├ Hex (full word): {}\n└ Decimal: {}", - Paint::red(format!("uint{}", bit_len)), - Paint::cyan(format!( + format!("uint{}", bit_len).red(), + format!( "0x{}", format!("{i:x}") .char_indices() @@ -375,50 +376,51 @@ fn format_token(token: DynSolValue) -> String { .take(bit_len / 4) .map(|(_, c)| c) .collect::() - )), - Paint::cyan(format!("{i:#x}")), - Paint::cyan(i) + ) + .cyan(), + format!("{i:#x}").cyan(), + i.cyan() ) } DynSolValue::Bool(b) => { - format!("Type: {}\n└ Value: {}", Paint::red("bool"), Paint::cyan(b)) + format!("Type: {}\n└ Value: {}", "bool".red(), b.cyan()) } DynSolValue::String(_) | DynSolValue::Bytes(_) => { let hex = hex::encode(token.abi_encode()); let s = token.as_str(); format!( "Type: {}\n{}├ Hex (Memory):\n├─ Length ({}): {}\n├─ Contents ({}): {}\n├ Hex (Tuple Encoded):\n├─ Pointer ({}): {}\n├─ Length ({}): {}\n└─ Contents ({}): {}", - Paint::red(if s.is_some() { "string" } else { "dynamic bytes" }), + if s.is_some() { "string" } else { "dynamic bytes" }.red(), if let Some(s) = s { - format!("├ UTF-8: {}\n", Paint::cyan(s)) + format!("├ UTF-8: {}\n", s.cyan()) } else { String::default() }, - Paint::yellow("[0x00:0x20]"), - Paint::cyan(format!("0x{}", &hex[64..128])), - Paint::yellow("[0x20:..]"), - Paint::cyan(format!("0x{}", &hex[128..])), - Paint::yellow("[0x00:0x20]"), - Paint::cyan(format!("0x{}", &hex[..64])), - Paint::yellow("[0x20:0x40]"), - Paint::cyan(format!("0x{}", &hex[64..128])), - Paint::yellow("[0x40:..]"), - Paint::cyan(format!("0x{}", &hex[128..])), + "[0x00:0x20]".yellow(), + format!("0x{}", &hex[64..128]).cyan(), + "[0x20:..]".yellow(), + format!("0x{}", &hex[128..]).cyan(), + "[0x00:0x20]".yellow(), + format!("0x{}", &hex[..64]).cyan(), + "[0x20:0x40]".yellow(), + format!("0x{}", &hex[64..128]).cyan(), + "[0x40:..]".yellow(), + format!("0x{}", &hex[128..]).cyan(), ) } DynSolValue::FixedArray(tokens) | DynSolValue::Array(tokens) => { let mut out = format!( "{}({}) = {}", - Paint::red("array"), - Paint::yellow(format!("{}", tokens.len())), - Paint::red('[') + "array".red(), + format!("{}", tokens.len()).yellow(), + '['.red() ); for token in tokens { out.push_str("\n ├ "); out.push_str(&format_token(token).replace('\n', "\n ")); out.push('\n'); } - out.push_str(&Paint::red(']').to_string()); + out.push_str(&']'.red().to_string()); out } DynSolValue::Tuple(tokens) => { @@ -428,18 +430,14 @@ fn format_token(token: DynSolValue) -> String { .map(|t| t.unwrap_or_default().into_owned()) .collect::>() .join(", "); - let mut out = format!( - "{}({}) = {}", - Paint::red("tuple"), - Paint::yellow(displayed_types), - Paint::red('(') - ); + let mut out = + format!("{}({}) = {}", "tuple".red(), displayed_types.yellow(), '('.red()); for token in tokens { out.push_str("\n ├ "); out.push_str(&format_token(token).replace('\n', "\n ")); out.push('\n'); } - out.push_str(&Paint::red(')').to_string()); + out.push_str(&')'.red().to_string()); out } _ => { @@ -487,7 +485,7 @@ fn format_event_definition(event_definition: &pt::EventDefinition) -> Result Result>() .join(", ") )), - Paint::cyan(event.signature()), - Paint::cyan(event.selector()), + event.signature().cyan(), + event.selector().cyan(), )) } diff --git a/crates/chisel/src/session_source.rs b/crates/chisel/src/session_source.rs index 47660ba091ae..46f06eeff516 100644 --- a/crates/chisel/src/session_source.rs +++ b/crates/chisel/src/session_source.rs @@ -97,7 +97,7 @@ impl SessionSourceConfig { SolcReq::Version(version.into()) } else { if !self.foundry_config.offline { - print!("{}", Paint::green("No solidity versions installed! ")); + print!("{}", "No solidity versions installed! ".green()); } // use default SolcReq::Version("0.8.19".parse().unwrap()) @@ -121,10 +121,7 @@ impl SessionSourceConfig { if self.foundry_config.offline { eyre::bail!("can't install missing solc {version} in offline mode") } - println!( - "{}", - Paint::green(format!("Installing solidity version {version}...")) - ); + println!("{}", format!("Installing solidity version {version}...").green()); Solc::blocking_install(&version)?; solc = Solc::find_svm_installed_version(version.to_string())?; } @@ -289,21 +286,21 @@ impl SessionSource { /// Clears global code from the source pub fn drain_global_code(&mut self) -> &mut Self { - self.global_code.clear(); + self.global_code.resetting(); self.generated_output = None; self } /// Clears top-level code from the source pub fn drain_top_level_code(&mut self) -> &mut Self { - self.top_level_code.clear(); + self.top_level_code.resetting(); self.generated_output = None; self } /// Clears the "run()" function's code pub fn drain_run(&mut self) -> &mut Self { - self.run_code.clear(); + self.run_code.resetting(); self.generated_output = None; self } diff --git a/crates/chisel/src/solidity_helper.rs b/crates/chisel/src/solidity_helper.rs index 42641a1f0a8d..f09ad168356e 100644 --- a/crates/chisel/src/solidity_helper.rs +++ b/crates/chisel/src/solidity_helper.rs @@ -19,7 +19,7 @@ use solang_parser::{ pt, }; use std::{borrow::Cow, str::FromStr}; -use yansi::{Color, Paint, Style}; +use yansi::{Color, Style}; /// The default pre-allocation for solang parsed comments const DEFAULT_COMMENTS: usize = 5; @@ -71,7 +71,7 @@ impl SolidityHelper { pt::Comment::DocLine(loc, _) | pt::Comment::DocBlock(loc, _) => loc, }; - (loc.start(), Style::default().dimmed(), loc.end()) + (loc.start(), Style::new().dim(), loc.end()) }); out.extend(comments_iter); @@ -102,7 +102,7 @@ impl SolidityHelper { /// Highlights a solidity source string pub fn highlight(input: &str) -> Cow { - if !Paint::is_enabled() { + if !yansi::is_enabled() { return Cow::Borrowed(input) } @@ -119,7 +119,7 @@ impl SolidityHelper { // cmd out.push(COMMAND_LEADER); let cmd_res = ChiselCommand::from_str(cmd); - let style = Style::new(if cmd_res.is_ok() { Color::Green } else { Color::Red }); + let style = (if cmd_res.is_ok() { Color::Green } else { Color::Red }).foreground(); Self::paint_unchecked(cmd, style, &mut out); // rest @@ -186,7 +186,7 @@ impl SolidityHelper { } /// Formats `input` with `style` into `out`, without checking `style.wrapping` or - /// `Paint::is_enabled` + /// `yansi::is_enabled` #[inline] fn paint_unchecked(string: &str, style: Style, out: &mut String) { if style == Style::default() { @@ -220,7 +220,7 @@ impl Highlighter for SolidityHelper { prompt: &'p str, _default: bool, ) -> Cow<'b, str> { - if !Paint::is_enabled() { + if !yansi::is_enabled() { return Cow::Borrowed(prompt) } @@ -231,12 +231,16 @@ impl Highlighter for SolidityHelper { let id_end = prompt.find(')').unwrap(); let id_span = 5..id_end; let id = &prompt[id_span.clone()]; - out.replace_range(id_span, &Self::paint_unchecked_owned(id, Color::Yellow.style())); - out.replace_range(1..=2, &Self::paint_unchecked_owned("ID", Color::Cyan.style())); + out.replace_range( + id_span, + &Self::paint_unchecked_owned(id, Color::Yellow.foreground()), + ); + out.replace_range(1..=2, &Self::paint_unchecked_owned("ID", Color::Cyan.foreground())); } if let Some(i) = out.find(PROMPT_ARROW) { - let style = if self.errored { Color::Red.style() } else { Color::Green.style() }; + let style = + if self.errored { Color::Red.foreground() } else { Color::Green.foreground() }; let mut arrow = String::with_capacity(MAX_ANSI_LEN + 4); @@ -278,7 +282,7 @@ impl<'a> TokenStyle for Token<'a> { fn style(&self) -> Style { use Token::*; match self { - StringLiteral(_, _) => Color::Green.style(), + StringLiteral(_, _) => Color::Green.foreground(), AddressLiteral(_) | HexLiteral(_) | @@ -286,21 +290,21 @@ impl<'a> TokenStyle for Token<'a> { RationalNumber(_, _, _) | HexNumber(_) | True | - False => Color::Yellow.style(), + False => Color::Yellow.foreground(), Memory | Storage | Calldata | Public | Private | Internal | External | Constant | Pure | View | Payable | Anonymous | Indexed | Abstract | Virtual | Override | - Modifier | Immutable | Unchecked => Color::Cyan.style(), + Modifier | Immutable | Unchecked => Color::Cyan.foreground(), Contract | Library | Interface | Function | Pragma | Import | Struct | Event | Enum | Type | Constructor | As | Is | Using | New | Delete | Do | Continue | Break | Throw | Emit | Return | Returns | Revert | For | While | If | Else | Try | Catch | Assembly | Let | Leave | Switch | Case | Default | YulArrow | Arrow => { - Color::Magenta.style() + Color::Magenta.foreground() } Uint(_) | Int(_) | Bytes(_) | Byte | DynamicBytes | Bool | Address | String | - Mapping => Color::Blue.style(), + Mapping => Color::Blue.foreground(), Identifier(_) => Style::default(), diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index fcc95d55e822..8582b0a6e29d 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -40,7 +40,7 @@ tokio = { version = "1", features = ["macros"] } tracing-error = "0.2" tracing-subscriber = { workspace = true, features = ["registry", "env-filter", "fmt"] } tracing.workspace = true -yansi = "0.5" +yansi = "1.0" hex.workspace = true futures = "0.3" diff --git a/crates/cli/src/handler.rs b/crates/cli/src/handler.rs index 6666686c5555..d6e34f3b8e1a 100644 --- a/crates/cli/src/handler.rs +++ b/crates/cli/src/handler.rs @@ -16,7 +16,7 @@ impl EyreHandler for Handler { return core::fmt::Debug::fmt(error, f) } writeln!(f)?; - write!(f, "{}", Paint::red(error))?; + write!(f, "{}", error.red())?; if let Some(cause) = error.source() { write!(f, "\n\nContext:")?; diff --git a/crates/cli/src/utils/cmd.rs b/crates/cli/src/utils/cmd.rs index 475fae2ed2e4..d8c5ab2227b8 100644 --- a/crates/cli/src/utils/cmd.rs +++ b/crates/cli/src/utils/cmd.rs @@ -128,7 +128,7 @@ pub fn needs_setup(abi: &JsonAbi) -> bool { if setup_fn.name != "setUp" { println!( "{} Found invalid setup function \"{}\" did you mean \"setUp()\"?", - Paint::yellow("Warning:").bold(), + "Warning:".yellow().bold(), setup_fn.signature() ); } @@ -437,9 +437,9 @@ pub async fn print_traces(result: &mut TraceResult, decoder: &CallTraceDecoder) println!(); if result.success { - println!("{}", Paint::green("Transaction successfully executed.")); + println!("{}", "Transaction successfully executed.".green()); } else { - println!("{}", Paint::red("Transaction failed.")); + println!("{}", "Transaction failed.".red()); } println!("Gas used: {}", result.gas_used); diff --git a/crates/cli/src/utils/mod.rs b/crates/cli/src/utils/mod.rs index 015ce2145af6..dccb7ab59601 100644 --- a/crates/cli/src/utils/mod.rs +++ b/crates/cli/src/utils/mod.rs @@ -13,7 +13,6 @@ use std::{ }; use tracing_error::ErrorLayer; use tracing_subscriber::prelude::*; -use yansi::Paint; mod cmd; pub use cmd::*; @@ -209,14 +208,12 @@ pub fn load_dotenv() { } /// Disables terminal colours if either: -/// - Running windows and the terminal does not support colour codes. /// - Colour has been disabled by some environment variable. /// - We are running inside a test 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(); + if env_colour_disabled { + yansi::disable(); } } diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 07f8837cabb8..085c6f8cae26 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -60,7 +60,7 @@ tokio = "1" tracing.workspace = true url = "2" walkdir = "2" -yansi = "0.5" +yansi = "1.0" rustc-hash.workspace = true num-format.workspace = true diff --git a/crates/common/src/fmt/mod.rs b/crates/common/src/fmt/mod.rs index fbe1670fc6cb..a43fe7dea088 100644 --- a/crates/common/src/fmt/mod.rs +++ b/crates/common/src/fmt/mod.rs @@ -23,7 +23,7 @@ pub use ui::{get_pretty_block_attr, get_pretty_tx_attr, get_pretty_tx_receipt_at /// use alloy_primitives::U256; /// use foundry_common::fmt::format_uint_exp as f; /// -/// # yansi::Paint::disable(); +/// # yansi::disable(); /// assert_eq!(f(U256::from(0)), "0"); /// assert_eq!(f(U256::from(1234)), "1234"); /// assert_eq!(f(U256::from(1234567890)), "1234567890 [1.234e9]"); @@ -36,7 +36,7 @@ pub fn format_uint_exp(num: U256) -> String { } let exp = to_exp_notation(num, 4, true, Sign::Positive); - format!("{num} {}", Paint::default(format!("[{exp}]")).dimmed()) + format!("{num} {}", format!("[{exp}]").dim()) } /// Formats a U256 number to string, adding an exponential notation _hint_. @@ -49,7 +49,7 @@ pub fn format_uint_exp(num: U256) -> String { /// use alloy_primitives::I256; /// use foundry_common::fmt::format_int_exp as f; /// -/// # yansi::Paint::disable(); +/// # yansi::disable(); /// assert_eq!(f(I256::try_from(0).unwrap()), "0"); /// assert_eq!(f(I256::try_from(-1).unwrap()), "-1"); /// assert_eq!(f(I256::try_from(1234).unwrap()), "1234"); @@ -72,5 +72,5 @@ pub fn format_int_exp(num: I256) -> String { } let exp = to_exp_notation(abs, 4, true, sign); - format!("{sign}{abs} {}", Paint::default(format!("[{exp}]")).dimmed()) + format!("{sign}{abs} {}", format!("[{exp}]").dim()) } diff --git a/crates/common/src/term.rs b/crates/common/src/term.rs index afeae0664049..5cfb5ef37fdd 100644 --- a/crates/common/src/term.rs +++ b/crates/common/src/term.rs @@ -69,7 +69,7 @@ impl Spinner { return } - let indicator = Paint::green(self.indicator[self.idx % self.indicator.len()]); + let indicator = self.indicator[self.idx % self.indicator.len()].green(); let indicator = Paint::new(format!("[{indicator}]")).bold(); print!("\r\x33[2K\r{indicator} {}", self.message); io::stdout().flush().unwrap(); @@ -194,7 +194,7 @@ impl Reporter for SpinnerReporter { } fn on_solc_installation_error(&self, version: &Version, error: &str) { - self.send_msg(Paint::red(format!("Failed to install Solc {version}: {error}")).to_string()); + self.send_msg(format!("Failed to install Solc {version}: {error}").red().to_string()); } fn on_unresolved_imports(&self, imports: &[(&Path, &Path)], remappings: &[Remapping]) { @@ -221,8 +221,8 @@ macro_rules! cli_warn { ($($arg:tt)*) => { eprintln!( "{}{} {}", - yansi::Paint::yellow("warning").bold(), - yansi::Paint::new(":").bold(), + yansi::Painted::new("warning").yellow().bold(), + yansi::Painted::new(":").bold(), format_args!($($arg)*) ) } diff --git a/crates/evm/traces/Cargo.toml b/crates/evm/traces/Cargo.toml index be3cecb36383..bb0aa5f3e0a0 100644 --- a/crates/evm/traces/Cargo.toml +++ b/crates/evm/traces/Cargo.toml @@ -31,7 +31,7 @@ once_cell = "1" serde = "1" tokio = { version = "1", features = ["time", "macros"] } tracing = "0.1" -yansi = "0.5" +yansi = "1.0" [dev-dependencies] tempfile = "3" diff --git a/crates/evm/traces/src/lib.rs b/crates/evm/traces/src/lib.rs index a52fd3b42eaa..16cadde109e7 100644 --- a/crates/evm/traces/src/lib.rs +++ b/crates/evm/traces/src/lib.rs @@ -125,8 +125,8 @@ pub async fn render_trace_arena( write!( s, "{child}{EDGE}{}{}", - color.paint(RETURN), - color.paint(format!("[{:?}] ", node.trace.status)) + RETURN.fg(color), + format!("[{:?}] ", node.trace.status).fg(color) )?; match return_data { Some(val) => write!(s, "{val}"), @@ -164,8 +164,8 @@ pub async fn render_trace( write!( &mut s, "{}{} {}@{}", - Paint::yellow(CALL), - Paint::yellow("new"), + CALL.yellow(), + "new".yellow(), decoded.label.as_deref().unwrap_or(""), address )?; @@ -198,14 +198,14 @@ pub async fn render_trace( write!( &mut s, "{addr}::{func_name}{opt_value}({inputs}){action}", - addr = color.paint(decoded.label.as_deref().unwrap_or(&address)), - func_name = color.paint(func_name), + addr = decoded.label.as_deref().unwrap_or(&address).fg(color), + func_name = func_name.fg(color), opt_value = if trace.value.is_zero() { String::new() } else { format!("{{value: {}}}", trace.value) }, - action = Paint::yellow(action), + action = action.yellow(), )?; } @@ -227,11 +227,11 @@ async fn render_trace_log( s, "{:>13}: {}", if i == 0 { "emit topic 0".to_string() } else { format!("topic {i}") }, - Paint::cyan(format!("{topic:?}")) + format!("{topic:?}").cyan() )?; } - write!(s, " data: {}", Paint::cyan(hex::encode_prefixed(&log.data)))?; + write!(s, " data: {}", hex::encode_prefixed(&log.data).cyan())?; } DecodedCallLog::Decoded(name, params) => { let params = params @@ -240,7 +240,7 @@ async fn render_trace_log( .collect::>() .join(", "); - write!(s, "emit {}({params})", Paint::cyan(name.clone()))?; + write!(s, "emit {}({params})", name.clone().cyan())?; } } diff --git a/crates/forge/Cargo.toml b/crates/forge/Cargo.toml index 7b05ee06e320..a7d4b87fd066 100644 --- a/crates/forge/Cargo.toml +++ b/crates/forge/Cargo.toml @@ -37,7 +37,7 @@ proptest = "1" rayon = "1" serde.workspace = true tracing.workspace = true -yansi = "0.5" +yansi = "1.0" humantime-serde = "1.1.1" # bin diff --git a/crates/forge/bin/cmd/coverage.rs b/crates/forge/bin/cmd/coverage.rs index fc919934f037..fd521d487c99 100644 --- a/crates/forge/bin/cmd/coverage.rs +++ b/crates/forge/bin/cmd/coverage.rs @@ -124,13 +124,13 @@ impl CoverageArgs { } // print warning message - let msg = Paint::yellow(concat!( + let msg = concat!( "Warning! \"--ir-minimum\" flag enables viaIR with minimum optimization, \ which can result in inaccurate source mappings.\n", "Only use this flag as a workaround if you are experiencing \"stack too deep\" errors.\n", "Note that \"viaIR\" is only available in Solidity 0.8.13 and above.\n", "See more: https://github.com/foundry-rs/foundry/issues/3357", - )); + ).yellow(); p_println!(!self.opts.silent => "{msg}"); // Enable viaIR with minimum optimization diff --git a/crates/forge/bin/cmd/fmt.rs b/crates/forge/bin/cmd/fmt.rs index 36c0800008f1..06e05a5680dc 100644 --- a/crates/forge/bin/cmd/fmt.rs +++ b/crates/forge/bin/cmd/fmt.rs @@ -12,7 +12,7 @@ use std::{ io::{Read, Write as _}, path::{Path, PathBuf}, }; -use yansi::Color; +use yansi::{Color, Paint, Style}; /// CLI arguments for `forge fmt`. #[derive(Clone, Debug, Parser)] @@ -217,24 +217,24 @@ where } for op in group { for change in diff.iter_inline_changes(&op) { - let dimmed = Color::Default.style().dimmed(); + let dimmed = Style::new().dim(); let (sign, s) = match change.tag() { - ChangeTag::Delete => ("-", Color::Red.style()), - ChangeTag::Insert => ("+", Color::Green.style()), + ChangeTag::Delete => ("-", Color::Red.foreground()), + ChangeTag::Insert => ("+", Color::Green.foreground()), ChangeTag::Equal => (" ", dimmed), }; let _ = write!( diff_summary, "{}{} |{}", - dimmed.paint(Line(change.old_index())), - dimmed.paint(Line(change.new_index())), - s.bold().paint(sign), + Line(change.old_index()).paint(dimmed), + Line(change.new_index()).paint(dimmed), + sign.paint(s.bold()), ); for (emphasized, value) in change.iter_strings_lossy() { let s = if emphasized { s.underline().bg(Color::Black) } else { s }; - let _ = write!(diff_summary, "{}", s.paint(value)); + let _ = write!(diff_summary, "{}", value.paint(s)); } if change.missing_newline() { diff --git a/crates/forge/bin/cmd/geiger/find.rs b/crates/forge/bin/cmd/geiger/find.rs index ed1d5e691ae8..3ea9c0234109 100644 --- a/crates/forge/bin/cmd/geiger/find.rs +++ b/crates/forge/bin/cmd/geiger/find.rs @@ -55,15 +55,15 @@ impl<'a, 'b> fmt::Display for SolFileMetricsPrinter<'a, 'b> { ($($name:literal => $field:ident),*) => {$( let $field = &metrics.cheatcodes.$field[..]; if !$field.is_empty() { - writeln!(f, " {} {}", Paint::red(metrics.cheatcodes.$field.len()), Paint::red($name))?; + writeln!(f, " {} {}", metrics.cheatcodes.$field.len().red(), $name.red())?; for &loc in $field { let content = &metrics.contents[loc.range()]; let (line, col) = offset_to_line_column(&metrics.contents, loc.start()); let pos = format!(" --> {}:{}:{}", file.display(), line, col); - writeln!(f,"{}", Paint::red(pos))?; + writeln!(f,"{}", pos.red())?; for line in content.lines() { - writeln!(f, " {}", Paint::red(line))?; + writeln!(f, " {}", line.red())?; } } } @@ -71,12 +71,7 @@ impl<'a, 'b> fmt::Display for SolFileMetricsPrinter<'a, 'b> { } if !metrics.cheatcodes.is_empty() { - writeln!( - f, - "{} {}", - Paint::red(metrics.cheatcodes.len()), - Paint::red(file.display()) - )?; + writeln!(f, "{} {}", metrics.cheatcodes.len().red(), file.display().red())?; print_unsafe_fn!( "ffi" => ffi, "readFile" => read_file, diff --git a/crates/forge/bin/cmd/geiger/mod.rs b/crates/forge/bin/cmd/geiger/mod.rs index 8e3bc6fc5660..27555ed1a794 100644 --- a/crates/forge/bin/cmd/geiger/mod.rs +++ b/crates/forge/bin/cmd/geiger/mod.rs @@ -91,7 +91,7 @@ impl GeigerArgs { let sources = self.sources(&config).wrap_err("Failed to resolve files")?; if config.ffi { - eprintln!("{}\n", Paint::red("ffi enabled")); + eprintln!("{}\n", "ffi enabled".red()); } let root = config.__root.0; diff --git a/crates/forge/bin/cmd/generate/mod.rs b/crates/forge/bin/cmd/generate/mod.rs index 190ea52b7752..fd40a78ae6ca 100644 --- a/crates/forge/bin/cmd/generate/mod.rs +++ b/crates/forge/bin/cmd/generate/mod.rs @@ -44,7 +44,7 @@ impl GenerateTestArgs { // Write the test content to the test file. fs::write(&test_file_path, test_content)?; - println!("{} test file: {}", Paint::green("Generated"), test_file_path.to_str().unwrap()); + println!("{} test file: {}", "Generated".green(), test_file_path.to_str().unwrap()); Ok(()) } } diff --git a/crates/forge/bin/cmd/init.rs b/crates/forge/bin/cmd/init.rs index d05c8a7bd472..87010244ccfe 100644 --- a/crates/forge/bin/cmd/init.rs +++ b/crates/forge/bin/cmd/init.rs @@ -159,7 +159,7 @@ impl InitArgs { } } - p_println!(!quiet => " {} forge project", Paint::green("Initialized")); + p_println!(!quiet => " {} forge project", "Initialized".green()); Ok(()) } } diff --git a/crates/forge/bin/cmd/install.rs b/crates/forge/bin/cmd/install.rs index 75fdbe3aa2ea..ccec7d5de4f1 100644 --- a/crates/forge/bin/cmd/install.rs +++ b/crates/forge/bin/cmd/install.rs @@ -103,9 +103,7 @@ impl DependencyInstallOpts { if self.install(config, Vec::new()).is_err() && !quiet { eprintln!( "{}", - Paint::yellow( - "Your project has missing dependencies that could not be installed." - ) + "Your project has missing dependencies that could not be installed.".yellow() ) } true @@ -193,7 +191,7 @@ impl DependencyInstallOpts { } if !quiet { - let mut msg = format!(" {} {}", Paint::green("Installed"), dep.name); + let mut msg = format!(" {} {}", "Installed".green(), dep.name); if let Some(tag) = dep.tag.or(installed_tag) { msg.push(' '); msg.push_str(tag.as_str()); diff --git a/crates/forge/bin/cmd/snapshot.rs b/crates/forge/bin/cmd/snapshot.rs index d7147f49b6c1..5f91951d834c 100644 --- a/crates/forge/bin/cmd/snapshot.rs +++ b/crates/forge/bin/cmd/snapshot.rs @@ -398,21 +398,21 @@ fn diff(tests: Vec, snaps: Vec) -> Result<()> { fn fmt_pct_change(change: f64) -> String { let change_pct = change * 100.0; match change.partial_cmp(&0.0).unwrap_or(Ordering::Equal) { - Ordering::Less => Paint::green(format!("{change_pct:.3}%")).to_string(), + Ordering::Less => format!("{change_pct:.3}%").green().to_string(), Ordering::Equal => { format!("{change_pct:.3}%") } - Ordering::Greater => Paint::red(format!("{change_pct:.3}%")).to_string(), + Ordering::Greater => format!("{change_pct:.3}%").red().to_string(), } } fn fmt_change(change: i128) -> String { match change.cmp(&0) { - Ordering::Less => Paint::green(format!("{change}")).to_string(), + Ordering::Less => format!("{change}").green().to_string(), Ordering::Equal => { format!("{change}") } - Ordering::Greater => Paint::red(format!("{change}")).to_string(), + Ordering::Greater => format!("{change}").red().to_string(), } } diff --git a/crates/forge/bin/cmd/test/mod.rs b/crates/forge/bin/cmd/test/mod.rs index 4a120adc7355..72835f097c92 100644 --- a/crates/forge/bin/cmd/test/mod.rs +++ b/crates/forge/bin/cmd/test/mod.rs @@ -408,7 +408,7 @@ impl TestArgs { // Print suite header. println!(); for warning in suite_result.warnings.iter() { - eprintln!("{} {warning}", Paint::yellow("Warning:").bold()); + eprintln!("{} {warning}", "Warning:".yellow().bold()); } if !tests.is_empty() { let len = tests.len(); diff --git a/crates/forge/src/gas_report.rs b/crates/forge/src/gas_report.rs index 2bdd6d4daec6..058af0587dab 100644 --- a/crates/forge/src/gas_report.rs +++ b/crates/forge/src/gas_report.rs @@ -12,6 +12,7 @@ use std::{ collections::{BTreeMap, HashSet}, fmt::Display, }; +use yansi::Paint; /// Represents the gas report for a set of contracts. #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -51,7 +52,7 @@ impl GasReport { // indicating the "double listing". eprintln!( "{}: {} is listed in both 'gas_reports' and 'gas_reports_ignore'.", - yansi::Paint::yellow("warning").bold(), + "warning".yellow().bold(), contract_name ); } diff --git a/crates/forge/src/result.rs b/crates/forge/src/result.rs index 7cef52a9e233..04f397c4834c 100644 --- a/crates/forge/src/result.rs +++ b/crates/forge/src/result.rs @@ -141,9 +141,9 @@ impl TestOutcome { suites, wall_clock_time, self.total_time(), - Paint::green(total_passed), - Paint::red(total_failed), - Paint::yellow(total_skipped), + total_passed.green(), + total_failed.red(), + total_skipped.yellow(), total_tests ) } @@ -179,8 +179,8 @@ impl TestOutcome { let successes = outcome.passed(); shell::println(format!( "Encountered a total of {} failing tests, {} tests succeeded", - Paint::red(failures.to_string()), - Paint::green(successes.to_string()) + failures.to_string().red(), + successes.to_string().green() ))?; // TODO: Avoid process::exit @@ -271,13 +271,13 @@ impl SuiteResult { /// Returns the summary of a single test suite. pub fn summary(&self) -> String { let failed = self.failed(); - let result = if failed == 0 { Paint::green("ok") } else { Paint::red("FAILED") }; + let result = if failed == 0 { "ok".green() } else { "FAILED".red() }; format!( "Suite result: {}. {} passed; {} failed; {} skipped; finished in {:.2?} ({:.2?} CPU time)", result, - Paint::green(self.passed()), - Paint::red(failed), - Paint::yellow(self.skipped()), + self.passed().green(), + failed.red(), + self.skipped().yellow(), self.duration, self.total_time(), ) @@ -397,8 +397,8 @@ pub struct TestResult { impl fmt::Display for TestResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.status { - TestStatus::Success => Paint::green("[PASS]").fmt(f), - TestStatus::Skipped => Paint::yellow("[SKIP]").fmt(f), + TestStatus::Success => "[PASS]".green().fmt(f), + TestStatus::Skipped => "[SKIP]".yellow().fmt(f), TestStatus::Failure => { let mut s = String::from("[FAIL. Reason: "); @@ -421,7 +421,7 @@ impl fmt::Display for TestResult { s.push(']'); } - Paint::red(s).fmt(f) + s.red().fmt(f) } } } diff --git a/crates/script/Cargo.toml b/crates/script/Cargo.toml index e62e054bfadb..3cda7b5af3e8 100644 --- a/crates/script/Cargo.toml +++ b/crates/script/Cargo.toml @@ -35,7 +35,7 @@ async-recursion = "1.0.5" itertools.workspace = true parking_lot = "0.12" -yansi = "0.5" +yansi = "1.0" revm-inspectors.workspace = true alloy-rpc-types.workspace = true alloy-json-abi.workspace = true diff --git a/crates/script/src/execute.rs b/crates/script/src/execute.rs index 6dc6a9617c09..66d44da0e5e2 100644 --- a/crates/script/src/execute.rs +++ b/crates/script/src/execute.rs @@ -267,7 +267,7 @@ For more information, please see https://eips.ethereum.org/EIPS/eip-3855", .map(|(_, chain)| *chain as u64) .format(", ") ); - shell::println(Paint::yellow(msg))?; + shell::println(msg.yellow())?; } Ok(()) } @@ -306,9 +306,7 @@ impl ExecutedState { if rpc_data.is_multi_chain() { shell::eprintln(format!( "{}", - Paint::yellow( - "Multi chain deployment is still under development. Use with caution." - ) + "Multi chain deployment is still under development. Use with caution.".yellow() ))?; if !self.build_data.libraries.is_empty() { eyre::bail!( @@ -453,7 +451,7 @@ impl PreSimulationState { } if result.success { - shell::println(format!("{}", Paint::green("Script ran successfully.")))?; + shell::println(format!("{}", "Script ran successfully.".green()))?; } if self.script_config.evm_opts.fork_url.is_none() { diff --git a/crates/script/src/lib.rs b/crates/script/src/lib.rs index cc43929a6e06..39b02d335d1a 100644 --- a/crates/script/src/lib.rs +++ b/crates/script/src/lib.rs @@ -420,9 +420,9 @@ impl ScriptArgs { prompt_user = self.broadcast; shell::println(format!( "{}", - Paint::red(format!( + format!( "`{name}` is above the contract size limit ({deployment_size} > {max_size})." - )) + ).red() ))?; } } diff --git a/crates/script/src/runner.rs b/crates/script/src/runner.rs index 23c25d133dc0..3a129d58d563 100644 --- a/crates/script/src/runner.rs +++ b/crates/script/src/runner.rs @@ -200,7 +200,8 @@ impl ScriptRunner { Ok(DeployResult { address, raw }) => (address, raw), Err(EvmError::Execution(err)) => { let ExecutionErr { raw, reason } = *err; - println!("{}", Paint::red(format!("\nFailed with `{reason}`:\n"))); + + println!("{}", format!("\nFailed with `{reason}`:\n").red()); (Address::ZERO, raw) } Err(e) => eyre::bail!("Failed deploying contract: {e:?}"), diff --git a/crates/script/src/sequence.rs b/crates/script/src/sequence.rs index 2d39c12923db..f98326564ffb 100644 --- a/crates/script/src/sequence.rs +++ b/crates/script/src/sequence.rs @@ -324,11 +324,12 @@ impl ScriptSequence { if !unverifiable_contracts.is_empty() { println!( "\n{}", - Paint::yellow(format!( + format!( "We haven't found any matching bytecode for the following contracts: {:?}.\n\n{}", unverifiable_contracts, "This may occur when resuming a verification, but the underlying source code or compiler version has changed." - )) + ) + .yellow() .bold(), ); diff --git a/crates/verify/Cargo.toml b/crates/verify/Cargo.toml index d365388d09f7..7bf201683e5d 100644 --- a/crates/verify/Cargo.toml +++ b/crates/verify/Cargo.toml @@ -35,7 +35,7 @@ futures = "0.3" semver = "1" regex = { version = "1", default-features = false } once_cell = "1" -yansi = "0.5" +yansi = "1.0" [dev-dependencies] tokio = { version = "1", features = ["macros"] } diff --git a/crates/verify/src/bytecode.rs b/crates/verify/src/bytecode.rs index d84acbccc998..065fcad80563 100644 --- a/crates/verify/src/bytecode.rs +++ b/crates/verify/src/bytecode.rs @@ -117,8 +117,8 @@ impl VerifyBytecodeArgs { if !self.json { println!( "Verifying bytecode for contract {} at address {}", - Paint::green(self.contract.name.clone()), - Paint::green(self.address.to_string()) + self.contract.name.clone().green(), + self.address.green() ); } @@ -174,7 +174,7 @@ impl VerifyBytecodeArgs { if provided_constructor_args != constructor_args.to_string() && !self.json { println!( "{}", - Paint::red("The provided constructor args do not match the constructor args from etherscan. This will result in a mismatch - Using the args from etherscan").bold(), + "The provided constructor args do not match the constructor args from etherscan. This will result in a mismatch - Using the args from etherscan".red().bold(), ); } @@ -453,8 +453,8 @@ impl VerifyBytecodeArgs { if !self.json { println!( "{} with status {}", - Paint::green(format!("{:?} code matched", bytecode_type)).bold(), - Paint::green(res.1.unwrap()).bold() + format!("{:?} code matched", bytecode_type).green().bold(), + res.1.unwrap().green().bold() ); } else { let json_res = JsonResult { @@ -468,15 +468,16 @@ impl VerifyBytecodeArgs { } else if !res.0 && !self.json { println!( "{}", - Paint::red(format!( + format!( "{:?} code did not match - this may be due to varying compiler settings", bytecode_type - )) + ) + .red() .bold() ); let mismatches = find_mismatch_in_settings(etherscan_config, config); for mismatch in mismatches { - println!("{}", Paint::red(mismatch).bold()); + println!("{}", mismatch.red().bold()); } } else if !res.0 && self.json { let json_res = JsonResult {