Skip to content

Commit

Permalink
Nicer error messages on toml/json io failure
Browse files Browse the repository at this point in the history
  • Loading branch information
Aszarsha authored and baskerville committed Mar 4, 2020
1 parent 51326f7 commit 9cc4075
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,23 +60,35 @@ pub fn decode_entities(text: &str) -> Cow<str> {
}

pub fn load_json<T, P: AsRef<Path>>(path: P) -> Result<T, Error> where for<'a> T: Deserialize<'a> {
let file = File::open(path).context("Can't open file.")?;
serde_json::from_reader(file).context("Can't parse file.").map_err(Into::into)
let file = File::open(path.as_ref())
.context(format!("'{}': Cannot open file", path.as_ref().display()))?;
serde_json::from_reader(file)
.context(format!("'{}': Cannot parse JSON file", path.as_ref().display()))
.map_err(Into::into)
}

pub fn save_json<T, P: AsRef<Path>>(data: &T, path: P) -> Result<(), Error> where T: Serialize {
let file = File::create(path).context("Can't create data file.")?;
serde_json::to_writer_pretty(file, data).context("Can't serialize data to file.").map_err(Into::into)
let file = File::create(path.as_ref())
.context(format!("'{}': Cannot create file", path.as_ref().display()))?;
serde_json::to_writer_pretty(file, data)
.context(format!("'{}': Cannot serialize to JSON file", path.as_ref().display()))
.map_err(Into::into)
}

pub fn load_toml<T, P: AsRef<Path>>(path: P) -> Result<T, Error> where for<'a> T: Deserialize<'a> {
let s = fs::read_to_string(path).context("Can't read file.")?;
toml::from_str(&s).context("Can't parse file.").map_err(Into::into)
let s = fs::read_to_string(path.as_ref())
.context(format!("'{}': Cannot read file", path.as_ref().display()))?;
toml::from_str(&s)
.context(format!("'{}': Cannot parse TOML content", path.as_ref().display()))
.map_err(Into::into)
}

pub fn save_toml<T, P: AsRef<Path>>(data: &T, path: P) -> Result<(), Error> where T: Serialize {
let s = toml::to_string(data).context("Can't serialize data.")?;
fs::write(path, &s).context("Can't write to file.").map_err(Into::into)
let s = toml::to_string(data)
.context("Cannot convert to TOML format")?;
fs::write(path.as_ref(), &s)
.context(format!("'{}': Cannot write to file", path.as_ref().display()))
.map_err(Into::into)
}

pub fn combine_sort_methods<'a, T, F1, F2>(mut f1: F1, mut f2: F2) -> Box<dyn FnMut(&T, &T) -> Ordering + 'a>
Expand Down

0 comments on commit 9cc4075

Please sign in to comment.