Skip to main content

foundry_cli/opts/
global.rs

1use clap::{ArgAction, Parser};
2use foundry_common::{
3    shell::{ColorChoice, OutputFormat, OutputMode, Shell, Verbosity},
4    version::{IS_NIGHTLY_VERSION, NIGHTLY_VERSION_WARNING_MESSAGE},
5};
6use foundry_config::{Config, figment::Profile};
7use foundry_evm::EVM_THREAD_STACK_SIZE;
8use serde::{Deserialize, Serialize};
9
10/// Global arguments for the CLI.
11#[derive(Clone, Debug, Default, Serialize, Deserialize, Parser)]
12pub struct GlobalArgs {
13    /// Verbosity level of the log messages.
14    ///
15    /// Pass multiple times to increase the verbosity (e.g. -v, -vv, -vvv).
16    ///
17    /// Depending on the context the verbosity levels have different meanings.
18    ///
19    /// For example, the verbosity levels of the EVM are:
20    /// - 2 (-vv): Print logs for all tests.
21    /// - 3 (-vvv): Print execution traces for failing tests.
22    /// - 4 (-vvvv): Print execution traces for all tests, and setup traces for failing tests.
23    /// - 5 (-vvvvv): Print execution and setup traces for all tests, including storage changes and
24    ///   backtraces with line numbers.
25    #[arg(help_heading = "Display options", global = true, short, long, verbatim_doc_comment, conflicts_with = "quiet", action = ArgAction::Count)]
26    verbosity: Verbosity,
27
28    /// Do not print log messages.
29    #[arg(help_heading = "Display options", global = true, short, long, alias = "silent")]
30    quiet: bool,
31
32    /// Format log messages as JSON.
33    #[arg(help_heading = "Display options", global = true, long, alias = "format-json", conflicts_with_all = &["quiet", "color"])]
34    json: bool,
35
36    /// Format log messages as Markdown.
37    #[arg(
38        help_heading = "Display options",
39        global = true,
40        long,
41        alias = "markdown",
42        conflicts_with = "json"
43    )]
44    md: bool,
45
46    /// The color of the log messages.
47    #[arg(help_heading = "Display options", global = true, long, value_enum)]
48    color: Option<ColorChoice>,
49
50    /// Number of threads to use. Specifying 0 defaults to the number of logical cores.
51    #[arg(global = true, long, short = 'j', visible_alias = "jobs")]
52    threads: Option<usize>,
53
54    /// The configuration profile to use.
55    #[arg(global = true, long, value_name = "PROFILE")]
56    profile: Option<Profile>,
57}
58
59impl GlobalArgs {
60    /// Check if `--markdown-help` was passed and print CLI reference as Markdown, then exit.
61    ///
62    /// This must be called **before** parsing arguments, since commands with required
63    /// subcommands would fail parsing before the flag is checked.
64    pub fn check_markdown_help<C: clap::CommandFactory>() {
65        if std::env::args_os().take_while(|a| a != "--").any(|a| a == "--markdown-help") {
66            // Pre-parse: `Shell` is not initialized yet, so `sh_*` is unavailable.
67            foundry_cli_markdown::print_help_markdown::<C>();
68            std::process::exit(0);
69        }
70    }
71
72    /// Initialize the global options.
73    pub fn init(&self) -> eyre::Result<()> {
74        if let Some(profile) = &self.profile
75            && let Err(selected) = Config::try_set_selected_profile(profile.clone())
76        {
77            eyre::bail!(
78                "configuration profile was already initialized as `{selected}`, cannot select \
79                 `{profile}`"
80            );
81        }
82        let _ = Config::selected_profile();
83
84        // Set the global shell.
85        let shell = self.shell();
86        // Argument takes precedence over the env var global color choice.
87        match shell.color_choice() {
88            ColorChoice::Auto => {}
89            ColorChoice::Always => yansi::enable(),
90            ColorChoice::Never => yansi::disable(),
91        }
92        shell.set();
93
94        if self.threads.is_some() {
95            self.force_init_thread_pool()?;
96        } else {
97            // The pool may already exist when the CLI runs in-process, which keeps its stack size.
98            let _ = init_thread_pool(0);
99        }
100
101        // Display a warning message if the current version is not stable.
102        if IS_NIGHTLY_VERSION
103            && !self.json
104            && std::env::var_os("FOUNDRY_DISABLE_NIGHTLY_WARNING").is_none()
105        {
106            let _ = sh_warn!("{}", NIGHTLY_VERSION_WARNING_MESSAGE);
107        }
108
109        Ok(())
110    }
111
112    /// Create a new shell instance.
113    pub fn shell(&self) -> Shell {
114        let mode = match self.quiet {
115            true => OutputMode::Quiet,
116            false => OutputMode::Normal,
117        };
118        let color = self.json.then_some(ColorChoice::Never).or(self.color).unwrap_or_default();
119        let format = if self.json {
120            OutputFormat::Json
121        } else if self.md {
122            OutputFormat::Markdown
123        } else {
124            OutputFormat::Text
125        };
126
127        Shell::new_with(format, mode, color, self.verbosity)
128    }
129
130    /// Initialize the global thread pool.
131    pub fn force_init_thread_pool(&self) -> eyre::Result<()> {
132        init_thread_pool(self.threads.unwrap_or(0))
133    }
134
135    /// Creates a new tokio runtime.
136    #[track_caller]
137    pub fn tokio_runtime(&self) -> tokio::runtime::Runtime {
138        let mut builder = tokio::runtime::Builder::new_multi_thread();
139        if let Some(threads) = self.threads
140            && threads > 0
141        {
142            builder.worker_threads(threads);
143        }
144        builder
145            .thread_stack_size(EVM_THREAD_STACK_SIZE)
146            .enable_all()
147            .build()
148            .expect("failed to create tokio runtime")
149    }
150
151    /// Creates a new tokio runtime and blocks on the future.
152    #[track_caller]
153    pub fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
154        self.tokio_runtime().block_on(future)
155    }
156}
157
158/// Initialize the global thread pool.
159pub fn init_thread_pool(threads: usize) -> eyre::Result<()> {
160    rayon::ThreadPoolBuilder::new()
161        .thread_name(|i| format!("foundry-{i}"))
162        .num_threads(threads)
163        .stack_size(EVM_THREAD_STACK_SIZE)
164        .build_global()?;
165    Ok(())
166}