ctl_input/field_path.rs
1//! The steps from a document's root to a field, and the place where a field is
2//! written.
3
4use std::fmt;
5
6#[cfg(feature = "validate")]
7use garde::error;
8
9/// One step down a [`FieldPath`]: a mapping key or a sequence index.
10///
11/// The set is closed, because a node of a YAML or TOML document is entered by
12/// one of these two ways and by no other.
13#[derive(Clone, Debug, PartialEq, Eq, Hash)]
14pub enum Step {
15 /// A key of a mapping or table. Any text: it may hold `.`, `*`, `/`, `[`,
16 /// or only digits.
17 Key(String),
18 /// An item of a sequence or array.
19 Index(usize),
20}
21
22/// The steps from a document's root down to a field.
23///
24/// Build one with [`FieldPath::root`], [`FieldPath::key`], and
25/// [`FieldPath::index`], or, with the `validate` feature, from garde's path
26/// with `FieldPath::from`. [`Input::place`](super::Input::place) turns it into
27/// a line and column.
28///
29/// A key is kept as written, so
30/// `FieldPath::root().key("files").key("docs/**/*.md")` names one key of
31/// `files`, not four. `Display` joins the steps the way garde prints a field,
32/// `files.docs/**/*.md`, which cannot tell a key that holds a dot from nesting.
33/// It is for people, and nothing reads it back.
34#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
35pub struct FieldPath(Vec<Step>);
36
37impl FieldPath {
38 /// The document's root.
39 #[must_use]
40 pub fn root() -> Self {
41 Self::default()
42 }
43
44 /// This path extended by a mapping or table key.
45 #[must_use]
46 pub fn key(mut self, key: impl Into<String>) -> Self {
47 self.0.push(Step::Key(key.into()));
48 self
49 }
50
51 /// This path extended by a sequence or array index.
52 #[must_use]
53 pub fn index(mut self, index: usize) -> Self {
54 self.0.push(Step::Index(index));
55 self
56 }
57
58 /// The steps from the root, in order.
59 #[must_use]
60 pub fn steps(&self) -> &[Step] {
61 &self.0
62 }
63
64 /// Whether this path's leading steps are the steps of `prefix`.
65 #[cfg(feature = "validate")]
66 pub(crate) fn starts_with(&self, prefix: &Self) -> bool {
67 self.0.starts_with(&prefix.0)
68 }
69
70 /// This path without the steps at `positions`, each an index into
71 /// [`Self::steps`].
72 #[cfg(feature = "validate")]
73 pub(crate) fn without(&self, positions: &[usize]) -> Self {
74 Self(
75 self.0
76 .iter()
77 .enumerate()
78 .filter(|(position, _)| !positions.contains(position))
79 .map(|(_, step)| step.clone())
80 .collect(),
81 )
82 }
83}
84
85/// The path as garde prints a field: keys joined by `.`, indexes in brackets,
86/// and nothing for the root.
87impl fmt::Display for FieldPath {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 for (position, step) in self.0.iter().enumerate() {
90 match step {
91 Step::Key(key) => {
92 if position > 0 {
93 formatter.write_str(".")?;
94 }
95 formatter.write_str(key)?;
96 }
97 Step::Index(index) => write!(formatter, "[{index}]")?,
98 }
99 }
100 Ok(())
101 }
102}
103
104/// The steps of garde's path, read from its parts and never from its printed
105/// string, so a key that holds a `.` stays one step.
106///
107/// A component garde marks as an index becomes [`Step::Index`], one it marks as
108/// a key becomes [`Step::Key`], and one it marks with no key, which names a
109/// wrapper such as a one-field tuple struct, is dropped. An index component
110/// that is not a number is kept as a key.
111#[cfg(feature = "validate")]
112impl From<&error::Path> for FieldPath {
113 fn from(path: &error::Path) -> Self {
114 use garde::error::Kind;
115
116 let mut steps = Vec::new();
117 // garde 0.23.0 keeps a path's parts behind `__iter`, which is public
118 // and `#[doc(hidden)]`. It yields the innermost component first, as
119 // `Display` reads it with `rev`. The workspace pins garde exactly so a
120 // release cannot change it unseen, and
121 // `a_garde_path_converts_from_its_parts` fails first if one does.
122 for (kind, component) in path.__iter().rev() {
123 match kind {
124 Kind::Key => steps.push(Step::Key(component.to_string())),
125 Kind::Index => steps.push(
126 component
127 .parse::<usize>()
128 .map_or_else(|_| Step::Key(component.to_string()), Step::Index),
129 ),
130 Kind::None => {}
131 }
132 }
133 Self(steps)
134 }
135}
136
137/// The 1-based line and column where a field is written.
138///
139/// The column counts characters. [`Input::place`](super::Input::place) returns
140/// one. The struct is non-exhaustive so a field such as an end position can
141/// join it.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct Place {
145 /// 1-based line in the whole file, frontmatter lines included.
146 pub line: usize,
147 /// 1-based column, counted in characters.
148 pub column: usize,
149}
150
151impl Place {
152 pub(crate) const fn new(line: usize, column: usize) -> Self {
153 Self { line, column }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 #[test]
162 fn a_path_prints_as_garde_prints_a_field() {
163 let path = FieldPath::root()
164 .key("files")
165 .key("docs/**/*.md")
166 .key("vocab")
167 .index(1);
168 assert_eq!(path.to_string(), "files.docs/**/*.md.vocab[1]");
169 assert_eq!(FieldPath::root().index(0).key("a").to_string(), "[0].a");
170 assert_eq!(FieldPath::root().to_string(), "");
171 }
172
173 #[cfg(feature = "validate")]
174 #[test]
175 fn a_garde_path_converts_from_its_parts() {
176 let path = error::Path::new("files")
177 .join("docs/**/*.md")
178 .join("vocab")
179 .join(0_usize);
180 assert_eq!(
181 FieldPath::from(&path).steps(),
182 [
183 Step::Key("files".to_owned()),
184 Step::Key("docs/**/*.md".to_owned()),
185 Step::Key("vocab".to_owned()),
186 Step::Index(0),
187 ]
188 );
189 assert_eq!(path.to_string(), "files.docs/**/*.md.vocab[0]");
190 }
191
192 #[cfg(feature = "validate")]
193 #[test]
194 fn a_numeric_key_stays_a_key_and_a_keyless_part_is_dropped() {
195 let path = error::Path::new("files")
196 .join("2")
197 .join(error::NoKey::default())
198 .join("label");
199 assert_eq!(
200 FieldPath::from(&path).steps(),
201 [
202 Step::Key("files".to_owned()),
203 Step::Key("2".to_owned()),
204 Step::Key("label".to_owned()),
205 ]
206 );
207 }
208}