kconfig_represent/
error.rs

1/*
2 Cargo KConfig - KConfig parser
3 Copyright (C) 2022  Sjoerd van Leent
4
5--------------------------------------------------------------------------------
6
7Copyright Notice: Apache
8
9Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10this file except in compliance with the License. You may obtain a copy of the
11License at
12
13   https://www.apache.org/licenses/LICENSE-2.0
14
15Unless required by applicable law or agreed to in writing, software distributed
16under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17CONDITIONS OF ANY KIND, either express or implied. See the License for the
18specific language governing permissions and limitations under the License.
19
20--------------------------------------------------------------------------------
21
22Copyright Notice: GPLv2
23
24This program is free software: you can redistribute it and/or modify
25it under the terms of the GNU General Public License as published by
26the Free Software Foundation, either version 2 of the License, or
27(at your option) any later version.
28
29This program is distributed in the hope that it will be useful,
30but WITHOUT ANY WARRANTY; without even the implied warranty of
31MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32GNU General Public License for more details.
33
34You should have received a copy of the GNU General Public License
35along with this program.  If not, see <https://www.gnu.org/licenses/>.
36
37--------------------------------------------------------------------------------
38
39Copyright Notice: MIT
40
41Permission is hereby granted, free of charge, to any person obtaining a copy of
42this software and associated documentation files (the “Software”), to deal in
43the Software without restriction, including without limitation the rights to
44use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
45the Software, and to permit persons to whom the Software is furnished to do so,
46subject to the following conditions:
47
48The above copyright notice and this permission notice shall be included in all
49copies or substantial portions of the Software.
50
51THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
53FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
54COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
55IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
56CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
57*/
58
59//! This file implements errors returned from the kconfig representation
60
61use std::{fmt::Display, io};
62
63/// An Error is returned when the representation of the AST into a higher-level
64/// presentation failed.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct Error {
67    msg: String,
68}
69
70impl Display for Error {
71    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
72        write!(f, "{}", self.msg,)
73    }
74}
75
76impl From<String> for Error {
77    fn from(s: String) -> Self {
78        Error::new(&s)
79    }
80}
81
82impl From<io::Error> for Error {
83    fn from(e: io::Error) -> Self {
84        Self {
85            msg: format!("{}", e),
86        }
87    }
88}
89
90impl From<&str> for Error {
91    fn from(s: &str) -> Self {
92        Error::new(s)
93    }
94}
95
96impl From<kconfig_parser::Error> for Error {
97    fn from(e: kconfig_parser::Error) -> Self {
98        Error::new(&format!("{}", e))
99    }
100}
101
102impl From<Vec<(String, String)>> for Error {
103    fn from(invalid_lines: Vec<(String, String)>) -> Self {
104        let mut err_msg = String::new();
105        for (msg, line) in invalid_lines {
106            err_msg.push_str(&format!("{}: {}\n", msg, line));
107        }
108        Error::new(&err_msg)
109    }
110}
111
112impl Error {
113    pub(crate) fn new(msg: &str) -> Self {
114        Self {
115            msg: msg.to_string(),
116        }
117    }
118}
119
120/// A LoadError is returned when during loading of a .config file, errors where found.
121/// Typically, this is non-destructive, but an end-user should be warned through the
122/// frontend that something went wrong during loading of the .config file.
123pub enum LoadError {
124    IoError(io::Error),
125    Error(Error),
126}
127
128impl From<io::Error> for LoadError {
129    fn from(e: io::Error) -> Self {
130        LoadError::IoError(e)
131    }
132}
133
134impl From<Error> for LoadError {
135    fn from(e: Error) -> Self {
136        LoadError::Error(e)
137    }
138}
139
140impl Display for LoadError {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        match self {
143            LoadError::IoError(e) => write!(f, "{}", e),
144            LoadError::Error(e) => write!(f, "{}", e),
145        }
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use std::io;
152
153    use crate::{Error, LoadError};
154
155    #[test]
156    fn ctor() -> Result<(), Error> {
157        let e = Error {
158            msg: "FOO".to_owned(),
159        };
160
161        assert_eq!("FOO".to_owned(), format!("{e}"));
162
163        Ok(())
164    }
165
166    #[test]
167    fn new() -> Result<(), Error> {
168        let e = Error::new("FOO");
169        assert_eq!("FOO".to_owned(), format!("{e}"));
170        Ok(())
171    }
172
173    #[test]
174    fn from_string() -> Result<(), Error> {
175        let e = Error::from("FOO".to_owned());
176        assert_eq!("FOO".to_owned(), format!("{e}"));
177        Ok(())
178    }
179
180    #[test]
181    fn from_str() -> Result<(), Error> {
182        let e = Error::from("FOO");
183        assert_eq!("FOO".to_owned(), format!("{e}"));
184        Ok(())
185    }
186
187    #[test]
188    fn from_io_error() -> Result<(), Error> {
189        let ioe = io::Error::new(io::ErrorKind::Unsupported, "FOO");
190        let e = Error::from(ioe);
191        assert_eq!("FOO".to_owned(), format!("{e}"));
192        Ok(())
193    }
194
195    #[test]
196    fn from_lines() -> Result<(), Error> {
197        let invalid_lines = vec![
198            ("FOO".to_owned(), "1".to_owned()),
199            ("BAR".to_owned(), "2".to_owned()),
200        ];
201        let e = Error::from(invalid_lines);
202        assert_eq!("FOO: 1\nBAR: 2\n", format!("{e}"));
203        Ok(())
204    }
205
206    #[test]
207    fn load_error_from_io_error() -> Result<(), Error> {
208        let ioe = io::Error::new(io::ErrorKind::Unsupported, "FOO");
209        let le = LoadError::from(ioe);
210        assert_eq!("FOO", format!("{le}"));
211        Ok(())
212    }
213
214    #[test]
215    fn load_error_from_error() -> Result<(), Error> {
216        let e = Error::from("FOO");
217        let le = LoadError::from(e);
218        assert_eq!("FOO", format!("{le}"));
219        Ok(())
220    }
221}