use std::fmt;
use toml_edit::{DocumentMut, TableLike};
use crate::config::Config;
use crate::error::{ValidationError, ValidationErrorKind, ValidationErrors};
use crate::public::{PublicConfig, PublicHash};
use crate::rules;
use crate::schema::{schema, SCHEMA_VERSION};
use crate::value::Value;
pub const MAX_DOCUMENT_BYTES: usize = 256 * 1024;
pub(crate) const SCHEMA_VERSION_KEY: &str = "schema_version";
#[derive(Clone, PartialEq, Eq)]
pub struct ConfigDocument {
text: String,
values: Vec<Value>,
config: Config,
}
impl ConfigDocument {
pub fn parse(text: &str) -> Result<Self, ValidationErrors> {
if text.len() > MAX_DOCUMENT_BYTES {
return Err(ValidationErrors::one(ValidationError::new(
ValidationErrorKind::TooLarge,
None,
format!("document is larger than the {MAX_DOCUMENT_BYTES}-byte limit"),
)));
}
let doc = parse_toml(text).map_err(ValidationErrors::one)?;
Self::from_toml(text.to_owned(), &doc)
}
pub(crate) fn from_toml(text: String, doc: &DocumentMut) -> Result<Self, ValidationErrors> {
let analysis = analyse(doc);
if let Some(errors) = ValidationErrors::from_vec(analysis.errors) {
return Err(errors);
}
let values: Vec<Value> = analysis
.values
.into_iter()
.collect::<Option<_>>()
.expect("analysis without errors yields a value for every field");
let config = Config::from_values(&values).map_err(ValidationErrors::one)?;
Ok(Self {
text,
values,
config,
})
}
pub fn text(&self) -> &str {
&self.text
}
pub fn value(&self, path: &str) -> Option<&Value> {
schema().index_of(path).and_then(|i| self.values.get(i))
}
pub fn config(&self) -> &Config {
&self.config
}
pub fn public_config(&self) -> PublicConfig {
PublicConfig::from_effective(&self.values)
}
pub fn public_hash(&self) -> PublicHash {
self.public_config().hash()
}
}
impl fmt::Debug for ConfigDocument {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConfigDocument")
.field("config", &self.config)
.field("public_hash", &self.public_hash())
.finish_non_exhaustive()
}
}
pub(crate) fn parse_toml(text: &str) -> Result<DocumentMut, ValidationError> {
text.parse::<DocumentMut>().map_err(|e| {
let message = match e.span() {
Some(span) => {
let (line, column) = line_column(text, span.start);
format!("invalid toml at line {line}, column {column}")
}
None => "invalid toml".to_owned(),
};
ValidationError::new(ValidationErrorKind::Syntax, None, message)
})
}
fn line_column(text: &str, offset: usize) -> (usize, usize) {
let before = text.get(..offset).unwrap_or(text);
let line = before.matches('\n').count() + 1;
let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
(line, column)
}
pub(crate) struct Analysis {
pub(crate) values: Vec<Option<Value>>,
pub(crate) errors: Vec<ValidationError>,
}
pub(crate) fn analyse(doc: &DocumentMut) -> Analysis {
let mut errors = Vec::new();
check_schema_version(doc, &mut errors);
check_unknown_keys(doc, &mut errors);
let mut values = Vec::with_capacity(schema().table().len());
for field in schema().fields() {
let section = doc.get(field.section()).and_then(|i| i.as_table_like());
let value = match section.and_then(|t| t.get(field.key())) {
None => Some(field.default_value()),
Some(item) => match Value::from_toml(item) {
Ok(value) => {
if let Err(e) = field.validate(&value) {
errors.push(e);
}
Some(value)
}
Err(found) => {
errors.push(ValidationError::at(
ValidationErrorKind::WrongType,
field.path(),
format!("expected {}, found {found}", type_name(field)),
));
None
}
},
};
values.push(value);
}
if let Some(e) = check_cross_field(&values, &errors) {
errors.push(e);
}
Analysis { values, errors }
}
fn type_name(field: &crate::schema::FieldDescriptor) -> &'static str {
field.default_value().kind_name()
}
fn check_schema_version(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
let key = SCHEMA_VERSION_KEY;
match doc.get(key) {
None => errors.push(ValidationError::new(
ValidationErrorKind::MissingSchemaVersion,
Some(key),
format!("missing; add schema_version = {SCHEMA_VERSION}"),
)),
Some(item) => match item.as_integer() {
Some(v) if v == i64::from(SCHEMA_VERSION) => {}
Some(v) => errors.push(ValidationError::at(
ValidationErrorKind::UnsupportedSchemaVersion,
key,
format!("unsupported schema version {v}; this library supports {SCHEMA_VERSION}"),
)),
None => errors.push(ValidationError::at(
ValidationErrorKind::WrongType,
key,
"expected an integer",
)),
},
}
}
fn check_unknown_keys(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
for (key, item) in doc.iter() {
if key == SCHEMA_VERSION_KEY {
continue;
}
if !schema().sections().any(|s| s == key) {
errors.push(ValidationError::at(
ValidationErrorKind::UnknownKey,
key,
"unknown key",
));
continue;
}
let Some(table) = item.as_table_like() else {
errors.push(ValidationError::at(
ValidationErrorKind::WrongType,
key,
"expected a table",
));
continue;
};
check_unknown_in_table(key, table, errors);
}
}
fn check_unknown_in_table(section: &str, table: &dyn TableLike, errors: &mut Vec<ValidationError>) {
for (key, _) in table.iter() {
let path = format!("{section}.{key}");
if schema().field(&path).is_none() {
errors.push(ValidationError::at(
ValidationErrorKind::UnknownKey,
&path,
"unknown key",
));
}
}
}
fn check_cross_field(
values: &[Option<Value>],
errors: &[ValidationError],
) -> Option<ValidationError> {
let clean = |path: &str| -> Option<&str> {
if errors.iter().any(|e| e.path() == Some(path)) {
return None;
}
schema()
.index_of(path)
.and_then(|i| values.get(i))
.and_then(Option::as_ref)
.and_then(Value::as_str)
};
let state = clean("storage.state_dir")?;
let backup = clean("storage.backup_dir")?;
rules::distinct_dirs(state, backup)
.err()
.map(|msg| ValidationError::at(ValidationErrorKind::Conflict, "storage.backup_dir", msg))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_column_counts_from_one() {
assert_eq!(line_column("ab\ncd", 4), (2, 2), "second line");
assert_eq!(line_column("ab", 0), (1, 1), "start");
}
}