foundry_config/
resolve.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//! Helper for resolving env vars

use regex::Regex;
use std::{env, env::VarError, fmt, sync::LazyLock};

/// A regex that matches `${val}` placeholders
pub static RE_PLACEHOLDER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)(?P<outer>\$\{\s*(?P<inner>.*?)\s*})").unwrap());

/// Error when we failed to resolve an env var
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnresolvedEnvVarError {
    /// The unresolved input string
    pub unresolved: String,
    /// Var that couldn't be resolved
    pub var: String,
    /// the `env::var` error
    pub source: VarError,
}

impl UnresolvedEnvVarError {
    /// Tries to resolve a value
    pub fn try_resolve(&self) -> Result<String, Self> {
        interpolate(&self.unresolved)
    }

    fn is_simple(&self) -> bool {
        RE_PLACEHOLDER.captures_iter(&self.unresolved).count() <= 1
    }
}

impl fmt::Display for UnresolvedEnvVarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "environment variable `{}` ", self.var)?;
        f.write_str(match self.source {
            VarError::NotPresent => "not found",
            VarError::NotUnicode(_) => "is not valid unicode",
        })?;
        if !self.is_simple() {
            write!(f, " in `{}`", self.unresolved)?;
        }
        Ok(())
    }
}

impl std::error::Error for UnresolvedEnvVarError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

/// Replaces all Env var placeholders in the input string with the values they hold
pub fn interpolate(input: &str) -> Result<String, UnresolvedEnvVarError> {
    let mut res = input.to_string();

    // loop over all placeholders in the input and replace them one by one
    for caps in RE_PLACEHOLDER.captures_iter(input) {
        let var = &caps["inner"];
        let value = env::var(var).map_err(|source| UnresolvedEnvVarError {
            unresolved: input.to_string(),
            var: var.to_string(),
            source,
        })?;

        res = res.replacen(&caps["outer"], &value, 1);
    }
    Ok(res)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_find_placeholder() {
        let val = "https://eth-mainnet.alchemyapi.io/v2/346273846238426342";
        assert!(!RE_PLACEHOLDER.is_match(val));

        let val = "${RPC_ENV}";
        assert!(RE_PLACEHOLDER.is_match(val));

        let val = "https://eth-mainnet.alchemyapi.io/v2/${API_KEY}";
        assert!(RE_PLACEHOLDER.is_match(val));

        let cap = RE_PLACEHOLDER.captures(val).unwrap();
        assert_eq!(cap.name("outer").unwrap().as_str(), "${API_KEY}");
        assert_eq!(cap.name("inner").unwrap().as_str(), "API_KEY");
    }
}