use crate::diagnostics::{
RenderedBlockMatcher, RenderedContentMatcher, RenderedDiagnostic, RenderedListAddress,
RenderedMatcher, RenderedReference, RenderedSchemaNode, RenderedTarget, ValidationResult,
};
use super::{escape_human, escape_human_quoted};
pub(super) fn render_human(results: &[ValidationResult], use_color: bool) -> String {
let diagnostic_count = results
.iter()
.map(|result| result.diagnostics.len())
.sum::<usize>();
if diagnostic_count == 0 {
return String::new();
}
let mut output = String::new();
for (index, diagnostic) in results
.iter()
.flat_map(|result| &result.diagnostics)
.enumerate()
{
if index != 0 {
output.push('\n');
}
let id = if use_color {
format!("\u{1b}[31m[{}]\u{1b}[0m", escape_human(&diagnostic.id))
} else {
format!("[{}]", escape_human(&diagnostic.id))
};
output.push_str(&format!(
"{}:{}:{} {} {}",
escape_human(&diagnostic.source_path),
diagnostic.line,
diagnostic.column,
id,
human_headline(diagnostic)
));
output.push('\n');
append_human_details(&mut output, diagnostic);
}
let files = results
.iter()
.filter(|result| !result.diagnostics.is_empty())
.count();
output.push('\n');
output.push_str(&format!(
"{} {} in {} {}\n",
diagnostic_count,
plural(diagnostic_count, "diagnostic", "diagnostics"),
files,
plural(files, "file", "files")
));
output
}
fn human_headline(diagnostic: &RenderedDiagnostic) -> String {
let headline = match diagnostic.id.as_str() {
"ordered" if !diagnostic.references.is_empty() => "sections are not in the required order",
"one_of" => "exactly one referenced condition must be satisfied",
"any_of" => "at least one referenced condition must be satisfied",
"at_most_one" => "at most one referenced condition may be satisfied",
"all_or_none" => "all referenced conditions or none of them must be satisfied",
"requires" => "a required consequence is missing",
"conflicts" => "conflicting conditions are satisfied",
_ => diagnostic.message.as_str(),
};
escape_human(headline)
}
fn append_human_details(output: &mut String, diagnostic: &RenderedDiagnostic) {
if let Some(target) = &diagnostic.target {
match target {
RenderedTarget::Header { path } if diagnostic.id == "ordered" => {
append_human_header_detail(output, "within", path);
}
RenderedTarget::Header { path } => {
append_human_header_detail(output, "section", path);
}
RenderedTarget::MissingHeader { parent, matcher } => {
append_human_quoted_detail(output, "expected", matcher);
if !parent.is_empty() {
append_human_header_detail(output, "within", parent);
}
}
RenderedTarget::Document => {}
RenderedTarget::Frontmatter {
line_range,
pointer,
} => {
if let Some(range) = line_range {
output.push_str(&format!(
" frontmatter: lines {}-{}\n",
range.start_line, range.end_line
));
}
if let Some(pointer) = pointer {
if pointer.is_empty() {
output.push_str(" value: <frontmatter root>\n");
} else {
append_human_quoted_detail(output, "value", pointer);
}
}
}
RenderedTarget::Block {
parent,
block,
index,
} => {
append_human_owner_detail(output, "preamble", parent);
output.push_str(&format!(
" block: {} occurrence {index}\n",
escape_human(block)
));
}
RenderedTarget::MissingBlock { parent, matcher } => {
append_human_owner_detail(output, "expected within", parent);
output.push_str(&format!(
" expected block: {}\n",
human_content_matcher(matcher)
));
}
RenderedTarget::Item { list, index } => {
append_human_list_detail(output, list);
output.push_str(&format!(" item: {index}\n"));
}
RenderedTarget::MissingItem { list, matcher } => {
append_human_list_detail(output, list);
append_human_quoted_detail(output, "expected item", matcher);
}
}
}
append_human_declaration_detail(output, diagnostic);
match diagnostic.id.as_str() {
"ordered" => append_human_ordering_evidence(output, diagnostic),
"order-violation" => append_human_violating_pair(output, diagnostic),
_ => append_human_constraint_evidence(output, diagnostic),
}
if let Some(location) = &diagnostic.schema_location {
let duplicates_primary = location.path == diagnostic.source_path
&& location.line == diagnostic.line
&& location.column == diagnostic.column;
if !duplicates_primary {
let label = match diagnostic.schema_node.as_ref() {
Some(RenderedSchemaNode::Constraint { .. }) => "constraint",
Some(RenderedSchemaNode::ContentRule { .. }) => "content rule",
Some(RenderedSchemaNode::ItemRule { .. }) => "item rule",
Some(RenderedSchemaNode::Rule { .. }) => "rule",
Some(RenderedSchemaNode::Guard { .. }) => "guard",
Some(RenderedSchemaNode::Capture { .. })
| Some(RenderedSchemaNode::FrontmatterCapture { .. })
| Some(RenderedSchemaNode::OrderEntry { .. }) => "declared",
_ => "schema",
};
output.push_str(&format!(
" {label}: {}:{}:{}\n",
escape_human(&location.path),
location.line,
location.column
));
}
}
}
fn append_human_declaration_detail(output: &mut String, diagnostic: &RenderedDiagnostic) {
match diagnostic.schema_node.as_ref() {
Some(RenderedSchemaNode::Capture { name, .. }) => {
append_human_quoted_detail(output, "capture", name);
}
Some(RenderedSchemaNode::FrontmatterCapture { name }) => {
append_human_quoted_detail(output, "capture", &format!("fm.{name}"));
}
Some(RenderedSchemaNode::OrderEntry { order_index, .. }) => {
output.push_str(&format!(" order entry: {order_index}\n"));
}
Some(RenderedSchemaNode::Guard { index, .. }) => {
output.push_str(&format!(" guard: {index}\n"));
}
_ => {}
}
}
fn append_human_quoted_detail(output: &mut String, label: &str, value: &str) {
output.push_str(&format!(" {label}: \"{}\"\n", escape_human_quoted(value)));
}
fn append_human_header_detail(output: &mut String, label: &str, path: &[String]) {
output.push_str(&format!(" {label}: \"{}\"\n", human_header_path(path)));
}
fn append_human_owner_detail(output: &mut String, label: &str, path: &[String]) {
if path.is_empty() {
output.push_str(&format!(" {label}: <document root>\n"));
} else {
append_human_header_detail(output, label, path);
}
}
fn append_human_list_detail(output: &mut String, list: &RenderedListAddress) {
append_human_owner_detail(output, "list within", &list.parent);
output.push_str(&format!(" list: {}\n", list.index));
}
fn human_content_matcher(matcher: &RenderedContentMatcher) -> String {
match matcher {
RenderedContentMatcher::Block(matcher) => human_block_matcher(matcher),
RenderedContentMatcher::OneOf(alternatives) => alternatives
.iter()
.map(human_block_matcher)
.collect::<Vec<_>>()
.join(" or "),
}
}
fn human_block_matcher(matcher: &RenderedBlockMatcher) -> String {
match matcher.list_kind.as_deref() {
Some(list_kind) => format!(
"{} ({})",
escape_human(&matcher.block),
escape_human(list_kind)
),
None => escape_human(&matcher.block),
}
}
fn append_human_ordering_evidence(output: &mut String, diagnostic: &RenderedDiagnostic) {
if !diagnostic.references.is_empty() {
output.push_str(" expected order (among sections that are present):\n");
for (index, reference) in diagnostic.references.iter().enumerate() {
output.push_str(&format!(
" {}. {}\n",
index + 1,
human_reference(reference)
));
}
}
if !diagnostic.involved_headers.is_empty() {
output.push_str(" observed order:\n");
for header in &diagnostic.involved_headers {
output.push_str(&format!(
" {}:{}:{} \"{}\"\n",
escape_human(&diagnostic.source_path),
header.line,
header.column,
human_header_path(&header.header_path)
));
}
}
}
fn append_human_violating_pair(output: &mut String, diagnostic: &RenderedDiagnostic) {
if diagnostic.involved_headers.is_empty() {
return;
}
output.push_str(" out-of-order pair:\n");
for (position, header) in diagnostic.involved_headers.iter().enumerate() {
output.push_str(&format!(
" {}. {}:{}:{} \"{}\"\n",
position + 1,
escape_human(&diagnostic.source_path),
header.line,
header.column,
human_header_path(&header.header_path)
));
}
}
fn append_human_constraint_evidence(output: &mut String, diagnostic: &RenderedDiagnostic) {
if !diagnostic.references.is_empty() {
output.push_str(" references:\n");
for reference in &diagnostic.references {
output.push_str(" - ");
output.push_str(&human_reference(reference));
output.push('\n');
}
}
if !diagnostic.involved_headers.is_empty() {
output.push_str(" involved sections:\n");
for header in &diagnostic.involved_headers {
output.push_str(&format!(
" {}:{}:{} \"{}\"\n",
escape_human(&diagnostic.source_path),
header.line,
header.column,
human_header_path(&header.header_path)
));
}
}
}
fn human_matcher(matcher: &RenderedMatcher) -> String {
match matcher {
RenderedMatcher::Exact(value) => format!("exact \"{}\"", escape_human_quoted(value)),
RenderedMatcher::Glob(value) => format!("glob \"{}\"", escape_human_quoted(value)),
RenderedMatcher::Regex(value) => format!("regex \"{}\"", escape_human_quoted(value)),
RenderedMatcher::Any => "any heading".to_owned(),
RenderedMatcher::Unknown => "unknown matcher".to_owned(),
}
}
fn human_header_path(path: &[String]) -> String {
path.iter()
.map(|part| escape_human_quoted(part))
.collect::<Vec<_>>()
.join(" > ")
}
fn human_reference(reference: &RenderedReference) -> String {
match reference {
RenderedReference::Rule {
locator, matcher, ..
} => {
format!("{} ({})", escape_human(locator), human_matcher(matcher))
}
RenderedReference::FrontmatterQuery { locator, .. } => escape_human(locator),
RenderedReference::FrontmatterCapture {
locator,
value_type,
..
} => format!("{} ({})", escape_human(locator), escape_human(value_type)),
}
}
fn plural<'a>(count: usize, singular: &'a str, plural: &'a str) -> &'a str {
if count == 1 {
singular
} else {
plural
}
}
#[cfg(test)]
mod tests {
use super::{escape_human, escape_human_quoted};
#[test]
fn human_escaping_neutralizes_terminal_controls_and_bidi_formatting() {
assert_eq!(
escape_human("\"title\" C:\\ \u{1b}\n\u{85}\u{2028}\u{202e}\u{2066}"),
"\"title\" C:\\ \\x1b\\n\\u{85}\\u{2028}\\u{202e}\\u{2066}"
);
assert_eq!(
escape_human_quoted("say \"hi\" \\ now\t"),
"say \\\"hi\\\" \\\\ now\\t"
);
}
}