#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterLevel {
None,
Minimal,
Aggressive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
Rust,
Python,
JavaScript,
TypeScript,
Go,
Shell,
Data,
Unknown,
}
impl Language {
pub fn from_extension(ext: &str) -> Self {
match ext.trim_start_matches('.').to_ascii_lowercase().as_str() {
"rs" => Self::Rust,
"py" | "pyi" => Self::Python,
"js" | "mjs" | "cjs" | "jsx" => Self::JavaScript,
"ts" | "tsx" => Self::TypeScript,
"go" => Self::Go,
"sh" | "bash" | "zsh" => Self::Shell,
"json" | "yaml" | "yml" | "toml" | "csv" => Self::Data,
_ => Self::Unknown,
}
}
pub fn comment_prefix(&self) -> Option<&'static str> {
match self {
Self::Rust | Self::JavaScript | Self::TypeScript | Self::Go => Some("//"),
Self::Python | Self::Shell => Some("#"),
Self::Data | Self::Unknown => None,
}
}
pub fn block_comment(&self) -> Option<(&'static str, &'static str)> {
match self {
Self::Rust | Self::JavaScript | Self::TypeScript | Self::Go => Some(("/*", "*/")),
Self::Python => Some(("\"\"\"", "\"\"\"")),
_ => None,
}
}
}
pub trait FilterStrategy: Send + Sync {
fn filter(&self, content: &str, lang: Language) -> String;
}
pub struct NoFilter;
impl FilterStrategy for NoFilter {
fn filter(&self, content: &str, _lang: Language) -> String {
content.to_string()
}
}
pub struct MinimalFilter;
impl FilterStrategy for MinimalFilter {
fn filter(&self, content: &str, _lang: Language) -> String {
content
.lines()
.map(|l| l.trim_end())
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
}
pub struct AggressiveFilter;
impl FilterStrategy for AggressiveFilter {
fn filter(&self, content: &str, lang: Language) -> String {
let prefix = lang.comment_prefix();
let mut out: Vec<&str> = Vec::new();
for line in content.lines() {
let trimmed = line.trim_end();
if trimmed.is_empty() {
continue;
}
if let Some(p) = prefix {
let leading = trimmed.trim_start();
if leading.starts_with(p) {
continue;
}
}
out.push(trimmed);
}
out.join("\n")
}
}
pub fn get_filter(level: FilterLevel) -> Box<dyn FilterStrategy> {
match level {
FilterLevel::None => Box::new(NoFilter),
FilterLevel::Minimal => Box::new(MinimalFilter),
FilterLevel::Aggressive => Box::new(AggressiveFilter),
}
}