Skip to main content

ctl_input/
placing.rs

1//! Where a path is written in the text, and the garde check that places its
2//! problems there.
3
4use std::slice;
5
6#[cfg(feature = "validate")]
7use garde::Validate;
8
9#[cfg(feature = "validate")]
10use super::InputError;
11use super::format::Reading;
12use super::{FieldPath, Input, Place, Problem, limits, tree};
13
14/// What a placing answers with for a key of the path: where its value starts,
15/// or where the key itself is written.
16#[derive(Clone, Copy)]
17pub(crate) enum At {
18    Value,
19    Key,
20}
21
22impl Input {
23    /// Declare that the schema field at `field` is flattened into its parent
24    /// with `#[serde(flatten)]`, so the file writes its entries directly under
25    /// the parent.
26    ///
27    /// garde names the field in each problem's path all the same, and serde
28    /// gives no sign of the flattening at run time, so the schema declares it.
29    /// [`Input::check`] then drops the field's step from each garde path whose
30    /// leading steps are `field`, before it places the problem and prints its
31    /// field. `field` is written in the schema's terms, the way garde names it,
32    /// and each call adds one field. A declaration that matches no garde path
33    /// changes nothing. [`Input::place`], [`Input::place_key`], and
34    /// [`Input::problem_at`] take paths in the file's terms, so a declaration
35    /// does not touch them.
36    ///
37    /// # Examples
38    ///
39    /// verctl's `assets` holds its targets in a flattened map field `targets`.
40    /// Without the declaration, the problem prints as
41    /// `assets.targets.linux-x64.files` and sits on the line below `assets:`.
42    ///
43    /// ```
44    /// # #[cfg(all(feature = "yaml", feature = "validate"))]
45    /// # {
46    /// use std::collections::BTreeMap;
47    ///
48    /// use ctl_input::{FieldPath, Input};
49    /// use garde::Validate;
50    /// use serde::Deserialize;
51    ///
52    /// #[derive(Debug, Deserialize, Validate)]
53    /// struct Config {
54    ///     #[garde(dive)]
55    ///     assets: Assets,
56    /// }
57    ///
58    /// #[derive(Debug, Deserialize, Validate)]
59    /// struct Assets {
60    ///     #[serde(flatten)]
61    ///     #[garde(dive)]
62    ///     targets: BTreeMap<String, Target>,
63    /// }
64    ///
65    /// #[derive(Debug, Deserialize, Validate)]
66    /// struct Target {
67    ///     #[garde(custom(at_least_one_file))]
68    ///     files: Vec<String>,
69    /// }
70    ///
71    /// fn at_least_one_file(files: &[String], _: &()) -> garde::Result {
72    ///     if files.is_empty() {
73    ///         return Err(garde::Error::new("must declare at least one file"));
74    ///     }
75    ///     Ok(())
76    /// }
77    ///
78    /// let error = Input::new("ver.yaml", "assets:\n  linux-x64:\n    files: []\n")
79    ///     .flattened(FieldPath::root().key("assets").key("targets"))
80    ///     .load::<Config>()
81    ///     .unwrap_err();
82    /// assert_eq!(
83    ///     error.to_string(),
84    ///     "ver.yaml:3:12: assets.linux-x64.files: must declare at least one file"
85    /// );
86    /// # }
87    /// ```
88    #[cfg(feature = "validate")]
89    #[must_use]
90    pub fn flattened(mut self, field: FieldPath) -> Self {
91        self.flattened.push(field);
92        self
93    }
94
95    /// `path` without the step of each declared flattened field it passes
96    /// through, or `None` when it passes through none.
97    #[cfg(feature = "validate")]
98    fn unflatten(&self, path: &FieldPath) -> Option<FieldPath> {
99        let positions: Vec<usize> = self
100            .flattened
101            .iter()
102            .filter(|field| path.starts_with(field))
103            .filter_map(|field| field.steps().len().checked_sub(1))
104            .collect();
105        (!positions.is_empty()).then(|| path.without(&positions))
106    }
107
108    /// Validate a parsed `value` against `context`.
109    ///
110    /// Each of garde's problems lands on the line of the field it names, or
111    /// of its nearest written ancestor. The place comes from the parts of
112    /// garde's path through [`Input::place`], so a key that holds a `.` is
113    /// found as one key. `Problem::field` is garde's printed path, for display
114    /// only. A path through a field [`Input::flattened`] declares loses that
115    /// field's step, and its `Problem::field` is the shorter path as
116    /// [`FieldPath`] prints it.
117    ///
118    /// # Errors
119    ///
120    /// An [`InputError`] with every problem garde reports.
121    #[cfg(feature = "validate")]
122    pub fn check<T: Validate + ?Sized>(
123        &self,
124        value: &T,
125        context: &T::Context,
126    ) -> Result<(), InputError> {
127        let Err(report) = value.validate_with(context) else {
128            return Ok(());
129        };
130        let reported: Vec<_> = report
131            .iter()
132            .map(|(path, error)| {
133                let steps = FieldPath::from(path);
134                let (field, steps) = match self.unflatten(&steps) {
135                    Some(kept) => (kept.to_string(), kept),
136                    None => (path.to_string(), steps),
137                };
138                (field, steps, error.message().to_owned())
139            })
140            .collect();
141        let paths: Vec<_> = reported.iter().map(|(_, path, _)| path.clone()).collect();
142        let places = self.places(&paths, At::Value);
143        let problems = reported
144            .into_iter()
145            .zip(places)
146            .map(|((field, _, message), place)| Problem {
147                line: place.map(|at| at.line),
148                column: place.map(|at| at.column),
149                field,
150                message,
151            });
152        InputError::try_new(self.name.clone(), problems).map_or(Ok(()), Err)
153    }
154
155    /// Where `path` is written in the text, or where its nearest written
156    /// ancestor is.
157    ///
158    /// The line counts the whole file, so a frontmatter input adds the lines
159    /// before it. A path the text lacks gives the place of the last step that
160    /// exists, and a caller that needs an exact hit compares the result with
161    /// the place of the path's parent. `None` when the text does not parse.
162    ///
163    /// `None` too when the text goes past the limits in force, as
164    /// [`Input::parse`] would refuse it, so placing never reads a text the
165    /// limits keep out.
166    ///
167    /// The first placing reads the text into the tree and keeps it, so
168    /// [`Input::parse`], [`Input::check`], [`Input::top_level`] and later calls
169    /// share one read, for every format. A repeated key or a merge key does not
170    /// stop placing, though [`Input::parse`] refuses it.
171    ///
172    /// ```
173    /// # #[cfg(feature = "yaml")]
174    /// # {
175    /// use ctl_input::{FieldPath, Input};
176    ///
177    /// let input = Input::new("app.yaml", "files:\n  'docs/**/*.md':\n    label: ''\n");
178    /// let path = FieldPath::root()
179    ///     .key("files")
180    ///     .key("docs/**/*.md")
181    ///     .key("label");
182    /// let at = input.place(&path).map(|at| (at.line, at.column));
183    /// assert_eq!(at, Some((3, 12)));
184    /// # }
185    /// ```
186    #[must_use]
187    pub fn place(&self, path: &FieldPath) -> Option<Place> {
188        self.places(slice::from_ref(path), At::Value)
189            .pop()
190            .flatten()
191    }
192
193    /// Where the last step of `path` is written as a key, or where its nearest
194    /// written ancestor's key is.
195    ///
196    /// [`Input::place`] gives where a value starts. For a scalar or a flow
197    /// value that is the line of the key, and for a block mapping or a block
198    /// list it is the first line below it. A fault about the key itself, such
199    /// as a key that names nothing, belongs on the key, and this finds it.
200    ///
201    /// A step that is an index has no key, and neither has the root, so they
202    /// give the place of their value, as `place` does. A path the text lacks
203    /// gives the key of the last step that exists. The line counts the whole
204    /// file, `None` is for a text that does not parse or goes past the limits,
205    /// and the tree is read once and shared with [`Input::place`].
206    ///
207    /// ```
208    /// # #[cfg(feature = "yaml")]
209    /// # {
210    /// use ctl_input::{FieldPath, Input};
211    ///
212    /// let input = Input::new("app.yaml", "files:\n  'docs/**/*.md':\n    label: ''\n");
213    /// let glob = FieldPath::root().key("files").key("docs/**/*.md");
214    /// let value = input.place(&glob).map(|at| (at.line, at.column));
215    /// let key = input.place_key(&glob).map(|at| (at.line, at.column));
216    /// assert_eq!(value, Some((3, 5)));
217    /// assert_eq!(key, Some((2, 3)));
218    /// # }
219    /// ```
220    #[must_use]
221    pub fn place_key(&self, path: &FieldPath) -> Option<Place> {
222        self.places(slice::from_ref(path), At::Key).pop().flatten()
223    }
224
225    /// A [`Problem`] for `path` with `message`, placed as [`Input::place`]
226    /// places it, with the path printed as garde prints a field.
227    ///
228    /// A CLI uses it for a check that runs after the read, such as one that
229    /// needs a file the config names.
230    #[must_use]
231    pub fn problem_at(&self, path: &FieldPath, message: impl Into<String>) -> Problem {
232        let place = self.place(path);
233        Problem {
234            line: place.map(|at| at.line),
235            column: place.map(|at| at.column),
236            field: path.to_string(),
237            message: message.into(),
238        }
239    }
240
241    /// The place of each path, with the frontmatter lines added.
242    fn places(&self, paths: &[FieldPath], at: At) -> Vec<Option<Place>> {
243        let limits = limits::effective(&self.limits);
244        if self.text.len() > limits.bounds().input_bytes {
245            return vec![None; paths.len()];
246        }
247        let read = self
248            .kept
249            .tree(self.format, &self.text, &limits, Reading::Listing);
250        let Ok(tree) = read.as_ref() else {
251            return vec![None; paths.len()];
252        };
253        paths
254            .iter()
255            .map(|path| {
256                let (line, column) =
257                    tree::position(&self.text, tree.nearest(path.steps(), at).start);
258                Some(Place::new(line + self.lines_before, column))
259            })
260            .collect()
261    }
262}