Skip to content

Commit 92a430a

Browse files
authored
fix: strip bom (#107)
1 parent 2fdf12f commit 92a430a

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

src/format_text.rs

+36-7
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,27 @@ pub fn format_text(
1818
config: &Configuration,
1919
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>>,
2020
) -> Result<Option<String>> {
21+
let result = format_text_inner(file_text, config, format_code_block_text)?;
22+
23+
match result {
24+
Some(result) if result == file_text => Ok(None),
25+
Some(result) => Ok(Some(result)),
26+
None => Ok(None),
27+
}
28+
}
29+
30+
fn format_text_inner(
31+
file_text: &str,
32+
config: &Configuration,
33+
format_code_block_text: impl for<'a> FnMut(&str, &'a str, u32) -> Result<Option<String>>,
34+
) -> Result<Option<String>> {
35+
let file_text = strip_bom(file_text);
2136
let (source_file, markdown_text) = match parse_source_file(file_text, config)? {
2237
ParseFileResult::IgnoreFile => return Ok(None),
2338
ParseFileResult::SourceFile(file) => file,
2439
};
2540

26-
let result = dprint_core::formatting::format(
41+
Ok(Some(dprint_core::formatting::format(
2742
|| {
2843
let mut context = Context::new(markdown_text, config, format_code_block_text);
2944
#[allow(clippy::let_and_return)]
@@ -32,12 +47,7 @@ pub fn format_text(
3247
print_items
3348
},
3449
config_to_print_options(file_text, config),
35-
);
36-
if result == file_text {
37-
Ok(None)
38-
} else {
39-
Ok(Some(result))
40-
}
50+
)))
4151
}
4252

4353
#[cfg(feature = "tracing")]
@@ -61,6 +71,10 @@ pub fn trace_file(
6171
)
6272
}
6373

74+
fn strip_bom(text: &str) -> &str {
75+
text.strip_prefix("\u{FEFF}").unwrap_or(text)
76+
}
77+
6478
enum ParseFileResult<'a> {
6579
IgnoreFile,
6680
SourceFile((crate::generation::common::SourceFile, &'a str)),
@@ -103,3 +117,18 @@ fn config_to_print_options(file_text: &str, config: &Configuration) -> PrintOpti
103117
new_line_text: resolve_new_line_kind(file_text, config.new_line_kind),
104118
}
105119
}
120+
121+
#[cfg(test)]
122+
mod test {
123+
use super::*;
124+
use crate::configuration::ConfigurationBuilder;
125+
126+
#[test]
127+
fn strips_bom() {
128+
for input_text in ["\u{FEFF}# Title", "\u{FEFF}# Title\n"] {
129+
let config = ConfigurationBuilder::new().build();
130+
let result = format_text(input_text, &config, |_, _, _| Ok(None)).unwrap();
131+
assert_eq!(result, Some("# Title\n".to_string()));
132+
}
133+
}
134+
}

0 commit comments

Comments
 (0)