Skip to content

Commit

Permalink
chore(chisel): enforce common::shell for chisel binary (#9177)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
zerosnacks authored Oct 24, 2024
1 parent 216b60a commit 6b4ad0d
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 45 deletions.
53 changes: 28 additions & 25 deletions crates/chisel/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(())
Expand All @@ -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."),
Expand All @@ -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."),
}
Expand All @@ -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 */ }
Expand All @@ -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 {
Expand All @@ -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
}
}
Expand All @@ -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<bool> {
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
Expand All @@ -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(())
Expand All @@ -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(())
}

Expand Down
24 changes: 13 additions & 11 deletions crates/chisel/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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}");
}
}
}
Expand Down Expand Up @@ -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)) => {
Expand Down Expand Up @@ -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}");
}
}

Expand Down Expand Up @@ -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))?;
}
}

Expand All @@ -970,7 +972,7 @@ impl ChiselDispatcher {
///
/// A formatted error [String].
pub fn make_error<T: std::fmt::Display>(msg: T) -> String {
format!("{} {}", format!("{CHISEL_CHAR} Chisel Error:").red(), msg.red())
format!("{}", msg.red())
}
}

Expand Down
14 changes: 7 additions & 7 deletions crates/chisel/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down Expand Up @@ -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");
Expand All @@ -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}")?;
}
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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}")
Expand Down
3 changes: 3 additions & 0 deletions crates/chisel/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
4 changes: 2 additions & 2 deletions crates/chisel/src/session_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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)
Expand Down

0 comments on commit 6b4ad0d

Please sign in to comment.