use confers::config::{Source, SourceKind};
use confers::loader::{parse_content, Format};
use confers::types::{AnnotatedValue, SourceId};
use std::path::PathBuf;
fn path_name(path: &Option<PathBuf>) -> Option<&str> {
path.as_ref()
.and_then(|p| p.file_name())
.and_then(|n| n.to_str())
}
#[derive(Debug)]
pub(super) struct TomlContentSource {
content: String,
priority: u8,
source_id: SourceId,
name: String,
path: Option<PathBuf>,
}
impl TomlContentSource {
pub(super) fn new(content: String, path: Option<PathBuf>) -> Self {
let name = path_name(&path).unwrap_or("toml-content").to_string();
let source_id = SourceId::new(name.as_str());
Self {
content,
priority: 0,
source_id,
name,
path,
}
}
pub(super) fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
}
impl Source for TomlContentSource {
fn collect(&self) -> confers::ConfigResult<AnnotatedValue> {
parse_content(
&self.content,
Format::Toml,
self.source_id.clone(),
self.path.as_deref(),
)
.map(|v| v.with_priority(self.priority))
}
fn priority(&self) -> u8 {
self.priority
}
fn name(&self) -> &str {
&self.name
}
fn source_kind(&self) -> SourceKind {
SourceKind::Memory
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collect_parses_valid_toml() {
let source = TomlContentSource::new(
r#"token_style = "jwt"
timeout = 1800"#
.to_string(),
None,
)
.with_priority(10);
let result = source.collect().expect("合法 TOML 应解析成功");
assert_eq!(result.priority, 10);
assert!(result.is_map(), "TOML 顶层应为 map");
}
#[test]
fn with_priority_sets_priority() {
let source = TomlContentSource::new(String::new(), None);
assert_eq!(source.priority(), 0);
let source = source.with_priority(42);
assert_eq!(source.priority(), 42);
}
#[test]
fn collect_propagates_parse_error() {
let source = TomlContentSource::new("this is not = valid = toml".to_string(), None);
let result = source.collect();
assert!(result.is_err(), "非法 TOML 应返回 Err");
}
#[test]
fn source_kind_is_memory() {
let source = TomlContentSource::new(String::new(), None);
assert_eq!(source.source_kind(), SourceKind::Memory);
}
#[test]
fn name_and_source_id_derived_from_path() {
let path = PathBuf::from("/some/dir/my-config.toml");
let source = TomlContentSource::new(String::new(), Some(path));
assert_eq!(source.name(), "my-config.toml");
assert_eq!(source.source_id.as_str(), "my-config.toml");
}
#[test]
fn name_fallback_when_path_none() {
let source = TomlContentSource::new(String::new(), None);
assert_eq!(source.name(), "toml-content");
assert_eq!(source.source_id.as_str(), "toml-content");
}
}