From 51caa967519ff63e987918133226acb119fbbc9f Mon Sep 17 00:00:00 2001 From: Alex Crawford Date: Thu, 8 Aug 2024 14:26:39 -0700 Subject: [PATCH] Include file path in error message This is especially helpful when the file listed in the "extends" attribute cannot be read. Before this change, the path listed was the outermost tsconfig.json, which can be very confusing. In order for this to work, an additional error type had to be created to distinguish between the two io:Error occurrences. This should also help to narrow down errors. --- src/lib.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 99ed354..5e31fb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,7 @@ //! //! ``` -use std::path::Path; +use std::path::{Path, PathBuf}; use std::{collections::HashMap, io::Read}; use json_comments::StripComments; @@ -36,8 +36,10 @@ pub type Result = std::result::Result; pub enum ConfigError { #[error("Could not parse configuration file")] ParseError(#[from] serde_json::Error), - #[error("Could not read file")] - CouldNotFindFile(#[from] std::io::Error), + #[error("Could not read file {0}")] + CouldNotReadFile(PathBuf, std::io::Error), + #[error("Invalid JSON data")] + InvalidJsonData(std::io::Error), #[error("Could not convert path into UTF-8: {0}")] InvalidPath(String), } @@ -133,7 +135,9 @@ impl TsConfig { // Remove trailing commas from objects. let re = Regex::new(r",(?P\s*})").unwrap(); let mut stripped = String::with_capacity(json.len()); - StripComments::new(json.as_bytes()).read_to_string(&mut stripped)?; + StripComments::new(json.as_bytes()) + .read_to_string(&mut stripped) + .map_err(|err| ConfigError::InvalidJsonData(err))?; let stripped = re.replace_all(&stripped, "$valid"); let r: TsConfig = serde_json::from_str(&stripped)?; Ok(r) @@ -203,7 +207,8 @@ fn merge(a: &mut Value, b: Value) { /// /// ``` pub fn parse_file_to_value>(path: &P) -> Result { - let s = std::fs::read_to_string(path)?; + let s = std::fs::read_to_string(path) + .map_err(|err| ConfigError::CouldNotReadFile(path.as_ref().into(), err))?; let mut value = parse_to_value(&s)?; if let Value::String(s) = &value["extends"] { @@ -252,7 +257,9 @@ pub fn parse_to_value(json: &str) -> Result { // Remove trailing commas from objects. let re = Regex::new(r",(?P\s*})").unwrap(); let mut stripped = String::with_capacity(json.len()); - StripComments::new(json.as_bytes()).read_to_string(&mut stripped)?; + StripComments::new(json.as_bytes()) + .read_to_string(&mut stripped) + .map_err(|err| ConfigError::InvalidJsonData(err))?; let stripped = re.replace_all(&stripped, "$valid"); let r: Value = serde_json::from_str(&stripped)?; Ok(r)