use crate::adr::format::{AdrFormat, detect_format, is_adr_document};
use comrak::nodes::{AstNode, NodeValue};
use mdbook_lint_core::Document;
use mdbook_lint_core::rule::{Rule, RuleCategory, RuleMetadata};
use mdbook_lint_core::violation::{Severity, Violation};
pub struct Adr004 {
format: AdrFormat,
}
impl Default for Adr004 {
fn default() -> Self {
Self {
format: AdrFormat::Auto,
}
}
}
impl Adr004 {
pub fn from_config(config: &toml::Value) -> Self {
let mut rule = Self::default();
if let Some(format) = config
.get("format")
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<AdrFormat>().ok())
{
rule.format = format;
}
rule
}
#[allow(dead_code)]
pub fn with_format(format: AdrFormat) -> Self {
Self { format }
}
fn effective_format(&self, content: &str) -> AdrFormat {
match self.format {
AdrFormat::Auto => detect_format(content),
other => other,
}
}
}
impl Rule for Adr004 {
fn id(&self) -> &'static str {
"ADR004"
}
fn name(&self) -> &'static str {
"adr-required-context"
}
fn description(&self) -> &'static str {
"ADR must have a context section"
}
fn metadata(&self) -> RuleMetadata {
RuleMetadata::stable(RuleCategory::Structure).introduced_in("mdbook-lint v0.14.0")
}
fn check_with_ast<'a>(
&self,
document: &Document,
_ast: Option<&'a AstNode<'a>>,
) -> mdbook_lint_core::error::Result<Vec<Violation>> {
if !is_adr_document(&document.content, Some(&document.path)) {
return Ok(Vec::new());
}
let mut violations = Vec::new();
let format = self.effective_format(&document.content);
let arena = comrak::Arena::new();
let ast_node = document.parse_ast(&arena);
let mut found_context = false;
for node in ast_node.descendants() {
if let NodeValue::Heading(heading) = &node.data.borrow().value
&& heading.level == 2
{
let mut heading_text = String::new();
for child in node.children() {
if let NodeValue::Text(text) = &child.data.borrow().value {
heading_text.push_str(text);
}
}
let heading_lower = heading_text.trim().to_lowercase();
match format {
AdrFormat::Nygard | AdrFormat::Auto => {
if heading_lower == "context" {
found_context = true;
break;
}
}
AdrFormat::Madr4 => {
if heading_lower == "context and problem statement" {
found_context = true;
break;
}
}
}
}
}
if !found_context {
let expected = match format {
AdrFormat::Madr4 => "## Context and Problem Statement",
_ => "## Context",
};
violations.push(self.create_violation(
format!("ADR is missing '{}' section", expected),
1,
1,
Severity::Error,
));
}
Ok(violations)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn create_test_document(content: &str) -> Document {
Document::new(content.to_string(), PathBuf::from("adr/0001-test-adr.md")).unwrap()
}
#[test]
fn test_ng_nygard_not_flagged_as_madr() {
let content = r#"---
status: accepted
date: 2024-01-15
---
# 1. Use PostgreSQL
## Context
We need a database.
## Decision
Use PostgreSQL.
## Consequences
It works.
"#;
let doc = create_test_document(content);
let violations = Adr004::default().check(&doc).unwrap();
assert!(
violations.is_empty(),
"ADR004 should not apply to a ng+Nygard document, got: {violations:?}"
);
}
#[test]
fn test_valid_nygard_context() {
let content = r#"# 1. Use Rust for implementation
Date: 2024-01-15
## Status
Accepted
## Context
We need to choose a programming language.
## Decision
We will use Rust.
## Consequences
Team needs Rust training.
"#;
let doc = create_test_document(content);
let rule = Adr004::default();
let violations = rule.check(&doc).unwrap();
assert!(
violations.is_empty(),
"Expected no violations for valid Nygard context"
);
}
#[test]
fn test_missing_nygard_context() {
let content = r#"# 1. Use Rust for implementation
Date: 2024-01-15
## Status
Accepted
## Decision
We will use Rust.
## Consequences
Team needs Rust training.
"#;
let doc = create_test_document(content);
let rule = Adr004::default();
let violations = rule.check(&doc).unwrap();
assert_eq!(violations.len(), 1);
assert!(violations[0].message.contains("## Context"));
}
#[test]
fn test_valid_madr_context() {
let content = r#"---
status: accepted
date: 2024-01-15
---
# Use PostgreSQL for persistence
## Context and Problem Statement
We need to select a database.
## Decision Outcome
Chosen option: PostgreSQL.
"#;
let doc = create_test_document(content);
let rule = Adr004::default();
let violations = rule.check(&doc).unwrap();
assert!(
violations.is_empty(),
"Expected no violations for valid MADR context"
);
}
#[test]
fn test_missing_madr_context() {
let content = r#"---
status: accepted
date: 2024-01-15
---
# Use PostgreSQL for persistence
## Decision Outcome
Chosen option: PostgreSQL.
"#;
let doc = create_test_document(content);
let rule = Adr004::default();
let violations = rule.check(&doc).unwrap();
assert_eq!(violations.len(), 1);
assert!(
violations[0]
.message
.contains("Context and Problem Statement")
);
}
#[test]
fn test_context_case_insensitive() {
let content = r#"# 1. Use Rust
Date: 2024-01-15
## Status
Accepted
## CONTEXT
We need a language.
"#;
let doc = create_test_document(content);
let rule = Adr004::default();
let violations = rule.check(&doc).unwrap();
assert!(
violations.is_empty(),
"Context section should be case-insensitive"
);
}
}