From 6b4ad0ddcf52445acb434e52339bfa15845d798b Mon Sep 17 00:00:00 2001 From: zerosnacks <95942363+zerosnacks@users.noreply.github.com> Date: Thu, 24 Oct 2024 19:27:00 +0200 Subject: [PATCH] chore(`chisel`): enforce `common::shell` for chisel binary (#9177) * enforce common::shell for chisel binary * revert accidental fmt changes * change UnrecognizedCommand(e) to use sh_err! * avoid message painting, use default error formatting for consistency * revert color changes as this is in a REPL * avoid double rendering of error prefix --- crates/chisel/bin/main.rs | 53 +++++++++++++++-------------- crates/chisel/src/dispatcher.rs | 24 +++++++------ crates/chisel/src/executor.rs | 14 ++++---- crates/chisel/src/lib.rs | 3 ++ crates/chisel/src/session_source.rs | 4 +-- 5 files changed, 53 insertions(+), 45 deletions(-) diff --git a/crates/chisel/bin/main.rs b/crates/chisel/bin/main.rs index c612a504706f..17697688bb3e 100644 --- a/crates/chisel/bin/main.rs +++ b/crates/chisel/bin/main.rs @@ -27,6 +27,9 @@ use std::path::PathBuf; use tracing::debug; use yansi::Paint; +#[macro_use] +extern crate foundry_common; + #[cfg(all(feature = "jemalloc", unix))] #[global_allocator] static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; @@ -148,9 +151,9 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { let sessions = dispatcher.dispatch_command(ChiselCommand::ListSessions, &[]).await; match sessions { DispatchResult::CommandSuccess(Some(session_list)) => { - println!("{session_list}"); + sh_println!("{session_list}")?; } - DispatchResult::CommandFailed(e) => eprintln!("{e}"), + DispatchResult::CommandFailed(e) => sh_err!("{e}")?, _ => panic!("Unexpected result: Please report this bug."), } return Ok(()) @@ -160,7 +163,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { match dispatcher.dispatch_command(ChiselCommand::Load, &[id]).await { DispatchResult::CommandSuccess(_) => { /* Continue */ } DispatchResult::CommandFailed(e) => { - eprintln!("{e}"); + sh_err!("{e}")?; return Ok(()) } _ => panic!("Unexpected result! Please report this bug."), @@ -170,7 +173,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { if matches!(args.cmd, Some(ChiselSubcommand::View { .. })) { match dispatcher.dispatch_command(ChiselCommand::Source, &[]).await { DispatchResult::CommandSuccess(Some(source)) => { - println!("{source}"); + sh_println!("{source}")?; } _ => panic!("Unexpected result! Please report this bug."), } @@ -179,14 +182,14 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { } Some(ChiselSubcommand::ClearCache) => { match dispatcher.dispatch_command(ChiselCommand::ClearCache, &[]).await { - DispatchResult::CommandSuccess(Some(msg)) => println!("{}", msg.green()), - DispatchResult::CommandFailed(e) => eprintln!("{e}"), + DispatchResult::CommandSuccess(Some(msg)) => sh_println!("{}", msg.green())?, + DispatchResult::CommandFailed(e) => sh_err!("{e}")?, _ => panic!("Unexpected result! Please report this bug."), } return Ok(()) } Some(ChiselSubcommand::Eval { command }) => { - dispatch_repl_line(&mut dispatcher, command).await; + dispatch_repl_line(&mut dispatcher, command).await?; return Ok(()) } None => { /* No chisel subcommand present; Continue */ } @@ -205,7 +208,7 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { } // Print welcome header - println!("Welcome to Chisel! Type `{}` to show available commands.", "!help".green()); + sh_println!("Welcome to Chisel! Type `{}` to show available commands.", "!help".green())?; // Begin Rustyline loop loop { @@ -224,20 +227,20 @@ async fn main_args(args: Chisel) -> eyre::Result<()> { interrupt = false; // Dispatch and match results - let errored = dispatch_repl_line(&mut dispatcher, &line).await; + let errored = dispatch_repl_line(&mut dispatcher, &line).await?; rl.helper_mut().unwrap().set_errored(errored); } Err(ReadlineError::Interrupted) => { if interrupt { break } else { - println!("(To exit, press Ctrl+C again)"); + sh_println!("(To exit, press Ctrl+C again)")?; interrupt = true; } } Err(ReadlineError::Eof) => break, Err(err) => { - println!("Error: {err:?}"); + sh_err!("{err:?}")?; break } } @@ -262,25 +265,25 @@ impl Provider for Chisel { } /// Evaluate a single Solidity line. -async fn dispatch_repl_line(dispatcher: &mut ChiselDispatcher, line: &str) -> bool { +async fn dispatch_repl_line(dispatcher: &mut ChiselDispatcher, line: &str) -> eyre::Result { let r = dispatcher.dispatch(line).await; match &r { DispatchResult::Success(msg) | DispatchResult::CommandSuccess(msg) => { debug!(%line, ?msg, "dispatch success"); if let Some(msg) = msg { - println!("{}", msg.green()); + sh_println!("{}", msg.green())?; } }, - DispatchResult::UnrecognizedCommand(e) => eprintln!("{e}"), + DispatchResult::UnrecognizedCommand(e) => sh_err!("{e}")?, DispatchResult::SolangParserFailed(e) => { - eprintln!("{}", "Compilation error".red()); - eprintln!("{}", format!("{e:?}").red()); + sh_err!("{}", "Compilation error".red())?; + sh_eprintln!("{}", format!("{e:?}").red())?; } - 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()), + DispatchResult::FileIoError(e) => sh_err!("{}", format!("File IO - {e}").red())?, + DispatchResult::CommandFailed(msg) | DispatchResult::Failure(Some(msg)) => sh_err!("{}", msg.red())?, + DispatchResult::Failure(None) => sh_err!("Please report this bug as a github issue if it persists: https://github.com/foundry-rs/foundry/issues/new/choose")?, } - r.is_error() + Ok(r.is_error()) } /// Evaluate multiple Solidity source files contained within a @@ -291,20 +294,20 @@ async fn evaluate_prelude( ) -> eyre::Result<()> { let Some(prelude_dir) = maybe_prelude else { return Ok(()) }; if prelude_dir.is_file() { - println!("{} {}", "Loading prelude source file:".yellow(), prelude_dir.display(),); + sh_println!("{} {}", "Loading prelude source file:".yellow(), prelude_dir.display())?; load_prelude_file(dispatcher, prelude_dir).await?; - println!("{}\n", "Prelude source file loaded successfully!".green()); + sh_println!("{}\n", "Prelude source file loaded successfully!".green())?; } else { let prelude_sources = fs::files_with_ext(&prelude_dir, "sol"); let mut print_success_msg = false; for source_file in prelude_sources { print_success_msg = true; - println!("{} {}", "Loading prelude source file:".yellow(), source_file.display()); + sh_println!("{} {}", "Loading prelude source file:".yellow(), source_file.display())?; load_prelude_file(dispatcher, source_file).await?; } if print_success_msg { - println!("{}\n", "All prelude source files loaded successfully!".green()); + sh_println!("{}\n", "All prelude source files loaded successfully!".green())?; } } Ok(()) @@ -314,7 +317,7 @@ async fn evaluate_prelude( async fn load_prelude_file(dispatcher: &mut ChiselDispatcher, file: PathBuf) -> eyre::Result<()> { let prelude = fs::read_to_string(file) .wrap_err("Could not load source file. Are you sure this path is correct?")?; - dispatch_repl_line(dispatcher, &prelude).await; + dispatch_repl_line(dispatcher, &prelude).await?; Ok(()) } diff --git a/crates/chisel/src/dispatcher.rs b/crates/chisel/src/dispatcher.rs index 6805edd45e43..d69de3bf540e 100644 --- a/crates/chisel/src/dispatcher.rs +++ b/crates/chisel/src/dispatcher.rs @@ -275,7 +275,7 @@ impl ChiselDispatcher { if let Err(e) = self.session.write() { return DispatchResult::FileIoError(e.into()) } - println!("{}", "Saved current session!".green()); + let _ = sh_println!("{}", "Saved current session!".green()); } // Parse the arguments @@ -426,7 +426,7 @@ impl ChiselDispatcher { if matches!(cmd, ChiselCommand::MemDump) { // Print memory by word (0..mem.len()).step_by(32).for_each(|i| { - println!( + let _ = sh_println!( "{}: {}", format!("[0x{:02x}:0x{:02x}]", i, i + 32).yellow(), hex::encode_prefixed(&mem[i..i + 32]).cyan() @@ -435,7 +435,7 @@ impl ChiselDispatcher { } else { // Print all stack items (0..stack.len()).rev().for_each(|i| { - println!( + let _ = sh_println!( "{}: {}", format!("[{}]", stack.len() - i - 1).yellow(), format!("0x{:02x}", stack[i]).cyan() @@ -712,9 +712,9 @@ impl ChiselDispatcher { // Show console logs, if there are any let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", "Logs:".green()); + let _ = sh_println!("{}", "Logs:".green()); for log in decoded_logs { - println!(" {log}"); + let _ = sh_println!(" {log}"); } } } @@ -830,7 +830,9 @@ impl ChiselDispatcher { // Should change up how this works. match source.inspect(input).await { // Continue and print - Ok((true, Some(res))) => println!("{res}"), + Ok((true, Some(res))) => { + let _ = sh_println!("{res}"); + } Ok((true, None)) => {} // Return successfully Ok((false, res)) => { @@ -859,9 +861,9 @@ impl ChiselDispatcher { // Show console logs, if there are any let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", "Logs:".green()); + let _ = sh_println!("{}", "Logs:".green()); for log in decoded_logs { - println!(" {log}"); + let _ = sh_println!(" {log}"); } } @@ -948,12 +950,12 @@ 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!("{}", "Traces:".green()); + sh_println!("{}", "Traces:".green())?; for (kind, trace) in &mut result.traces { // Display all Setup + Execution traces. if matches!(kind, TraceKind::Setup | TraceKind::Execution) { decode_trace_arena(trace, decoder).await?; - println!("{}", render_trace_arena(trace)); + sh_println!("{}", render_trace_arena(trace))?; } } @@ -970,7 +972,7 @@ impl ChiselDispatcher { /// /// A formatted error [String]. pub fn make_error(msg: T) -> String { - format!("{} {}", format!("{CHISEL_CHAR} Chisel Error:").red(), msg.red()) + format!("{}", msg.red()) } } diff --git a/crates/chisel/src/executor.rs b/crates/chisel/src/executor.rs index 1a2267719c56..b7f3973b09d5 100644 --- a/crates/chisel/src/executor.rs +++ b/crates/chisel/src/executor.rs @@ -179,7 +179,7 @@ impl SessionSource { Ok((_, res)) => (res, Some(err)), Err(_) => { if self.config.foundry_config.verbosity >= 3 { - eprintln!("Could not inspect: {err}"); + sh_err!("Could not inspect: {err}")?; } return Ok((true, None)) } @@ -207,7 +207,7 @@ impl SessionSource { // we were unable to check the event if self.config.foundry_config.verbosity >= 3 { - eprintln!("Failed eval: {err}"); + sh_err!("Failed eval: {err}")?; } debug!(%err, %input, "failed abi encode input"); @@ -221,9 +221,9 @@ impl SessionSource { } let decoded_logs = decode_console_logs(&res.logs); if !decoded_logs.is_empty() { - println!("{}", "Logs:".green()); + sh_println!("{}", "Logs:".green())?; for log in decoded_logs { - println!(" {log}"); + sh_println!(" {log}")?; } } @@ -1709,12 +1709,12 @@ mod tests { match solc { Ok((v, solc)) => { // successfully installed - eprintln!("found installed Solc v{v} @ {}", solc.solc.display()); + let _ = sh_println!("found installed Solc v{v} @ {}", solc.solc.display()); break } Err(e) => { // try reinstalling - eprintln!("error while trying to re-install Solc v{version}: {e}"); + let _ = sh_err!("error while trying to re-install Solc v{version}: {e}"); let solc = Solc::blocking_install(&version.parse().unwrap()); if solc.map_err(SolcError::from).is_ok() { *is_preinstalled = true; @@ -1753,7 +1753,7 @@ mod tests { if let Err(e) = s.parse() { for err in e { - eprintln!("{}:{}: {}", err.loc.start(), err.loc.end(), err.message); + let _ = sh_eprintln!("{}:{}: {}", err.loc.start(), err.loc.end(), err.message); } let source = s.to_repl_source(); panic!("could not parse input:\n{source}") diff --git a/crates/chisel/src/lib.rs b/crates/chisel/src/lib.rs index 9e7dcc9fb829..ccae2db2ddbe 100644 --- a/crates/chisel/src/lib.rs +++ b/crates/chisel/src/lib.rs @@ -1,6 +1,9 @@ #![doc = include_str!("../README.md")] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +#[macro_use] +extern crate foundry_common; + pub mod dispatcher; pub mod cmd; diff --git a/crates/chisel/src/session_source.rs b/crates/chisel/src/session_source.rs index f80761e0de86..128873167a44 100644 --- a/crates/chisel/src/session_source.rs +++ b/crates/chisel/src/session_source.rs @@ -98,7 +98,7 @@ impl SessionSourceConfig { SolcReq::Version(version) } else { if !self.foundry_config.offline { - print!("{}", "No solidity versions installed! ".green()); + sh_print!("{}", "No solidity versions installed! ".green())?; } // use default SolcReq::Version(Version::new(0, 8, 19)) @@ -112,7 +112,7 @@ impl SessionSourceConfig { if self.foundry_config.offline { eyre::bail!("can't install missing solc {version} in offline mode") } - println!("{}", format!("Installing solidity version {version}...").green()); + sh_println!("{}", format!("Installing solidity version {version}...").green())?; Solc::blocking_install(&version)? }; Ok(solc)