Skip to main content

hyperlane_plugin_env/
fn.rs

1use super::*;
2
3/// Validates an environment variable key (`[A-Za-z_][A-Za-z0-9_]*`).
4///
5/// # Arguments
6///
7/// - `&str` - Candidate key name.
8///
9/// # Returns
10///
11/// - `bool` - `true` when valid.
12pub(crate) fn is_valid_key(key: &str) -> bool {
13    let bytes: &[u8] = key.as_bytes();
14    if bytes.is_empty() || !(bytes[0].is_ascii_alphabetic() || bytes[0] == b'_') {
15        return false;
16    }
17    bytes
18        .iter()
19        .all(|b: &u8| b.is_ascii_alphanumeric() || *b == b'_')
20}
21
22/// Expands `${VAR}` placeholders using already-parsed entries and OS environment variables.
23///
24/// # Arguments
25///
26/// - `&str` - Raw value text.
27/// - `&BTreeMap<String, String>` - Already parsed variables.
28///
29/// # Returns
30///
31/// - `String` - Interpolated string.
32pub(crate) fn interpolate(raw: &str, parsed: &BTreeMap<String, String>) -> String {
33    if !raw.as_bytes().contains(&b'$') || !raw.contains("${") {
34        return raw.to_owned();
35    }
36    let mut out: String = String::with_capacity(raw.len());
37    let mut rest: &str = raw;
38    while let Some(idx) = rest.find("${") {
39        out.push_str(&rest[..idx]);
40        let after: &str = &rest[idx + 2..];
41        if let Some(close) = after.find('}') {
42            let key: &str = after[..close].trim();
43            if let Some(val) = parsed.get(key) {
44                out.push_str(val);
45            } else if let Ok(val) = env::var(key) {
46                out.push_str(&val);
47            }
48            rest = &after[close + 1..];
49        } else {
50            out.push_str("${");
51            rest = after;
52        }
53    }
54    out.push_str(rest);
55    out
56}
57
58/// Parses a double-quoted `.env` value with escape sequences.
59///
60/// # Arguments
61///
62/// - `&str` - Slice starting immediately after the opening `"`.
63/// - `usize` - 1-based line number for error reporting.
64///
65/// # Returns
66///
67/// - `Result<String, EnvError>` - Unescaped value or syntax error.
68pub(crate) fn parse_double_quoted(raw: &str, line: usize) -> Result<String, EnvError> {
69    let mut out: String = String::with_capacity(raw.len());
70    let mut chars: Chars<'_> = raw.chars();
71    while let Some(ch) = chars.next() {
72        if ch == '"' {
73            return Ok(out);
74        }
75        if ch == '\\' {
76            let Some(esc) = chars.next() else {
77                return Err(EnvError::Syntax {
78                    line,
79                    reason: ERR_UNCLOSED_QUOTE.to_owned(),
80                });
81            };
82            match esc {
83                'n' => out.push('\n'),
84                'r' => out.push('\r'),
85                't' => out.push('\t'),
86                '"' => out.push('"'),
87                '\\' => out.push('\\'),
88                other => {
89                    out.push('\\');
90                    out.push(other);
91                }
92            }
93        } else {
94            out.push(ch);
95        }
96    }
97    Err(EnvError::Syntax {
98        line,
99        reason: ERR_UNCLOSED_QUOTE.to_owned(),
100    })
101}
102
103/// Parses `.env` text into an ordered key-value map supporting quotes, `export`, comments, and `${VAR}`.
104///
105/// # Arguments
106///
107/// - `&str` - `.env` document content.
108///
109/// # Returns
110///
111/// - `Result<BTreeMap<String, String>, EnvError>` - Parsed key-value map or syntax error.
112pub fn parse_dotenv(content: &str) -> Result<BTreeMap<String, String>, EnvError> {
113    let mut out: BTreeMap<String, String> = BTreeMap::new();
114    for (idx, raw_line) in content.lines().enumerate() {
115        let line_no: usize = idx + 1;
116        let trimmed: &str = raw_line.trim();
117        if trimmed.is_empty() || trimmed.starts_with('#') {
118            continue;
119        }
120        let body: &str = trimmed
121            .strip_prefix(EXPORT_PREFIX)
122            .unwrap_or(trimmed)
123            .trim_start();
124        let Some((key_raw, val_raw)) = body.split_once('=') else {
125            return Err(EnvError::Syntax {
126                line: line_no,
127                reason: ERR_MISSING_EQ.to_owned(),
128            });
129        };
130        let key: &str = key_raw.trim();
131        if !is_valid_key(key) {
132            return Err(EnvError::Syntax {
133                line: line_no,
134                reason: ERR_INVALID_KEY.to_owned(),
135            });
136        }
137        let val_trim: &str = val_raw.trim();
138        let value: String = if let Some(after_sq) = val_trim.strip_prefix('\'') {
139            let Some(end) = after_sq.find('\'') else {
140                return Err(EnvError::Syntax {
141                    line: line_no,
142                    reason: ERR_UNCLOSED_QUOTE.to_owned(),
143                });
144            };
145            after_sq[..end].to_owned()
146        } else if let Some(after_dq) = val_trim.strip_prefix('"') {
147            let unescaped: String = parse_double_quoted(after_dq, line_no)?;
148            interpolate(&unescaped, &out)
149        } else {
150            let no_comment: &str = match val_trim.find(" #") {
151                Some(pos) => val_trim[..pos].trim_end(),
152                None => val_trim,
153            };
154            interpolate(no_comment, &out)
155        };
156        let _: Option<String> = out.insert(key.to_owned(), value);
157    }
158    Ok(out)
159}