use std::borrow::Cow;
use std::fmt;
#[derive(Debug, Clone)]
pub struct ConfigKey {
env: String,
parts: Vec<(String, usize)>,
}
impl ConfigKey {
pub fn new() -> ConfigKey {
ConfigKey {
env: "CARGO".to_string(),
parts: Vec::new(),
}
}
pub fn from_str(key: &str) -> ConfigKey {
let mut cfg = ConfigKey::new();
for part in key.split('.') {
cfg.push(part);
}
cfg
}
pub fn push(&mut self, name: &str) {
let env = name.replace("-", "_").to_uppercase();
self._push(&env, name);
}
pub fn push_sensitive(&mut self, name: &str) {
self._push(name, name);
}
fn _push(&mut self, env: &str, config: &str) {
self.parts.push((config.to_string(), self.env.len()));
self.env.push('_');
self.env.push_str(env);
}
pub fn pop(&mut self) {
let (_part, env) = self.parts.pop().unwrap();
self.env.truncate(env);
}
pub fn as_env_key(&self) -> &str {
&self.env
}
pub(crate) fn parts(&self) -> impl Iterator<Item = &str> {
self.parts.iter().map(|p| p.0.as_ref())
}
pub fn is_root(&self) -> bool {
self.parts.is_empty()
}
pub fn matches(&self, pattern: &str) -> bool {
let mut parts = self.parts();
pattern
.split('.')
.all(|pat| parts.next() == Some(pat) || pat == "*")
&& parts.next().is_none()
}
}
impl fmt::Display for ConfigKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let parts: Vec<_> = self.parts().map(|part| escape_key_part(part)).collect();
parts.join(".").fmt(f)
}
}
#[derive(Debug, Clone)]
pub enum KeyOrIdx {
Key(String),
Idx(usize),
}
#[derive(Debug, Clone)]
pub struct ArrayItemKeyPath {
base: ConfigKey,
path: Vec<KeyOrIdx>,
}
impl ArrayItemKeyPath {
pub fn new(base: ConfigKey) -> Self {
Self {
base,
path: Vec::new(),
}
}
pub fn push_key(&mut self, k: String) {
self.path.push(KeyOrIdx::Key(k))
}
pub fn push_index(&mut self, i: usize) {
self.path.push(KeyOrIdx::Idx(i))
}
}
impl fmt::Display for ArrayItemKeyPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.base)?;
for k in self.path.iter().rev() {
match k {
KeyOrIdx::Key(s) => {
f.write_str(".")?;
f.write_str(&escape_key_part(&s))?;
}
KeyOrIdx::Idx(i) => {
write!(f, "[{i}]")?;
}
}
}
Ok(())
}
}
pub(super) fn escape_key_part<'a>(part: &'a str) -> Cow<'a, str> {
let ok = part.chars().all(|c| {
matches!(c,
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_')
});
if ok {
Cow::Borrowed(part)
} else {
Cow::Owned(toml::Value::from(part).to_string())
}
}
#[cfg(test)]
mod tests {
use snapbox::assert_data_eq;
use snapbox::str;
use super::*;
#[test]
fn array_item_key_path_display() {
let base = ConfigKey::from_str("array");
let mut key_path = ArrayItemKeyPath::new(base);
key_path.push_index(1);
key_path.push_key("rustflags".into());
key_path.push_key("thumbv8m.base-none-eabi".into());
key_path.push_index(2);
key_path.push_index(3);
assert_data_eq!(
key_path.to_string(),
str![[r#"array[3][2]."thumbv8m.base-none-eabi".rustflags[1]"#]]
);
}
}