lib_humus/
toml_helper.rs

1
2// This whole module is deprecated, don't warn about usage of deprecated code within it
3#![allow(deprecated)]
4
5
6use serde::Deserialize;
7
8use std::fmt;
9use std::fs;
10use std::path::Path;
11use std::path::PathBuf;
12use std::error::Error;
13
14
15/// Reads from a specified filepath, parses as toml and returns as the
16/// desired deserialized type.
17///
18/// Example:
19/// ```
20/// use serde::Deserialize;
21/// use lib_humus::read_toml_from_file;
22///
23/// #[derive(Deserialize)]
24/// struct Config {
25///		name: String,
26/// }
27///
28///	let cfg: Config = read_toml_from_file("example_config.toml").unwrap();
29///	println!("Hello {}!", cfg.name);
30/// ```
31///
32#[deprecated( since = "0.4.0", note = "Please use the lib-humus-configuration crate instead.")]
33pub fn read_toml_from_file<T>(path: impl AsRef<Path>) -> Result<T,TomlError>
34where T: for<'de> Deserialize<'de> {
35	let text = match fs::read_to_string(&path) {
36		Ok(t) => t,
37		Err(e) => {
38			return Err(TomlError::FileError{
39				path: path.as_ref().into(),
40				io_error: e
41			});
42		}
43	};
44	match toml::from_str(&text) {
45		Ok(t) => Ok(t),
46		Err(e) => {
47			return Err(TomlError::ParseError{
48				path: path.as_ref().into(),
49				toml_error: e
50			});
51		}
52	}
53}
54
55/// Returned when [read_toml_from_file()] fails.
56///
57/// [read_toml_from_file]: ./fn.read_toml_from_file.html
58#[derive(Debug)]
59#[deprecated( since = "0.4.0", note = "Please use the lib-humus-configuration crate instead.")]
60pub enum TomlError {
61	
62	/// There was an error reading the file from the filesystem.
63	FileError{
64		/// The path the file is supposed to be at
65		path: PathBuf,
66		/// What went wrong
67		io_error: std::io::Error
68	},
69	
70	/// There was an error parsing the file content as toml.
71	ParseError{
72		/// The path the file was read from
73		path: PathBuf,
74		/// What went wrong
75		toml_error: toml::de::Error
76	},
77}
78
79impl fmt::Display for TomlError {
80	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81		match self {
82			Self::FileError{path, io_error} =>
83				write!(f,"Error while reading file '{path:?}': {io_error}"),
84			Self::ParseError{path, toml_error} =>
85				write!(f,"Unable to parse file as toml '{path:?}':\n{toml_error}"),
86		}
87	}
88}
89
90impl Error for TomlError {
91    fn source(&self) -> Option<&(dyn Error + 'static)> {
92        match self {
93			Self::FileError{io_error, ..} =>
94				Some(io_error),
95			Self::ParseError{toml_error, ..} =>
96				Some(toml_error),
97        }
98    }
99}