use std::sync::LazyLock;
use regex::Regex;
use super::decode::Decoder;
use super::yaml;
const WS: &str = r"[\t\n\f\r ]";
static COMMENT: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r"^{WS}*#{WS}*")).expect("static regex"));
static YAML_MAP: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r"^({WS}*)(#{WS}*)([^:]+:.*)$")).expect("static regex"));
static SCHEMA: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r"^{WS}*#{WS}@schema{WS}*")).expect("static regex"));
fn valid(text: &str) -> bool {
let Ok(doc) = yaml::parse(text) else {
return false;
};
let mut decoder = Decoder::new(&doc);
let decoded = doc
.root
.and_then(|r| doc.nodes[r].content.first().copied())
.map(|id| decoder.any(id));
decoded.is_none_or(|r| r.is_ok()) && decoder.errors.is_empty()
}
pub(super) fn remove_comments(text: &str) -> String {
let mut result = String::new();
let mut buff = String::new();
let mut in_code = false;
let mut in_schema = false;
let mut lines: Vec<&str> = text.split('\n').collect();
if lines.last() == Some(&"") {
lines.pop();
}
for line in lines.into_iter().map(|l| l.strip_suffix('\r').unwrap_or(l)) {
if line.is_empty() && in_code {
result.push_str(&buff);
result.push('\n');
result.push('\n');
buff.clear();
in_code = false;
continue;
}
if SCHEMA.is_match(line) {
in_schema = !in_schema;
result.push_str(line);
result.push('\n');
continue;
}
if in_schema {
result.push_str(line);
result.push('\n');
continue;
}
let mut indentation = String::new();
let mut marker_len = 0;
if !in_code && let Some(m) = YAML_MAP.captures(line) {
indentation = m[1].to_owned();
marker_len = m[2].len();
in_code = true;
}
if in_code {
if COMMENT.is_match(line) {
let stripped = format!("{indentation}{}", &line[indentation.len() + marker_len..]);
let before = buff.len();
buff.push_str(&stripped);
buff.push('\n');
if !valid(&buff) {
buff.truncate(before);
buff.push_str(line);
buff.push('\n');
}
continue;
}
result.push_str(&buff);
result.push('\n');
buff.clear();
in_code = false;
buff.push_str(line);
buff.push('\n');
continue;
}
if !buff.is_empty() {
result.push_str(&buff);
buff.clear();
}
result.push_str(line);
result.push('\n');
}
if !buff.is_empty() {
result.push_str(&buff);
result.push('\n');
}
result
}
#[cfg(test)]
mod tests;