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

feat: add foundry_common::shell to unify log behavior #9109

Merged
merged 46 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
2b7bd49
replace existing shell::println, add macros
zerosnacks Oct 4, 2024
9b6d7bf
finish replacing shell::println
zerosnacks Oct 4, 2024
95569c6
remove p_println
zerosnacks Oct 4, 2024
4113fbd
remove redundant quiet or silent variables
zerosnacks Oct 4, 2024
74b2349
install global shells in binaries
zerosnacks Oct 4, 2024
757085a
CastArgs -> Cast, Cast -> CastInstance
zerosnacks Oct 4, 2024
8b525c2
fix tests, always initialize Mutex::new(Shell::new()) on initial acce…
zerosnacks Oct 4, 2024
9544177
merge in master
zerosnacks Oct 11, 2024
37463fd
revert .quiet(true)
zerosnacks Oct 11, 2024
43c9c07
add back quiet
zerosnacks Oct 11, 2024
df1968c
Merge branch 'master' into zerosnacks/common-shell-2
zerosnacks Oct 14, 2024
b3bf6f4
undo CastInstance -> Cast, Cast -> CastArgs
zerosnacks Oct 14, 2024
69603dd
add global --json format
zerosnacks Oct 15, 2024
bffc2bb
use global --json flag
zerosnacks Oct 15, 2024
aa14ec8
Merge branch 'master' into zerosnacks/common-shell-2
zerosnacks Oct 15, 2024
59cb879
revert sequence / multisequence save silent mode
zerosnacks Oct 15, 2024
59da13e
fix failing tests
zerosnacks Oct 15, 2024
624604a
merge in master
zerosnacks Oct 15, 2024
4c37387
fix tests
zerosnacks Oct 15, 2024
133180b
fix tests
zerosnacks Oct 15, 2024
06c5818
replace cli_warn with sh_warn
zerosnacks Oct 15, 2024
9c89ce7
use shell json directly instead of passing in
zerosnacks Oct 15, 2024
05571e1
clean up, document print modes in respect to --quiet flag
zerosnacks Oct 15, 2024
b359478
group shell options under display options
zerosnacks Oct 15, 2024
ae0e62e
revert global --json flag
zerosnacks Oct 16, 2024
b70d7e4
remove redundant import
zerosnacks Oct 16, 2024
d002fdf
fix: quiet
zerosnacks Oct 16, 2024
236dd18
remove faulty argument conflict test as there is no way to currently …
zerosnacks Oct 16, 2024
e5044f1
add back conflicts_with quiet flag, global args w/ conflicts_with wor…
zerosnacks Oct 16, 2024
5755a3c
remove yellow()
zerosnacks Oct 16, 2024
e94fa11
Apply suggestions from code review
zerosnacks Oct 16, 2024
71372a9
Merge branch 'zerosnacks/common-shell-2' of github.com:foundry-rs/fou…
zerosnacks Oct 16, 2024
4415957
fix deprecated terminal_size method
zerosnacks Oct 16, 2024
488a436
revert quiet flag, fix os:fd import for windows
zerosnacks Oct 16, 2024
7682ac0
add replacing tests, add back quiet conflicting flag
zerosnacks Oct 16, 2024
0609af9
make output windows compatible
zerosnacks Oct 16, 2024
d2c81fb
to avoid visual regression, style warning message content in yellow, …
zerosnacks Oct 17, 2024
c4aa9c5
fix docs links
zerosnacks Oct 17, 2024
765daee
Merge branch 'master' into zerosnacks/common-shell-2
zerosnacks Oct 17, 2024
3f9cd29
Merge branch 'master' into zerosnacks/common-shell-2
zerosnacks Oct 17, 2024
82c2da2
fix junit throwing mixed content on warnings, avoid modifying global …
zerosnacks Oct 17, 2024
03a11d7
remove set_verbosity shell helper, redundant
zerosnacks Oct 17, 2024
73c2112
revert default .expect on printing, prefer passing. revert message st…
zerosnacks Oct 21, 2024
c4f8d4d
fix doc test, fix formatting
zerosnacks Oct 21, 2024
6f6b280
fix merge conflict
zerosnacks Oct 23, 2024
efce06a
fix merge issues
zerosnacks Oct 23, 2024
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
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.3.3"
op-alloy-consensus = "0.3.3"

## 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)]
zerosnacks marked this conversation as resolved.
Show resolved Hide resolved
#[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
Loading