Skip to main content

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//! and `toml` parses TOML with the `toml` crate; neither needs the other.
6//! `validate` adds `Input::check` and `Input::load`, which validate with
7//! garde. This is the one boundary where a CLI's config enters. Downstream
8//! code keeps the validated type and never checks it again. With no format
9//! feature the crate is empty.
10//!
11//! A check that runs after the read, such as one that needs a file the config
12//! names, places its problem with a [`FieldPath`] and [`Input::problem_at`],
13//! the way the loader places garde's.
14//!
15//! A text's [`Format`] is chosen, never guessed. [`Input::open`] reads it from
16//! the file's extension, and [`Input::new_with_format`] takes it for text in
17//! memory. With `yaml`, `Input::new` and `Input::read` are YAML.
18//!
19//! ```
20//! # #[cfg(all(feature = "yaml", feature = "validate"))]
21//! # {
22//! use ctl_input::Input;
23//! use serde::Deserialize;
24//!
25//! #[derive(Debug, Deserialize)]
26//! struct Config {
27//!     name: String,
28//! }
29//!
30//! let config: Config = Input::new("toy.yaml", "name: release\n").parse()?;
31//! assert_eq!(config.name, "release");
32//!
33//! let error = Input::new("toy.yaml", "name: a\nname: b\n")
34//!     .parse::<Config>()
35//!     .unwrap_err();
36//! assert!(error.to_string().starts_with("toy.yaml"));
37//! # }
38//! # Ok::<(), ctl_input::InputError>(())
39//! ```
40//!
41//! ## Cargo features
42#![cfg_attr(
43    not(any(feature = "yaml", feature = "toml")),
44    doc = "",
45    doc = "[`FieldPath`]: crate#cargo-features",
46    doc = "[`Input::problem_at`]: crate#cargo-features",
47    doc = "[`Format`]: crate#cargo-features",
48    doc = "[`Input::open`]: crate#cargo-features",
49    doc = "[`Input::new_with_format`]: crate#cargo-features"
50)]
51#![doc = document_features::document_features!()]
52#![cfg_attr(docsrs, feature(doc_cfg))]
53#![cfg(any(feature = "yaml", feature = "toml"))]
54
55use std::error::Error;
56use std::path::Path;
57use std::{fmt, fs, io, slice};
58
59#[cfg(feature = "validate")]
60use garde::Validate;
61use serde::de::DeserializeOwned;
62
63mod entries;
64mod field_path;
65mod limits;
66#[cfg(feature = "toml")]
67mod toml_entries;
68#[cfg(feature = "toml")]
69mod toml_text;
70#[cfg(feature = "yaml")]
71mod yaml_entries;
72#[cfg(feature = "yaml")]
73mod yaml_text;
74
75pub use entries::{Entry, Written};
76pub use field_path::{FieldPath, Place, Step};
77use limits::{Exceeded, Raise};
78pub use limits::{Limits, set_default_limits};
79#[cfg(feature = "yaml")]
80pub use limits::{Loosened, REPO_FILE, use_repo_limits};
81/// A value and the YAML tag written on its node, such as `!override` in
82/// `code_span_size: !override 0`: `Tagged(0, Some("!override".into()))`.
83/// A node with no tag reads as `Tagged(value, None)`, and an untagged enum
84/// inside reads the plain value of a tagged node.
85#[cfg(feature = "yaml")]
86pub use serde_saphyr::Tagged;
87
88/// What a placing answers with for a key of the path: where its value starts,
89/// or where the key itself is written.
90#[derive(Clone, Copy)]
91enum At {
92    Value,
93    Key,
94}
95
96/// How a text is written.
97///
98/// Non-exhaustive: each variant exists only with its format's feature.
99/// Cargo unifies features across a build, so a caller's `match` needs a
100/// wildcard arm.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum Format {
104    /// YAML, read by serde-saphyr and placed by yamled.
105    #[cfg(feature = "yaml")]
106    Yaml,
107    /// TOML, read and placed by the `toml` crate.
108    #[cfg(feature = "toml")]
109    Toml,
110}
111
112impl Format {
113    /// The format a file's extension names, compared without regard to case:
114    /// `.toml` is TOML, and `.yaml` and `.yml` are YAML.
115    ///
116    /// # Errors
117    ///
118    /// An [`InputError`] with no line for any other extension or none, naming
119    /// the extension and the accepted ones. One naming the feature for an
120    /// extension whose format's feature is off.
121    pub fn of(path: &Path) -> Result<Self, InputError> {
122        let name = path.display().to_string();
123        let extension = path
124            .extension()
125            .map(|extension| extension.to_string_lossy().to_ascii_lowercase());
126        match extension.as_deref() {
127            #[cfg(feature = "yaml")]
128            Some("yaml" | "yml") => Ok(Self::Yaml),
129            #[cfg(not(feature = "yaml"))]
130            Some(yaml @ ("yaml" | "yml")) => Err(InputError::whole(
131                name,
132                format!("`.{yaml}` needs ctl-core's input-yaml feature; {ACCEPTED}"),
133            )),
134            #[cfg(feature = "toml")]
135            Some("toml") => Ok(Self::Toml),
136            #[cfg(not(feature = "toml"))]
137            Some("toml") => Err(InputError::whole(
138                name,
139                format!("`.toml` needs ctl-core's input-toml feature; {ACCEPTED}"),
140            )),
141            Some(other) => Err(InputError::whole(
142                name,
143                format!("unsupported extension .{other}; {ACCEPTED}"),
144            )),
145            None => Err(InputError::whole(
146                name,
147                format!("no file extension; {ACCEPTED}"),
148            )),
149        }
150    }
151}
152
153/// What a refusal tells a person to name the file: the extensions this build
154/// reads.
155#[cfg(all(feature = "yaml", feature = "toml"))]
156const ACCEPTED: &str = "name the file *.toml, *.yaml, or *.yml";
157#[cfg(all(feature = "yaml", not(feature = "toml")))]
158const ACCEPTED: &str = "name the file *.yaml or *.yml";
159#[cfg(all(feature = "toml", not(feature = "yaml")))]
160const ACCEPTED: &str = "name the file *.toml";
161
162/// A named text, ready to parse and validate.
163///
164/// The name is usually the file's path, and appears in every problem. Build
165/// one with [`Input::new_with_format`] for text in memory, or [`Input::open`]
166/// for a file. With `yaml`, `Input::new` and `Input::read` build a YAML
167/// one.
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct Input {
170    name: String,
171    text: String,
172    lines_before: usize,
173    limits: Limits,
174    format: Format,
175    /// The schema fields serde flattens into their parents, which
176    /// [`Input::flattened`] declares.
177    #[cfg(feature = "validate")]
178    flattened: Vec<FieldPath>,
179    /// The YAML document that placing reads, built on first use.
180    #[cfg(feature = "yaml")]
181    yaml_document: yaml_text::Located,
182}
183
184/// Why an input was refused: every problem found, each placed on a line when
185/// the text allows it.
186///
187/// `Display` prints one problem per line as `name:line:column: field: message`,
188/// leaving out what is not known.
189///
190/// A file that could not be read keeps its [`io::ErrorKind`], which
191/// [`Self::io_failure`] returns. So a caller can treat a missing file apart
192/// from a refused one. A field can join this type in a minor release.
193#[derive(Clone, Debug, PartialEq, Eq)]
194#[non_exhaustive]
195pub struct InputError {
196    /// The input's name, usually its path.
197    pub name: String,
198    /// What is wrong, in the order found.
199    pub problems: Vec<Problem>,
200    /// The I/O failure, for an input that could not be read.
201    io_failure: Option<io::ErrorKind>,
202}
203
204/// One thing wrong with an input.
205#[derive(Clone, Debug, PartialEq, Eq)]
206pub struct Problem {
207    /// 1-based line, when known.
208    pub line: Option<usize>,
209    /// 1-based column, when known.
210    pub column: Option<usize>,
211    /// The field it concerns, as garde names it (`packages[1].name`); empty
212    /// for a problem with the whole text.
213    pub field: String,
214    /// What a person changes to fix it.
215    pub message: String,
216}
217
218impl Input {
219    /// A YAML input from text already in memory, whatever the extension of
220    /// `name`. Set another format with [`Input::format`].
221    #[cfg(feature = "yaml")]
222    #[must_use]
223    pub fn new(name: impl Into<String>, text: impl Into<String>) -> Self {
224        Self::new_with_format(name, text, Format::Yaml)
225    }
226
227    /// An input of `format` from text already in memory, whatever the
228    /// extension of `name`. It needs only `format`'s feature, so a build
229    /// without YAML builds text in memory with it.
230    #[must_use]
231    pub fn new_with_format(
232        name: impl Into<String>,
233        text: impl Into<String>,
234        format: Format,
235    ) -> Self {
236        Self {
237            name: name.into(),
238            text: text.into(),
239            lines_before: 0,
240            limits: Limits::NONE,
241            format,
242            #[cfg(feature = "validate")]
243            flattened: Vec::new(),
244            #[cfg(feature = "yaml")]
245            yaml_document: yaml_text::Located::default(),
246        }
247    }
248
249    /// Read a YAML file, named by its path, whatever its extension.
250    ///
251    /// # Errors
252    ///
253    /// An [`InputError`] with the I/O failure.
254    #[cfg(feature = "yaml")]
255    pub fn read(path: &Path) -> Result<Self, InputError> {
256        let (name, text) = read_text(path)?;
257        Ok(Self::new(name, text))
258    }
259
260    /// Read a file and take its [`Format`] from its extension, as
261    /// [`Format::of`] does. The extension is checked before the file is read.
262    ///
263    /// # Errors
264    ///
265    /// An [`InputError`] for an extension [`Format::of`] refuses, or with the
266    /// I/O failure.
267    pub fn open(path: &Path) -> Result<Self, InputError> {
268        let format = Format::of(path)?;
269        let (name, text) = read_text(path)?;
270        Ok(Self::new_with_format(name, text, format))
271    }
272
273    /// Set how the text is written, over what the constructor took.
274    #[must_use]
275    pub fn format(mut self, format: Format) -> Self {
276        self.format = format;
277        self
278    }
279
280    /// The name given at construction, usually the file's path.
281    #[must_use]
282    pub fn name(&self) -> &str {
283        &self.name
284    }
285
286    /// The text as read, unchanged.
287    #[must_use]
288    pub fn text(&self) -> &str {
289        &self.text
290    }
291
292    /// Split YAML frontmatter from a Markdown body.
293    ///
294    /// The frontmatter is the text between a first line of `---` and the next
295    /// line of `---`. It is YAML whatever this input's format, and problems in
296    /// it keep the line numbers of the whole file. The second item is the body
297    /// after the closing line. Returns `None` when the text does not start with
298    /// a `---` line, or never closes it.
299    #[cfg(feature = "yaml")]
300    #[must_use]
301    pub fn frontmatter(&self) -> Option<(Self, &str)> {
302        let text = self.text.strip_prefix('\u{feff}').unwrap_or(&self.text);
303        let rest = text
304            .strip_prefix("---\n")
305            .or_else(|| text.strip_prefix("---\r\n"))?;
306        let mut offset = 0;
307        for line in rest.split_inclusive('\n') {
308            if line.trim_end() == "---" {
309                let matter = Self {
310                    name: self.name.clone(),
311                    text: rest[..offset].to_owned(),
312                    lines_before: self.lines_before + 1,
313                    limits: self.limits.clone(),
314                    format: Format::Yaml,
315                    #[cfg(feature = "validate")]
316                    flattened: self.flattened.clone(),
317                    yaml_document: yaml_text::Located::default(),
318                };
319                return Some((matter, &rest[offset + line.len()..]));
320            }
321            offset += line.len();
322        }
323        None
324    }
325
326    /// Override limits for this input alone, above every other tier. See
327    /// [`Limits`] for the order.
328    #[must_use]
329    pub fn limits(mut self, limits: Limits) -> Self {
330        self.limits = limits;
331        self
332    }
333
334    /// Declare that the schema field at `field` is flattened into its parent
335    /// with `#[serde(flatten)]`, so the file writes its entries directly under
336    /// the parent.
337    ///
338    /// garde names the field in each problem's path all the same, and serde
339    /// gives no sign of the flattening at run time, so the schema declares it.
340    /// [`Input::check`] then drops the field's step from each garde path whose
341    /// leading steps are `field`, before it places the problem and prints its
342    /// field. `field` is written in the schema's terms, the way garde names it,
343    /// and each call adds one field. A declaration that matches no garde path
344    /// changes nothing. [`Input::place`], [`Input::place_key`], and
345    /// [`Input::problem_at`] take paths in the file's terms, so a declaration
346    /// does not touch them.
347    ///
348    /// # Examples
349    ///
350    /// verctl's `assets` holds its targets in a flattened map field `targets`.
351    /// Without the declaration, the problem prints as
352    /// `assets.targets.linux-x64.files` and sits on the line below `assets:`.
353    ///
354    /// ```
355    /// # #[cfg(all(feature = "yaml", feature = "validate"))]
356    /// # {
357    /// use std::collections::BTreeMap;
358    ///
359    /// use ctl_input::{FieldPath, Input};
360    /// use garde::Validate;
361    /// use serde::Deserialize;
362    ///
363    /// #[derive(Debug, Deserialize, Validate)]
364    /// struct Config {
365    ///     #[garde(dive)]
366    ///     assets: Assets,
367    /// }
368    ///
369    /// #[derive(Debug, Deserialize, Validate)]
370    /// struct Assets {
371    ///     #[serde(flatten)]
372    ///     #[garde(dive)]
373    ///     targets: BTreeMap<String, Target>,
374    /// }
375    ///
376    /// #[derive(Debug, Deserialize, Validate)]
377    /// struct Target {
378    ///     #[garde(custom(at_least_one_file))]
379    ///     files: Vec<String>,
380    /// }
381    ///
382    /// fn at_least_one_file(files: &[String], _: &()) -> garde::Result {
383    ///     if files.is_empty() {
384    ///         return Err(garde::Error::new("must declare at least one file"));
385    ///     }
386    ///     Ok(())
387    /// }
388    ///
389    /// let error = Input::new("ver.yaml", "assets:\n  linux-x64:\n    files: []\n")
390    ///     .flattened(FieldPath::root().key("assets").key("targets"))
391    ///     .load::<Config>()
392    ///     .unwrap_err();
393    /// assert_eq!(
394    ///     error.to_string(),
395    ///     "ver.yaml:3:12: assets.linux-x64.files: must declare at least one file"
396    /// );
397    /// # }
398    /// ```
399    #[cfg(feature = "validate")]
400    #[must_use]
401    pub fn flattened(mut self, field: FieldPath) -> Self {
402        self.flattened.push(field);
403        self
404    }
405
406    /// `path` without the step of each declared flattened field it passes
407    /// through, or `None` when it passes through none.
408    #[cfg(feature = "validate")]
409    fn unflatten(&self, path: &FieldPath) -> Option<FieldPath> {
410        let positions: Vec<usize> = self
411            .flattened
412            .iter()
413            .filter(|field| path.starts_with(field))
414            .filter_map(|field| field.steps().len().checked_sub(1))
415            .collect();
416        (!positions.is_empty()).then(|| path.without(&positions))
417    }
418
419    /// Parse the text into `T`, without validating it.
420    ///
421    /// In YAML only `true` and `false` are booleans, and a duplicate key or a
422    /// merge key (`<<`) is refused. In TOML the format itself refuses a
423    /// duplicate key.
424    ///
425    /// The text must fit the limits in force, decided field by field through
426    /// the tiers [`Limits`] lists. TOML reads only `max_reader_input_bytes`,
427    /// `max_depth`, and `max_nodes`, because the other fields name YAML
428    /// syntax.
429    ///
430    /// # Errors
431    ///
432    /// An [`InputError`] with the parser's problem and its line. A limit
433    /// problem names the limit, its value, and where to raise it, or, without
434    /// `yaml`, that the tool sets it.
435    pub fn parse<T: DeserializeOwned>(&self) -> Result<T, InputError> {
436        self.parse_within(&limits::effective(&self.limits), Raise::FOR_TEXT)
437    }
438
439    /// [`Self::parse`] under exactly `limits`, whatever the tiers say.
440    fn parse_within<T: DeserializeOwned>(
441        &self,
442        limits: &Limits,
443        raise: Raise,
444    ) -> Result<T, InputError> {
445        self.fits(limits, raise)?;
446        match self.format {
447            #[cfg(feature = "yaml")]
448            Format::Yaml => yaml_text::parse(self, &limits.budget(), raise),
449            #[cfg(feature = "toml")]
450            Format::Toml => toml_text::parse(self, limits.bounds(), raise),
451        }
452    }
453
454    /// Whether the text is within the size `limits` allow.
455    fn fits(&self, limits: &Limits, raise: Raise) -> Result<(), InputError> {
456        let bounds = limits.bounds();
457        if self.text.len() > bounds.input_bytes {
458            return Err(InputError::whole(
459                self.name.clone(),
460                format!(
461                    "is {} bytes, which {}",
462                    self.text.len(),
463                    Exceeded::input_bytes(bounds.input_bytes, raise)
464                ),
465            ));
466        }
467        Ok(())
468    }
469
470    /// Validate a parsed `value` against `context`.
471    ///
472    /// Each of garde's problems lands on the line of the field it names, or
473    /// of its nearest written ancestor. The place comes from the parts of
474    /// garde's path through [`Input::place`], so a key that holds a `.` is
475    /// found as one key. `Problem::field` is garde's printed path, for display
476    /// only. A path through a field [`Input::flattened`] declares loses that
477    /// field's step, and its `Problem::field` is the shorter path as
478    /// [`FieldPath`] prints it.
479    ///
480    /// # Errors
481    ///
482    /// An [`InputError`] with every problem garde reports.
483    #[cfg(feature = "validate")]
484    pub fn check<T: Validate + ?Sized>(
485        &self,
486        value: &T,
487        context: &T::Context,
488    ) -> Result<(), InputError> {
489        let Err(report) = value.validate_with(context) else {
490            return Ok(());
491        };
492        let reported: Vec<_> = report
493            .iter()
494            .map(|(path, error)| {
495                let steps = FieldPath::from(path);
496                let (field, steps) = match self.unflatten(&steps) {
497                    Some(kept) => (kept.to_string(), kept),
498                    None => (path.to_string(), steps),
499                };
500                (field, steps, error.message().to_owned())
501            })
502            .collect();
503        let paths: Vec<_> = reported.iter().map(|(_, path, _)| path.clone()).collect();
504        let places = self.places(&paths, At::Value);
505        let problems = reported
506            .into_iter()
507            .zip(places)
508            .map(|((field, _, message), place)| Problem {
509                line: place.map(|at| at.line),
510                column: place.map(|at| at.column),
511                field,
512                message,
513            });
514        InputError::try_new(self.name.clone(), problems).map_or(Ok(()), Err)
515    }
516
517    /// Where `path` is written in the text, or where its nearest written
518    /// ancestor is.
519    ///
520    /// The line counts the whole file, so a frontmatter input adds the lines
521    /// before it. A path the text lacks gives the place of the last step that
522    /// exists, and a caller that needs an exact hit compares the result with
523    /// the place of the path's parent. `None` when the text does not parse.
524    ///
525    /// `None` too when the text goes past the limits in force, as
526    /// [`Input::parse`] would refuse it, so placing never parses a text the
527    /// limits keep out. A YAML input checks `max_reader_input_bytes`,
528    /// `max_depth` and `max_nodes` before it hands the text to yamled, which
529    /// has no budget. A TOML input checks `max_reader_input_bytes`, and
530    /// the parse of its tree is the one [`Input::parse`] does first.
531    ///
532    /// A YAML input parses its text for the first placing and keeps the
533    /// result, so [`Input::check`] and later calls read one document. A TOML
534    /// input parses its text on each call.
535    ///
536    /// ```
537    /// # #[cfg(feature = "yaml")]
538    /// # {
539    /// use ctl_input::{FieldPath, Input};
540    ///
541    /// let input = Input::new("app.yaml", "files:\n  'docs/**/*.md':\n    label: ''\n");
542    /// let path = FieldPath::root()
543    ///     .key("files")
544    ///     .key("docs/**/*.md")
545    ///     .key("label");
546    /// let at = input.place(&path).map(|at| (at.line, at.column));
547    /// assert_eq!(at, Some((3, 12)));
548    /// # }
549    /// ```
550    #[must_use]
551    pub fn place(&self, path: &FieldPath) -> Option<Place> {
552        self.places(slice::from_ref(path), At::Value)
553            .pop()
554            .flatten()
555    }
556
557    /// Where the last step of `path` is written as a key, or where its nearest
558    /// written ancestor's key is.
559    ///
560    /// [`Input::place`] gives where a value starts. For a scalar or a flow
561    /// value that is the line of the key, and for a block mapping or a block
562    /// list it is the first line below it. A fault about the key itself, such
563    /// as a key that names nothing, belongs on the key, and this finds it.
564    ///
565    /// A step that is an index has no key, and neither has the root, so they
566    /// give the place of their value, as `place` does. A path the text lacks
567    /// gives the key of the last step that exists. The line counts the whole
568    /// file, `None` is for a text that does not parse or goes past the limits,
569    /// and a YAML document is built once and shared with [`Input::place`].
570    ///
571    /// ```
572    /// # #[cfg(feature = "yaml")]
573    /// # {
574    /// use ctl_input::{FieldPath, Input};
575    ///
576    /// let input = Input::new("app.yaml", "files:\n  'docs/**/*.md':\n    label: ''\n");
577    /// let glob = FieldPath::root().key("files").key("docs/**/*.md");
578    /// let value = input.place(&glob).map(|at| (at.line, at.column));
579    /// let key = input.place_key(&glob).map(|at| (at.line, at.column));
580    /// assert_eq!(value, Some((3, 5)));
581    /// assert_eq!(key, Some((2, 3)));
582    /// # }
583    /// ```
584    #[must_use]
585    pub fn place_key(&self, path: &FieldPath) -> Option<Place> {
586        self.places(slice::from_ref(path), At::Key).pop().flatten()
587    }
588
589    /// A [`Problem`] for `path` with `message`, placed as [`Input::place`]
590    /// places it, with the path printed as garde prints a field.
591    ///
592    /// A CLI uses it for a check that runs after the read, such as one that
593    /// needs a file the config names.
594    #[must_use]
595    pub fn problem_at(&self, path: &FieldPath, message: impl Into<String>) -> Problem {
596        let place = self.place(path);
597        Problem {
598            line: place.map(|at| at.line),
599            column: place.map(|at| at.column),
600            field: path.to_string(),
601            message: message.into(),
602        }
603    }
604
605    /// The place of each path, with the frontmatter lines added.
606    fn places(&self, paths: &[FieldPath], at: At) -> Vec<Option<Place>> {
607        let limits = limits::effective(&self.limits);
608        if self.text.len() > limits.bounds().input_bytes {
609            return vec![None; paths.len()];
610        }
611        let found = match self.format {
612            #[cfg(feature = "yaml")]
613            Format::Yaml => yaml_text::places(self, &limits, paths, at),
614            #[cfg(feature = "toml")]
615            Format::Toml => toml_text::places(&self.text, paths, at),
616        };
617        found
618            .into_iter()
619            .map(|at| at.map(|(line, column)| Place::new(line + self.lines_before, column)))
620            .collect()
621    }
622
623    /// Parse the text into `T`, then validate it with `T`'s default context.
624    ///
625    /// # Errors
626    ///
627    /// As [`Input::parse`] and [`Input::check`].
628    #[cfg(feature = "validate")]
629    pub fn load<T>(&self) -> Result<T, InputError>
630    where
631        T: DeserializeOwned + Validate,
632        T::Context: Default,
633    {
634        let value = self.parse::<T>()?;
635        self.check(&value, &T::Context::default())?;
636        Ok(value)
637    }
638}
639
640/// The file at `path`, named by its path, or the I/O failure.
641fn read_text(path: &Path) -> Result<(String, String), InputError> {
642    let name = path.display().to_string();
643    match fs::read_to_string(path) {
644        Ok(text) => Ok((name, text)),
645        Err(error) => Err(InputError::unread(name, &error)),
646    }
647}
648
649impl InputError {
650    /// The problems a CLI found in the input `name`, in the order given, so
651    /// it reports its own refusals as ctl-core reports garde's. Each
652    /// [`Problem`] is placed with [`Input::place`] or [`Input::problem_at`],
653    /// or carries no line.
654    ///
655    /// Returns `None` when `problems` is empty, since an error with no problem
656    /// would print nothing. So a CLI hands it every check's findings and
657    /// refuses the input only when one turned up.
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// use ctl_input::{InputError, Problem};
663    ///
664    /// let refused = InputError::try_new(
665    ///     "compose.yaml",
666    ///     [Problem {
667    ///         line: Some(4),
668    ///         column: Some(5),
669    ///         field: "services.dev.privileged".to_owned(),
670    ///         message: "this host runs no privileged service".to_owned(),
671    ///     }],
672    /// );
673    /// assert_eq!(
674    ///     refused.map(|error| error.to_string()).as_deref(),
675    ///     Some("compose.yaml:4:5: services.dev.privileged: this host runs no privileged service")
676    /// );
677    /// assert_eq!(InputError::try_new("compose.yaml", []), None);
678    /// ```
679    #[must_use]
680    pub fn try_new(
681        name: impl Into<String>,
682        problems: impl IntoIterator<Item = Problem>,
683    ) -> Option<Self> {
684        let problems = problems.into_iter().collect::<Vec<_>>();
685        (!problems.is_empty()).then(|| Self {
686            name: name.into(),
687            problems,
688            io_failure: None,
689        })
690    }
691
692    /// A refusal of the whole input `name`, on no line and no field, such as
693    /// a value that only makes sense once the file is read whole.
694    ///
695    /// # Examples
696    ///
697    /// ```
698    /// use ctl_input::InputError;
699    ///
700    /// let error = InputError::whole("compose.yaml", "the file names no service");
701    /// assert_eq!(error.to_string(), "compose.yaml: the file names no service");
702    /// ```
703    #[must_use]
704    pub fn whole(name: impl Into<String>, message: impl Into<String>) -> Self {
705        Self::one(
706            name.into(),
707            Problem {
708                line: None,
709                column: None,
710                field: String::new(),
711                message: message.into(),
712            },
713        )
714    }
715
716    /// The one problem ctl-core found in the input `name`, with no I/O
717    /// failure.
718    pub(crate) fn one(name: String, problem: Problem) -> Self {
719        Self {
720            name,
721            problems: vec![problem],
722            io_failure: None,
723        }
724    }
725
726    /// The input `name` could not be read: the failure's text is the one
727    /// problem, and its `io::ErrorKind` is kept.
728    fn unread(name: String, error: &io::Error) -> Self {
729        Self {
730            io_failure: Some(error.kind()),
731            ..Self::whole(name, error.to_string())
732        }
733    }
734
735    /// The I/O failure when the file could not be read, such as
736    /// [`io::ErrorKind::NotFound`]. `None` when the text was read and refused.
737    #[must_use]
738    pub const fn io_failure(&self) -> Option<io::ErrorKind> {
739        self.io_failure
740    }
741}
742
743/// One problem per line: `name:line:column: field: message`, leaving out
744/// what is not known.
745impl fmt::Display for InputError {
746    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
747        for (index, problem) in self.problems.iter().enumerate() {
748            if index > 0 {
749                writeln!(formatter)?;
750            }
751            write!(formatter, "{}", self.name)?;
752            if let Some(line) = problem.line {
753                write!(formatter, ":{line}")?;
754                if let Some(column) = problem.column {
755                    write!(formatter, ":{column}")?;
756                }
757            }
758            if problem.field.is_empty() {
759                write!(formatter, ": {}", problem.message)?;
760            } else {
761                write!(formatter, ": {}: {}", problem.field, problem.message)?;
762            }
763        }
764        Ok(())
765    }
766}
767
768impl Error for InputError {}