Skip to content

Commit 1a88fe7

Browse files
committed
fix: strip utf-8 bom
1 parent 6501441 commit 1a88fe7

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/format_text.rs

+26-3
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,35 @@ use std::path::Path;
1010
use taplo::syntax::SyntaxNode;
1111

1212
pub fn format_text(file_path: &Path, text: &str, config: &Configuration) -> Result<Option<String>> {
13-
let node = parse_and_process_node(file_path, text, config)?;
14-
15-
let result = dprint_core::formatting::format(|| generate(node, text, config), config_to_print_options(text, config));
13+
let result = format_text_inner(file_path, text, config)?;
1614
if result == text {
1715
Ok(None)
1816
} else {
1917
Ok(Some(result))
2018
}
2119
}
2220

21+
fn format_text_inner(file_path: &Path, text: &str, config: &Configuration) -> Result<String> {
22+
let text = strip_bom(text);
23+
let node = parse_and_process_node(file_path, text, config)?;
24+
25+
Ok(dprint_core::formatting::format(
26+
|| generate(node, text, config),
27+
config_to_print_options(text, config),
28+
))
29+
}
30+
2331
#[cfg(feature = "tracing")]
2432
pub fn trace_file(file_path: &Path, text: &str, config: &Configuration) -> dprint_core::formatting::TracingResult {
2533
let node = parse_and_process_node(file_path, text, config).unwrap();
2634

2735
dprint_core::formatting::trace_printing(|| generate(node, text, config), config_to_print_options(text, config))
2836
}
2937

38+
fn strip_bom(text: &str) -> &str {
39+
text.strip_prefix("\u{FEFF}").unwrap_or(text)
40+
}
41+
3042
fn parse_and_process_node(file_path: &Path, text: &str, config: &Configuration) -> Result<SyntaxNode> {
3143
let node = parse_taplo(text)?;
3244

@@ -58,3 +70,14 @@ fn config_to_print_options(text: &str, config: &Configuration) -> PrintOptions {
5870
new_line_text: resolve_new_line_kind(text, config.new_line_kind),
5971
}
6072
}
73+
74+
#[cfg(test)]
75+
mod test {
76+
#[test]
77+
fn strips_bom() {
78+
let config = crate::configuration::ConfigurationBuilder::new().build();
79+
let file_text = crate::format_text::format_text(&std::path::PathBuf::from("file.toml"), "\u{FEFF}# 1\n# 2\n", &config).unwrap();
80+
81+
assert_eq!(file_text.unwrap(), "# 1\n# 2\n");
82+
}
83+
}

0 commit comments

Comments
 (0)