use std::sync::LazyLock;
use crate::{
Finding, Locator, RepoPath, Result, Spanned, Yaml,
check::{self, CheckOptions, CheckOutput, DocView, Host},
edit::{self, AnchorEdit},
grammar::Schema,
markdown::{self, Body, Dialect, Segments, split_frontmatter},
yaml,
};
#[derive(Debug, Clone, PartialEq)]
pub struct Document {
pub path: RepoPath,
pub text: String,
pub frontmatter: Option<Spanned>,
pub problem: Option<Finding>,
pub body: Body,
pub segments: Segments,
pub body_line: usize,
}
impl Document {
pub fn parse(path: RepoPath, text: &str, dialect: &Dialect) -> Self {
let mut text = text.replace("\r\n", "\n");
if text.contains('\r') {
text = text.replace('\r', "\n");
}
let split = split_frontmatter(&text);
let (frontmatter, problem) = match split.frontmatter {
None => (None, None),
Some((written, line)) => match yaml::parse(written, line) {
Ok(y) => (Some(y), None),
Err(e) => {
let criterion = if e.is_refused() { "TL_123" } else { "TL_53" };
(
None,
Some(Finding::error(
path.clone(),
Some(line - 1),
criterion,
format!("the frontmatter does not read: {e}"),
)),
)
}
},
};
let segments = markdown::segments(split.body, split.body_line, dialect);
let body = markdown::parse(split.body, split.body_line, &segments, dialect);
let body_line = split.body_line;
Document {
path,
text,
frontmatter,
problem,
body,
segments,
body_line,
}
}
pub fn check(&self, schema: &Schema, host: &dyn Host, locator: Locator) -> CheckOutput {
let states = schema.states(self.frontmatter.as_ref());
let mut out = check::check_against(
self.view(),
schema,
&states,
host,
CheckOptions::default(),
locator,
);
if let Some(problem) = &self.problem {
out.findings.insert(0, problem.clone());
}
out
}
pub fn repair(&self, out: &CheckOutput) -> Result<Option<String>> {
let anchors = AnchorEdit {
body: &self.body,
placements: &out.anchors,
text: &self.text,
renames: &[],
};
let edits = edit::line_edits(
&self.text,
&self.segments,
&out.repairs,
&out.label_repairs,
Some(&anchors),
);
if edits.is_empty() {
return Ok(None);
}
let repaired = edit::apply(&self.text, &edits)?;
Ok((repaired != self.text).then_some(repaired))
}
pub fn line_count(&self) -> usize {
self.text.lines().count()
}
pub fn view(&self) -> DocView<'_> {
static EMPTY: LazyLock<Spanned> = LazyLock::new(|| Spanned::new(Yaml::Map(vec![]), 1));
let frontmatter = match (&self.frontmatter, &self.problem) {
(_, Some(_)) => None,
(Some(f), None) if f.as_map().is_some() => Some(f),
_ => Some(&*EMPTY),
};
DocView {
path: &self.path,
frontmatter,
body: &self.body,
segments: &self.segments,
line_count: self.line_count(),
text: &self.text,
body_line: self.body_line,
}
}
}