ctl_input/lib.rs
1//! Declared input: read a file, parse it, validate it once, and report every
2//! problem on its file and line.
3//!
4//! Each format is its own feature. `yaml` parses YAML with `serde-saphyr`,
5//! `json` parses JSON with an own strict reader that links no parser crate, and
6//! `toml` parses TOML with the `toml` crate; none needs another.
7//! `validate` adds `Input::check` and `Input::load`, which validate with
8//! garde. This is the one boundary where a CLI's config enters. Downstream
9//! code keeps the validated type and never checks it again. With no format
10//! feature the crate is empty.
11//!
12//! A check that runs after the read, such as one that needs a file the config
13//! names, places its problem with a [`FieldPath`] and [`Input::problem_at`],
14//! the way the loader places garde's.
15//!
16//! A text's [`Format`] is chosen, never guessed. [`Input::open`] takes it from
17//! the file's extension through the process's [`Formats`] registry,
18//! [`Formats::open`] through a registry of the caller's, and
19//! [`Input::new_with_format`] takes it for text in memory. With `yaml`,
20//! `Input::new` and `Input::read` are YAML.
21//!
22//! ## The tree, the format trait and the registry
23//!
24//! `tree` holds the located tree: each node keeps its byte span, each scalar
25//! its processed value and style, and each mapping its key and value nodes.
26//! `format::Format` is the trait that reads a text into that tree and
27//! resolves one scalar for the type a field needs, and `Formats` is the
28//! registry a CLI adds its own format to. `YAML`, `JSON` and `TOML` are the
29//! built-in formats, each a value of its feature.
30//!
31//! An [`Input`] reads its text into that tree once and keeps it. Parsing,
32//! placing a problem, listing the top-level entries and checking with garde
33//! all work on it, so every format, a CLI's own included, is read, placed and
34//! worded the same way.
35//!
36//! ## The Deserializer, the messages and `Tagged`
37//!
38//! `de::deserialize` reads a typed value from a tree, asking the format to
39//! resolve each scalar for the type its field needs.
40//! A problem is a `format::Fault` with the bytes it sits at, and
41//! `Messages` words it, in English by default and in another voice after
42//! `set_messages`.
43//! `Tagged` reads a node's tag beside its value.
44//!
45//! ```
46//! # #[cfg(all(feature = "yaml", feature = "validate"))]
47//! # {
48//! use ctl_input::Input;
49//! use serde::Deserialize;
50//!
51//! #[derive(Debug, Deserialize)]
52//! struct Config {
53//! name: String,
54//! }
55//!
56//! let config: Config = Input::new("toy.yaml", "name: release\n").parse()?;
57//! assert_eq!(config.name, "release");
58//!
59//! let error = Input::new("toy.yaml", "name: a\nname: b\n")
60//! .parse::<Config>()
61//! .unwrap_err();
62//! assert!(error.to_string().starts_with("toy.yaml"));
63//! # }
64//! # Ok::<(), ctl_input::InputError>(())
65//! ```
66//!
67//! ## Cargo features
68#![cfg_attr(
69 not(any(feature = "yaml", feature = "json", feature = "toml")),
70 doc = "",
71 doc = "[`FieldPath`]: crate#cargo-features",
72 doc = "[`Input::problem_at`]: crate#cargo-features",
73 doc = "[`Format`]: crate#cargo-features",
74 doc = "[`Formats`]: crate#cargo-features",
75 doc = "[`Formats::open`]: crate#cargo-features",
76 doc = "[`Input`]: crate#cargo-features",
77 doc = "[`Input::open`]: crate#cargo-features",
78 doc = "[`Input::new_with_format`]: crate#cargo-features"
79)]
80#![doc = document_features::document_features!()]
81#![cfg_attr(docsrs, feature(doc_cfg))]
82#![cfg(any(feature = "yaml", feature = "json", feature = "toml"))]
83
84use std::fmt;
85use std::path::Path;
86
87#[cfg(feature = "validate")]
88use garde::Validate;
89use serde::de::DeserializeOwned;
90
91pub mod de;
92mod entries;
93mod exceeded;
94mod field_path;
95pub mod format;
96mod formats;
97mod input_error;
98#[cfg(feature = "json")]
99mod json;
100#[cfg(feature = "json")]
101mod json_format;
102mod kept;
103mod limits;
104mod messages;
105mod placing;
106#[cfg(feature = "toml")]
107mod toml_format;
108pub mod tree;
109#[cfg(feature = "yaml")]
110mod yaml_format;
111
112pub use de::Tagged;
113pub use entries::{Entry, Written};
114pub use field_path::{FieldPath, Place, Step};
115pub use format::Format;
116#[cfg(feature = "json")]
117pub use format::JSON;
118#[cfg(feature = "toml")]
119pub use format::TOML;
120#[cfg(feature = "yaml")]
121pub use format::YAML;
122use format::{Fault, Raise, Reading, Refusal};
123pub use formats::{Formats, default_formats, set_default_formats};
124use input_error::read_text;
125pub use input_error::{InputError, Problem};
126use kept::Kept;
127pub use limits::{Limits, set_default_limits};
128#[cfg(feature = "yaml")]
129pub use limits::{Loosened, REPO_FILE, use_repo_limits};
130use messages::messages;
131pub use messages::{EnglishMessages, Messages, set_messages};
132use placing::At;
133
134/// A named text, ready to parse and validate.
135///
136/// The name is usually the file's path, and appears in every problem. Build
137/// one with [`Input::new_with_format`] for text in memory, or [`Input::open`]
138/// for a file. With `yaml`, `Input::new` and `Input::read` build a YAML
139/// one.
140#[derive(Clone)]
141pub struct Input {
142 name: String,
143 text: String,
144 lines_before: usize,
145 limits: Limits,
146 format: &'static dyn Format,
147 /// The schema fields serde flattens into their parents, which
148 /// [`Input::flattened`] declares.
149 #[cfg(feature = "validate")]
150 flattened: Vec<FieldPath>,
151 /// The tree the text was read into, for every operation to share.
152 kept: Kept,
153}
154
155/// A format has no `Debug`, so it shows by its name, and the kept tree is
156/// left out.
157impl fmt::Debug for Input {
158 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159 let mut shown = formatter.debug_struct("Input");
160 shown
161 .field("name", &self.name)
162 .field("text", &self.text)
163 .field("lines_before", &self.lines_before)
164 .field("limits", &self.limits)
165 .field("format", &self.format.name());
166 #[cfg(feature = "validate")]
167 shown.field("flattened", &self.flattened);
168 shown.finish_non_exhaustive()
169 }
170}
171
172/// Two inputs are equal when they read the same text the same way. A format
173/// is compared by its name, and the kept tree is derived from the rest, so
174/// placing on one input does not make it differ from its clone.
175impl PartialEq for Input {
176 fn eq(&self, other: &Self) -> bool {
177 let same = self.name == other.name
178 && self.text == other.text
179 && self.lines_before == other.lines_before
180 && self.limits == other.limits
181 && self.format.name() == other.format.name();
182 #[cfg(feature = "validate")]
183 let same = same && self.flattened == other.flattened;
184 same
185 }
186}
187
188impl Eq for Input {}
189
190impl Input {
191 /// A YAML input from text already in memory, whatever the extension of
192 /// `name`. Set another format with [`Input::format`].
193 #[cfg(feature = "yaml")]
194 #[must_use]
195 pub fn new(name: impl Into<String>, text: impl Into<String>) -> Self {
196 Self::new_with_format(name, text, &YAML)
197 }
198
199 /// An input of `format` from text already in memory, whatever the
200 /// extension of `name`. The format is any [`Format`], one a CLI wrote
201 /// included, and a build needs only its own feature: a build without YAML
202 /// builds text in memory with it.
203 #[must_use]
204 pub fn new_with_format(
205 name: impl Into<String>,
206 text: impl Into<String>,
207 format: &'static dyn Format,
208 ) -> Self {
209 Self {
210 name: name.into(),
211 text: text.into(),
212 lines_before: 0,
213 limits: Limits::NONE,
214 format,
215 #[cfg(feature = "validate")]
216 flattened: Vec::new(),
217 kept: Kept::default(),
218 }
219 }
220
221 /// Read a YAML file, named by its path, whatever its extension.
222 ///
223 /// # Errors
224 ///
225 /// An [`InputError`] with the I/O failure.
226 #[cfg(feature = "yaml")]
227 pub fn read(path: &Path) -> Result<Self, InputError> {
228 let (name, text) = read_text(path)?;
229 Ok(Self::new(name, text))
230 }
231
232 /// Read a file and take its [`Format`] from its extension, through the
233 /// registry the process uses: what [`set_default_formats`] installed, or
234 /// else [`Formats::builtin`]. [`Formats::open`] reads through a registry
235 /// of the caller's instead.
236 ///
237 /// # Errors
238 ///
239 /// An [`InputError`] for an extension [`Formats::of`] refuses, which is
240 /// checked before the file is read, or with the I/O failure.
241 pub fn open(path: &Path) -> Result<Self, InputError> {
242 formats::default_formats().open(path)
243 }
244
245 /// Set how the text is written, over what the constructor took.
246 #[must_use]
247 pub fn format(mut self, format: &'static dyn Format) -> Self {
248 self.format = format;
249 self.kept = Kept::default();
250 self
251 }
252
253 /// The name given at construction, usually the file's path.
254 #[must_use]
255 pub fn name(&self) -> &str {
256 &self.name
257 }
258
259 /// The text as read, unchanged.
260 #[must_use]
261 pub fn text(&self) -> &str {
262 &self.text
263 }
264
265 /// Split YAML frontmatter from a Markdown body.
266 ///
267 /// The frontmatter is the text between a first line of `---` and the next
268 /// line of `---`. It is YAML whatever this input's format, and problems in
269 /// it keep the line numbers of the whole file. The second item is the body
270 /// after the closing line. Returns `None` when the text does not start with
271 /// a `---` line, or never closes it.
272 #[cfg(feature = "yaml")]
273 #[must_use]
274 pub fn frontmatter(&self) -> Option<(Self, &str)> {
275 let text = self.text.strip_prefix('\u{feff}').unwrap_or(&self.text);
276 let rest = text
277 .strip_prefix("---\n")
278 .or_else(|| text.strip_prefix("---\r\n"))?;
279 let mut offset = 0;
280 for line in rest.split_inclusive('\n') {
281 if line.trim_end() == "---" {
282 let matter = Self {
283 name: self.name.clone(),
284 text: rest[..offset].to_owned(),
285 lines_before: self.lines_before + 1,
286 limits: self.limits.clone(),
287 format: &YAML,
288 #[cfg(feature = "validate")]
289 flattened: self.flattened.clone(),
290 kept: Kept::default(),
291 };
292 return Some((matter, &rest[offset + line.len()..]));
293 }
294 offset += line.len();
295 }
296 None
297 }
298
299 /// Override limits for this input alone, above every other tier. See
300 /// [`Limits`] for the order.
301 #[must_use]
302 pub fn limits(mut self, limits: Limits) -> Self {
303 self.limits = limits;
304 self
305 }
306
307 /// Parse the text into `T`, without validating it.
308 ///
309 /// The text is read into the input's tree, which the input keeps for
310 /// placing and listing, and `T` is read from that tree. The first problem
311 /// found is the one reported, in the order the text is written. The format
312 /// decides what a scalar can be: in YAML only `true` and `false` are
313 /// booleans, and a TOML string fills only a string. A duplicate key or a
314 /// merge key (`<<`) is refused.
315 ///
316 /// The text must fit the limits in force, decided field by field through
317 /// the tiers [`Limits`] lists. TOML and JSON read only
318 /// `max_reader_input_bytes`, `max_depth`, and `max_nodes`, because the
319 /// other fields name YAML syntax.
320 ///
321 /// # Errors
322 ///
323 /// An [`InputError`] with the problem and its line. A limit problem names
324 /// the limit, its value, and where to raise it, or, without `yaml`, that
325 /// the tool sets it.
326 pub fn parse<T: DeserializeOwned>(&self) -> Result<T, InputError> {
327 self.parse_within(&limits::effective(&self.limits), Raise::FOR_TEXT)
328 }
329
330 /// Lend the root node of the text's tree to `walk`, read as
331 /// [`Self::parse`] reads it, and return what `walk` returns.
332 ///
333 /// The read is strict, under the limits in force, so a duplicate key, a
334 /// merge key, a second document and a text past a limit are refused the
335 /// same way, each on its line. The node is the tree the input keeps for
336 /// placing, lent without a copy. A caller that walks the tree itself, such
337 /// as one that turns a document into command-line arguments, places its
338 /// own problems with [`Input::place`] and [`Input::place_key`].
339 ///
340 /// # Errors
341 ///
342 /// An [`InputError`] with the problem and its line, as [`Self::parse`]
343 /// reports it.
344 pub fn tree<T>(&self, walk: impl FnOnce(&tree::Node) -> T) -> Result<T, InputError> {
345 let limits = limits::effective(&self.limits);
346 self.fits(&limits, Raise::FOR_TEXT)?;
347 let read = self
348 .kept
349 .tree(self.format, &self.text, &limits, Reading::Strict);
350 match read.as_ref() {
351 Ok(root) => Ok(walk(root)),
352 Err(refusal) => Err(self.refused(refusal, Raise::FOR_TEXT)),
353 }
354 }
355
356 /// [`Self::parse`] under exactly `limits`, whatever the tiers say.
357 /// `raise` is where a person raises a limit the text goes past.
358 fn parse_within<T: DeserializeOwned>(
359 &self,
360 limits: &Limits,
361 raise: Raise,
362 ) -> Result<T, InputError> {
363 self.fits(limits, raise)?;
364 let read = self
365 .kept
366 .tree(self.format, &self.text, limits, Reading::Strict);
367 let tree = read
368 .as_ref()
369 .as_ref()
370 .map_err(|refusal| self.refused(refusal, raise))?;
371 de::deserialize(tree, self.format).map_err(|refusal| self.refused(&refusal, raise))
372 }
373
374 /// The input's problem for `refusal`, placed on its line and column, and
375 /// worded by [`Messages`]. A refusal in a node an alias replayed also
376 /// names where its value is defined, counted from the file.
377 fn refused(&self, refusal: &Refusal, raise: Raise) -> InputError {
378 let fault = if let Fault::Limit { name, value, .. } = refusal.fault().clone() {
379 Fault::Limit { name, value, raise }
380 } else {
381 refusal.fault().clone()
382 };
383 let mut message = worded(&fault);
384 if let Some(defined) = refusal.defined_at() {
385 let (line, column) = tree::position(&self.text, defined.start);
386 let line = line + self.lines_before;
387 message = format!("{message} (defined at line {line}, column {column})");
388 }
389 let place = refusal
390 .span()
391 .map(|span| tree::position(&self.text, span.start));
392 InputError::one(
393 self.name.clone(),
394 Problem {
395 line: place.map(|(line, _)| line + self.lines_before),
396 column: place.map(|(_, column)| column),
397 field: String::new(),
398 message,
399 },
400 )
401 }
402
403 /// Whether the text is within the size `limits` allow.
404 fn fits(&self, limits: &Limits, raise: Raise) -> Result<(), InputError> {
405 let bounds = limits.bounds();
406 if self.text.len() > bounds.input_bytes {
407 let fault = Fault::TooLarge {
408 bytes: u64::try_from(self.text.len()).unwrap_or(u64::MAX),
409 limit: u64::try_from(bounds.input_bytes).unwrap_or(u64::MAX),
410 raise,
411 };
412 return Err(InputError::whole(self.name.clone(), worded(&fault)));
413 }
414 Ok(())
415 }
416
417 /// Parse the text into `T`, then validate it with `T`'s default context.
418 ///
419 /// # Errors
420 ///
421 /// As [`Input::parse`] and [`Input::check`].
422 #[cfg(feature = "validate")]
423 pub fn load<T>(&self) -> Result<T, InputError>
424 where
425 T: DeserializeOwned + Validate,
426 T::Context: Default,
427 {
428 let value = self.parse::<T>()?;
429 self.check(&value, &T::Context::default())?;
430 Ok(value)
431 }
432}
433
434/// The words of `fault` from the process's [`Messages`], with each control
435/// character escaped so a name or a value the text wrote cannot move a
436/// terminal that prints the problem.
437fn worded(fault: &Fault) -> String {
438 messages::printable(&messages().message(fault))
439}