hyperlane-plugin-env 23.3.0

A zero-dependency .env parser, layered typed environment configuration loader, redacting SecretValue wrapper, and HYPERLANE_* ServerConfig builder plugin for the Hyperlane framework.
Documentation
use super::*;

/// Validates an environment variable key (`[A-Za-z_][A-Za-z0-9_]*`).
///
/// # Arguments
///
/// - `&str` - Candidate key name.
///
/// # Returns
///
/// - `bool` - `true` when valid.
pub(crate) fn is_valid_key(key: &str) -> bool {
    let bytes: &[u8] = key.as_bytes();
    if bytes.is_empty() || !(bytes[0].is_ascii_alphabetic() || bytes[0] == b'_') {
        return false;
    }
    bytes
        .iter()
        .all(|b: &u8| b.is_ascii_alphanumeric() || *b == b'_')
}

/// Expands `${VAR}` placeholders using already-parsed entries and OS environment variables.
///
/// # Arguments
///
/// - `&str` - Raw value text.
/// - `&BTreeMap<String, String>` - Already parsed variables.
///
/// # Returns
///
/// - `String` - Interpolated string.
pub(crate) fn interpolate(raw: &str, parsed: &BTreeMap<String, String>) -> String {
    if !raw.as_bytes().contains(&b'$') || !raw.contains("${") {
        return raw.to_owned();
    }
    let mut out: String = String::with_capacity(raw.len());
    let mut rest: &str = raw;
    while let Some(idx) = rest.find("${") {
        out.push_str(&rest[..idx]);
        let after: &str = &rest[idx + 2..];
        if let Some(close) = after.find('}') {
            let key: &str = after[..close].trim();
            if let Some(val) = parsed.get(key) {
                out.push_str(val);
            } else if let Ok(val) = env::var(key) {
                out.push_str(&val);
            }
            rest = &after[close + 1..];
        } else {
            out.push_str("${");
            rest = after;
        }
    }
    out.push_str(rest);
    out
}

/// Parses a double-quoted `.env` value with escape sequences.
///
/// # Arguments
///
/// - `&str` - Slice starting immediately after the opening `"`.
/// - `usize` - 1-based line number for error reporting.
///
/// # Returns
///
/// - `Result<String, EnvError>` - Unescaped value or syntax error.
pub(crate) fn parse_double_quoted(raw: &str, line: usize) -> Result<String, EnvError> {
    let mut out: String = String::with_capacity(raw.len());
    let mut chars: Chars<'_> = raw.chars();
    while let Some(ch) = chars.next() {
        if ch == '"' {
            return Ok(out);
        }
        if ch == '\\' {
            let Some(esc) = chars.next() else {
                return Err(EnvError::Syntax {
                    line,
                    reason: ERR_UNCLOSED_QUOTE.to_owned(),
                });
            };
            match esc {
                'n' => out.push('\n'),
                'r' => out.push('\r'),
                't' => out.push('\t'),
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                other => {
                    out.push('\\');
                    out.push(other);
                }
            }
        } else {
            out.push(ch);
        }
    }
    Err(EnvError::Syntax {
        line,
        reason: ERR_UNCLOSED_QUOTE.to_owned(),
    })
}

/// Parses `.env` text into an ordered key-value map supporting quotes, `export`, comments, and `${VAR}`.
///
/// # Arguments
///
/// - `&str` - `.env` document content.
///
/// # Returns
///
/// - `Result<BTreeMap<String, String>, EnvError>` - Parsed key-value map or syntax error.
pub fn parse_dotenv(content: &str) -> Result<BTreeMap<String, String>, EnvError> {
    let mut out: BTreeMap<String, String> = BTreeMap::new();
    for (idx, raw_line) in content.lines().enumerate() {
        let line_no: usize = idx + 1;
        let trimmed: &str = raw_line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let body: &str = trimmed
            .strip_prefix(EXPORT_PREFIX)
            .unwrap_or(trimmed)
            .trim_start();
        let Some((key_raw, val_raw)) = body.split_once('=') else {
            return Err(EnvError::Syntax {
                line: line_no,
                reason: ERR_MISSING_EQ.to_owned(),
            });
        };
        let key: &str = key_raw.trim();
        if !is_valid_key(key) {
            return Err(EnvError::Syntax {
                line: line_no,
                reason: ERR_INVALID_KEY.to_owned(),
            });
        }
        let val_trim: &str = val_raw.trim();
        let value: String = if let Some(after_sq) = val_trim.strip_prefix('\'') {
            let Some(end) = after_sq.find('\'') else {
                return Err(EnvError::Syntax {
                    line: line_no,
                    reason: ERR_UNCLOSED_QUOTE.to_owned(),
                });
            };
            after_sq[..end].to_owned()
        } else if let Some(after_dq) = val_trim.strip_prefix('"') {
            let unescaped: String = parse_double_quoted(after_dq, line_no)?;
            interpolate(&unescaped, &out)
        } else {
            let no_comment: &str = match val_trim.find(" #") {
                Some(pos) => val_trim[..pos].trim_end(),
                None => val_trim,
            };
            interpolate(no_comment, &out)
        };
        let _: Option<String> = out.insert(key.to_owned(), value);
    }
    Ok(out)
}