Skip to content

Commit

Permalink
fix: strip bom (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret authored May 27, 2024
1 parent 292af9d commit 67886e7
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/format_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,24 @@ use crate::configuration::Configuration;
use crate::generation::generate;

pub fn format_text(_file_path: &Path, text: &str, config: &Configuration) -> Result<Option<String>> {
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 {
Ok(Some(result))
}
}

fn format_inner(text: &str, config: &Configuration) -> Result<String> {
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();
Expand All @@ -29,6 +37,10 @@ fn parse_node(text: &str) -> Result<Dockerfile> {
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,
Expand All @@ -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");
}
}
}

0 comments on commit 67886e7

Please sign in to comment.