use std::io::{self, Write};
use sokf_core::{BlockGuide, DocumentGuide, GuideLabel, GuideReport};
pub fn text<W: Write>(w: &mut W, report: &GuideReport) -> io::Result<()> {
let mut parts: Vec<Vec<String>> = Vec::new();
for doc in &report.documents {
parts.extend(document(doc));
}
let chunks: Vec<String> = parts.iter().map(|lines| lines.join("\n")).collect();
if !chunks.is_empty() {
writeln!(w, "{}", chunks.join("\n\n"))?;
}
Ok(())
}
fn document(doc: &DocumentGuide) -> Vec<Vec<String>> {
let mut named = vec![doc.type_name.clone()];
named.extend(
doc.states
.iter()
.map(|(k, v)| format!("{k}={}", v.as_str().unwrap_or_default())),
);
let mut parts = vec![vec![format!("{} ({})", doc.path, named.join(", "))]];
if !doc.labels.is_empty() {
let mut lines = vec!["Labels:".to_string()];
lines.extend(doc.labels.iter().map(|l| match &l.meaning {
Some(m) => format!(" [{}]: {m}", l.words),
None => format!(" [{}]", l.words),
}));
parts.push(lines);
}
if let Some(t) = &doc.text {
parts.push(vec![t.clone()]);
}
let body_text = doc.body_text.as_str();
let held_key = |e: &&str| holds_as_written(&doc.frontmatter_text, e);
let held = |e: &&str| holds(body_text, e);
let mut front: Vec<String> = Vec::new();
for k in &doc.frontmatter {
let example = k.example.as_deref().filter(|e| !held_key(e));
if k.text.is_none() && example.is_none() {
continue;
}
let name = format!("{}{}", k.key, if k.optional { " (optional)" } else { "" });
front.push(match &k.text {
Some(text) => format!(" {name}: {text}"),
None => format!(" {name}:"),
});
front.extend(example_lines(example, 2));
}
for l in &doc.links {
let optional = if l.optional { ", optional" } else { "" };
let name = format!("links ({}{optional})", l.rel);
front.push(match &l.text {
Some(text) => format!(" {name}: {text}"),
None => format!(" {name}:"),
});
front.extend(example_lines(Some(&l.example), 2));
}
if !front.is_empty() {
front.insert(0, "Frontmatter:".to_string());
parts.push(front);
}
if let Some(p) = &doc.preamble {
let mut lines = vec!["Preamble:".to_string()];
lines.extend(p.text.iter().map(|t| format!(" {t}")));
let example = p.example.as_deref().filter(|e| !held(e));
lines.extend(example_lines(example, 1));
blocks(body_text, &p.blocks, 1, example.is_some(), &mut lines);
if lines.len() > 1 {
parts.push(lines);
}
}
let mut covering: Vec<&str> = Vec::new();
for s in &doc.sections {
let absent_parent = s.parent.as_ref().and_then(|p| {
doc.sections
.iter()
.find(|o| o.rule_id.as_ref() == Some(p) && !o.held)
});
let mark = match (s.held, s.optional, absent_parent) {
(true, _, _) => String::new(),
(false, true, _) => " (absent, optional)".to_string(),
(false, false, Some(p)) => format!(" (absent, required under {})", p.heading),
(false, false, None) => " (absent, required)".to_string(),
};
let mut lines = vec![format!(
"{} {}{mark}",
"#".repeat(usize::from(s.level)),
s.heading
)];
lines.extend(s.text.iter().map(|t| format!(" {t}")));
let covered = s.parent.as_deref().is_some_and(|p| covering.contains(&p));
let example = s
.example
.as_deref()
.filter(|e| !covered && !heading_alone(e, s.level))
.filter(|_| s.repeat || !s.held);
if (covered || example.is_some())
&& let Some(id) = &s.rule_id
{
covering.push(id);
}
lines.extend(example_lines(example, 1));
blocks(
body_text,
&s.blocks,
1,
covered || example.is_some(),
&mut lines,
);
parts.push(lines);
}
parts
}
fn blocks(body: &str, list: &[BlockGuide], depth: usize, covered: bool, out: &mut Vec<String>) {
let indent = " ".repeat(depth);
for b in list {
let example = b.example.as_deref().filter(|e| !covered && !holds(body, e));
let mut inner = Vec::new();
blocks(
body,
&b.blocks,
depth + 1,
covered || example.is_some(),
&mut inner,
);
let mark = marks(b);
match &b.text {
Some(t) => out.push(format!("{indent}{}{mark}: {t}", b.kind)),
None if !inner.is_empty() || !mark.is_empty() || example.is_some() => {
out.push(format!("{indent}{}{mark}", b.kind));
}
None => {}
}
out.extend(example_lines(example, depth + 1));
out.extend(inner);
}
}
fn heading_alone(example: &str, level: u8) -> bool {
let mut lines = example.lines().filter(|l| !l.trim().is_empty());
let marks = "#".repeat(usize::from(level)) + " ";
lines.next().is_some_and(|l| l.starts_with(&marks)) && lines.next().is_none()
}
fn example_lines(example: Option<&str>, depth: usize) -> Vec<String> {
let Some(example) = example else {
return Vec::new();
};
let indent = " ".repeat(depth);
let mut lines = vec![format!("{indent}Example:")];
lines.extend(example.lines().map(|l| {
if l.is_empty() {
String::new()
} else {
format!("{indent} {l}")
}
}));
lines
}
fn holds_as_written(text: &str, example: &str) -> bool {
let want: Vec<&str> = example.lines().collect();
let have: Vec<&str> = text.lines().collect();
!want.is_empty() && have.windows(want.len()).any(|w| w == want.as_slice())
}
fn holds(document: &str, text: &str) -> bool {
let want: Vec<&str> = text.lines().map(str::trim_start).collect();
let have: Vec<&str> = document.lines().map(str::trim_start).collect();
!want.is_empty() && have.windows(want.len()).any(|w| w == want.as_slice())
}
fn marks(b: &BlockGuide) -> String {
let labels: Vec<String> = b
.labels
.iter()
.enumerate()
.map(|(i, l)| {
let kind = match l.label {
GuideLabel::Required => "required",
GuideLabel::Optional => "optional",
};
let rule = match (l.rule, &l.rule_id) {
(None, _) => String::new(),
(Some(_), Some(id)) => format!(" for `{id}`"),
(Some(_), None) => format!(" for the rule at line {}", l.line),
};
let lead = if i == 0 { "label " } else { "" };
format!("{lead}{kind}{rule}")
})
.collect();
let mut parts = Vec::new();
if b.optional {
parts.push("optional".to_string());
}
if !labels.is_empty() {
parts.push(labels.join("; "));
}
if parts.is_empty() {
String::new()
} else {
format!(" ({})", parts.join("; "))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_example_is_held_by_its_own_part_of_the_document() {
let front = "type: Note\nreviewer:\n owner: ada";
assert!(holds_as_written(front, "type: Note"));
assert!(!holds_as_written(front, "owner: ada"));
assert!(holds("- a\n - b\n", "- b"));
assert!(heading_alone("## XYZ", 2) && heading_alone("## Step 1\n", 2));
assert!(!heading_alone("## Notes\n\nThe kettle is full.", 2));
assert!(!heading_alone("### Notes", 2));
}
}