joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use crate::error::{Error, Result};

/// Key/value configuration, read from the environment or a file.
///
/// Keys are normalised to lowercase with `_` collapsed to `.`, so
/// `APP_DATABASE_URL` and a file's `database.url` are the same setting whichever
/// way it arrives.
#[derive(Debug, Clone, Default)]
pub struct Config {
    values: BTreeMap<String, String>,
}

impl Config {
    pub fn new() -> Config {
        Config::default()
    }

    /// Read from the process environment, keeping variables that start with
    /// `prefix` and stripping it.
    pub fn from_env(prefix: &str) -> Config {
        Config::from_pairs(prefix, std::env::vars())
    }

    /// The testable half of `from_env`: same rules, explicit input.
    pub fn from_pairs<I, K, V>(prefix: &str, pairs: I) -> Config
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let mut values = BTreeMap::new();
        for (key, value) in pairs {
            let key = key.as_ref();
            if !key.starts_with(prefix) {
                continue;
            }
            let stripped = &key[prefix.len()..];
            if stripped.is_empty() {
                continue;
            }
            values.insert(normalise(stripped), value.as_ref().to_string());
        }
        Config { values }
    }

    /// Read `key = value` lines. `#` starts a comment, blank lines are ignored,
    /// and surrounding quotes on a value are stripped.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
        let text = fs::read_to_string(path.as_ref())
            .map_err(|e| Error::Config(format!("{}: {e}", path.as_ref().display())))?;
        Config::parse(&text)
    }

    pub fn parse(text: &str) -> Result<Config> {
        let mut values = BTreeMap::new();
        for (index, raw) in text.lines().enumerate() {
            let line = match raw.split_once('#') {
                Some((before, _)) => before.trim(),
                None => raw.trim(),
            };
            if line.is_empty() {
                continue;
            }
            let (key, value) = line.split_once('=').ok_or_else(|| {
                Error::Config(format!("line {}: expected key = value", index + 1))
            })?;
            let key = key.trim();
            if key.is_empty() {
                return Err(Error::Config(format!("line {}: empty key", index + 1)));
            }
            values.insert(normalise(key), unquote(value.trim()).to_string());
        }
        Ok(Config { values })
    }

    pub fn get(&self, key: &str) -> Option<&str> {
        self.values.get(&normalise(key)).map(|s| s.as_str())
    }

    pub fn get_or<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
        self.get(key).unwrap_or(default)
    }

    pub fn int(&self, key: &str) -> Option<i64> {
        self.get(key)?.trim().parse().ok()
    }

    /// `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are
    /// false. Anything else is `None` rather than a guess.
    pub fn bool(&self, key: &str) -> Option<bool> {
        match self.get(key)?.trim().to_ascii_lowercase().as_str() {
            "true" | "1" | "yes" | "on" => Some(true),
            "false" | "0" | "no" | "off" => Some(false),
            _ => None,
        }
    }

    pub fn set(&mut self, key: &str, value: &str) {
        self.values.insert(normalise(key), value.to_string());
    }

    /// Overlay `other` on top of this one. Later wins, which is what makes
    /// "file for defaults, environment for overrides" work.
    pub fn merge(&mut self, other: Config) {
        for (key, value) in other.values {
            self.values.insert(key, value);
        }
    }

    pub fn len(&self) -> usize {
        self.values.len()
    }

    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.values.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }
}

fn normalise(key: &str) -> String {
    key.trim()
        .trim_start_matches('_')
        .to_ascii_lowercase()
        .replace('_', ".")
}

fn unquote(value: &str) -> &str {
    let bytes = value.as_bytes();
    if bytes.len() >= 2
        && ((bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"')
            || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''))
    {
        &value[1..value.len() - 1]
    } else {
        value
    }
}

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

    #[test]
    fn reads_prefixed_environment_variables() {
        let cfg = Config::from_pairs(
            "APP_",
            vec![
                ("APP_DATABASE_URL", "postgres://localhost"),
                ("APP_PORT", "8080"),
                ("PATH", "/usr/bin"),
            ],
        );
        assert_eq!(cfg.get("database.url"), Some("postgres://localhost"));
        assert_eq!(cfg.int("port"), Some(8080));
        assert_eq!(cfg.get("path"), None);
    }

    #[test]
    fn environment_and_file_keys_agree() {
        let from_env = Config::from_pairs("APP_", vec![("APP_DATABASE_URL", "a")]);
        let from_file = Config::parse("database.url = b").unwrap();
        assert!(from_env.get("database.url").is_some());
        assert!(from_file.get("DATABASE_URL").is_some());
    }

    #[test]
    fn parses_comments_blanks_and_quotes() {
        let cfg =
            Config::parse("# a comment\n\nport = 3000\nname = \"joist\"  # trailing\nempty =\n")
                .unwrap();
        assert_eq!(cfg.int("port"), Some(3000));
        assert_eq!(cfg.get("name"), Some("joist"));
        assert_eq!(cfg.get("empty"), Some(""));
    }

    #[test]
    fn rejects_a_line_that_is_not_a_pair() {
        assert!(Config::parse("port 3000").is_err());
        assert!(Config::parse("= 3000").is_err());
    }

    #[test]
    fn booleans_accept_the_usual_spellings() {
        let cfg = Config::parse("a = true\nb = 0\nc = ON\nd = maybe").unwrap();
        assert_eq!(cfg.bool("a"), Some(true));
        assert_eq!(cfg.bool("b"), Some(false));
        assert_eq!(cfg.bool("c"), Some(true));
        assert_eq!(cfg.bool("d"), None);
    }

    #[test]
    fn merge_lets_the_later_source_win() {
        let mut base = Config::parse("port = 3000\nhost = localhost").unwrap();
        let overrides = Config::from_pairs("APP_", vec![("APP_PORT", "9000")]);
        base.merge(overrides);
        assert_eq!(cfg_port(&base), 9000);
        assert_eq!(base.get("host"), Some("localhost"));
    }

    fn cfg_port(c: &Config) -> i64 {
        c.int("port").unwrap()
    }

    #[test]
    fn get_or_supplies_a_default() {
        let cfg = Config::new();
        assert_eq!(cfg.get_or("host", "127.0.0.1"), "127.0.0.1");
    }
}