Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(chisel): enforce common::shell for chisel binary #9177

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 28 additions & 26 deletions crates/chisel/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ use foundry_config::{
use rustyline::{config::Configurer, error::ReadlineError, Editor};
use std::path::PathBuf;
use tracing::debug;
use yansi::Paint;

#[macro_use]
extern crate foundry_common;

#[cfg(all(feature = "jemalloc", unix))]
#[global_allocator]
Expand Down Expand Up @@ -148,9 +150,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 +162,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 +172,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 +181,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}")?,
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 +207,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")?;
Copy link
Member Author

@zerosnacks zerosnacks Oct 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @DaniPopes in #9109 you noted messages ought not to be painted in color except for the warn / error keyword, is removing this here correct? Where yellow is used for warnings we use sh_warn!, for red (if an error) we use sh_err! and success (or used in an random way) should not be painted green, correct?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah but that's for err and warn, and here it's in a REPL too, so it's fine


// Begin Rustyline loop
loop {
Expand All @@ -224,20 +226,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 +264,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}")?;
}
},
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")?;
sh_eprintln!("{e:?}")?;
}
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!("{e}")?,
DispatchResult::CommandFailed(msg) | DispatchResult::Failure(Some(msg)) => sh_err!("{msg}")?,
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 +293,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: {}", 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!")?;
} 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: {}", 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!")?;
}
}
Ok(())
Expand All @@ -314,7 +316,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 @@ -828,7 +828,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 @@ -857,9 +859,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 @@ -946,12 +948,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 @@ -968,7 +970,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}")
}
}

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
Loading