1use std::fmt;
4
5use toml_edit::{DocumentMut, TableLike};
6
7use crate::config::Config;
8use crate::error::{ValidationError, ValidationErrorKind, ValidationErrors};
9use crate::public::{PublicConfig, PublicHash};
10use crate::rules;
11use crate::schema::{schema, SCHEMA_VERSION};
12use crate::value::Value;
13
14pub const MAX_DOCUMENT_BYTES: usize = 256 * 1024;
22
23pub(crate) const SCHEMA_VERSION_KEY: &str = "schema_version";
25
26#[derive(Clone, PartialEq, Eq)]
47pub struct ConfigDocument {
48 text: String,
49 values: Vec<Value>,
50 config: Config,
51}
52
53impl ConfigDocument {
54 pub fn parse(text: &str) -> Result<Self, ValidationErrors> {
80 if text.len() > MAX_DOCUMENT_BYTES {
81 return Err(ValidationErrors::one(ValidationError::new(
82 ValidationErrorKind::TooLarge,
83 None,
84 format!("document is larger than the {MAX_DOCUMENT_BYTES}-byte limit"),
85 )));
86 }
87 let doc = parse_toml(text).map_err(ValidationErrors::one)?;
88 Self::from_toml(text.to_owned(), &doc)
89 }
90
91 pub(crate) fn from_toml(text: String, doc: &DocumentMut) -> Result<Self, ValidationErrors> {
93 let analysis = analyse(doc);
94 if let Some(errors) = ValidationErrors::from_vec(analysis.errors) {
95 return Err(errors);
96 }
97 let values: Vec<Value> = analysis
100 .values
101 .into_iter()
102 .collect::<Option<_>>()
103 .expect("analysis without errors yields a value for every field");
104 let config = Config::from_values(&values).map_err(ValidationErrors::one)?;
105 Ok(Self {
106 text,
107 values,
108 config,
109 })
110 }
111
112 pub fn text(&self) -> &str {
114 &self.text
115 }
116
117 pub fn value(&self, path: &str) -> Option<&Value> {
120 schema().index_of(path).and_then(|i| self.values.get(i))
121 }
122
123 pub fn config(&self) -> &Config {
125 &self.config
126 }
127
128 pub fn public_config(&self) -> PublicConfig {
131 PublicConfig::from_effective(&self.values)
132 }
133
134 pub fn public_hash(&self) -> PublicHash {
137 self.public_config().hash()
138 }
139}
140
141impl fmt::Debug for ConfigDocument {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.debug_struct("ConfigDocument")
146 .field("config", &self.config)
147 .field("public_hash", &self.public_hash())
148 .finish_non_exhaustive()
149 }
150}
151
152pub(crate) fn parse_toml(text: &str) -> Result<DocumentMut, ValidationError> {
158 text.parse::<DocumentMut>().map_err(|e| {
159 let message = match e.span() {
160 Some(span) => {
161 let (line, column) = line_column(text, span.start);
162 format!("invalid toml at line {line}, column {column}")
163 }
164 None => "invalid toml".to_owned(),
165 };
166 ValidationError::new(ValidationErrorKind::Syntax, None, message)
167 })
168}
169
170fn line_column(text: &str, offset: usize) -> (usize, usize) {
172 let before = text.get(..offset).unwrap_or(text);
173 let line = before.matches('\n').count() + 1;
174 let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
175 (line, column)
176}
177
178pub(crate) struct Analysis {
180 pub(crate) values: Vec<Option<Value>>,
184 pub(crate) errors: Vec<ValidationError>,
185}
186
187pub(crate) fn analyse(doc: &DocumentMut) -> Analysis {
189 let mut errors = Vec::new();
190 check_schema_version(doc, &mut errors);
191 check_unknown_keys(doc, &mut errors);
192
193 let mut values = Vec::with_capacity(schema().table().len());
194 for field in schema().fields() {
195 let section = doc.get(field.section()).and_then(|i| i.as_table_like());
196 let value = match section.and_then(|t| t.get(field.key())) {
197 None => Some(field.default_value()),
198 Some(item) => match Value::from_toml(item) {
199 Ok(value) => {
200 if let Err(e) = field.validate(&value) {
201 errors.push(e);
202 }
203 Some(value)
204 }
205 Err(found) => {
206 errors.push(ValidationError::at(
207 ValidationErrorKind::WrongType,
208 field.path(),
209 format!("expected {}, found {found}", type_name(field)),
210 ));
211 None
212 }
213 },
214 };
215 values.push(value);
216 }
217
218 if let Some(e) = check_cross_field(&values, &errors) {
219 errors.push(e);
220 }
221 Analysis { values, errors }
222}
223
224fn type_name(field: &crate::schema::FieldDescriptor) -> &'static str {
225 field.default_value().kind_name()
226}
227
228fn check_schema_version(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
229 let key = SCHEMA_VERSION_KEY;
230 match doc.get(key) {
231 None => errors.push(ValidationError::new(
232 ValidationErrorKind::MissingSchemaVersion,
233 Some(key),
234 format!("missing; add schema_version = {SCHEMA_VERSION}"),
235 )),
236 Some(item) => match item.as_integer() {
237 Some(v) if v == i64::from(SCHEMA_VERSION) => {}
238 Some(v) => errors.push(ValidationError::at(
239 ValidationErrorKind::UnsupportedSchemaVersion,
240 key,
241 format!("unsupported schema version {v}; this library supports {SCHEMA_VERSION}"),
242 )),
243 None => errors.push(ValidationError::at(
244 ValidationErrorKind::WrongType,
245 key,
246 "expected an integer",
247 )),
248 },
249 }
250}
251
252fn check_unknown_keys(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
253 for (key, item) in doc.iter() {
254 if key == SCHEMA_VERSION_KEY {
255 continue;
256 }
257 if !schema().sections().any(|s| s == key) {
258 errors.push(ValidationError::at(
259 ValidationErrorKind::UnknownKey,
260 key,
261 "unknown key",
262 ));
263 continue;
264 }
265 let Some(table) = item.as_table_like() else {
266 errors.push(ValidationError::at(
267 ValidationErrorKind::WrongType,
268 key,
269 "expected a table",
270 ));
271 continue;
272 };
273 check_unknown_in_table(key, table, errors);
274 }
275}
276
277fn check_unknown_in_table(section: &str, table: &dyn TableLike, errors: &mut Vec<ValidationError>) {
278 for (key, _) in table.iter() {
279 let path = format!("{section}.{key}");
280 if schema().field(&path).is_none() {
281 errors.push(ValidationError::at(
282 ValidationErrorKind::UnknownKey,
283 &path,
284 "unknown key",
285 ));
286 }
287 }
288}
289
290fn check_cross_field(
293 values: &[Option<Value>],
294 errors: &[ValidationError],
295) -> Option<ValidationError> {
296 let clean = |path: &str| -> Option<&str> {
297 if errors.iter().any(|e| e.path() == Some(path)) {
298 return None;
299 }
300 schema()
301 .index_of(path)
302 .and_then(|i| values.get(i))
303 .and_then(Option::as_ref)
304 .and_then(Value::as_str)
305 };
306 let state = clean("storage.state_dir")?;
307 let backup = clean("storage.backup_dir")?;
308 rules::distinct_dirs(state, backup)
309 .err()
310 .map(|msg| ValidationError::at(ValidationErrorKind::Conflict, "storage.backup_dir", msg))
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 #[test]
318 fn line_column_counts_from_one() {
319 assert_eq!(line_column("ab\ncd", 4), (2, 2), "second line");
320 assert_eq!(line_column("ab", 0), (1, 1), "start");
321 }
322}