Skip to content

Commit

Permalink
feat: add foundry_common::shell to unify log behavior (#9109)
Browse files Browse the repository at this point in the history
* replace existing shell::println, add macros

* finish replacing shell::println

* remove p_println

* remove redundant quiet or silent variables

* install global shells in binaries

* CastArgs -> Cast, Cast -> CastInstance

* fix tests, always initialize Mutex::new(Shell::new()) on initial access, for some reason cfg!(test) path is not handled when running with tokio tests

* revert .quiet(true)

* add back quiet

* undo CastInstance -> Cast, Cast -> CastArgs

* add global --json format

* use global --json flag

* revert sequence / multisequence save silent mode

* fix failing tests

* fix tests

* fix tests

* replace cli_warn with sh_warn

* use shell json directly instead of passing in

* clean up, document print modes in respect to --quiet flag

* group shell options under display options

* revert global --json flag

* remove redundant import

* fix: quiet

* remove faulty argument conflict test as there is no way to currently assert a conflict between global and local args without custom reject at runtime

* add back conflicts_with quiet flag, global args w/ conflicts_with works fine

* remove yellow()

* Apply suggestions from code review

- update dependencies
- use default

Co-authored-by: DaniPopes <[email protected]>

* fix deprecated terminal_size method

* revert quiet flag, fix os:fd import for windows

* add replacing tests, add back quiet conflicting flag

* make output windows compatible

* to avoid visual regression, style warning message content in yellow, error message content in red - both not bold

* fix docs links

* fix junit throwing mixed content on warnings, avoid modifying global verbosity

* remove set_verbosity shell helper, redundant

* revert default .expect on printing, prefer passing. revert message style formatting - no longer style the message

* fix doc test, fix formatting

* fix merge issues

---------

Co-authored-by: DaniPopes <[email protected]>
  • Loading branch information
zerosnacks and DaniPopes authored Oct 23, 2024
1 parent 7b118fa commit cd71da4
Show file tree
Hide file tree
Showing 63 changed files with 1,267 additions and 765 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

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

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ alloy-trie = "0.6.0"
op-alloy-rpc-types = "0.5.0"
op-alloy-consensus = "0.5.0"

## cli
anstream = "0.6.15"
anstyle = "1.0.8"
terminal_size = "0.4"

# macros
proc-macro2 = "1.0.82"
quote = "1.0"
Expand Down
8 changes: 8 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,11 @@ msrv = "1.80"
# bytes::Bytes is included by default and alloy_primitives::Bytes is a wrapper around it,
# so it is safe to ignore it as well
ignore-interior-mutability = ["bytes::Bytes", "alloy_primitives::Bytes"]

# disallowed-macros = [
# # See `foundry_common::shell`
# { path = "std::print", reason = "use `sh_print` or similar macros instead" },
# { path = "std::eprint", reason = "use `sh_eprint` or similar macros instead" },
# { path = "std::println", reason = "use `sh_println` or similar macros instead" },
# { path = "std::eprintln", reason = "use `sh_eprintln` or similar macros instead" },
# ]
16 changes: 14 additions & 2 deletions crates/anvil/src/anvil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

use anvil::cmd::NodeArgs;
use clap::{CommandFactory, Parser, Subcommand};
use foundry_cli::utils;
use eyre::Result;
use foundry_cli::{opts::ShellOpts, utils};

#[cfg(all(feature = "jemalloc", unix))]
#[global_allocator]
Expand All @@ -17,6 +18,9 @@ pub struct Anvil {

#[command(subcommand)]
pub cmd: Option<AnvilSubcommand>,

#[clap(flatten)]
pub shell: ShellOpts,
}

#[derive(Subcommand)]
Expand All @@ -33,10 +37,18 @@ pub enum AnvilSubcommand {
GenerateFigSpec,
}

fn main() -> eyre::Result<()> {
fn main() {
if let Err(err) = run() {
let _ = foundry_common::Shell::get().error(&err);
std::process::exit(1);
}
}

fn run() -> Result<()> {
utils::load_dotenv();

let mut args = Anvil::parse();
args.shell.shell().set();
args.node.evm_opts.resolve_rpc_alias();

if let Some(cmd) = &args.cmd {
Expand Down
5 changes: 0 additions & 5 deletions crates/anvil/src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@ pub struct NodeArgs {
#[arg(long)]
pub derivation_path: Option<String>,

/// Don't print anything on startup and don't print logs
#[arg(long)]
pub silent: bool,

/// The EVM hardfork to use.
///
/// Choose the hardfork by name, e.g. `shanghai`, `paris`, `london`, etc...
Expand Down Expand Up @@ -258,7 +254,6 @@ impl NodeArgs {
.with_storage_caching(self.evm_opts.no_storage_caching)
.with_server_config(self.server_config)
.with_host(self.host)
.set_silent(self.silent)
.set_config_out(self.config_out)
.with_chain_id(self.evm_opts.chain_id)
.with_transaction_order(self.order)
Expand Down
24 changes: 3 additions & 21 deletions crates/anvil/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,6 @@ pub struct NodeConfig {
pub port: u16,
/// maximum number of transactions in a block
pub max_transactions: usize,
/// don't print anything on startup
pub silent: bool,
/// url of the rpc server that should be used for any rpc calls
pub eth_rpc_url: Option<String>,
/// pins the block number or transaction hash for the state fork
Expand Down Expand Up @@ -394,7 +392,7 @@ impl NodeConfig {
/// random, free port by setting it to `0`
#[doc(hidden)]
pub fn test() -> Self {
Self { enable_tracing: true, silent: true, port: 0, ..Default::default() }
Self { enable_tracing: true, port: 0, ..Default::default() }
}

/// Returns a new config which does not initialize any accounts on node startup.
Expand Down Expand Up @@ -429,7 +427,6 @@ impl Default for NodeConfig {
port: NODE_PORT,
// TODO make this something dependent on block capacity
max_transactions: 1_000,
silent: false,
eth_rpc_url: None,
fork_choice: None,
account_generator: None,
Expand Down Expand Up @@ -732,18 +729,6 @@ impl NodeConfig {
self
}

/// Makes the node silent to not emit anything on stdout
#[must_use]
pub fn silent(self) -> Self {
self.set_silent(true)
}

#[must_use]
pub fn set_silent(mut self, silent: bool) -> Self {
self.silent = silent;
self
}

/// Sets the ipc path to use
///
/// Note: this is a double Option for
Expand All @@ -763,7 +748,7 @@ impl NodeConfig {
self
}

/// Makes the node silent to not emit anything on stdout
/// Disables storage caching
#[must_use]
pub fn no_storage_caching(self) -> Self {
self.with_storage_caching(true)
Expand Down Expand Up @@ -921,11 +906,8 @@ impl NodeConfig {
)
.expect("Failed writing json");
}
if self.silent {
return;
}

println!("{}", self.as_string(fork))
let _ = sh_println!("{}", self.as_string(fork));
}

/// Returns the path where the cache file should be stored
Expand Down
38 changes: 21 additions & 17 deletions crates/anvil/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]

#[macro_use]
extern crate tracing;

use crate::{
eth::{
backend::{info::StorageInfo, mem},
Expand All @@ -23,7 +20,10 @@ use crate::{
use alloy_primitives::{Address, U256};
use alloy_signer_local::PrivateKeySigner;
use eth::backend::fork::ClientFork;
use foundry_common::provider::{ProviderBuilder, RetryProvider};
use foundry_common::{
provider::{ProviderBuilder, RetryProvider},
shell,
};
use foundry_evm::revm;
use futures::{FutureExt, TryFutureExt};
use parking_lot::Mutex;
Expand Down Expand Up @@ -74,6 +74,12 @@ mod tasks;
#[cfg(feature = "cmd")]
pub mod cmd;

#[macro_use]
extern crate foundry_common;

#[macro_use]
extern crate tracing;

/// Creates the node and runs the server.
///
/// Returns the [EthApi] that can be used to interact with the node and the [JoinHandle] of the
Expand Down Expand Up @@ -125,7 +131,7 @@ pub async fn spawn(config: NodeConfig) -> (EthApi, NodeHandle) {
/// ```
pub async fn try_spawn(mut config: NodeConfig) -> io::Result<(EthApi, NodeHandle)> {
let logger = if config.enable_tracing { init_tracing() } else { Default::default() };
logger.set_enabled(!config.silent);
logger.set_enabled(!shell::is_quiet());

let backend = Arc::new(config.setup().await);

Expand Down Expand Up @@ -292,19 +298,17 @@ impl NodeHandle {
/// Prints the launch info.
pub(crate) fn print(&self, fork: Option<&ClientFork>) {
self.config.print(fork);
if !self.config.silent {
if let Some(ipc_path) = self.ipc_path() {
println!("IPC path: {ipc_path}");
}
println!(
"Listening on {}",
self.addresses
.iter()
.map(|addr| { addr.to_string() })
.collect::<Vec<String>>()
.join(", ")
);
if let Some(ipc_path) = self.ipc_path() {
let _ = sh_println!("IPC path: {ipc_path}");
}
let _ = sh_println!(
"Listening on {}",
self.addresses
.iter()
.map(|addr| { addr.to_string() })
.collect::<Vec<String>>()
.join(", ")
);
}

/// The address of the launched server.
Expand Down
8 changes: 3 additions & 5 deletions crates/anvil/tests/it/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ pub fn fork_config() -> NodeConfig {
NodeConfig::test()
.with_eth_rpc_url(Some(rpc::next_http_archive_rpc_endpoint()))
.with_fork_block_number(Some(BLOCK_NUMBER))
.silent()
}

#[tokio::test(flavor = "multi_thread")]
Expand Down Expand Up @@ -829,10 +828,9 @@ async fn test_fork_init_base_fee() {

#[tokio::test(flavor = "multi_thread")]
async fn test_reset_fork_on_new_blocks() {
let (api, handle) = spawn(
NodeConfig::test().with_eth_rpc_url(Some(rpc::next_http_archive_rpc_endpoint())).silent(),
)
.await;
let (api, handle) =
spawn(NodeConfig::test().with_eth_rpc_url(Some(rpc::next_http_archive_rpc_endpoint())))
.await;

let anvil_provider = handle.http_provider();
let endpoint = next_http_rpc_endpoint();
Expand Down
5 changes: 4 additions & 1 deletion crates/cast/bin/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use alloy_primitives::{Address, B256, U256};
use alloy_rpc_types::BlockId;
use clap::{Parser, Subcommand, ValueHint};
use eyre::Result;
use foundry_cli::opts::{EtherscanOpts, RpcOpts};
use foundry_cli::opts::{EtherscanOpts, RpcOpts, ShellOpts};
use foundry_common::ens::NameOrAddress;
use std::{path::PathBuf, str::FromStr};

Expand All @@ -32,6 +32,9 @@ const VERSION_MESSAGE: &str = concat!(
pub struct Cast {
#[command(subcommand)]
pub cmd: CastSubcommand,

#[clap(flatten)]
pub shell: ShellOpts,
}

#[derive(Subcommand)]
Expand Down
2 changes: 1 addition & 1 deletion crates/cast/bin/cmd/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub struct RunArgs {
/// Executes the transaction only with the state from the previous block.
///
/// May result in different results than the live execution!
#[arg(long, short)]
#[arg(long)]
quick: bool,

/// Prints the full address of the contract.
Expand Down
4 changes: 2 additions & 2 deletions crates/cast/bin/cmd/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use foundry_cli::{
opts::{EthereumOpts, TransactionOpts},
utils,
};
use foundry_common::{cli_warn, ens::NameOrAddress};
use foundry_common::ens::NameOrAddress;
use foundry_config::Config;
use std::{path::PathBuf, str::FromStr};

Expand Down Expand Up @@ -145,7 +145,7 @@ impl SendTxArgs {
// switch chain if current chain id is not the same as the one specified in the
// config
if config_chain_id != current_chain_id {
cli_warn!("Switching to chain {}", config_chain);
sh_warn!("Switching to chain {}", config_chain)?;
provider
.raw_request(
"wallet_switchEthereumChain".into(),
Expand Down
16 changes: 14 additions & 2 deletions crates/cast/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use cast::{Cast, SimpleCast};
use clap::{CommandFactory, Parser};
use clap_complete::generate;
use eyre::Result;
use foundry_cli::{handler, prompt, stdin, utils};
use foundry_cli::{handler, utils};
use foundry_common::{
abi::get_event,
ens::{namehash, ProviderEnsExt},
Expand All @@ -19,6 +19,7 @@ use foundry_common::{
import_selectors, parse_signatures, pretty_calldata, ParsedSignatures, SelectorImportData,
SelectorType,
},
stdin,
};
use foundry_config::Config;
use std::time::Instant;
Expand All @@ -29,16 +30,27 @@ pub mod tx;

use args::{Cast as CastArgs, CastSubcommand, ToBaseArgs};

#[macro_use]
extern crate foundry_common;

#[cfg(all(feature = "jemalloc", unix))]
#[global_allocator]
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

fn main() -> Result<()> {
fn main() {
if let Err(err) = run() {
let _ = foundry_common::Shell::get().error(&err);
std::process::exit(1);
}
}

fn run() -> Result<()> {
handler::install();
utils::load_dotenv();
utils::subscriber();
utils::enable_paint();
let args = CastArgs::parse();
args.shell.shell().set();
main_args(args)
}

Expand Down
Loading

0 comments on commit cd71da4

Please sign in to comment.