Skip to content

Commit

Permalink
Clean up error location reporting for yaml parsing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Feb 19, 2024
1 parent 64d6647 commit 9f9c890
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 25 deletions.
9 changes: 4 additions & 5 deletions src/content/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use std::fmt;
/// An internal error type for content related errors.
#[derive(Debug)]
pub enum Error {
FailedParsingYaml(Option<std::path::PathBuf>),
FailedParsingYaml(std::path::PathBuf),
UnexpectedDataType,
#[cfg(feature = "_cargo_insta_internal")]
MissingField,
Expand All @@ -29,10 +29,9 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FailedParsingYaml(None) => f.write_str("Failed parsing the provided YAML text"),
Self::FailedParsingYaml(Some(pathbuf)) => f.write_str(
format!("Failed parsing the YAML from {:?}", pathbuf.as_os_str()).as_str(),
),
Self::FailedParsingYaml(p) => {
f.write_str(format!("Failed parsing the YAML from {:?}", p.display()).as_str())
}
Self::UnexpectedDataType => {
f.write_str("The present data type wasn't what was expected")
}
Expand Down
22 changes: 13 additions & 9 deletions src/content/yaml.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
use std::path::Path;

use crate::content::{Content, Error};

use yaml_rust::{yaml::Hash as YamlObj, Yaml as YamlValue};

pub fn parse_str(s: &str) -> Result<Content, Error> {
let mut blobs =
yaml_rust::YamlLoader::load_from_str(s).map_err(|_| Error::FailedParsingYaml(None))?;
pub fn parse_str(s: &str, filename: &Path) -> Result<Content, Error> {
let mut blobs = yaml_rust::YamlLoader::load_from_str(s)
.map_err(|_| Error::FailedParsingYaml(filename.to_path_buf()))?;

match (blobs.pop(), blobs.pop()) {
(Some(blob), None) => from_yaml_blob(blob).map_err(Into::into),
_ => Err(Error::FailedParsingYaml(None)),
(Some(blob), None) => from_yaml_blob(blob, filename),
_ => Err(Error::FailedParsingYaml(filename.to_path_buf())),
}
}

fn from_yaml_blob(blob: YamlValue) -> Result<Content, Error> {
fn from_yaml_blob(blob: YamlValue, filename: &Path) -> Result<Content, Error> {
match blob {
YamlValue::Null => Ok(Content::None),
YamlValue::Boolean(b) => Ok(Content::from(b)),
Expand All @@ -25,18 +27,20 @@ fn from_yaml_blob(blob: YamlValue) -> Result<Content, Error> {
YamlValue::Array(seq) => {
let seq = seq
.into_iter()
.map(from_yaml_blob)
.map(|x| from_yaml_blob(x, filename))
.collect::<Result<_, Error>>()?;
Ok(Content::Seq(seq))
}
YamlValue::Hash(obj) => {
let obj = obj
.into_iter()
.map(|(k, v)| Ok((from_yaml_blob(k)?, from_yaml_blob(v)?)))
.map(|(k, v)| Ok((from_yaml_blob(k, filename)?, from_yaml_blob(v, filename)?)))
.collect::<Result<_, Error>>()?;
Ok(Content::Map(obj))
}
YamlValue::BadValue | YamlValue::Alias(_) => Err(Error::FailedParsingYaml(None)),
YamlValue::BadValue | YamlValue::Alias(_) => {
Err(Error::FailedParsingYaml(filename.to_path_buf()))
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,9 @@ impl ToolConfig {
let mut cfg = None;
for choice in &[".config/insta.yaml", "insta.yaml", ".insta.yaml"] {
let path = workspace_dir.join(choice);
match fs::read_to_string(path) {
match fs::read_to_string(&path) {
Ok(s) => {
cfg = Some(yaml::parse_str(&s).map_err(Error::Deserialize)?);
cfg = Some(yaml::parse_str(&s, &path).map_err(Error::Deserialize)?);
break;
}
// ideally we would not swallow all errors here but unfortunately there are
Expand Down
11 changes: 2 additions & 9 deletions src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl PendingInlineSnapshot {
let mut rv: Vec<Self> = contents
.lines()
.map(|line| {
let value = yaml::parse_str(line)?;
let value = yaml::parse_str(line, p)?;
Self::from_content(value)
})
.collect::<Result<_, Box<dyn Error>>>()?;
Expand Down Expand Up @@ -286,14 +286,7 @@ impl Snapshot {
break;
}
}
let content = yaml::parse_str(&buf).map_err(|e| {
// Add file context to error
if matches!(e, content::Error::FailedParsingYaml(None)) {
content::Error::FailedParsingYaml(Some(p.to_path_buf()))
} else {
e
}
})?;
let content = yaml::parse_str(&buf, p)?;
MetaData::from_content(content)?
// legacy format
} else {
Expand Down

0 comments on commit 9f9c890

Please sign in to comment.