Skip to content

Commit

Permalink
extract function to detect syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
g-plane committed May 11, 2024
1 parent e1260c7 commit a0a7c39
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
18 changes: 6 additions & 12 deletions dprint_plugin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use dprint_core::{
configuration::{ConfigKeyMap, GlobalConfiguration, ResolveConfigurationResult},
plugins::{FileMatchingInfo, PluginInfo, SyncPluginHandler, SyncPluginInfo},
};
use malva::{config::FormatOptions, format_text, Syntax};
use malva::{config::FormatOptions, detect_syntax, format_text};
use std::path::Path;

mod config;
Expand Down Expand Up @@ -57,17 +57,11 @@ impl SyncPluginHandler<FormatOptions> for MalvaPluginHandler {
config: &FormatOptions,
_: impl FnMut(&Path, Vec<u8>, &ConfigKeyMap) -> Result<Option<Vec<u8>>>,
) -> Result<Option<Vec<u8>>> {
let syntax = match file_path.extension().and_then(|s| s.to_str()) {
Some(ext) if ext.eq_ignore_ascii_case("css") => Syntax::Css,
Some(ext) if ext.eq_ignore_ascii_case("scss") => Syntax::Scss,
Some(ext) if ext.eq_ignore_ascii_case("sass") => Syntax::Sass,
Some(ext) if ext.eq_ignore_ascii_case("less") => Syntax::Less,
_ => {
return Err(anyhow::anyhow!(
"unknown file extension of file: {}",
file_path.display()
));
}
let Some(syntax) = detect_syntax(file_path) else {
return Err(anyhow::anyhow!(
"unknown file extension of file: {}",
file_path.display()
));
};
format_text(std::str::from_utf8(&file_text)?, syntax, config)
.map(|s| Some(s.into_bytes()))
Expand Down
12 changes: 12 additions & 0 deletions malva/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{config::FormatOptions, ctx::Ctx, doc_gen::DocGen};
pub use crate::{error::Error, line_bounds::LineBounds};
pub use raffia::Syntax;
use raffia::{ast::Stylesheet, token::Comment, ParserBuilder, ParserOptions};
use std::path::Path;

/// Format the given source code.
pub fn format_text(input: &str, syntax: Syntax, options: &FormatOptions) -> Result<String, Error> {
Expand Down Expand Up @@ -73,3 +74,14 @@ pub fn print_stylesheet<'a, 's>(
},
)
}

/// Detect syntax from file extension.
pub fn detect_syntax(path: impl AsRef<Path>) -> Option<Syntax> {
match path.as_ref().extension().and_then(std::ffi::OsStr::to_str) {
Some(ext) if ext.eq_ignore_ascii_case("css") => Some(Syntax::Css),
Some(ext) if ext.eq_ignore_ascii_case("scss") => Some(Syntax::Scss),
Some(ext) if ext.eq_ignore_ascii_case("sass") => Some(Syntax::Sass),
Some(ext) if ext.eq_ignore_ascii_case("less") => Some(Syntax::Less),
_ => None,
}
}

0 comments on commit a0a7c39

Please sign in to comment.