Skip to content

Commit

Permalink
fix: strip bom (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret authored May 27, 2024
1 parent 3df017f commit 828434f
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/format_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,24 @@ use super::configuration::Configuration;
use super::generation::generate;

pub fn format_text(path: &Path, text: &str, config: &Configuration) -> Result<Option<String>> {
let parse_result = parse(text)?;
let is_jsonc = is_jsonc_file(path, config);
let result = dprint_core::formatting::format(
|| generate(parse_result, text, config, is_jsonc),
config_to_print_options(text, config),
);
let result = format_text_inner(path, text, config)?;
if result == text {
Ok(None)
} else {
Ok(Some(result))
}
}

fn format_text_inner(path: &Path, text: &str, config: &Configuration) -> Result<String> {
let text = strip_bom(text);
let parse_result = parse(text)?;
let is_jsonc = is_jsonc_file(path, config);
Ok(dprint_core::formatting::format(
|| generate(parse_result, text, config, is_jsonc),
config_to_print_options(text, config),
))
}

#[cfg(feature = "tracing")]
pub fn trace_file(text: &str, config: &Configuration) -> dprint_core::formatting::TracingResult {
let parse_result = parse(text).unwrap();
Expand All @@ -35,6 +40,10 @@ pub fn trace_file(text: &str, config: &Configuration) -> dprint_core::formatting
)
}

fn strip_bom(text: &str) -> &str {
text.strip_prefix("\u{FEFF}").unwrap_or(text)
}

fn parse(text: &str) -> Result<ParseResult<'_>> {
let parse_result = parse_to_ast(
text,
Expand Down Expand Up @@ -150,4 +159,14 @@ mod tests {
assert!(is_jsonc_file(&PathBuf::from("test\\.vscode\\settings.json"), &config));
}
}

#[test]
fn should_strip_bom() {
for input_text in ["\u{FEFF}{}", "\u{FEFF}{ }"] {
let global_config = GlobalConfiguration::default();
let config = resolve_config(ConfigKeyMap::new(), &global_config).config;
let output_text = format_text(Path::new("."), input_text, &config).unwrap().unwrap();
assert_eq!(output_text, "{}\n");
}
}
}

0 comments on commit 828434f

Please sign in to comment.