Skip to main content

foundry_config/
utils.rs

1//! Utility functions
2
3use crate::Config;
4use alloy_primitives::U256;
5use figment::value::Value;
6use foundry_compilers::artifacts::remappings::{Remapping, RemappingError};
7use serde::{
8    Deserialize, Deserializer, Serializer,
9    de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor},
10};
11use std::{
12    fmt, fs,
13    io::{self, BufReader},
14    path::{Path, PathBuf},
15    str::FromStr,
16};
17
18// TODO: Why do these exist separately from `Config::load`?
19
20/// Loads the config for the current project workspace.
21pub fn load_config() -> eyre::Result<Config> {
22    load_config_with_root(None)
23}
24
25/// Loads the config for the current project workspace or the provided root path.
26pub fn load_config_with_root(root: Option<&Path>) -> eyre::Result<Config> {
27    let root = match root {
28        Some(root) => root,
29        None => &find_project_root(None)?,
30    };
31    Ok(Config::load_with_root(root)?.sanitized())
32}
33
34/// Returns the path of the top-level directory of the working git tree.
35pub fn find_git_root(relative_to: &Path) -> io::Result<Option<PathBuf>> {
36    let root =
37        if relative_to.is_absolute() { relative_to } else { &dunce::canonicalize(relative_to)? };
38    Ok(root.ancestors().find(|p| p.join(".git").exists()).map(Path::to_path_buf))
39}
40
41/// Returns the root path to set for the project root.
42///
43/// Traverse the dir tree up and look for a `foundry.toml` file starting at the given path or cwd,
44/// but only until the root dir of the current repo so that:
45///
46/// ```text
47/// -- foundry.toml
48///
49/// -- repo
50///   |__ .git
51///   |__sub
52///      |__ [given_path | cwd]
53/// ```
54///
55/// will still detect `repo` as root.
56///
57/// Returns `repo` or `cwd` if no `foundry.toml` is found in the tree.
58///
59/// Returns an error if:
60/// - `cwd` is `Some` and is not a valid directory;
61/// - `cwd` is `None` and the [`std::env::current_dir`] call fails.
62pub fn find_project_root(cwd: Option<&Path>) -> io::Result<PathBuf> {
63    let cwd = match cwd {
64        Some(path) => path,
65        None => &std::env::current_dir()?,
66    };
67    let boundary = find_git_root(cwd)?;
68    let found = cwd
69        .ancestors()
70        // Don't look outside of the git repo if it exists.
71        .take_while(|p| boundary.as_ref().is_none_or(|boundary| p.starts_with(boundary)))
72        .find(|p| p.join(Config::FILE_NAME).is_file())
73        .map(Path::to_path_buf);
74    Ok(found.or(boundary).unwrap_or_else(|| cwd.to_path_buf()))
75}
76
77/// Returns all [`Remapping`]s contained in the `remappings` str separated by newlines
78///
79/// # Example
80///
81/// ```
82/// use foundry_config::remappings_from_newline;
83/// let remappings: Result<Vec<_>, _> = remappings_from_newline(
84///     r#"
85///              file-ds-test/=lib/ds-test/
86///              file-other/=lib/other/
87///          "#,
88/// )
89/// .collect();
90/// ```
91pub fn remappings_from_newline(
92    remappings: &str,
93) -> impl Iterator<Item = Result<Remapping, RemappingError>> + '_ {
94    remappings.lines().map(|x| x.trim()).filter(|x| !x.is_empty()).map(Remapping::from_str)
95}
96
97/// Returns the remappings from the given var
98///
99/// Returns `None` if the env var is not set, otherwise all Remappings, See
100/// `remappings_from_newline`
101pub fn remappings_from_env_var(env_var: &str) -> Option<Result<Vec<Remapping>, RemappingError>> {
102    let val = std::env::var(env_var).ok()?;
103    Some(remappings_from_newline(&val).collect())
104}
105
106/// Converts the `val` into a `figment::Value::Array`
107///
108/// The values should be separated by commas, surrounding brackets are also supported `[a,b,c]`
109pub fn to_array_value(val: &str) -> Result<Value, figment::Error> {
110    Ok(val
111        .trim()
112        .trim_start_matches('[')
113        .trim_end_matches(']')
114        .split(',')
115        .map(str::trim)
116        .filter(|s| !s.is_empty())
117        .map(String::from)
118        .collect::<Vec<_>>()
119        .into())
120}
121
122/// Returns a list of _unique_ paths to all folders under `root` that contain a `foundry.toml` file
123///
124/// This will also resolve symlinks
125///
126/// # Example
127///
128/// ```no_run
129/// use foundry_config::utils;
130/// let dirs = utils::foundry_toml_dirs("./lib");
131/// ```
132///
133/// for following layout this will return
134/// `["lib/dep1", "lib/dep2"]`
135///
136/// ```text
137/// lib
138/// └── dep1
139/// │   ├── foundry.toml
140/// └── dep2
141///     ├── foundry.toml
142/// ```
143pub fn foundry_toml_dirs(root: impl AsRef<Path>) -> Vec<PathBuf> {
144    walkdir::WalkDir::new(root)
145        .max_depth(1)
146        .into_iter()
147        .filter_map(Result::ok)
148        .filter(|entry| entry.file_type().is_dir())
149        .filter_map(|entry| dunce::canonicalize(entry.path()).ok())
150        .filter(|path| path.join(Config::FILE_NAME).exists())
151        .collect()
152}
153
154/// A depth-one dependency path and the canonical directory it resolves to.
155#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
156pub(crate) struct FoundryTomlDir {
157    /// The canonical directory used to identify the dependency config.
158    pub canonical: PathBuf,
159    /// The lexical path under the configured dependency directory.
160    pub path: PathBuf,
161}
162
163/// Returns depth-one dependency entries that resolve to directories containing `foundry.toml`.
164pub(crate) fn foundry_toml_dir_entries(root: impl AsRef<Path>) -> Vec<FoundryTomlDir> {
165    let mut dirs = walkdir::WalkDir::new(root)
166        .max_depth(1)
167        .into_iter()
168        .filter_map(Result::ok)
169        .filter_map(|entry| {
170            let canonical = dunce::canonicalize(entry.path()).ok()?;
171            (canonical.is_dir() && canonical.join(Config::FILE_NAME).exists())
172                .then(|| FoundryTomlDir { path: entry.path().to_path_buf(), canonical })
173        })
174        .collect::<Vec<_>>();
175    dirs.sort_unstable_by(|a, b| a.canonical.cmp(&b.canonical).then_with(|| a.path.cmp(&b.path)));
176    dirs.dedup();
177    dirs
178}
179
180/// Returns a remapping for the given dir
181pub(crate) fn get_dir_remapping(dir: impl AsRef<Path>) -> Option<Remapping> {
182    let dir = dir.as_ref();
183    dir.file_name().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).map(|dir_name| {
184        let mut r = Remapping {
185            context: None,
186            name: format!("{dir_name}/"),
187            path: format!("{}", dir.display()),
188        };
189        if !r.path.ends_with('/') {
190            r.path.push('/')
191        }
192        r
193    })
194}
195
196/// Deserialize stringified percent. The value must be between 0 and 100 inclusive.
197pub(crate) fn deserialize_stringified_percent<'de, D>(deserializer: D) -> Result<u32, D::Error>
198where
199    D: Deserializer<'de>,
200{
201    let num: U256 = Numeric::deserialize(deserializer)?.into();
202    let num: u64 = num.try_into().map_err(serde::de::Error::custom)?;
203    if num <= 100 {
204        num.try_into().map_err(serde::de::Error::custom)
205    } else {
206        Err(serde::de::Error::custom("percent must be lte 100"))
207    }
208}
209
210/// Deserialize a `u64` or "max" for `u64::MAX`.
211pub(crate) fn deserialize_u64_or_max<'de, D>(deserializer: D) -> Result<u64, D::Error>
212where
213    D: Deserializer<'de>,
214{
215    #[derive(Deserialize)]
216    #[serde(untagged)]
217    enum Val {
218        Number(u64),
219        String(String),
220    }
221
222    match Val::deserialize(deserializer)? {
223        Val::Number(num) => Ok(num),
224        Val::String(s) if s.eq_ignore_ascii_case("max") => Ok(u64::MAX),
225        Val::String(s) => s.parse::<u64>().map_err(D::Error::custom),
226    }
227}
228
229/// Deserialize a `usize` or "max" for `usize::MAX`.
230pub(crate) fn deserialize_usize_or_max<'de, D>(deserializer: D) -> Result<usize, D::Error>
231where
232    D: Deserializer<'de>,
233{
234    deserialize_u64_or_max(deserializer)?.try_into().map_err(D::Error::custom)
235}
236
237/// Serialize a `usize` as `"max"` if it equals `usize::MAX`, as a string if it exceeds
238/// `i64::MAX` (TOML integer limit), or as a plain number otherwise.
239pub(crate) fn serialize_usize_or_max<S>(value: &usize, serializer: S) -> Result<S::Ok, S::Error>
240where
241    S: Serializer,
242{
243    if *value == usize::MAX {
244        serializer.serialize_str("max")
245    } else if *value > i64::MAX as usize {
246        serializer.serialize_str(&value.to_string())
247    } else {
248        serializer.serialize_u64(*value as u64)
249    }
250}
251
252/// Deserialize into `U256` from either a `u64`, a `U256` hex string, or a decimal string.
253pub fn deserialize_u64_to_u256<'de, D>(deserializer: D) -> Result<U256, D::Error>
254where
255    D: Deserializer<'de>,
256{
257    #[derive(Deserialize)]
258    #[serde(untagged)]
259    enum NumericValue {
260        U256(U256),
261        U64(u64),
262        String(String),
263    }
264
265    match NumericValue::deserialize(deserializer)? {
266        NumericValue::U64(n) => Ok(U256::from(n)),
267        NumericValue::U256(n) => Ok(n),
268        NumericValue::String(s) => {
269            // Handle decimal strings (e.g., "18446744073709551615")
270            U256::from_str(&s).map_err(D::Error::custom)
271        }
272    }
273}
274
275/// Serialize `U256` as `u64` if it fits, otherwise as a hex string.
276/// If the number fits into a i64, serialize it as number without quotation marks.
277/// If the number fits into a u64, serialize it as a stringified number with quotation marks.
278/// Otherwise, serialize it as a hex string with quotation marks.
279pub fn serialize_u64_or_u256<S>(n: &U256, serializer: S) -> Result<S::Ok, S::Error>
280where
281    S: Serializer,
282{
283    // The TOML specification handles integers as i64 so the number representation is limited to
284    // i64. If the number is larger than `i64::MAX` and up to `u64::MAX`, we serialize it as a
285    // string to avoid losing precision.
286    if let Ok(n_i64) = i64::try_from(*n) {
287        serializer.serialize_i64(n_i64)
288    } else if let Ok(n_u64) = u64::try_from(*n) {
289        serializer.serialize_str(&n_u64.to_string())
290    } else {
291        serializer.serialize_str(&format!("{n:#x}"))
292    }
293}
294
295/// Helper type to parse both `u64` and `U256`
296#[derive(Clone, Copy, Deserialize)]
297#[serde(untagged)]
298pub enum Numeric {
299    /// A [U256] value.
300    U256(U256),
301    /// A `u64` value.
302    Num(u64),
303}
304
305impl From<Numeric> for U256 {
306    fn from(n: Numeric) -> Self {
307        match n {
308            Numeric::U256(n) => n,
309            Numeric::Num(n) => Self::from(n),
310        }
311    }
312}
313
314impl FromStr for Numeric {
315    type Err = String;
316
317    fn from_str(s: &str) -> Result<Self, Self::Err> {
318        if s.starts_with("0x") {
319            U256::from_str_radix(s, 16).map(Numeric::U256).map_err(|err| err.to_string())
320        } else {
321            U256::from_str(s).map(Numeric::U256).map_err(|err| err.to_string())
322        }
323    }
324}
325
326/// Reads the compiler `input` of the build info at `path`, or `None` if the build info leaves it
327/// out, as build infos do unless `build_info` is set. A JSON object with neither an `id` nor an
328/// `input` is not a build info and fails.
329///
330/// The read stops after the input, which build infos write before the much larger output.
331pub fn read_build_info_input<T: DeserializeOwned>(path: &Path) -> eyre::Result<Option<T>> {
332    let mut input = None;
333    let reader = BufReader::new(fs::File::open(path)?);
334    let read =
335        serde_json::Deserializer::from_reader(reader).deserialize_map(BuildInfoInput(&mut input));
336    match (input, read) {
337        (Some(input), _) => Ok(Some(input)),
338        (None, Ok(())) => Ok(None),
339        (None, Err(error)) => Err(error.into()),
340    }
341}
342
343/// Reads the `input` of a build info into `input`.
344struct BuildInfoInput<'a, T>(&'a mut Option<T>);
345
346impl<'de, T: Deserialize<'de>> Visitor<'de> for BuildInfoInput<'_, T> {
347    type Value = ();
348
349    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
350        formatter.write_str("a build info")
351    }
352
353    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
354        let mut id = false;
355        while let Some(key) = map.next_key::<String>()? {
356            if key == "input" {
357                *self.0 = Some(map.next_value()?);
358                // An error is the only way to stop the deserializer before the end of the map.
359                return Err(A::Error::custom("stopped after the input"));
360            }
361            id |= key == "id";
362            map.next_value::<IgnoredAny>()?;
363        }
364        if id { Ok(()) } else { Err(A::Error::custom("not a build info")) }
365    }
366}
367
368/// A value that is there, deserialized without reading it. [`read_build_info_input`] stops after
369/// the input, so `read_build_info_input::<Present>` only checks that a build info has one.
370pub(crate) struct Present;
371
372impl<'de> Deserialize<'de> for Present {
373    fn deserialize<D: Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
374        Ok(Self)
375    }
376}
377
378#[cfg(all(test, unix))]
379mod tests {
380    use super::{FoundryTomlDir, foundry_toml_dir_entries, foundry_toml_dirs};
381    use std::{fs, os::unix::fs::symlink};
382    use tempfile::tempdir;
383
384    #[test]
385    fn finds_physical_foundry_toml_dirs_without_recursing() {
386        let temp = tempdir().unwrap();
387        let root = temp.path().join("lib");
388        let dependency = root.join("dependency");
389        let nested = dependency.join("nested");
390        fs::create_dir_all(&nested).unwrap();
391        fs::write(dependency.join("foundry.toml"), "").unwrap();
392        fs::write(nested.join("foundry.toml"), "").unwrap();
393
394        assert_eq!(foundry_toml_dirs(&root), vec![dunce::canonicalize(dependency).unwrap()]);
395    }
396
397    #[test]
398    fn preserves_sorted_aliases_for_the_same_canonical_dependency() {
399        let temp = tempdir().unwrap();
400        let root = temp.path().join("lib");
401        let dependency = temp.path().join("dependency");
402        fs::create_dir_all(&root).unwrap();
403        fs::create_dir_all(&dependency).unwrap();
404        fs::write(dependency.join("foundry.toml"), "").unwrap();
405        symlink(&dependency, root.join("z-alias")).unwrap();
406        symlink(&dependency, root.join("a-alias")).unwrap();
407
408        let canonical = dunce::canonicalize(dependency).unwrap();
409        assert_eq!(
410            foundry_toml_dir_entries(&root),
411            vec![
412                FoundryTomlDir { path: root.join("a-alias"), canonical: canonical.clone() },
413                FoundryTomlDir { path: root.join("z-alias"), canonical },
414            ]
415        );
416    }
417
418    #[test]
419    fn sorts_distinct_dependencies_by_canonical_path() {
420        let temp = tempdir().unwrap();
421        let root = temp.path().join("lib");
422        let dependency_a = temp.path().join("dependency-a");
423        let dependency_z = temp.path().join("dependency-z");
424        fs::create_dir_all(&root).unwrap();
425        for dependency in [&dependency_z, &dependency_a] {
426            fs::create_dir_all(dependency).unwrap();
427            fs::write(dependency.join("foundry.toml"), "").unwrap();
428        }
429        symlink(&dependency_z, root.join("a-alias")).unwrap();
430        symlink(&dependency_a, root.join("z-alias")).unwrap();
431
432        let canonical = foundry_toml_dir_entries(&root)
433            .into_iter()
434            .map(|entry| entry.canonical)
435            .collect::<Vec<_>>();
436        assert_eq!(
437            canonical,
438            vec![
439                dunce::canonicalize(dependency_a).unwrap(),
440                dunce::canonicalize(dependency_z).unwrap(),
441            ]
442        );
443    }
444
445    #[test]
446    fn ignores_broken_and_cyclic_symlinks() {
447        let temp = tempdir().unwrap();
448        let root = temp.path().join("lib");
449        fs::create_dir_all(&root).unwrap();
450        symlink("missing", root.join("broken")).unwrap();
451        symlink("cycle-b", root.join("cycle-a")).unwrap();
452        symlink("cycle-a", root.join("cycle-b")).unwrap();
453
454        assert!(foundry_toml_dir_entries(&root).is_empty());
455    }
456}