From 67886e7b44be956837a45a3fb85d57ce5c1b005f Mon Sep 17 00:00:00 2001 From: David Sherret Date: Sun, 26 May 2024 23:11:20 -0400 Subject: [PATCH] fix: strip bom (#14) --- src/format_text.rs | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/format_text.rs b/src/format_text.rs index bdb1387..c4e7c77 100644 --- a/src/format_text.rs +++ b/src/format_text.rs @@ -8,9 +8,7 @@ use crate::configuration::Configuration; use crate::generation::generate; pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Result> { - let node = parse_node(text)?; - - let result = dprint_core::formatting::format(|| generate(&node, text, config), config_to_print_options(text, config)); + let result = format_inner(text, config)?; if result == text { Ok(None) } else { @@ -18,6 +16,16 @@ pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Res } } +fn format_inner(text: &str, config: &Configuration) -> Result { + let text = strip_bom(text); + let node = parse_node(text)?; + + Ok(dprint_core::formatting::format( + || generate(&node, text, config), + config_to_print_options(text, config), + )) +} + #[cfg(feature = "tracing")] pub fn trace_file(_file_path: &Path, text: &str, config: &Configuration) -> dprint_core::formatting::TracingResult { let node = parse_node(text).unwrap(); @@ -29,6 +37,10 @@ fn parse_node(text: &str) -> Result { Ok(Dockerfile::parse(text)?) } +fn strip_bom(text: &str) -> &str { + text.strip_prefix("\u{FEFF}").unwrap_or(text) +} + fn config_to_print_options(text: &str, config: &Configuration) -> PrintOptions { PrintOptions { indent_width: 1, @@ -37,3 +49,22 @@ fn config_to_print_options(text: &str, config: &Configuration) -> PrintOptions { new_line_text: resolve_new_line_kind(text, config.new_line_kind), } } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn strips_bom() { + for input_text in ["\u{FEFF}FROM example:12.16.1\n", "\u{FEFF}FROM example:12.16.1\n"] { + let text = format_text( + &std::path::PathBuf::from("test.dockerfile"), + input_text, + &crate::configuration::ConfigurationBuilder::new().build(), + ) + .unwrap() + .unwrap(); + assert_eq!(text, "FROM example:12.16.1\n"); + } + } +}