diff --git a/front/src/lib.rs b/front/src/lib.rs index 4a2ad10..51fb3d8 100644 --- a/front/src/lib.rs +++ b/front/src/lib.rs @@ -13,7 +13,6 @@ pub fn main() -> Result<(), JsValue> { #[wasm_bindgen] pub fn format(before: String, path: String) -> String { let config = alejandra::config::Config::new(); - let after = alejandra::format::string(&config, path, before); - return after; + alejandra::format::string_or_passthrough(&config, path, before) } diff --git a/src/cli.rs b/src/cli.rs index f8c9b08..b5fbf05 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -33,7 +33,9 @@ pub fn stdin(config: crate::config::Config) -> std::io::Result<()> { eprintln!("Formatting stdin, run with --help to see all options."); let mut stdin = String::new(); std::io::stdin().read_to_string(&mut stdin).unwrap(); - print!("{}", crate::format::string(&config, "stdin".to_string(), stdin)); + + let stdout = crate::format::string(&config, "stdin".to_string(), stdin)?; + print!("{}", stdout); Ok(()) } diff --git a/src/format.rs b/src/format.rs index 0b725b9..3fe74d3 100644 --- a/src/format.rs +++ b/src/format.rs @@ -2,19 +2,33 @@ pub fn string( config: &crate::config::Config, path: String, string: String, -) -> String { +) -> std::io::Result { let tokens = rnix::tokenizer::Tokenizer::new(&string); let ast = rnix::parser::parse(tokens); - for error in ast.errors() { - eprintln!("Error: {}, at: {}", error, path); - return ast.node().to_string(); + let errors = ast.errors(); + if !errors.is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + errors[0].to_string(), + )); } let green_node = crate::builder::build(config, ast.node().into(), false, path).unwrap(); - green_node.to_string() + Ok(green_node.to_string()) +} + +pub fn string_or_passthrough( + config: &crate::config::Config, + path: String, + before: String, +) -> String { + match crate::format::string(&config, path, before.clone()) { + Ok(after) => after, + Err(_) => before, + } } pub fn file( @@ -27,7 +41,7 @@ pub fn file( let input_clone = input.clone(); let input_bytes = input_clone.as_bytes(); - let output = crate::format::string(config, path.clone(), input); + let output = crate::format::string(config, path.clone(), input)?; let output_bytes = output.as_bytes(); let changed = input_bytes != output_bytes; diff --git a/tests/fmt.rs b/tests/fmt.rs index b74ffb2..74f89a1 100644 --- a/tests/fmt.rs +++ b/tests/fmt.rs @@ -16,8 +16,11 @@ fn cases() { let path_in = format!("tests/cases/{}/in", case); let path_out = format!("tests/cases/{}/out", case); let content_in = std::fs::read_to_string(path_in.clone()).unwrap(); - let content_got = - alejandra::format::string(&config, path_in, content_in.clone()); + let content_got = alejandra::format::string_or_passthrough( + &config, + path_in, + content_in.clone(), + ); if should_update { std::fs::File::create(&path_out)