Files
crank/crates/crank-config/src/source.rs

86 lines
2.9 KiB
Rust

use std::{collections::BTreeMap, ffi::OsString};
use crate::{ConfigError, Diagnostic, DiagnosticCode, deployment_field_registry, field_registry};
#[derive(Clone, Debug, Default)]
pub struct ConfigSource {
values: BTreeMap<String, String>,
}
impl ConfigSource {
pub fn from_utf8(values: BTreeMap<String, String>) -> Self {
Self { values }
}
pub fn from_os() -> Result<Self, ConfigError> {
Self::from_os_iter(std::env::vars_os())
}
pub fn from_os_for_migrator() -> Result<Self, ConfigError> {
Self::from_os_iter_filtered(std::env::vars_os(), |name| {
name.starts_with("POSTGRES_") || name.starts_with("CRANK_DATABASE_")
})
}
pub fn from_os_iter<I>(values: I) -> Result<Self, ConfigError>
where
I: IntoIterator<Item = (OsString, OsString)>,
{
Self::from_os_iter_filtered(values, |_| true)
}
fn from_os_iter_filtered<I, F>(values: I, include: F) -> Result<Self, ConfigError>
where
I: IntoIterator<Item = (OsString, OsString)>,
F: Fn(&str) -> bool,
{
let mut parsed = BTreeMap::new();
let mut diagnostics = Vec::new();
for (name, value) in values {
let Ok(name) = name.into_string() else {
// Owned names are ASCII. A non-UTF-8 name therefore cannot belong
// to Crank and must not make startup depend on unrelated OS state.
continue;
};
if !include(&name) {
continue;
}
let owned = name.starts_with("CRANK_")
|| name.starts_with("POSTGRES_")
|| name.starts_with("OTEL_");
let known = field_registry().iter().any(|field| field.env_name == name)
|| deployment_field_registry().contains(&name.as_str());
if !owned && !known {
continue;
}
let value = match value.into_string() {
Ok(value) => value,
Err(_) => {
let field = field_registry()
.iter()
.find(|field| field.env_name == name)
.map_or("environment.unknown", |field| field.semantic_path);
diagnostics.push(Diagnostic::new(DiagnosticCode::InvalidEncoding, field));
continue;
}
};
parsed.insert(name, value);
}
if diagnostics.is_empty() {
Ok(Self { values: parsed })
} else {
Err(ConfigError::from_diagnostics(diagnostics))
}
}
pub(crate) fn values(&self) -> &BTreeMap<String, String> {
&self.values
}
pub(crate) fn retain_for_migrator(mut self) -> Self {
self.values
.retain(|name, _| name.starts_with("POSTGRES_") || name.starts_with("CRANK_DATABASE_"));
self
}
}