use std::collections::BTreeMap;
use serde_json::Value;
use super::decode::AliasBudget;
use super::error::{GenerateError, Result};
use super::yaml::{self, Kind, YamlError};
use super::{comments, parse_values};
#[derive(Debug, Clone, PartialEq)]
pub struct Annotation {
pub path: Vec<String>,
pub keywords: BTreeMap<String, Value>,
pub description: String,
pub root: bool,
}
struct Walk<'a> {
doc: &'a yaml::Doc,
keep_full_comment: bool,
path: Vec<String>,
active: Vec<usize>,
budget: AliasBudget,
out: Vec<Annotation>,
}
impl Walk<'_> {
fn collect(&mut self, id: usize, first_comment: Option<&str>) -> Result<()> {
let doc = self.doc;
let node = &doc.nodes[id];
if node.kind != Kind::Mapping {
return Ok(());
}
self.active.push(id);
for (index, pair) in node.content.chunks(2).enumerate() {
self.budget.tick()?;
let key = &doc.nodes[pair[0]];
let head = match first_comment {
Some(text) if index == 0 => text,
_ => key.head_comment.as_str(),
};
let comment = if self.keep_full_comment {
head
} else {
comments::remove_leading(head)
};
self.path.push(key.value.clone());
if let Some((keywords, description)) =
comments::keywords(comment, false).map_err(|m| {
GenerateError::annotation(
format!("error parsing comment of key {}", key.value),
m,
)
})?
{
self.out.push(Annotation {
path: self.path.clone(),
keywords,
description,
root: false,
});
}
let value = &doc.nodes[pair[1]];
let target = if value.kind == Kind::Alias {
value.alias.unwrap_or(pair[1])
} else {
pair[1]
};
if self.active.contains(&target) {
return Err(YamlError::plain(&format!(
"anchor '{}' value contains itself",
value.value
))
.into());
}
if target != pair[1] {
self.budget.enter_alias();
}
self.collect(target, None)?;
if target != pair[1] {
self.budget.leave_alias();
}
self.path.pop();
}
self.active.pop();
Ok(())
}
}
pub fn annotations(values_yaml: &str, keep_full_comment: bool) -> Result<Vec<Annotation>> {
let doc = parse_values(&values_yaml.replace("\r\n", "\n"))?;
let root = doc.root.unwrap_or_default();
let mut out = Vec::new();
let mut heads = vec![doc.nodes[root].head_comment.as_str()];
let mut first_comment = None;
if let Some(&first) = doc.nodes[root].content.first()
&& let Some(&key) = doc.nodes[first].content.first()
{
heads.push(&doc.nodes[key].head_comment);
}
for (index, head) in heads.into_iter().enumerate() {
if let Some((keywords, description)) = comments::keywords(head, true).map_err(|m| {
GenerateError::annotation("error parsing root schema comment".to_owned(), m)
})? {
if index == 1 {
first_comment = Some(description.clone());
}
out.push(Annotation {
path: Vec::new(),
keywords,
description,
root: true,
});
}
}
let mut walk = Walk {
doc: &doc,
keep_full_comment,
path: Vec::new(),
active: Vec::new(),
budget: AliasBudget::default(),
out,
};
if let Some(&child) = doc.nodes[root].content.first() {
walk.collect(child, first_comment.as_deref())?;
}
Ok(walk.out)
}
#[cfg(test)]
mod tests;