use crate::config::Config;
use crate::node::{Node, Shape};
use crate::render::{is_secret_name, upper_first};
const SECRET_MARK: &str = "*****";
pub fn status<T: Config>(value: &T) -> String {
let mut out = String::new();
if is_secret_name(T::NAME) {
out.push_str(T::NAME);
out.push_str(" = ");
out.push_str(SECRET_MARK);
out.push('\n');
return out;
}
out.push_str(T::NAME);
out.push('\n');
children(value.shape(), "", &mut out);
out
}
fn children(shape: Shape<'_>, prefix: &str, out: &mut String) {
let named: Vec<(String, &dyn Node)> = match shape {
Shape::Section(fields) => fields
.into_iter()
.map(|field| (upper_first(field.name), field.node as &dyn Node))
.collect(),
Shape::Dictionary(entries) => entries
.into_iter()
.map(|(key, node)| (key.to_owned(), node as &dyn Node))
.collect(),
Shape::Sequence(items) => items
.into_iter()
.enumerate()
.map(|(index, node)| (index.to_string(), node as &dyn Node))
.collect(),
_ => Vec::new(),
};
let total = named.len();
for (index, (name, node)) in named.into_iter().enumerate() {
let last = index + 1 == total;
let head = format!("{prefix}{}", if last { "╰─" } else { "├─" });
let next = format!("{prefix}{}", if last { " " } else { "│ " });
item(&name, node, &head, &next, out);
}
}
fn item(name: &str, node: &dyn Node, head: &str, next: &str, out: &mut String) {
match node.shape() {
Shape::Optional(None) => named_value(head, name, "(null)", out),
Shape::Optional(Some(inner)) => item(name, inner, head, next, out),
Shape::Scalar(text) => {
let value = if is_secret_name(name) {
SECRET_MARK.to_owned()
} else {
text.replace('\n', "\\n").replace('\t', "\\t")
};
let value = if value.is_empty() {
"''".to_owned()
} else {
value
};
named_value(head, name, &value, out);
}
shape => {
if is_secret_name(name) {
named_value(head, name, SECRET_MARK, out);
return;
}
if let Some(mark) = empty_mark(&shape) {
named_value(head, name, mark, out);
return;
}
out.push_str(head);
out.push_str(name);
out.push('\n');
children(shape, next, out);
}
}
}
fn named_value(head: &str, name: &str, value: &str, out: &mut String) {
out.push_str(head);
out.push_str(name);
out.push_str(" = ");
out.push_str(value);
out.push('\n');
}
fn empty_mark(shape: &Shape<'_>) -> Option<&'static str> {
match shape {
Shape::Section(fields) if fields.is_empty() => Some("{}"),
Shape::Dictionary(entries) if entries.is_empty() => Some("{}"),
Shape::Sequence(items) if items.is_empty() => Some("[]"),
_ => None,
}
}