1use crate::{
2 cmd::{cache::CacheSubcommands, watch},
3 opts::{Forge, ForgeSubcommand},
4};
5use clap::{CommandFactory, Parser};
6use clap_complete::generate;
7use eyre::Result;
8use foundry_cli::utils;
9use foundry_common::{sh_warn, shell};
10use foundry_evm::inspectors::cheatcodes::{ForgeContext, set_execution_context};
11
12pub fn run() -> Result<()> {
14 foundry_cli::opts::GlobalArgs::check_markdown_help::<Forge>();
15
16 let warnings = setup()?;
17
18 let args = Forge::parse();
19 args.global.init()?;
20 for warning in warnings {
21 let _ = foundry_common::sh_warn!("{warning}");
22 }
23
24 run_command(args)
25}
26
27pub fn setup() -> Result<Vec<String>> {
29 let warnings = utils::common_setup();
30 utils::subscriber();
31
32 Ok(warnings)
33}
34
35pub fn run_command(args: Forge) -> Result<()> {
37 let context = match &args.cmd {
39 ForgeSubcommand::Test(_) | ForgeSubcommand::Fuzz(_) => ForgeContext::Test,
40 ForgeSubcommand::Coverage(_) => ForgeContext::Coverage,
41 ForgeSubcommand::Snapshot(_) => ForgeContext::Snapshot,
42 ForgeSubcommand::Script(cmd) => {
43 if cmd.broadcast {
44 ForgeContext::ScriptBroadcast
45 } else if cmd.resume {
46 ForgeContext::ScriptResume
47 } else {
48 ForgeContext::ScriptDryRun
49 }
50 }
51 _ => ForgeContext::Unknown,
52 };
53 set_execution_context(context);
54
55 let global = &args.global;
56
57 match args.cmd {
59 ForgeSubcommand::Test(cmd) => {
60 if cmd.is_watch() {
61 block_on_watch(global, watch::watch_test(cmd))
62 } else {
63 let silent = cmd.junit || shell::is_json();
64 let outcome = global.block_on(cmd.run())?;
65 outcome.ensure_ok(silent)
66 }
67 }
68 ForgeSubcommand::Fuzz(cmd) => {
69 let silent = cmd.is_junit() || shell::is_json();
70 let outcome = global.block_on(cmd.run())?;
71 outcome.ensure_ok(silent)
72 }
73 ForgeSubcommand::Properties(cmd) => cmd.run(),
74 ForgeSubcommand::Script(cmd) => block_on_command(global, || cmd.run_script()),
75 ForgeSubcommand::Coverage(cmd) => {
76 if cmd.is_watch() {
77 block_on_watch(global, watch::watch_coverage(cmd))
78 } else {
79 global.block_on(cmd.run())
80 }
81 }
82 ForgeSubcommand::Bind(cmd) => cmd.run(),
83 ForgeSubcommand::Build { args, locked } => {
84 if args.is_watch() {
85 block_on_watch(global, watch::watch_build(args))
86 } else {
87 global.block_on(args.run(locked)).map(drop)
88 }
89 }
90 ForgeSubcommand::VerifyContract(mut args) => {
91 args.print_submission_result_to_stdout = true;
92 global.block_on(args.run())
93 }
94 ForgeSubcommand::VerifyCheck(args) => global.block_on(args.run()),
95 ForgeSubcommand::VerifyBytecode(cmd) => global.block_on(cmd.run()),
96 ForgeSubcommand::Clone(cmd) => global.block_on(cmd.run()),
97 ForgeSubcommand::Cache(cmd) => match cmd.sub {
98 CacheSubcommands::Clean(cmd) => cmd.run(),
99 CacheSubcommands::Ls(cmd) => cmd.run(),
100 },
101 ForgeSubcommand::Create(cmd) => global.block_on(cmd.run()),
102 ForgeSubcommand::Update(cmd) => cmd.run(),
103 ForgeSubcommand::Install(cmd) => global.block_on(cmd.run()),
104 ForgeSubcommand::Reinit(cmd) => cmd.run(),
105 ForgeSubcommand::Remove(cmd) => cmd.run(),
106 ForgeSubcommand::Remappings(cmd) => cmd.run(),
107 ForgeSubcommand::Init(cmd) => global.block_on(cmd.run()),
108 ForgeSubcommand::Completions { shell } => {
109 generate(shell, &mut Forge::command(), "forge", &mut std::io::stdout());
110 Ok(())
111 }
112 ForgeSubcommand::Clean { root } => {
113 let config = utils::load_config_with_root(root.as_deref())?;
114 let project = config.project()?;
115 for warning in config.cleanup(&project)? {
116 let _ = sh_warn!("{warning}");
117 }
118 Ok(())
119 }
120 ForgeSubcommand::Snapshot(cmd) => {
121 if cmd.is_watch() {
122 block_on_watch(global, watch::watch_gas_snapshot(cmd))
123 } else {
124 global.block_on(cmd.run())
125 }
126 }
127 ForgeSubcommand::Fmt(cmd) => {
128 if cmd.is_watch() {
129 block_on_watch(global, watch::watch_fmt(cmd))
130 } else {
131 cmd.run()
132 }
133 }
134 ForgeSubcommand::Config(cmd) => cmd.run(),
135 ForgeSubcommand::Flatten(cmd) => cmd.run(),
136 ForgeSubcommand::Inspect(cmd) => cmd.run(),
137 ForgeSubcommand::Tree(cmd) => cmd.run(),
138 ForgeSubcommand::Geiger(cmd) => global.block_on(cmd.run()),
139 ForgeSubcommand::Exploit(cmd) => global.block_on(cmd.run()),
140 ForgeSubcommand::Equivalence(cmd) => global.block_on(cmd.run()),
141 ForgeSubcommand::Doc(cmd) => {
142 if cmd.is_watch() {
143 block_on_watch(global, watch::watch_doc(cmd))
144 } else {
145 global.block_on(cmd.run())
146 }
147 }
148 ForgeSubcommand::Selectors { command } => global.block_on(command.run()),
149 ForgeSubcommand::Compiler(cmd) => cmd.run(),
150 ForgeSubcommand::Soldeer(cmd) => global.block_on(cmd.run()),
151 ForgeSubcommand::Eip712(cmd) => cmd.run(),
152 ForgeSubcommand::BindJson(cmd) => cmd.run(),
153 ForgeSubcommand::Lint(cmd) => global.block_on(cmd.run()),
154 ForgeSubcommand::Lsp(cmd) => global.block_on(crate::cmd::lsp::run(cmd)),
155 }
156}
157
158fn block_on_command<Fut>(
159 global: &foundry_cli::opts::GlobalArgs,
160 make_future: impl FnOnce() -> Fut,
161) -> Fut::Output
162where
163 Fut: std::future::Future,
164{
165 global.block_on(make_future())
166}
167
168fn block_on_watch<F: std::future::Future>(
170 global: &foundry_cli::opts::GlobalArgs,
171 future: F,
172) -> F::Output {
173 let runtime = global.tokio_runtime();
174 let result = runtime.block_on(future);
175 runtime.shutdown_timeout(std::time::Duration::from_secs(1));
178 result
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use std::{
185 sync::mpsc::{self, TryRecvError},
186 time::Duration,
187 };
188
189 #[test]
190 fn watch_shutdown_does_not_wait_for_blocking_reader() {
191 let (release_tx, release_rx) = mpsc::channel();
192 let (finished_tx, finished_rx) = mpsc::channel();
193 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
194
195 let result = block_on_watch(&Default::default(), async move {
196 tokio::task::spawn_blocking(move || {
197 started_tx.send(()).unwrap();
198 let _ = release_rx.recv_timeout(Duration::from_secs(10));
200 finished_tx.send(()).unwrap();
201 });
202 started_rx.await.unwrap();
203 Err::<(), _>("watch failed")
204 });
205
206 assert_eq!(result, Err("watch failed"));
207 assert_eq!(finished_rx.try_recv(), Err(TryRecvError::Empty));
208 release_tx.send(()).unwrap();
209 finished_rx.recv_timeout(Duration::from_secs(5)).unwrap();
210 }
211}