Skip to main content

foundry_cli/utils/
mod.rs

1use alloy_json_abi::JsonAbi;
2use alloy_primitives::{Address, U256, map::HashMap};
3use alloy_provider::{Network, Provider, RootProvider, network::AnyNetwork};
4use eyre::{ContextCompat, Result, WrapErr};
5use foundry_common::{provider::ProviderBuilder, shell};
6use foundry_config::{Chain, Config};
7use itertools::Itertools;
8use path_slash::PathExt;
9use regex::Regex;
10use serde::de::DeserializeOwned;
11use std::{
12    collections::{BTreeMap, BTreeSet},
13    ffi::{OsStr, OsString},
14    path::{Path, PathBuf},
15    process::{Command, Output, Stdio},
16    str::FromStr,
17    sync::{LazyLock, OnceLock},
18    time::{Duration, SystemTime, UNIX_EPOCH},
19};
20use tracing_subscriber::{EnvFilter, prelude::*, reload};
21
22mod cmd;
23pub use cmd::*;
24
25mod suggestions;
26pub use suggestions::*;
27
28mod abi;
29pub use abi::*;
30
31mod allocator;
32pub use allocator::*;
33
34mod tempo;
35pub use tempo::*;
36
37// reexport all `foundry_config::utils`
38#[doc(hidden)]
39pub use foundry_config::utils::*;
40
41/// Deterministic fuzzer seed used for gas snapshots and coverage reports.
42///
43/// The keccak256 hash of "foundry rulez"
44pub const STATIC_FUZZ_SEED: [u8; 32] = [
45    0x01, 0x00, 0xfa, 0x69, 0xa5, 0xf1, 0x71, 0x0a, 0x95, 0xcd, 0xef, 0x94, 0x88, 0x9b, 0x02, 0x84,
46    0x5d, 0x64, 0x0b, 0x19, 0xad, 0xf0, 0xe3, 0x57, 0xb8, 0xd4, 0xbe, 0x7d, 0x49, 0xee, 0x70, 0xe6,
47];
48
49/// Applies an optional percentage multiplier to a gas estimate.
50pub fn apply_gas_estimate_multiplier(estimate: u64, multiplier: Option<u64>) -> Result<u64> {
51    let Some(multiplier) = multiplier else { return Ok(estimate) };
52    let adjusted = u128::from(estimate) * u128::from(multiplier) / 100;
53    adjusted.try_into().map_err(|_| eyre::eyre!("multiplied gas estimate exceeds u64"))
54}
55
56/// Regex used to parse `git submodule status` output.
57pub static SUBMODULE_STATUS_REGEX: LazyLock<Regex> =
58    LazyLock::new(|| Regex::new(r"^[\s+-]?([a-f0-9]+)\s+([^\s]+)(?:\s+\([^)]+\))?$").unwrap());
59
60/// Handle to reload the tracing `EnvFilter` at runtime.
61static FILTER_RELOAD_HANDLE: OnceLock<reload::Handle<EnvFilter, tracing_subscriber::Registry>> =
62    OnceLock::new();
63
64/// Useful extensions to [`std::path::Path`].
65pub trait FoundryPathExt {
66    /// Returns true if the [`Path`] ends with `.t.sol`
67    fn is_sol_test(&self) -> bool;
68
69    /// Returns true if the  [`Path`] has a `sol` extension
70    fn is_sol(&self) -> bool;
71
72    /// Returns true if the  [`Path`] has a `yul` extension
73    fn is_yul(&self) -> bool;
74}
75
76impl<T: AsRef<Path>> FoundryPathExt for T {
77    fn is_sol_test(&self) -> bool {
78        self.as_ref()
79            .file_name()
80            .and_then(|s| s.to_str())
81            .map(|s| s.ends_with(".t.sol"))
82            .unwrap_or_default()
83    }
84
85    fn is_sol(&self) -> bool {
86        self.as_ref().extension() == Some(std::ffi::OsStr::new("sol"))
87    }
88
89    fn is_yul(&self) -> bool {
90        self.as_ref().extension() == Some(std::ffi::OsStr::new("yul"))
91    }
92}
93
94/// Initializes a tracing Subscriber for logging.
95///
96/// The `EnvFilter` is wrapped in a [`reload::Layer`] so it can be reconfigured at runtime via
97/// [`update_tracing_filter`].
98pub fn subscriber() {
99    let (filter_layer, reload_handle) = reload::Layer::new(env_filter());
100    let registry = tracing_subscriber::Registry::default().with(filter_layer);
101    #[cfg(feature = "tracy")]
102    let registry = registry.with(tracing_tracy::TracyLayer::default());
103    registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr)).init();
104    let _ = FILTER_RELOAD_HANDLE.set(reload_handle);
105}
106
107/// Replaces the active tracing `EnvFilter` at runtime.
108///
109/// `directives` is parsed as an [`EnvFilter`] (e.g. `"info"`, `"debug,hyper=off"`).
110/// This is a no-op if [`subscriber`] has not been called yet.
111pub fn update_tracing_filter(directives: &str) {
112    let Some(handle) = FILTER_RELOAD_HANDLE.get() else {
113        return;
114    };
115    let Ok(new_filter) = directives.parse::<EnvFilter>() else {
116        return;
117    };
118    let _ = handle.reload(new_filter);
119}
120
121fn env_filter() -> EnvFilter {
122    const DEFAULT_DIRECTIVES: &[&str] = &include!("./default_directives.txt");
123    let mut filter = EnvFilter::from_default_env();
124    for &directive in DEFAULT_DIRECTIVES {
125        filter = filter.add_directive(directive.parse().unwrap());
126    }
127    filter
128}
129
130/// Returns a [`RootProvider`] instantiated using [Config]'s RPC settings.
131pub fn get_provider(config: &Config) -> Result<RootProvider<AnyNetwork>> {
132    get_provider_builder(config)?.build()
133}
134
135/// Returns a [ProviderBuilder] instantiated using [Config] values.
136///
137/// Defaults to `http://localhost:8545` and `Mainnet`.
138pub fn get_provider_builder(config: &Config) -> Result<ProviderBuilder> {
139    ProviderBuilder::from_config(config)
140}
141
142pub async fn get_chain<N, P>(chain: Option<Chain>, provider: P) -> Result<Chain>
143where
144    N: Network,
145    P: Provider<N>,
146{
147    match chain {
148        Some(chain) => Ok(chain),
149        None => Ok(Chain::from_id(provider.get_chain_id().await?)),
150    }
151}
152
153/// Parses an ether value from a string.
154///
155/// The amount can be tagged with a unit, e.g. "1ether".
156///
157/// If the string represents an untagged amount (e.g. "100") then
158/// it is interpreted as wei.
159pub fn parse_ether_value(value: &str) -> Result<U256> {
160    Ok(if value.starts_with("0x") || value.starts_with("0X") {
161        U256::from_str(value)?
162    } else {
163        alloy_dyn_abi::DynSolType::coerce_str(&alloy_dyn_abi::DynSolType::Uint(256), value)?
164            .as_uint()
165            .wrap_err("Could not parse ether value from string")?
166            .0
167    })
168}
169
170/// Parses a `T` from a string using [`serde_json::from_str`].
171pub fn parse_json<T: DeserializeOwned>(value: &str) -> serde_json::Result<T> {
172    serde_json::from_str(value)
173}
174
175/// Parses a `Duration` from a &str
176pub fn parse_delay(delay: &str) -> Result<Duration> {
177    let delay = if delay.ends_with("ms") {
178        let d: u64 = delay.trim_end_matches("ms").parse()?;
179        Duration::from_millis(d)
180    } else {
181        let d: f64 = delay.parse()?;
182        let delay = (d * 1000.0).round();
183        if delay.is_infinite() || delay.is_nan() || delay.is_sign_negative() {
184            eyre::bail!("delay must be finite and non-negative");
185        }
186
187        Duration::from_millis(delay as u64)
188    };
189    Ok(delay)
190}
191
192/// Returns the current time as a [`Duration`] since the Unix epoch.
193pub fn now() -> Duration {
194    SystemTime::now().duration_since(UNIX_EPOCH).expect("time went backwards")
195}
196
197/// Common setup for all CLI tools. Does not include [tracing subscriber](subscriber).
198pub fn common_setup() -> Vec<String> {
199    install_crypto_provider();
200    crate::handler::install();
201    let warnings = load_dotenv();
202    enable_paint();
203    warnings
204}
205
206/// Loads dotenv files from the cwd and project root, deferring diagnostics until shell setup.
207pub fn load_dotenv() -> Vec<String> {
208    // we only want the .env file of the cwd and project root
209    // `find_project_root` calls `current_dir` internally so both paths are either both `Ok` or
210    // both `Err`
211    let mut paths = Vec::new();
212    if let (Ok(cwd), Ok(project_root)) = (std::env::current_dir(), find_project_root(None)) {
213        let project_env = project_root.join(".env");
214        if project_env.is_file() {
215            paths.push(project_env);
216        }
217        if cwd != project_root {
218            // prj root and cwd can be identical
219            let cwd_env = cwd.join(".env");
220            if cwd_env.is_file() {
221                paths.push(cwd_env);
222            }
223        }
224    }
225
226    let mut warnings = Vec::new();
227    for path in paths {
228        if let Err(err) = dotenvy::from_path(&path) {
229            // Parse errors contain the source line, which may include secrets.
230            let reason = match err {
231                dotenvy::Error::LineParse(..) => {
232                    "invalid syntax; remaining variables were not loaded".to_string()
233                }
234                _ => err.to_string(),
235            };
236            warnings.push(format!("Failed to load {}: {}", path.display(), reason));
237        }
238    }
239    warnings
240}
241
242/// Sets the default [`yansi`] color output condition.
243pub fn enable_paint() {
244    let enable = yansi::Condition::os_support() && yansi::Condition::tty_and_color_live();
245    yansi::whenever(yansi::Condition::cached(enable));
246}
247
248/// This force installs the default crypto provider.
249///
250/// This is necessary in case there are more than one available backends enabled in rustls (ring,
251/// aws-lc-rs).
252///
253/// This should be called high in the main fn.
254///
255/// See also:
256///   <https://github.com/snapview/tokio-tungstenite/issues/353#issuecomment-2455100010>
257///   <https://github.com/awslabs/aws-sdk-rust/discussions/1257>
258pub fn install_crypto_provider() {
259    // https://github.com/snapview/tokio-tungstenite/issues/353
260    rustls::crypto::ring::default_provider()
261        .install_default()
262        .expect("Failed to install default rustls crypto provider");
263}
264
265/// Fetches the ABI of a contract from Etherscan.
266///
267/// If `follow_proxy` is set and Etherscan reports the contract as a proxy, the ABI of its
268/// implementation is appended after the proxy's own. Failing to fetch the implementation only
269/// produces a warning.
270pub async fn fetch_abi_from_etherscan(
271    address: Address,
272    config: &foundry_config::Config,
273    follow_proxy: bool,
274) -> Result<Vec<(JsonAbi, String)>> {
275    let chain = config.chain.unwrap_or_default();
276    let client = config
277        .get_etherscan_config_with_chain(Some(chain))?
278        .ok_or_else(|| eyre::eyre!("No Etherscan API key configured for chain {chain}"))?
279        .into_client_with_no_proxy(config.eth_rpc_no_proxy)?;
280    let fetch_abis = async |address| -> Result<_> {
281        let source = client.contract_source_code(address).await?;
282        let implementation = source
283            .items
284            .first()
285            .filter(|item| item.proxy != 0)
286            .and_then(|item| item.implementation);
287        let abis = source
288            .abis()?
289            .into_iter()
290            .zip(source.items.into_iter().map(|item| item.contract_name))
291            .collect::<Vec<_>>();
292        Ok((abis, implementation))
293    };
294    let (mut abis, implementation) = fetch_abis(address).await?;
295    if follow_proxy && let Some(implementation) = implementation {
296        sh_status!(
297            "Contract at {address} is a proxy, fetching implementation at {implementation}..."
298        )?;
299        match fetch_abis(implementation).await {
300            Ok((implementation, _)) => abis.extend(implementation),
301            Err(err) => sh_warn!("Could not fetch implementation ABI: {err}")?,
302        }
303    }
304    Ok(abis)
305}
306
307/// Useful extensions to [`std::process::Command`].
308pub trait CommandUtils {
309    /// Returns the command's output if execution is successful, otherwise, throws an error.
310    fn exec(&mut self) -> Result<Output>;
311
312    /// Runs the command and returns its output whatever the exit status. Unlike
313    /// [`Command::output`], the error names the program when it cannot be started.
314    fn spawn_output(&mut self) -> Result<Output>;
315
316    /// Returns the command's stdout if execution is successful, otherwise, throws an error.
317    fn get_stdout_lossy(&mut self) -> Result<String>;
318}
319
320impl CommandUtils for Command {
321    #[track_caller]
322    fn exec(&mut self) -> Result<Output> {
323        trace!(command=?self, "executing");
324
325        let output = self.spawn_output()?;
326
327        trace!(code=?output.status.code(), ?output);
328
329        if output.status.success() {
330            Ok(output)
331        } else {
332            let stdout = String::from_utf8_lossy(&output.stdout);
333            let stdout = stdout.trim();
334            let stderr = String::from_utf8_lossy(&output.stderr);
335            let stderr = stderr.trim();
336            let msg = if stdout.is_empty() {
337                stderr.to_string()
338            } else if stderr.is_empty() {
339                stdout.to_string()
340            } else {
341                format!("stdout:\n{stdout}\n\nstderr:\n{stderr}")
342            };
343
344            let mut name = self.get_program().to_string_lossy();
345            if let Some(arg) = self.get_args().next() {
346                let arg = arg.to_string_lossy();
347                if !arg.starts_with('-') {
348                    let name = name.to_mut();
349                    name.push(' ');
350                    name.push_str(&arg);
351                }
352            }
353
354            let mut err = match output.status.code() {
355                Some(code) => format!("{name} exited with code {code}"),
356                None => format!("{name} terminated by a signal"),
357            };
358            if !msg.is_empty() {
359                err.push(':');
360                err.push(if msg.lines().count() == 1 { ' ' } else { '\n' });
361                err.push_str(&msg);
362            }
363            Err(eyre::eyre!(err))
364        }
365    }
366
367    fn spawn_output(&mut self) -> Result<Output> {
368        self.output().wrap_err_with(|| {
369            let program = self.get_program().to_string_lossy();
370            if let Some(dir) = self.get_current_dir() {
371                format!("could not run `{program}` in {}", dir.display())
372            } else {
373                format!("could not run `{program}`")
374            }
375        })
376    }
377
378    #[track_caller]
379    fn get_stdout_lossy(&mut self) -> Result<String> {
380        let output = self.exec()?;
381        let stdout = String::from_utf8_lossy(&output.stdout);
382        Ok(stdout.trim().into())
383    }
384}
385
386#[derive(Clone, Copy, Debug)]
387pub struct Git<'a> {
388    pub root: &'a Path,
389    pub quiet: bool,
390    pub shallow: bool,
391}
392
393impl<'a> Git<'a> {
394    pub fn new(root: &'a Path) -> Self {
395        Self { root, quiet: shell::is_quiet(), shallow: false }
396    }
397
398    pub fn from_config(config: &'a Config) -> Self {
399        Self::new(config.root.as_path())
400    }
401
402    pub fn root_of(relative_to: &Path) -> Result<PathBuf> {
403        let output = Self::cmd_no_root()
404            .current_dir(relative_to)
405            .args(["rev-parse", "--show-toplevel"])
406            .get_stdout_lossy()?;
407        Ok(PathBuf::from(output))
408    }
409
410    pub fn clone(
411        shallow: bool,
412        from: impl AsRef<OsStr>,
413        to: Option<impl AsRef<OsStr>>,
414    ) -> Result<()> {
415        Self::cmd_no_root()
416            .stderr(Stdio::inherit())
417            .args(["clone", "--recurse-submodules"])
418            .args(shallow.then_some("--depth=1"))
419            .args(shallow.then_some("--shallow-submodules"))
420            .arg(from)
421            .args(to)
422            .exec()
423            .map(drop)
424    }
425
426    pub fn fetch(
427        self,
428        shallow: bool,
429        remote: impl AsRef<OsStr>,
430        branch: Option<impl AsRef<OsStr>>,
431    ) -> Result<()> {
432        self.cmd()
433            .stderr(Stdio::inherit())
434            .arg("fetch")
435            .args(shallow.then_some("--no-tags"))
436            .args(shallow.then_some("--depth=1"))
437            .arg(remote)
438            .args(branch)
439            .exec()
440            .map(drop)
441    }
442
443    pub const fn root(self, root: &Path) -> Git<'_> {
444        Git { root, ..self }
445    }
446
447    pub const fn quiet(self, quiet: bool) -> Self {
448        Self { quiet, ..self }
449    }
450
451    /// True to perform shallow clones
452    pub const fn shallow(self, shallow: bool) -> Self {
453        Self { shallow, ..self }
454    }
455
456    pub fn checkout(self, recursive: bool, tag: impl AsRef<OsStr>) -> Result<()> {
457        let tag = tag.as_ref();
458        validate_checkout_ref(tag)?;
459        self.cmd()
460            .arg("checkout")
461            .args(recursive.then_some("--recurse-submodules"))
462            .arg(tag)
463            .arg("--")
464            .exec()
465            .map(drop)
466    }
467
468    /// Returns the current HEAD commit hash of the current branch.
469    pub fn head(self) -> Result<String> {
470        self.cmd().args(["rev-parse", "HEAD"]).get_stdout_lossy()
471    }
472
473    pub fn checkout_at(self, tag: impl AsRef<OsStr>, at: &Path) -> Result<()> {
474        let tag = tag.as_ref();
475        validate_checkout_ref(tag)?;
476        self.cmd_at(at).arg("checkout").arg(tag).arg("--").exec().map(drop)
477    }
478
479    pub fn init(self) -> Result<()> {
480        self.cmd().arg("init").exec().map(drop)
481    }
482
483    pub fn current_rev_branch(self, at: &Path) -> Result<(String, String)> {
484        let rev = self.cmd_at(at).args(["rev-parse", "HEAD"]).get_stdout_lossy()?;
485        let branch =
486            self.cmd_at(at).args(["rev-parse", "--abbrev-ref", "HEAD"]).get_stdout_lossy()?;
487        Ok((rev, branch))
488    }
489
490    #[expect(clippy::should_implement_trait)] // this is not std::ops::Add clippy
491    pub fn add<I, S>(self, paths: I) -> Result<()>
492    where
493        I: IntoIterator<Item = S>,
494        S: AsRef<OsStr>,
495    {
496        self.cmd().arg("add").args(paths).exec().map(drop)
497    }
498
499    pub fn add_literal(self, path: &Path) -> Result<()> {
500        self.cmd().args(["--literal-pathspecs", "add", "--"]).arg(path).exec().map(drop)
501    }
502
503    pub fn reset(self, hard: bool, tree: impl AsRef<OsStr>) -> Result<()> {
504        self.cmd().arg("reset").args(hard.then_some("--hard")).arg(tree).exec().map(drop)
505    }
506
507    pub fn commit_tree(
508        self,
509        tree: impl AsRef<OsStr>,
510        msg: Option<impl AsRef<OsStr>>,
511    ) -> Result<String> {
512        self.cmd()
513            .arg("commit-tree")
514            .arg(tree)
515            .args(msg.as_ref().is_some().then_some("-m"))
516            .args(msg)
517            .get_stdout_lossy()
518    }
519
520    pub fn rm<I, S>(self, force: bool, paths: I) -> Result<()>
521    where
522        I: IntoIterator<Item = S>,
523        S: AsRef<OsStr>,
524    {
525        self.cmd().arg("rm").args(force.then_some("--force")).args(paths).exec().map(drop)
526    }
527
528    pub fn remove_index_path(self, path: &Path) -> Result<()> {
529        self.cmd()
530            .args(["--literal-pathspecs", "rm", "--cached", "--force", "--"])
531            .arg(path)
532            .exec()
533            .map(drop)
534    }
535
536    pub fn commit(self, msg: &str) -> Result<()> {
537        let output = self
538            .cmd()
539            .args(["commit", "-m", msg])
540            .args(cfg!(any(test, debug_assertions)).then_some("--no-gpg-sign"))
541            .spawn_output()?;
542        if !output.status.success() {
543            let stdout = String::from_utf8_lossy(&output.stdout);
544            let stderr = String::from_utf8_lossy(&output.stderr);
545            // ignore "nothing to commit" error
546            let msg = "nothing to commit, working tree clean";
547            if !(stdout.contains(msg) || stderr.contains(msg)) {
548                return Err(eyre::eyre!(
549                    "failed to commit (code={:?}, stdout={:?}, stderr={:?})",
550                    output.status.code(),
551                    stdout.trim(),
552                    stderr.trim()
553                ));
554            }
555        }
556        Ok(())
557    }
558
559    pub fn is_in_repo(self) -> Result<bool> {
560        self.cmd()
561            .args(["rev-parse", "--is-inside-work-tree"])
562            .spawn_output()
563            .map(|output| output.status.success())
564    }
565
566    pub fn is_repo_root(self) -> Result<bool> {
567        self.cmd().args(["rev-parse", "--show-cdup"]).get_stdout_lossy().map(|s| s.is_empty())
568    }
569
570    pub fn is_clean(self) -> Result<bool> {
571        self.cmd().args(["status", "--porcelain"]).exec().map(|out| out.stdout.is_empty())
572    }
573
574    pub fn is_path_clean(self, path: &Path) -> Result<bool> {
575        self.cmd()
576            .args(["--literal-pathspecs", "status", "--porcelain", "--"])
577            .arg(path)
578            .exec()
579            .map(|out| out.stdout.is_empty())
580    }
581
582    pub fn has_branch(self, branch: impl AsRef<OsStr>, at: &Path) -> Result<bool> {
583        self.cmd_at(at)
584            .args(["branch", "--list", "--no-color"])
585            .arg(branch)
586            .get_stdout_lossy()
587            .map(|stdout| !stdout.is_empty())
588    }
589
590    pub fn has_tag(self, tag: impl AsRef<OsStr>, at: &Path) -> Result<bool> {
591        self.cmd_at(at)
592            .args(["tag", "--list"])
593            .arg(tag)
594            .get_stdout_lossy()
595            .map(|stdout| !stdout.is_empty())
596    }
597
598    pub fn has_rev(self, rev: impl AsRef<OsStr>, at: &Path) -> Result<bool> {
599        self.cmd_at(at)
600            .args(["cat-file", "-t"])
601            .arg(rev)
602            .get_stdout_lossy()
603            .map(|stdout| &stdout == "commit")
604    }
605
606    pub fn get_rev(self, tag_or_branch: impl AsRef<OsStr>, at: &Path) -> Result<String> {
607        self.cmd_at(at).args(["rev-list", "-n", "1"]).arg(tag_or_branch).get_stdout_lossy()
608    }
609
610    pub fn ensure_clean(self) -> Result<()> {
611        if self.is_clean()? {
612            Ok(())
613        } else {
614            Err(eyre::eyre!(
615                "\
616The target directory is a part of or on its own an already initialized git repository,
617and it requires clean working and staging areas, including no untracked files.
618
619Check the current git repository's status with `git status`.
620Then, you can track files with `git add ...` and then commit them with `git commit`,
621ignore them in the `.gitignore` file."
622            ))
623        }
624    }
625
626    pub fn commit_hash(self, short: bool, revision: &str) -> Result<String> {
627        self.cmd()
628            .arg("rev-parse")
629            .args(short.then_some("--short"))
630            .arg(revision)
631            .get_stdout_lossy()
632    }
633
634    pub fn tag(self) -> Result<String> {
635        self.cmd().arg("tag").get_stdout_lossy()
636    }
637
638    /// Returns the tag the commit first appeared in.
639    ///
640    /// E.g Take rev = `abc1234`. This commit can be found in multiple releases (tags).
641    /// Consider releases: `v0.1.0`, `v0.2.0`, `v0.3.0` in chronological order, `rev` first appeared
642    /// in `v0.2.0`.
643    ///
644    /// Hence, `tag_for_commit("abc1234")` will return `v0.2.0`.
645    pub fn tag_for_commit(self, rev: &str, at: &Path) -> Result<Option<String>> {
646        self.cmd_at(at)
647            .args(["tag", "--contains"])
648            .arg(rev)
649            .get_stdout_lossy()
650            .map(|stdout| stdout.lines().next().map(str::to_string))
651    }
652
653    /// Returns a list of tuples of submodule paths and their respective branches.
654    ///
655    /// This function reads the `.gitmodules` file and returns the paths of all submodules that have
656    /// a branch. The paths are relative to the Git::root_of(git.root) and not lib/ directory.
657    ///
658    /// `at` is the dir in which the `.gitmodules` file is located, this is the git root.
659    /// `lib` is name of the directory where the submodules are located.
660    pub fn read_submodules_with_branch(
661        self,
662        at: &Path,
663        lib: &OsStr,
664    ) -> Result<HashMap<PathBuf, String>> {
665        // Let Git decode config quoting, escapes, whitespace, and comments.
666        let gitmodules = self
667            .cmd_at(at)
668            .args(["config", "--null", "--list", "--file", ".gitmodules"])
669            .get_stdout_lossy()?;
670        let entries = gitmodules
671            .split_terminator('\0')
672            .filter_map(|entry| entry.split_once('\n'))
673            .collect::<Vec<_>>();
674        // Resolve paths using Git's last-value semantics, but retain branch record order so
675        // the last branch wins when different submodule paths normalize to the same path.
676        let values = entries.iter().copied().collect::<HashMap<_, _>>();
677
678        let paths = entries
679            .iter()
680            .filter_map(|(key, branch)| {
681                let name = key.strip_prefix("submodule.")?.strip_suffix(".branch")?;
682                let path = PathBuf::from(*values.get(format!("submodule.{name}.path").as_str())?);
683                trace!(path = %path.display(), "unstripped path");
684
685                // Keep only the components that come after the lib directory.
686                // This needs to be done because the lockfile uses paths relative foundry project
687                // root whereas .gitmodules use paths relative to the git root which may not be the
688                // project root. e.g monorepo.
689                // Hence, if path is lib/solady, then `lib/solady` is kept. if path is
690                // packages/contract-bedrock/lib/solady, then `lib/solady` is kept.
691                let lib_pos = path.components().find_position(|c| c.as_os_str() == lib);
692                let path = path
693                    .components()
694                    .skip(lib_pos.map(|(i, _)| i).unwrap_or(0))
695                    .collect::<PathBuf>();
696
697                Some((path, (*branch).to_string()))
698            })
699            .collect::<HashMap<_, _>>();
700
701        Ok(paths)
702    }
703
704    pub fn has_missing_dependencies<I, S>(self, paths: I) -> Result<bool>
705    where
706        I: IntoIterator<Item = S>,
707        S: AsRef<OsStr>,
708    {
709        let paths = paths.into_iter().map(|path| path.as_ref().to_owned()).collect::<Vec<_>>();
710        if self.submodules_initialized(&paths).unwrap_or(false) {
711            return Ok(false);
712        }
713
714        self.cmd()
715            .args(["submodule", "status"])
716            .args(&paths)
717            .get_stdout_lossy()
718            .map(|stdout| stdout.lines().any(|line| line.starts_with('-')))
719    }
720
721    /// Returns true if all submodules matching `paths` have initialized worktrees.
722    fn submodules_initialized(self, paths: &[OsString]) -> Result<bool> {
723        // Let Git resolve relative roots.
724        if !self.root.is_absolute() {
725            return Ok(false);
726        }
727        let Some(root) = find_git_root(self.root)? else {
728            return Ok(true);
729        };
730        let root = root.as_path();
731        if paths.iter().any(|path| {
732            Path::new(path)
733                .components()
734                .any(|component| matches!(component, std::path::Component::ParentDir))
735        }) {
736            return Ok(false);
737        }
738        let relative_root = self.root.strip_prefix(root).unwrap_or_else(|_| Path::new(""));
739        let gitmodules = root.join(".gitmodules");
740        if !gitmodules.is_file() {
741            // Removing .gitmodules does not remove gitlinks from the index. Let Git handle
742            // any remaining submodules, including those without a .gitmodules mapping.
743            return Ok(false);
744        }
745
746        let output = Command::new("git")
747            .args(["config", "--null", "--file"])
748            .arg(gitmodules)
749            .args(["--get-regexp", r"^submodule\..*\.path$"])
750            .get_stdout_lossy()?;
751
752        for entry in output.split_terminator('\0') {
753            let (_, path) = entry
754                .split_once('\n')
755                .ok_or_else(|| eyre::eyre!("invalid submodule path config"))?;
756            let path = Path::new(path);
757            let matches = paths.is_empty()
758                || paths.iter().any(|prefix| {
759                    let prefix = Path::new(prefix);
760                    if prefix.is_absolute() {
761                        prefix.strip_prefix(root).is_ok_and(|prefix| path.starts_with(prefix))
762                    } else {
763                        path.starts_with(relative_root.join(prefix))
764                    }
765                });
766            if matches && !root.join(path).join(".git").exists() {
767                return Ok(false);
768            }
769        }
770        Ok(true)
771    }
772
773    /// Returns true if the given path has submodules by checking `git submodule status`
774    pub fn has_submodules<I, S>(self, paths: I) -> Result<bool>
775    where
776        I: IntoIterator<Item = S>,
777        S: AsRef<OsStr>,
778    {
779        self.cmd()
780            .args(["submodule", "status"])
781            .args(paths)
782            .get_stdout_lossy()
783            .map(|stdout| stdout.trim().lines().next().is_some())
784    }
785
786    pub fn submodule_add(
787        self,
788        force: bool,
789        url: impl AsRef<OsStr>,
790        path: impl AsRef<OsStr>,
791    ) -> Result<()> {
792        self.cmd()
793            .arg("--literal-pathspecs")
794            .stderr(self.stderr())
795            .args(["submodule", "add"])
796            .args(self.shallow.then_some("--depth=1"))
797            .args(force.then_some("--force"))
798            .arg(url)
799            .arg(path)
800            .exec()
801            .map(drop)
802    }
803
804    pub fn submodule_update<I, S>(
805        self,
806        force: bool,
807        remote: bool,
808        no_fetch: bool,
809        recursive: bool,
810        paths: I,
811    ) -> Result<()>
812    where
813        I: IntoIterator<Item = S>,
814        S: AsRef<OsStr>,
815    {
816        self.cmd()
817            .arg("--literal-pathspecs")
818            .stderr(self.stderr())
819            .args(["submodule", "update", "--progress", "--init"])
820            .args(self.shallow.then_some("--depth=1"))
821            .args(force.then_some("--force"))
822            .args(remote.then_some("--remote"))
823            .args(no_fetch.then_some("--no-fetch"))
824            .args(recursive.then_some("--recursive"))
825            .arg("--")
826            .args(paths)
827            .exec()
828            .map(drop)
829    }
830
831    pub fn submodule_foreach(self, recursive: bool, cmd: impl AsRef<OsStr>) -> Result<()> {
832        self.cmd()
833            .stderr(self.stderr())
834            .args(["submodule", "foreach"])
835            .args(recursive.then_some("--recursive"))
836            .arg(cmd)
837            .exec()
838            .map(drop)
839    }
840
841    /// If the status is prefix with `-`, the submodule is not initialized.
842    ///
843    /// Ref: <https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-status--cached--recursive--ltpathgt82308203>
844    pub fn submodules_uninitialized(self) -> Result<bool> {
845        // keep behavior consistent with `has_missing_dependencies`, but avoid duplicating the
846        // "submodule status has '-' prefix" logic.
847        self.has_missing_dependencies(std::iter::empty::<&OsStr>())
848    }
849
850    /// Initializes the git submodules.
851    pub fn submodule_init(self) -> Result<()> {
852        self.cmd().stderr(self.stderr()).args(["submodule", "init"]).exec().map(drop)
853    }
854
855    pub fn submodules(&self) -> Result<Submodules> {
856        self.cmd().args(["submodule", "status"]).get_stdout_lossy().map(|stdout| stdout.parse())?
857    }
858
859    /// Returns submodules at or below `path`, with paths relative to this Git root.
860    pub fn submodules_in(&self, path: &Path) -> Result<Vec<SubmoduleCheckout>> {
861        self.submodules_in_worktree(path, self.root, Path::new(""))
862    }
863
864    /// Returns submodules at or below `path`, with paths relative to this Git root, using mappings
865    /// from the enclosing worktree.
866    pub fn submodules_in_worktree(
867        &self,
868        path: &Path,
869        worktree_root: &Path,
870        worktree_prefix: &Path,
871    ) -> Result<Vec<SubmoduleCheckout>> {
872        let pathspec = if path.as_os_str().is_empty() { Path::new(".") } else { path };
873        let output = self
874            .cmd()
875            .args(["--literal-pathspecs", "ls-files", "--stage", "-z", "--"])
876            .arg(pathspec)
877            .exec()?;
878        let (_, mappings) = self.submodule_mappings_at(worktree_root)?;
879        let mut gitlinks = BTreeMap::new();
880        for entry in output.stdout.split(|byte| *byte == 0).filter(|entry| !entry.is_empty()) {
881            let Some(separator) = entry.iter().position(|byte| *byte == b'\t') else {
882                return Err(eyre::eyre!("invalid index entry"));
883            };
884            let mut fields = std::str::from_utf8(&entry[..separator])?.split_ascii_whitespace();
885            let Some(mode) = fields.next() else {
886                return Err(eyre::eyre!("invalid index entry"));
887            };
888            let Some(rev) = fields.next() else {
889                return Err(eyre::eyre!("invalid index entry"));
890            };
891            let Some(stage) = fields.next() else {
892                return Err(eyre::eyre!("invalid index entry"));
893            };
894            if fields.next().is_some() {
895                return Err(eyre::eyre!("invalid index entry"));
896            }
897            if mode != "160000" {
898                continue;
899            }
900
901            let submodule_path = PathBuf::from(std::str::from_utf8(&entry[separator + 1..])?);
902            let worktree_path =
903                foundry_common::fs::normalize_path(&worktree_prefix.join(&submodule_path));
904            if !mappings.contains(&worktree_path) {
905                gitlinks.insert(
906                    submodule_path.clone(),
907                    SubmoduleCheckout {
908                        status: SubmoduleCheckoutStatus::MissingMapping,
909                        rev: rev.to_string(),
910                        path: submodule_path,
911                    },
912                );
913                continue;
914            }
915            if stage != "0" {
916                gitlinks.insert(
917                    submodule_path.clone(),
918                    SubmoduleCheckout {
919                        status: SubmoduleCheckoutStatus::Conflicted,
920                        rev: rev.to_string(),
921                        path: submodule_path,
922                    },
923                );
924                continue;
925            }
926
927            let status = self
928                .cmd()
929                .args(["--literal-pathspecs", "submodule", "status", "--"])
930                .arg(&submodule_path)
931                .get_stdout_lossy()?;
932            let (status, rev) = match status.as_bytes().first() {
933                Some(b'-') => (SubmoduleCheckoutStatus::Uninitialized, &status[1..]),
934                Some(b'+') => (SubmoduleCheckoutStatus::Modified, &status[1..]),
935                Some(b'U') => (SubmoduleCheckoutStatus::Conflicted, &status[1..]),
936                Some(_) => (SubmoduleCheckoutStatus::Current, status.as_str()),
937                None => return Err(eyre::eyre!("missing submodule status")),
938            };
939            let rev = rev
940                .split_ascii_whitespace()
941                .next()
942                .ok_or_else(|| eyre::eyre!("invalid submodule status"))?;
943            gitlinks.insert(
944                submodule_path.clone(),
945                SubmoduleCheckout { status, rev: rev.to_string(), path: submodule_path },
946            );
947        }
948        Ok(gitlinks.into_values().collect())
949    }
950
951    pub fn submodule_sync(self) -> Result<()> {
952        self.cmd().stderr(self.stderr()).args(["submodule", "sync"]).exec().map(drop)
953    }
954
955    /// Get the URL of a submodule from git config
956    pub fn submodule_url(self, path: &Path) -> Result<Option<String>> {
957        self.cmd()
958            .args(["config", "--get", &format!("submodule.{}.url", path.to_slash_lossy())])
959            .get_stdout_lossy()
960            .map(|url| Some(url.trim().to_string()))
961    }
962
963    /// Returns whether `.gitmodules` contains the default section name or an exact path mapping.
964    pub fn has_submodule_mapping(self, path: &Path) -> Result<bool> {
965        let (names, paths) = self.submodule_mappings()?;
966        Ok(names.contains(path) || paths.contains(path))
967    }
968
969    fn submodule_mappings(self) -> Result<(BTreeSet<PathBuf>, BTreeSet<PathBuf>)> {
970        self.submodule_mappings_at(self.root)
971    }
972
973    fn submodule_mappings_at(self, root: &Path) -> Result<(BTreeSet<PathBuf>, BTreeSet<PathBuf>)> {
974        let gitmodules = root.join(".gitmodules");
975        if !gitmodules.exists() {
976            return Ok(Default::default());
977        }
978
979        let output = self
980            .cmd()
981            .args(["config", "--null", "--file"])
982            .arg(gitmodules)
983            .args(["--get-regexp", r"^submodule\..*"])
984            .spawn_output()?;
985        match output.status.code() {
986            Some(0) => {
987                let mut names = BTreeSet::new();
988                let mut paths = BTreeSet::new();
989                for entry in
990                    output.stdout.split(|byte| *byte == 0).filter(|entry| !entry.is_empty())
991                {
992                    let Some(separator) = entry.iter().position(|byte| *byte == b'\n') else {
993                        return Err(eyre::eyre!("invalid submodule mapping entry"));
994                    };
995                    let key = std::str::from_utf8(&entry[..separator])?;
996                    let value = std::str::from_utf8(&entry[separator + 1..])?;
997                    let Some(key) = key.strip_prefix("submodule.") else { continue };
998                    let Some((name, field)) = key.rsplit_once('.') else { continue };
999                    names.insert(PathBuf::from(name));
1000                    if field == "path" {
1001                        paths.insert(PathBuf::from(value));
1002                    }
1003                }
1004                Ok((names, paths))
1005            }
1006            Some(1) => Ok(Default::default()),
1007            _ => Err(eyre::eyre!(
1008                "failed to inspect .gitmodules: {}",
1009                String::from_utf8_lossy(&output.stderr).trim()
1010            )),
1011        }
1012    }
1013
1014    /// Returns whether the index contains a submodule at the given path.
1015    pub fn is_gitlink(self, path: &Path) -> Result<bool> {
1016        self.cmd().args(["ls-files", "--stage", "-z", "--"]).arg(path).exec().map(|output| {
1017            let expected_path = path.to_slash_lossy();
1018            output.stdout.split(|byte| *byte == 0).any(|entry| {
1019                entry.starts_with(b"160000 ")
1020                    && entry
1021                        .iter()
1022                        .position(|byte| *byte == b'\t')
1023                        .and_then(|separator| entry.get(separator + 1..))
1024                        == Some(expected_path.as_bytes())
1025            })
1026        })
1027    }
1028
1029    /// Returns whether the index contains any entry at or below the given path.
1030    pub fn has_index_entries(self, path: &Path) -> Result<bool> {
1031        self.cmd()
1032            .args(["--literal-pathspecs", "ls-files", "--stage", "-z", "--"])
1033            .arg(path)
1034            .exec()
1035            .map(|output| !output.stdout.is_empty())
1036    }
1037
1038    /// Returns whether a regular stage-0 index entry has no flags and matches the worktree.
1039    pub fn is_normal_tracked_file(self, path: &Path) -> Result<bool> {
1040        let output = self
1041            .cmd()
1042            .args(["--literal-pathspecs", "ls-files", "--stage", "-v", "-z", "--"])
1043            .arg(path)
1044            .exec()?;
1045        let mut entries = output.stdout.split(|byte| *byte == 0).filter(|entry| !entry.is_empty());
1046        let Some(entry) = entries.next() else { return Ok(false) };
1047        if entries.next().is_some() {
1048            return Ok(false);
1049        }
1050        let Some(separator) = entry.iter().position(|byte| *byte == b'\t') else {
1051            return Err(eyre::eyre!("invalid index entry"));
1052        };
1053        if entry.get(separator + 1..) != Some(path.to_slash_lossy().as_bytes()) {
1054            return Ok(false);
1055        }
1056        let mut fields = std::str::from_utf8(&entry[..separator])?.split_ascii_whitespace();
1057        if fields.next() != Some("H") || !matches!(fields.next(), Some("100644" | "100755")) {
1058            return Ok(false);
1059        }
1060        let Some(index_hash) = fields.next() else { return Ok(false) };
1061        if fields.next() != Some("0") || fields.next().is_some() {
1062            return Ok(false);
1063        }
1064        let worktree_hash = self.cmd().args(["hash-object", "--"]).arg(path).get_stdout_lossy()?;
1065        Ok(worktree_hash.trim() == index_hash)
1066    }
1067
1068    /// Returns whether local config contains values for the given submodule.
1069    pub fn has_submodule_config(self, path: &Path) -> Result<bool> {
1070        let pattern = format!(r"^submodule\.{}\.", regex::escape(&path.to_slash_lossy()));
1071        let output =
1072            self.cmd().args(["config", "--local", "--get-regexp", &pattern]).spawn_output()?;
1073        match output.status.code() {
1074            Some(0) => Ok(true),
1075            Some(1) => Ok(false),
1076            _ => Err(eyre::eyre!(
1077                "failed to inspect submodule config: {}",
1078                String::from_utf8_lossy(&output.stderr).trim()
1079            )),
1080        }
1081    }
1082
1083    /// Removes all local config values for the given submodule.
1084    pub fn remove_submodule_config(self, path: &Path) -> Result<()> {
1085        if self.has_submodule_config(path)? {
1086            let section = format!("submodule.{}", path.to_slash_lossy());
1087            self.cmd().args(["config", "--local", "--remove-section", &section]).exec()?;
1088        }
1089        Ok(())
1090    }
1091
1092    /// Returns the absolute path to the repository's Git directory.
1093    pub fn absolute_git_dir(self) -> Result<PathBuf> {
1094        self.cmd().args(["rev-parse", "--absolute-git-dir"]).get_stdout_lossy().map(PathBuf::from)
1095    }
1096
1097    /// Returns the fetch URL of the given remote, or `None` if it doesn't exist.
1098    pub fn remote_url(self, name: &str) -> Option<String> {
1099        self.cmd().args(["remote", "get-url", name]).get_stdout_lossy().ok()
1100    }
1101
1102    /// Sets the branch for a submodule.
1103    pub fn set_submodule_branch(self, rel_path: &Path, branch: &str) -> Result<()> {
1104        self.cmd()
1105            .args(["submodule", "set-branch", "-b", branch])
1106            .arg(rel_path.to_slash_lossy().as_ref())
1107            .exec()
1108            .map(drop)
1109    }
1110
1111    /// Returns remote branch names as a newline-separated string.
1112    pub fn remote_branches(self) -> Result<String> {
1113        self.cmd().args(["branch", "-r", "--no-color", "--no-column"]).get_stdout_lossy()
1114    }
1115
1116    /// Fetches a branch from origin and checks out a local tracking branch at the given path.
1117    pub fn fetch_and_checkout_branch(self, at: &Path, branch: &str) -> Result<()> {
1118        self.cmd_at(at).args(["fetch", "--", "origin", branch]).exec().map_err(|e| {
1119            eyre::eyre!(
1120                "Could not fetch latest changes for branch {branch} in submodule at {}: {e}",
1121                at.display()
1122            )
1123        })?;
1124        self.cmd_at(at)
1125            .args(["checkout", "-B", branch, &format!("origin/{branch}")])
1126            .exec()
1127            .map_err(|e| {
1128                eyre::eyre!(
1129                    "Could not checkout and track origin/{branch} for submodule at {}: {e}",
1130                    at.display()
1131                )
1132            })?;
1133        Ok(())
1134    }
1135
1136    /// Checks out a branch without fetching or resetting an existing local branch.
1137    pub fn checkout_branch(self, recursive: bool, branch: &str) -> Result<()> {
1138        validate_checkout_ref(branch.as_ref())?;
1139        if self.has_branch(branch, self.root)? {
1140            return self.checkout(recursive, branch);
1141        }
1142        self.cmd()
1143            .arg("checkout")
1144            .args(recursive.then_some("--recurse-submodules"))
1145            .args(["-b", branch, &format!("refs/remotes/origin/{branch}"), "--"])
1146            .exec()
1147            .map(drop)
1148    }
1149
1150    fn cmd(self) -> Command {
1151        let mut cmd = Self::cmd_no_root();
1152        cmd.current_dir(self.root);
1153        cmd
1154    }
1155
1156    fn cmd_at(self, path: &Path) -> Command {
1157        let mut cmd = Self::cmd_no_root();
1158        cmd.current_dir(path);
1159        cmd
1160    }
1161
1162    fn cmd_no_root() -> Command {
1163        let mut cmd = Command::new("git");
1164        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1165        cmd
1166    }
1167
1168    // don't set this in cmd() because it's not wanted for all commands
1169    fn stderr(self) -> Stdio {
1170        if self.quiet { Stdio::piped() } else { Stdio::inherit() }
1171    }
1172}
1173
1174fn validate_checkout_ref(reference: &OsStr) -> Result<()> {
1175    if reference.is_empty() || reference.as_encoded_bytes().starts_with(b"-") {
1176        eyre::bail!("Git checkout reference must not be empty or start with `-`");
1177    }
1178    Ok(())
1179}
1180
1181/// Deserialized `git submodule status lib/dep` output.
1182#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
1183pub struct Submodule {
1184    /// Current commit hash the submodule is checked out at.
1185    rev: String,
1186    /// Relative path to the submodule.
1187    path: PathBuf,
1188}
1189
1190impl Submodule {
1191    pub const fn new(rev: String, path: PathBuf) -> Self {
1192        Self { rev, path }
1193    }
1194
1195    pub fn rev(&self) -> &str {
1196        &self.rev
1197    }
1198
1199    pub const fn path(&self) -> &PathBuf {
1200        &self.path
1201    }
1202}
1203
1204/// A submodule checkout inspected without changing its worktree or index.
1205#[derive(Debug, Clone, PartialEq, Eq)]
1206pub struct SubmoduleCheckout {
1207    status: SubmoduleCheckoutStatus,
1208    rev: String,
1209    path: PathBuf,
1210}
1211
1212impl SubmoduleCheckout {
1213    pub const fn status(&self) -> SubmoduleCheckoutStatus {
1214        self.status
1215    }
1216
1217    pub fn rev(&self) -> &str {
1218        &self.rev
1219    }
1220
1221    pub const fn path(&self) -> &PathBuf {
1222        &self.path
1223    }
1224}
1225
1226/// State of an inspected submodule checkout.
1227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1228pub enum SubmoduleCheckoutStatus {
1229    /// The checkout matches the commit recorded by the superproject.
1230    Current,
1231    /// The submodule has not been initialized.
1232    Uninitialized,
1233    /// The checkout differs from the commit recorded by the superproject.
1234    Modified,
1235    /// The submodule has merge conflicts.
1236    Conflicted,
1237    /// The index contains a gitlink without a corresponding `.gitmodules` mapping.
1238    MissingMapping,
1239}
1240
1241impl FromStr for Submodule {
1242    type Err = eyre::Report;
1243
1244    fn from_str(s: &str) -> Result<Self> {
1245        let caps = SUBMODULE_STATUS_REGEX
1246            .captures(s)
1247            .ok_or_else(|| eyre::eyre!("Invalid submodule status format"))?;
1248
1249        Ok(Self {
1250            rev: caps.get(1).unwrap().as_str().to_string(),
1251            path: PathBuf::from(caps.get(2).unwrap().as_str()),
1252        })
1253    }
1254}
1255
1256/// Deserialized `git submodule status` output.
1257#[derive(Debug, Clone, PartialEq, Eq)]
1258pub struct Submodules(pub Vec<Submodule>);
1259
1260impl Submodules {
1261    pub const fn len(&self) -> usize {
1262        self.0.len()
1263    }
1264
1265    pub const fn is_empty(&self) -> bool {
1266        self.0.is_empty()
1267    }
1268}
1269
1270impl FromStr for Submodules {
1271    type Err = eyre::Report;
1272
1273    fn from_str(s: &str) -> Result<Self> {
1274        let subs = s.lines().map(str::parse).collect::<Result<Vec<Submodule>>>()?;
1275        Ok(Self(subs))
1276    }
1277}
1278
1279impl<'a> IntoIterator for &'a Submodules {
1280    type Item = &'a Submodule;
1281    type IntoIter = std::slice::Iter<'a, Submodule>;
1282
1283    fn into_iter(self) -> Self::IntoIter {
1284        self.0.iter()
1285    }
1286}
1287#[cfg(test)]
1288mod tests {
1289    use super::*;
1290    use foundry_common::fs;
1291    use std::{env, fs::File, io::Write};
1292    use tempfile::tempdir;
1293
1294    #[cfg(unix)]
1295    use std::os::unix::fs::PermissionsExt;
1296
1297    #[test]
1298    fn applies_gas_estimate_multiplier() {
1299        assert_eq!(apply_gas_estimate_multiplier(21_000, None).unwrap(), 21_000);
1300        assert_eq!(apply_gas_estimate_multiplier(21_000, Some(150)).unwrap(), 31_500);
1301        assert_eq!(
1302            apply_gas_estimate_multiplier(21_000, Some(1_000_000_000_000_000)).unwrap(),
1303            210_000_000_000_000_000
1304        );
1305        assert!(apply_gas_estimate_multiplier(u64::MAX, Some(101)).is_err());
1306    }
1307
1308    #[test]
1309    fn checkout_does_not_parse_revision_as_option() {
1310        let tmp = tempdir().unwrap();
1311        let git = Git::new(tmp.path());
1312        git.init().unwrap();
1313        fs::write(tmp.path().join("file"), "clean\n").unwrap();
1314        git.add(["file"]).unwrap();
1315        git.commit("initial").unwrap();
1316        fs::write(tmp.path().join("file"), "dirty\n").unwrap();
1317
1318        assert!(git.checkout_at("-f", tmp.path()).is_err());
1319        assert!(git.checkout_branch(false, "-f").is_err());
1320        assert_eq!(fs::read_to_string(tmp.path().join("file")).unwrap(), "dirty\n");
1321    }
1322
1323    #[cfg(unix)]
1324    #[test]
1325    fn fetch_does_not_parse_branch_as_option() {
1326        let remote = tempdir().unwrap();
1327        let remote_git = Git::new(remote.path());
1328        remote_git.init().unwrap();
1329        fs::write(remote.path().join("file"), "content\n").unwrap();
1330        remote_git.add(["file"]).unwrap();
1331        remote_git.commit("initial").unwrap();
1332
1333        let tmp = tempdir().unwrap();
1334        Git::clone(false, remote.path(), Some(tmp.path())).unwrap();
1335
1336        let marker = tmp.path().join("upload-pack-ran");
1337        let upload_pack = tmp.path().join("upload-pack");
1338        fs::write(
1339            &upload_pack,
1340            format!("#!/bin/sh\ntouch '{}'\nexec git-upload-pack \"$@\"\n", marker.display()),
1341        )
1342        .unwrap();
1343        let mut permissions = std::fs::metadata(&upload_pack).unwrap().permissions();
1344        permissions.set_mode(0o755);
1345        std::fs::set_permissions(&upload_pack, permissions).unwrap();
1346
1347        let branch = format!("--upload-pack={}", upload_pack.display());
1348        assert!(Git::new(tmp.path()).fetch_and_checkout_branch(tmp.path(), &branch).is_err());
1349        assert!(!marker.exists());
1350    }
1351
1352    #[test]
1353    fn parse_submodule_status() {
1354        let s = "+8829465a08cac423dcf59852f21e448449c1a1a8 lib/openzeppelin-contracts (v4.8.0-791-g8829465a)";
1355        let sub = Submodule::from_str(s).unwrap();
1356        assert_eq!(sub.rev(), "8829465a08cac423dcf59852f21e448449c1a1a8");
1357        assert_eq!(sub.path(), Path::new("lib/openzeppelin-contracts"));
1358
1359        let s = "-8829465a08cac423dcf59852f21e448449c1a1a8 lib/openzeppelin-contracts";
1360        let sub = Submodule::from_str(s).unwrap();
1361        assert_eq!(sub.rev(), "8829465a08cac423dcf59852f21e448449c1a1a8");
1362        assert_eq!(sub.path(), Path::new("lib/openzeppelin-contracts"));
1363
1364        let s = "8829465a08cac423dcf59852f21e448449c1a1a8 lib/openzeppelin-contracts";
1365        let sub = Submodule::from_str(s).unwrap();
1366        assert_eq!(sub.rev(), "8829465a08cac423dcf59852f21e448449c1a1a8");
1367        assert_eq!(sub.path(), Path::new("lib/openzeppelin-contracts"));
1368    }
1369
1370    #[test]
1371    fn parse_multiline_submodule_status() {
1372        let s = r#"+d3db4ef90a72b7d24aa5a2e5c649593eaef7801d lib/forge-std (v1.9.4-6-gd3db4ef)
1373+8829465a08cac423dcf59852f21e448449c1a1a8 lib/openzeppelin-contracts (v4.8.0-791-g8829465a)
1374"#;
1375        let subs = Submodules::from_str(s).unwrap().0;
1376        assert_eq!(subs.len(), 2);
1377        assert_eq!(subs[0].rev(), "d3db4ef90a72b7d24aa5a2e5c649593eaef7801d");
1378        assert_eq!(subs[0].path(), Path::new("lib/forge-std"));
1379        assert_eq!(subs[1].rev(), "8829465a08cac423dcf59852f21e448449c1a1a8");
1380        assert_eq!(subs[1].path(), Path::new("lib/openzeppelin-contracts"));
1381    }
1382
1383    #[test]
1384    fn deserialize_submodule() {
1385        let submodule: Submodule =
1386            parse_json(r#"{"rev":"8829465a08cac423dcf59852f21e448449c1a1a8","path":"lib/dep"}"#)
1387                .unwrap();
1388        assert_eq!(submodule.rev(), "8829465a08cac423dcf59852f21e448449c1a1a8");
1389        assert_eq!(submodule.path(), Path::new("lib/dep"));
1390        assert_eq!(
1391            serde_json::to_value(submodule).unwrap(),
1392            serde_json::json!({
1393                "rev": "8829465a08cac423dcf59852f21e448449c1a1a8",
1394                "path": "lib/dep",
1395            })
1396        );
1397    }
1398
1399    #[test]
1400    fn skips_submodule_status_if_dependencies_are_initialized() {
1401        let tmp = tempdir().unwrap();
1402        let root = tmp.path();
1403        std::fs::create_dir(root.join(".git")).unwrap();
1404        std::fs::write(
1405            root.join(".gitmodules"),
1406            r#"[submodule "lib/forge-std"]
1407	path = lib/forge-std
1408	url = https://github.com/foundry-rs/forge-std
1409"#,
1410        )
1411        .unwrap();
1412        std::fs::create_dir_all(root.join("lib/forge-std/.git")).unwrap();
1413
1414        let git = Git::new(root);
1415        assert!(git.submodules_initialized(&["lib".into()]).unwrap());
1416        assert!(git.submodules_initialized(&[root.join("lib").into()]).unwrap());
1417
1418        let nested = root.join("packages/contracts");
1419        std::fs::create_dir_all(&nested).unwrap();
1420        assert!(!Git::new(&nested).submodules_initialized(&["../../lib".into()]).unwrap());
1421
1422        // The fast path succeeds even though this is not a real Git repository.
1423        assert!(!git.has_missing_dependencies(["lib"]).unwrap());
1424
1425        std::fs::remove_dir(root.join("lib/forge-std/.git")).unwrap();
1426        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1427    }
1428
1429    #[test]
1430    fn foundry_path_ext_works() {
1431        let p = Path::new("contracts/MyTest.t.sol");
1432        assert!(p.is_sol_test());
1433        assert!(p.is_sol());
1434        let p = Path::new("contracts/Greeter.sol");
1435        assert!(!p.is_sol_test());
1436    }
1437
1438    #[test]
1439    fn parse_ether_value_accepts_hex_prefixed_wei() {
1440        assert_eq!(parse_ether_value("0x10").unwrap(), U256::from(16));
1441        assert_eq!(parse_ether_value("0X10").unwrap(), U256::from(16));
1442        assert_eq!(parse_ether_value("0x12").unwrap(), U256::from(0x12));
1443        assert_eq!(parse_ether_value("0xff").unwrap(), U256::from(0xff));
1444        assert_eq!(parse_ether_value("100").unwrap(), U256::from(100));
1445        assert_eq!(parse_ether_value("1ether").unwrap(), U256::from(1000000000000000000u128));
1446    }
1447
1448    // loads .env from cwd and project dir, See [`find_project_root()`]
1449    #[test]
1450    fn can_load_dotenv() {
1451        let temp = tempdir().unwrap();
1452        Git::new(temp.path()).init().unwrap();
1453        let cwd_env = temp.path().join(".env");
1454        fs::create_file(temp.path().join("foundry.toml")).unwrap();
1455        let nested = temp.path().join("nested");
1456        fs::create_dir(&nested).unwrap();
1457
1458        let mut cwd_file = File::create(cwd_env).unwrap();
1459        let mut prj_file = File::create(nested.join(".env")).unwrap();
1460
1461        cwd_file.write_all(b"TESTCWDKEY=cwd_val\nBROWSER=./project-browser").unwrap();
1462        cwd_file.sync_all().unwrap();
1463
1464        prj_file.write_all(b"TESTPRJKEY=prj_val\nBROWSER=./nested-browser").unwrap();
1465        prj_file.sync_all().unwrap();
1466
1467        let browser = env::var_os("BROWSER");
1468        unsafe { env::remove_var("BROWSER") };
1469        let cwd = env::current_dir().unwrap();
1470        env::set_current_dir(&nested).unwrap();
1471        load_dotenv();
1472        env::set_current_dir(cwd).unwrap();
1473
1474        let loaded_browser = env::var_os("BROWSER");
1475        unsafe {
1476            if let Some(browser) = browser {
1477                env::set_var("BROWSER", browser);
1478            } else {
1479                env::remove_var("BROWSER");
1480            }
1481        }
1482
1483        assert_eq!(env::var("TESTCWDKEY").unwrap(), "cwd_val");
1484        assert_eq!(env::var("TESTPRJKEY").unwrap(), "prj_val");
1485        assert_eq!(loaded_browser.as_deref(), Some(OsStr::new("./project-browser")));
1486    }
1487
1488    #[test]
1489    fn test_read_gitmodules() {
1490        let tmp = tempdir().unwrap();
1491        let read = |contents: &str| {
1492            fs::write(tmp.path().join(".gitmodules"), contents).unwrap();
1493            Git::new(tmp.path()).read_submodules_with_branch(tmp.path(), OsStr::new("lib")).unwrap()
1494        };
1495        let gitmodules = r#"
1496        [submodule "lib/solady"]
1497        path = lib/solady
1498        url = ""
1499        branch = v0.1.0
1500        [submodule "lib/openzeppelin-contracts"]
1501        path = lib/openzeppelin-contracts
1502        url = ""
1503        branch = v4.8.0-791-g8829465a
1504        [submodule "lib/forge-std"]
1505        path = lib/forge-std
1506        url = ""
1507"#;
1508
1509        let paths = read(gitmodules);
1510
1511        assert_eq!(paths.get(Path::new("lib/solady")).unwrap(), "v0.1.0");
1512        assert_eq!(
1513            paths.get(Path::new("lib/openzeppelin-contracts")).unwrap(),
1514            "v4.8.0-791-g8829465a"
1515        );
1516
1517        let no_branch_gitmodules = r#"
1518        [submodule "lib/solady"]
1519        path = lib/solady
1520        url = ""
1521        [submodule "lib/openzeppelin-contracts"]
1522        path = lib/openzeppelin-contracts
1523        url = ""
1524        [submodule "lib/forge-std"]
1525        path = lib/forge-std
1526        url = ""
1527"#;
1528        let paths = read(no_branch_gitmodules);
1529
1530        assert!(paths.is_empty());
1531
1532        let branch_in_between = r#"
1533        [submodule "lib/solady"]
1534        path = lib/solady
1535        url = ""
1536        [submodule "lib/openzeppelin-contracts"]
1537        path = lib/openzeppelin-contracts
1538        url = ""
1539        branch = v4.8.0-791-g8829465a
1540        [submodule "lib/forge-std"]
1541        path = lib/forge-std
1542        url = ""
1543        "#;
1544
1545        let paths = read(branch_in_between);
1546
1547        assert_eq!(paths.len(), 1);
1548        assert_eq!(
1549            paths.get(Path::new("lib/openzeppelin-contracts")).unwrap(),
1550            "v4.8.0-791-g8829465a"
1551        );
1552
1553        let quoted = r#"
1554        [submodule "named-dependency"]
1555        path = "packages/contracts/lib/dependency"
1556        branch="v1" # Git config quotes are not part of the branch name.
1557        [submodule "escaped"]
1558        path = lib/escaped
1559        branch = "feature/\"quoted\""
1560        [submodule "untracked"]
1561        path = lib/untracked
1562        "#;
1563        assert_eq!(
1564            read(quoted),
1565            HashMap::from_iter([
1566                (PathBuf::from("lib/dependency"), "v1".to_string()),
1567                (PathBuf::from("lib/escaped"), "feature/\"quoted\"".to_string()),
1568            ])
1569        );
1570
1571        let collision = r#"
1572        [submodule "nested"]
1573        path = packages/other/lib/dep
1574        branch = develop
1575        [submodule "root"]
1576        path = lib/dep
1577        branch = stable
1578        "#;
1579        assert_eq!(
1580            read(collision),
1581            HashMap::from_iter([(PathBuf::from("lib/dep"), "stable".to_string())])
1582        );
1583
1584        let duplicate_keys = r#"
1585        [submodule "dep"]
1586        path = lib/old
1587        branch = develop
1588        [submodule "dep"]
1589        branch = "stable"
1590        path = "packages/other/lib/dep"
1591        "#;
1592        assert_eq!(
1593            read(duplicate_keys),
1594            HashMap::from_iter([(PathBuf::from("lib/dep"), "stable".to_string())])
1595        );
1596    }
1597
1598    #[test]
1599    fn skips_submodule_status_outside_repository() {
1600        let tmp = tempdir().unwrap();
1601        let root = tmp.path().join("nested/project");
1602        fs::create_dir_all(&root).unwrap();
1603        let git = Git::new(&root);
1604        assert!(git.submodules_initialized(&["lib".into()]).unwrap());
1605        assert!(!git.has_missing_dependencies(["lib"]).unwrap());
1606    }
1607
1608    #[test]
1609    fn keeps_submodule_status_without_gitmodules() {
1610        let tmp = tempdir().unwrap();
1611        let git = Git::new(tmp.path());
1612        git.init().unwrap();
1613        fs::write(tmp.path().join("tracked"), "tracked file").unwrap();
1614        git.add(["tracked"]).unwrap();
1615
1616        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1617        assert!(git.has_missing_dependencies(["lib"]).is_err());
1618
1619        let nested = tmp.path().join("packages/contracts");
1620        fs::create_dir_all(&nested).unwrap();
1621        let git = git.root(&nested);
1622        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1623        assert!(git.has_missing_dependencies(["lib"]).is_err());
1624    }
1625
1626    #[test]
1627    fn detects_missing_dependencies_with_deleted_gitmodules() {
1628        let tmp = tempdir().unwrap();
1629        let git = Git::new(tmp.path());
1630        git.init().unwrap();
1631        let gitmodules = tmp.path().join(".gitmodules");
1632        fs::write(&gitmodules, "[submodule \"lib/dep\"]\n\tpath = lib/dep\n\turl = ../dep\n")
1633            .unwrap();
1634        git.add([".gitmodules"]).unwrap();
1635        git.cmd()
1636            .args([
1637                "update-index",
1638                "--add",
1639                "--cacheinfo",
1640                "160000,1111111111111111111111111111111111111111,lib/dep",
1641            ])
1642            .exec()
1643            .unwrap();
1644        assert!(git.has_missing_dependencies(["lib"]).unwrap());
1645
1646        fs::remove_file(gitmodules).unwrap();
1647        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1648        assert!(git.has_missing_dependencies(["lib"]).unwrap());
1649
1650        let nested = tmp.path().join("nested");
1651        fs::create_dir(&nested).unwrap();
1652        assert!(!git.root(&nested).submodules_initialized(&[]).unwrap());
1653        assert!(git.root(&nested).submodules_uninitialized().unwrap());
1654
1655        git.cmd().args(["rm", "--cached", ".gitmodules"]).exec().unwrap();
1656        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1657        assert!(git.has_missing_dependencies(["lib"]).is_err());
1658    }
1659
1660    #[test]
1661    fn keeps_submodule_status_in_worktree_without_gitmodules() {
1662        let tmp = tempdir().unwrap();
1663        let root = tmp.path().join("main");
1664        fs::create_dir(&root).unwrap();
1665        let git = Git::new(&root);
1666        git.init().unwrap();
1667        git.cmd()
1668            .args([
1669                "-c",
1670                "user.name=Foundry",
1671                "-c",
1672                "user.email=foundry@example.com",
1673                "commit",
1674                "--no-gpg-sign",
1675                "--allow-empty",
1676                "-m",
1677                "test: initialize worktree fixture",
1678            ])
1679            .exec()
1680            .unwrap();
1681        let worktree = tmp.path().join("worktree");
1682        git.cmd().args(["worktree", "add", "--detach"]).arg(&worktree).exec().unwrap();
1683
1684        assert!(worktree.join(".git").is_file());
1685        let git = git.root(&worktree);
1686        assert!(!git.submodules_initialized(&["lib".into()]).unwrap());
1687        assert!(git.has_missing_dependencies(["lib"]).is_err());
1688    }
1689
1690    #[test]
1691    fn sets_submodule_branch_with_native_path() {
1692        let tmp = tempdir().unwrap();
1693        let git = Git::new(tmp.path());
1694        git.init().unwrap();
1695        fs::write(
1696            tmp.path().join(".gitmodules"),
1697            "[submodule \"lib/dep\"]\npath = lib/dep\nurl = https://example.invalid/dep\n",
1698        )
1699        .unwrap();
1700
1701        git.set_submodule_branch(&Path::new("lib").join("dep"), "feature/v1").unwrap();
1702
1703        assert_eq!(
1704            git.read_submodules_with_branch(tmp.path(), OsStr::new("lib")).unwrap(),
1705            HashMap::from_iter([(PathBuf::from("lib/dep"), "feature/v1".to_string())])
1706        );
1707    }
1708
1709    #[test]
1710    fn spawn_output_names_the_program() {
1711        let dir = tempdir().unwrap();
1712        let program = dir.path().join("missing-program");
1713        let err = Command::new(&program).spawn_output().unwrap_err();
1714        assert_eq!(err.to_string(), format!("could not run `{}`", program.display()));
1715        assert_eq!(
1716            err.downcast_ref::<std::io::Error>().unwrap().kind(),
1717            std::io::ErrorKind::NotFound
1718        );
1719    }
1720
1721    #[test]
1722    fn spawn_output_preserves_working_directory_errors() {
1723        let dir = tempdir().unwrap();
1724        let missing = dir.path().join("missing");
1725        let file = dir.path().join("file");
1726        fs::write(&file, "not a directory").unwrap();
1727
1728        for cwd in [&missing, &file] {
1729            let mut command = Command::new("git");
1730            command.current_dir(cwd);
1731            let original = command.output().unwrap_err();
1732            let err = command.spawn_output().unwrap_err();
1733            assert_eq!(err.to_string(), format!("could not run `git` in {}", cwd.display()));
1734            assert_eq!(err.downcast_ref::<std::io::Error>().unwrap().kind(), original.kind());
1735        }
1736    }
1737
1738    #[cfg(unix)]
1739    #[test]
1740    fn spawn_output_preserves_executable_errors() {
1741        let dir = tempdir().unwrap();
1742        let program = dir.path().join("program");
1743        let interpreter = dir.path().join("missing-interpreter");
1744        fs::write(&program, format!("#!{}\n", interpreter.display())).unwrap();
1745
1746        for (mode, kind) in
1747            [(0o755, std::io::ErrorKind::NotFound), (0o644, std::io::ErrorKind::PermissionDenied)]
1748        {
1749            let mut permissions = std::fs::metadata(&program).unwrap().permissions();
1750            permissions.set_mode(mode);
1751            std::fs::set_permissions(&program, permissions).unwrap();
1752            let err = Command::new(&program).spawn_output().unwrap_err();
1753            assert_eq!(err.to_string(), format!("could not run `{}`", program.display()));
1754            assert_eq!(err.downcast_ref::<std::io::Error>().unwrap().kind(), kind);
1755        }
1756    }
1757}