| 1 | use std::path::PathBuf; |
| 2 | |
| 3 | use serde::Deserialize; |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | #[derive(Debug, Clone, Deserialize)] |
| 9 | pub struct AppConfig { |
| 10 | |
| 11 | #[serde(default = "default_database_url")] |
| 12 | pub database_url: String, |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | #[serde(default = "default_data_dir")] |
| 20 | pub data_dir: PathBuf, |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | #[serde(default)] |
| 28 | pub insecure_cookies: bool, |
| 29 | } |
| 30 | |
| 31 | fn default_database_url() -> String { |
| 32 | "sqlite:steid.db?mode=rwc".to_owned() |
| 33 | } |
| 34 | |
| 35 | fn default_data_dir() -> PathBuf { |
| 36 | PathBuf::from("./data") |
| 37 | } |
| 38 | |
| 39 | impl AppConfig { |
| 40 | |
| 41 | pub fn from_env() -> Result<Self, envy::Error> { |
| 42 | envy::prefixed("STEID_").from_env() |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | #[cfg(test)] |
| 47 | mod tests { |
| 48 | use super::*; |
| 49 | |
| 50 | |
| 51 | |
| 52 | fn from_pairs(pairs: &[(&str, &str)]) -> Result<AppConfig, envy::Error> { |
| 53 | envy::prefixed("STEID_").from_iter( |
| 54 | pairs |
| 55 | .iter() |
| 56 | .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())), |
| 57 | ) |
| 58 | } |
| 59 | |
| 60 | #[test] |
| 61 | fn applies_defaults_when_environment_is_empty() { |
| 62 | let config = from_pairs(&[]).expect("defaults should satisfy every field"); |
| 63 | |
| 64 | assert_eq!(config.database_url, "sqlite:steid.db?mode=rwc"); |
| 65 | assert_eq!(config.data_dir, PathBuf::from("./data")); |
| 66 | } |
| 67 | |
| 68 | #[test] |
| 69 | fn reads_prefixed_variables() { |
| 70 | let config = from_pairs(&[ |
| 71 | ("STEID_DATABASE_URL", "sqlite:custom.db?mode=rwc"), |
| 72 | ("STEID_DATA_DIR", "/srv/steid/repos"), |
| 73 | ]) |
| 74 | .expect("explicit values should parse"); |
| 75 | |
| 76 | assert_eq!(config.database_url, "sqlite:custom.db?mode=rwc"); |
| 77 | assert_eq!(config.data_dir, PathBuf::from("/srv/steid/repos")); |
| 78 | } |
| 79 | |
| 80 | #[test] |
| 81 | fn ignores_unprefixed_variables() { |
| 82 | let config = from_pairs(&[("DATA_DIR", "/should/be/ignored")]) |
| 83 | .expect("unprefixed keys should not interfere"); |
| 84 | |
| 85 | assert_eq!(config.data_dir, PathBuf::from("./data")); |
| 86 | } |
| 87 | } |