use std::path::{Path, PathBuf};
use alint_core::{
Context, Error, Level, PathsSpec, PerFileRule, Result, Rule, RuleSpec, Scope, Violation,
};
use regex::Regex;
use serde::Deserialize;
use serde_json::Value;
use serde_json_path::JsonPath;
fn is_literal_path(pattern: &str) -> bool {
!pattern.starts_with('!')
&& !pattern
.chars()
.any(|c| matches!(c, '*' | '?' | '[' | ']' | '{' | '}'))
}
fn extract_literal_paths(spec: &PathsSpec) -> Option<Vec<PathBuf>> {
let patterns: Vec<&str> = match spec {
PathsSpec::Single(s) => vec![s.as_str()],
PathsSpec::Many(v) => v.iter().map(String::as_str).collect(),
PathsSpec::IncludeExclude { include, exclude } if exclude.is_empty() => {
include.iter().map(String::as_str).collect()
}
PathsSpec::IncludeExclude { .. } => return None,
};
if patterns.iter().all(|p| is_literal_path(p)) {
Some(patterns.iter().map(PathBuf::from).collect())
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Json,
Yaml,
Toml,
Xml,
}
impl Format {
pub(crate) fn parse(self, text: &str) -> std::result::Result<Value, String> {
match self {
Self::Json => serde_json::from_str(text).map_err(|e| e.to_string()),
Self::Yaml => serde_yaml_ng::from_str(text).map_err(|e| e.to_string()),
Self::Toml => toml::from_str(text).map_err(|e| e.to_string()),
Self::Xml => xml_to_value(text),
}
}
pub(crate) fn label(self) -> &'static str {
match self {
Self::Json => "JSON",
Self::Yaml => "YAML",
Self::Toml => "TOML",
Self::Xml => "XML",
}
}
pub(crate) fn detect_from_path(path: &std::path::Path) -> Option<Self> {
match path.extension()?.to_str()? {
"json" => Some(Self::Json),
"yaml" | "yml" => Some(Self::Yaml),
"toml" => Some(Self::Toml),
"xml" | "csproj" | "props" | "targets" | "vbproj" | "fsproj" | "nuspec" => {
Some(Self::Xml)
}
_ => None,
}
}
}
#[derive(Debug)]
pub enum Op {
Equals(Value),
Matches(Regex),
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct EqualsOptions {
path: String,
equals: Value,
#[serde(default)]
if_present: bool,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct MatchesOptions {
path: String,
matches: String,
#[serde(default)]
if_present: bool,
}
#[derive(Debug)]
pub struct StructuredPathRule {
id: String,
level: Level,
policy_url: Option<String>,
message: Option<String>,
scope: Scope,
literal_paths: Option<Vec<PathBuf>>,
format: Format,
path_expr: JsonPath,
path_src: String,
op: Op,
if_present: bool,
}
impl Rule for StructuredPathRule {
fn id(&self) -> &str {
&self.id
}
fn level(&self) -> Level {
self.level
}
fn policy_url(&self) -> Option<&str> {
self.policy_url.as_deref()
}
fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
let mut violations = Vec::new();
if let Some(literals) = self.literal_paths.as_ref() {
for literal in literals {
if !ctx.index.contains_file(literal) {
continue;
}
let full = ctx.root.join(literal);
let Ok(bytes) = std::fs::read(&full) else {
continue;
};
violations.extend(self.evaluate_file(ctx, literal, &bytes)?);
}
} else {
for entry in ctx.index.files() {
if !self.scope.matches(&entry.path, ctx.index) {
continue;
}
let full = ctx.root.join(&entry.path);
let Ok(bytes) = std::fs::read(&full) else {
continue;
};
violations.extend(self.evaluate_file(ctx, &entry.path, &bytes)?);
}
}
Ok(violations)
}
fn as_per_file(&self) -> Option<&dyn PerFileRule> {
Some(self)
}
}
impl PerFileRule for StructuredPathRule {
fn path_scope(&self) -> &Scope {
&self.scope
}
fn evaluate_file(
&self,
_ctx: &Context<'_>,
path: &Path,
bytes: &[u8],
) -> Result<Vec<Violation>> {
let Ok(text) = std::str::from_utf8(bytes) else {
return Ok(Vec::new());
};
let root_value = match self.format.parse(text) {
Ok(v) => v,
Err(err) => {
return Ok(vec![
Violation::new(format!(
"not a valid {} document: {err}",
self.format.label()
))
.with_path(std::sync::Arc::<Path>::from(path)),
]);
}
};
let matches = self.path_expr.query(&root_value);
if matches.is_empty() {
if self.if_present {
return Ok(Vec::new());
}
let msg = self
.message
.clone()
.unwrap_or_else(|| format!("JSONPath `{}` produced no match", self.path_src));
return Ok(vec![
Violation::new(msg).with_path(std::sync::Arc::<Path>::from(path)),
]);
}
let mut violations = Vec::new();
for m in matches.iter() {
if let Some(v) = check_match(m, &self.op) {
let base = self.message.clone().unwrap_or(v);
violations.push(Violation::new(base).with_path(std::sync::Arc::<Path>::from(path)));
}
}
Ok(violations)
}
}
fn check_match(m: &Value, op: &Op) -> Option<String> {
match op {
Op::Equals(expected) => {
if m == expected {
None
} else {
Some(format!(
"value at path does not equal expected: expected {}, got {}",
short_render(expected),
short_render(m),
))
}
}
Op::Matches(re) => {
let Some(s) = m.as_str() else {
return Some(format!(
"value at path is not a string (got {}), can't apply regex",
kind_name(m)
));
};
if re.is_match(s) {
None
} else {
Some(format!(
"value at path {} does not match regex {}",
short_render(m),
re.as_str(),
))
}
}
}
}
fn short_render(v: &Value) -> String {
let raw = v.to_string();
if raw.len() <= 80 {
raw
} else {
format!("{}…", &raw[..80])
}
}
fn kind_name(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "bool",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
const MAX_XML_DEPTH: usize = 256;
fn xml_to_value(text: &str) -> std::result::Result<Value, String> {
let doc = roxmltree::Document::parse(text).map_err(|e| e.to_string())?;
let root = doc.root_element();
let mut obj = serde_json::Map::new();
obj.insert(
root.tag_name().name().to_owned(),
element_to_value(root, 0)?,
);
Ok(Value::Object(obj))
}
fn element_to_value(node: roxmltree::Node, depth: usize) -> std::result::Result<Value, String> {
if depth >= MAX_XML_DEPTH {
return Err(format!(
"XML nesting exceeds the maximum supported depth ({MAX_XML_DEPTH})"
));
}
let mut obj = serde_json::Map::new();
for attr in node.attributes() {
obj.insert(
format!("@{}", attr.name()),
Value::String(attr.value().to_owned()),
);
}
let mut has_child_elem = false;
for child in node.children().filter(roxmltree::Node::is_element) {
has_child_elem = true;
let name = child.tag_name().name().to_owned();
let val = element_to_value(child, depth + 1)?;
match obj.get_mut(&name) {
Some(Value::Array(arr)) => arr.push(val),
Some(slot) => {
let prev = slot.take();
*slot = Value::Array(vec![prev, val]);
}
None => {
obj.insert(name, val);
}
}
}
let text: String = node
.children()
.filter(roxmltree::Node::is_text)
.filter_map(|n| n.text())
.collect();
let text = text.trim();
if obj.is_empty() && !has_child_elem {
return Ok(if text.is_empty() {
Value::Null
} else {
Value::String(text.to_owned())
});
}
if !text.is_empty() {
obj.insert("#text".to_owned(), Value::String(text.to_owned()));
}
Ok(Value::Object(obj))
}
pub fn json_path_equals_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_equals(spec, Format::Json, "json_path_equals")
}
pub fn json_path_matches_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_matches(spec, Format::Json, "json_path_matches")
}
pub fn yaml_path_equals_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_equals(spec, Format::Yaml, "yaml_path_equals")
}
pub fn yaml_path_matches_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_matches(spec, Format::Yaml, "yaml_path_matches")
}
pub fn toml_path_equals_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_equals(spec, Format::Toml, "toml_path_equals")
}
pub fn toml_path_matches_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_matches(spec, Format::Toml, "toml_path_matches")
}
pub fn xml_path_equals_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_equals(spec, Format::Xml, "xml_path_equals")
}
pub fn xml_path_matches_build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
build_matches(spec, Format::Xml, "xml_path_matches")
}
fn build_equals(spec: &RuleSpec, format: Format, kind_label: &str) -> Result<Box<dyn Rule>> {
let paths = spec.paths.as_ref().ok_or_else(|| {
Error::rule_config(&spec.id, format!("{kind_label} requires a `paths` field"))
})?;
let opts: EqualsOptions = spec
.deserialize_options()
.map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
let path_expr = JsonPath::parse(&opts.path).map_err(|e| {
Error::rule_config(
&spec.id,
alint_core::jsonpath_diagnostics::format_parse_error(&opts.path, e),
)
})?;
Ok(Box::new(StructuredPathRule {
id: spec.id.clone(),
level: spec.level,
policy_url: spec.policy_url.clone(),
message: spec.message.clone(),
scope: Scope::from_spec(spec)?,
literal_paths: extract_literal_paths(paths),
format,
path_expr,
path_src: opts.path,
op: Op::Equals(opts.equals),
if_present: opts.if_present,
}))
}
fn build_matches(spec: &RuleSpec, format: Format, kind_label: &str) -> Result<Box<dyn Rule>> {
let paths = spec.paths.as_ref().ok_or_else(|| {
Error::rule_config(&spec.id, format!("{kind_label} requires a `paths` field"))
})?;
let opts: MatchesOptions = spec
.deserialize_options()
.map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
let path_expr = JsonPath::parse(&opts.path).map_err(|e| {
Error::rule_config(
&spec.id,
alint_core::jsonpath_diagnostics::format_parse_error(&opts.path, e),
)
})?;
let re = Regex::new(&opts.matches).map_err(|e| {
Error::rule_config(&spec.id, format!("invalid regex {:?}: {e}", opts.matches))
})?;
Ok(Box::new(StructuredPathRule {
id: spec.id.clone(),
level: spec.level,
policy_url: spec.policy_url.clone(),
message: spec.message.clone(),
scope: Scope::from_spec(spec)?,
literal_paths: extract_literal_paths(paths),
format,
path_expr,
path_src: opts.path,
op: Op::Matches(re),
if_present: opts.if_present,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
#[test]
fn build_rejects_missing_paths() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
path: \"$.name\"\n\
equals: \"x\"\n\
level: error\n",
);
assert!(json_path_equals_build(&spec).is_err());
}
#[test]
fn build_rejects_invalid_jsonpath() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$..[invalid\"\n\
equals: \"x\"\n\
level: error\n",
);
assert!(json_path_equals_build(&spec).is_err());
}
#[test]
fn build_rejects_invalid_regex_in_matches() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_matches\n\
paths: \"package.json\"\n\
path: \"$.version\"\n\
matches: \"[unterminated\"\n\
level: error\n",
);
let e = json_path_matches_build(&spec).unwrap_err().to_string();
assert!(e.contains("regex"), "expected a regex error, got: {e}");
}
#[test]
fn json_path_equals_passes_when_value_matches() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$.name\"\n\
equals: \"demo\"\n\
level: error\n",
);
let rule = json_path_equals_build(&spec).unwrap();
let (tmp, idx) =
tempdir_with_files(&[("package.json", br#"{"name":"demo","version":"1.0.0"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "matching value should pass: {v:?}");
}
#[test]
fn json_path_equals_fires_on_mismatch() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$.name\"\n\
equals: \"demo\"\n\
level: error\n",
);
let rule = json_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", br#"{"name":"other"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1);
}
#[test]
fn json_path_equals_fires_on_missing_path() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$.name\"\n\
equals: \"demo\"\n\
level: error\n",
);
let rule = json_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", br#"{"version":"1.0"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1, "missing path should fire");
}
#[test]
fn json_path_if_present_silent_on_missing() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$.name\"\n\
equals: \"demo\"\n\
if_present: true\n\
level: error\n",
);
let rule = json_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", br#"{"version":"1.0"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "if_present should silence: {v:?}");
}
#[test]
fn json_path_matches_passes_on_pattern_hit() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_matches\n\
paths: \"package.json\"\n\
path: \"$.version\"\n\
matches: \"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$\"\n\
level: error\n",
);
let rule = json_path_matches_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", br#"{"version":"1.2.3"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "matching version should pass: {v:?}");
}
#[test]
fn json_path_matches_fires_on_pattern_miss() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_matches\n\
paths: \"package.json\"\n\
path: \"$.version\"\n\
matches: \"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$\"\n\
level: error\n",
);
let rule = json_path_matches_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", br#"{"version":"v1.x"}"#)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1);
}
#[test]
fn yaml_path_equals_passes_when_value_matches() {
let spec = spec_yaml(
"id: t\n\
kind: yaml_path_equals\n\
paths: \".github/workflows/*.yml\"\n\
path: \"$.name\"\n\
equals: \"CI\"\n\
level: error\n",
);
let rule = yaml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
".github/workflows/ci.yml",
b"name: CI\non: push\njobs: {}\n",
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "matching name should pass: {v:?}");
}
#[test]
fn yaml_path_matches_uses_bracket_notation_for_dashed_keys() {
let spec = spec_yaml(
"id: t\n\
kind: yaml_path_matches\n\
paths: \"action.yml\"\n\
path: \"$.runs['using']\"\n\
matches: \"^node\\\\d+$\"\n\
level: error\n",
);
let rule = yaml_path_matches_build(&spec).unwrap();
let (tmp, idx) =
tempdir_with_files(&[("action.yml", b"runs:\n using: node20\n main: index.js\n")]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "bracket notation should match: {v:?}");
}
#[test]
fn toml_path_equals_passes_when_value_matches() {
let spec = spec_yaml(
"id: t\n\
kind: toml_path_equals\n\
paths: \"Cargo.toml\"\n\
path: \"$.package.edition\"\n\
equals: \"2024\"\n\
level: error\n",
);
let rule = toml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"Cargo.toml",
b"[package]\nname = \"x\"\nedition = \"2024\"\n",
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "matching edition should pass: {v:?}");
}
#[test]
fn toml_path_matches_fires_on_floating_version() {
let spec = spec_yaml(
"id: t\n\
kind: toml_path_matches\n\
paths: \"Cargo.toml\"\n\
path: \"$.dependencies.serde\"\n\
matches: \"^[~=]\"\n\
level: error\n",
);
let rule = toml_path_matches_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"Cargo.toml",
b"[package]\nname = \"x\"\n[dependencies]\nserde = \"1\"\n",
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1, "floating `serde = \"1\"` should fire");
}
#[test]
fn xml_path_equals_passes_on_csproj_leaf() {
let spec = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"App.csproj\"\n\
path: \"$.Project.PropertyGroup.TargetFramework\"\n\
equals: \"net8.0\"\n\
level: error\n",
);
let rule = xml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"App.csproj",
br#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>"#,
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "leaf element should match: {v:?}");
}
#[test]
fn xml_path_equals_fires_on_csproj_mismatch() {
let spec = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"App.csproj\"\n\
path: \"$.Project.PropertyGroup.TargetFramework\"\n\
equals: \"net8.0\"\n\
level: error\n",
);
let rule = xml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"App.csproj",
br"<Project><PropertyGroup><TargetFramework>net6.0</TargetFramework></PropertyGroup></Project>",
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1);
}
#[test]
fn xml_path_matches_on_packageref_attribute_array() {
let spec = spec_yaml(
"id: t\n\
kind: xml_path_matches\n\
paths: \"App.csproj\"\n\
path: \"$.Project.ItemGroup.PackageReference[*]['@Version']\"\n\
matches: \"^\\\\d\"\n\
level: error\n",
);
let rule = xml_path_matches_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"App.csproj",
br#"<Project><ItemGroup><PackageReference Include="A" Version="1.2.3"/><PackageReference Include="B" Version="4.0.0"/></ItemGroup></Project>"#,
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "both @Version attrs should match: {v:?}");
}
#[test]
fn xml_pom_namespace_flattened_and_repeated_dependency_array() {
let pom = br#"<project xmlns="http://maven.apache.org/POM/4.0.0"><modelVersion>4.0.0</modelVersion><dependencies><dependency><artifactId>guava</artifactId></dependency><dependency><artifactId>junit</artifactId></dependency></dependencies></project>"#;
let eq = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"pom.xml\"\n\
path: \"$.project.modelVersion\"\n\
equals: \"4.0.0\"\n\
level: error\n",
);
let (tmp, idx) = tempdir_with_files(&[("pom.xml", pom)]);
assert!(
xml_path_equals_build(&eq)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap()
.is_empty(),
"namespace-flattened modelVersion should match"
);
let m = spec_yaml(
"id: t\n\
kind: xml_path_matches\n\
paths: \"pom.xml\"\n\
path: \"$.project.dependencies.dependency[*].artifactId\"\n\
matches: \"^[a-z]+$\"\n\
level: error\n",
);
let v = xml_path_matches_build(&m)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap();
assert!(v.is_empty(), "both deps' artifactId should match: {v:?}");
}
#[test]
fn xml_path_if_present_silences_missing() {
let spec = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"App.csproj\"\n\
path: \"$.Project.PropertyGroup.Nullable\"\n\
equals: \"enable\"\n\
if_present: true\n\
level: error\n",
);
let rule = xml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[(
"App.csproj",
br"<Project><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>",
)]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert!(v.is_empty(), "if_present should silence missing: {v:?}");
}
#[test]
fn xml_malformed_fires_one_violation() {
let spec = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"App.csproj\"\n\
path: \"$.Project\"\n\
equals: \"x\"\n\
level: error\n",
);
let rule = xml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("App.csproj", b"<Project><Unclosed></Project>")]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1, "not-well-formed XML should fire once");
assert!(v[0].message.contains("XML"), "{:?}", v[0].message);
}
#[test]
fn xml_deeply_nested_is_a_parse_error_not_an_abort() {
let depth = MAX_XML_DEPTH + 50;
let xml = format!("{}deep{}", "<a>".repeat(depth), "</a>".repeat(depth));
let spec = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"deep.xml\"\n\
path: \"$.a\"\n\
equals: \"x\"\n\
level: error\n",
);
let rule = xml_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("deep.xml", xml.as_bytes())]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(
v.len(),
1,
"deeply-nested XML must yield exactly one parse-error violation: {v:?}"
);
assert!(
v[0].message.contains("not a valid XML") && v[0].message.contains("depth"),
"expected a depth parse-error message, got: {}",
v[0].message
);
}
#[test]
fn xml_leaf_values_are_string_typed() {
let xml: &[u8] = b"<Config><n>8</n></Config>";
let as_str = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"c.xml\"\n\
path: \"$.Config.n\"\n\
equals: \"8\"\n\
level: error\n",
);
let (tmp, idx) = tempdir_with_files(&[("c.xml", xml)]);
assert!(
xml_path_equals_build(&as_str)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap()
.is_empty(),
"string 8 should match the string-typed leaf"
);
let as_int = spec_yaml(
"id: t\n\
kind: xml_path_equals\n\
paths: \"c.xml\"\n\
path: \"$.Config.n\"\n\
equals: 8\n\
level: error\n",
);
let v = xml_path_equals_build(&as_int)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap();
assert_eq!(v.len(), 1, "integer 8 must NOT equal string \"8\"");
}
#[test]
fn xml_empty_element_is_null() {
let xml: &[u8] = b"<Config><empty/></Config>";
let (tmp, idx) = tempdir_with_files(&[("c.xml", xml)]);
let as_null = spec_yaml(
"id: t\nkind: xml_path_equals\npaths: \"c.xml\"\n\
path: \"$.Config.empty\"\nequals: null\nlevel: error\n",
);
assert!(
xml_path_equals_build(&as_null)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap()
.is_empty(),
"an empty element must equal null"
);
let as_empty_str = spec_yaml(
"id: t\nkind: xml_path_equals\npaths: \"c.xml\"\n\
path: \"$.Config.empty\"\nequals: \"\"\nlevel: error\n",
);
assert_eq!(
xml_path_equals_build(&as_empty_str)
.unwrap()
.evaluate(&ctx(tmp.path(), &idx))
.unwrap()
.len(),
1,
"null must NOT equal the empty string"
);
}
#[test]
fn evaluate_fires_on_malformed_input() {
let spec = spec_yaml(
"id: t\n\
kind: json_path_equals\n\
paths: \"package.json\"\n\
path: \"$.name\"\n\
equals: \"x\"\n\
level: error\n",
);
let rule = json_path_equals_build(&spec).unwrap();
let (tmp, idx) = tempdir_with_files(&[("package.json", b"{not valid json")]);
let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
assert_eq!(v.len(), 1, "malformed JSON should fire one violation");
}
}