Skip to main content

ctl_input/
input_error.rs

1//! The error an input is refused with, and the problems it lists.
2
3use std::error::Error;
4use std::path::Path;
5use std::{fmt, fs, io};
6
7#[cfg(doc)]
8use super::Input;
9
10/// Why an input was refused: every problem found, each placed on a line when
11/// the text allows it.
12///
13/// `Display` prints one problem per line as `name:line:column: field: message`,
14/// leaving out what is not known.
15///
16/// A file that could not be read keeps its [`io::ErrorKind`], which
17/// [`Self::io_failure`] returns. So a caller can treat a missing file apart
18/// from a refused one. A field can join this type in a minor release.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct InputError {
22    /// The input's name, usually its path.
23    pub name: String,
24    /// What is wrong, in the order found.
25    pub problems: Vec<Problem>,
26    /// The I/O failure, for an input that could not be read.
27    io_failure: Option<io::ErrorKind>,
28}
29
30/// One thing wrong with an input.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Problem {
33    /// 1-based line, when known.
34    pub line: Option<usize>,
35    /// 1-based column, when known.
36    pub column: Option<usize>,
37    /// The field it concerns, as garde names it (`packages[1].name`); empty
38    /// for a problem with the whole text.
39    pub field: String,
40    /// What a person changes to fix it.
41    pub message: String,
42}
43
44/// The file at `path`, named by its path, or the I/O failure.
45pub(crate) fn read_text(path: &Path) -> Result<(String, String), InputError> {
46    let name = path.display().to_string();
47    match fs::read_to_string(path) {
48        Ok(text) => Ok((name, text)),
49        Err(error) => Err(InputError::unread(name, &error)),
50    }
51}
52
53impl InputError {
54    /// The problems a CLI found in the input `name`, in the order given, so
55    /// it reports its own refusals as ctl-core reports garde's. Each
56    /// [`Problem`] is placed with [`Input::place`] or [`Input::problem_at`],
57    /// or carries no line.
58    ///
59    /// Returns `None` when `problems` is empty, since an error with no problem
60    /// would print nothing. So a CLI hands it every check's findings and
61    /// refuses the input only when one turned up.
62    ///
63    /// # Examples
64    ///
65    /// ```
66    /// use ctl_input::{InputError, Problem};
67    ///
68    /// let refused = InputError::try_new(
69    ///     "compose.yaml",
70    ///     [Problem {
71    ///         line: Some(4),
72    ///         column: Some(5),
73    ///         field: "services.dev.privileged".to_owned(),
74    ///         message: "this host runs no privileged service".to_owned(),
75    ///     }],
76    /// );
77    /// assert_eq!(
78    ///     refused.map(|error| error.to_string()).as_deref(),
79    ///     Some("compose.yaml:4:5: services.dev.privileged: this host runs no privileged service")
80    /// );
81    /// assert_eq!(InputError::try_new("compose.yaml", []), None);
82    /// ```
83    #[must_use]
84    pub fn try_new(
85        name: impl Into<String>,
86        problems: impl IntoIterator<Item = Problem>,
87    ) -> Option<Self> {
88        let problems = problems.into_iter().collect::<Vec<_>>();
89        (!problems.is_empty()).then(|| Self {
90            name: name.into(),
91            problems,
92            io_failure: None,
93        })
94    }
95
96    /// A refusal of the whole input `name`, on no line and no field, such as
97    /// a value that only makes sense once the file is read whole.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use ctl_input::InputError;
103    ///
104    /// let error = InputError::whole("compose.yaml", "the file names no service");
105    /// assert_eq!(error.to_string(), "compose.yaml: the file names no service");
106    /// ```
107    #[must_use]
108    pub fn whole(name: impl Into<String>, message: impl Into<String>) -> Self {
109        Self::one(
110            name.into(),
111            Problem {
112                line: None,
113                column: None,
114                field: String::new(),
115                message: message.into(),
116            },
117        )
118    }
119
120    /// The one problem ctl-core found in the input `name`, with no I/O
121    /// failure.
122    pub(crate) fn one(name: String, problem: Problem) -> Self {
123        Self {
124            name,
125            problems: vec![problem],
126            io_failure: None,
127        }
128    }
129
130    /// The input `name` could not be read: the failure's text is the one
131    /// problem, and its `io::ErrorKind` is kept.
132    pub(crate) fn unread(name: String, error: &io::Error) -> Self {
133        Self {
134            io_failure: Some(error.kind()),
135            ..Self::whole(name, error.to_string())
136        }
137    }
138
139    /// The I/O failure when the file could not be read, such as
140    /// [`io::ErrorKind::NotFound`]. `None` when the text was read and refused.
141    #[must_use]
142    pub const fn io_failure(&self) -> Option<io::ErrorKind> {
143        self.io_failure
144    }
145}
146
147/// One problem per line: `name:line:column: field: message`, leaving out
148/// what is not known.
149impl fmt::Display for InputError {
150    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
151        for (index, problem) in self.problems.iter().enumerate() {
152            if index > 0 {
153                writeln!(formatter)?;
154            }
155            write!(formatter, "{}", self.name)?;
156            if let Some(line) = problem.line {
157                write!(formatter, ":{line}")?;
158                if let Some(column) = problem.column {
159                    write!(formatter, ":{column}")?;
160                }
161            }
162            if problem.field.is_empty() {
163                write!(formatter, ": {}", problem.message)?;
164            } else {
165                write!(formatter, ": {}: {}", problem.field, problem.message)?;
166            }
167        }
168        Ok(())
169    }
170}
171
172impl Error for InputError {}