1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::{fmt, fs, path::Path};
use error_stack::{Context, IntoReport, Report, ResultExt};
pub type Config = String;
#[derive(Debug)]
struct ParseConfigError;
impl ParseConfigError {
pub fn new() -> Self {
Self
}
}
impl fmt::Display for ParseConfigError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("Could not parse configuration file")
}
}
impl Context for ParseConfigError {}
struct Suggestion(&'static str);
fn parse_config(path: impl AsRef<Path>) -> Result<Config, Report<ParseConfigError>> {
let path = path.as_ref();
let content = fs::read_to_string(path)
.into_report()
.change_context(ParseConfigError::new())
.attach(Suggestion("use a file you can read next time!"))
.attach_printable_lazy(|| format!("could not read file {path:?}"))?;
Ok(content)
}
fn main() {
if let Err(report) = parse_config("config.json") {
eprintln!("{report:?}");
#[cfg(nightly)]
for suggestion in report.request_ref::<Suggestion>() {
eprintln!("Suggestion: {}", suggestion.0);
}
}
}