use std::marker::PhantomData;
use crate::config::Config;
use crate::names::lower_camel;
use crate::node::{Field, Node, Shape};
use crate::problems::{Problem, Problems};
use crate::source::Source;
use crate::variant::Variant;
const TAB: &str = " ";
const MAX_LINE: i64 = 160;
const MIN_INLINE_COMMENT: i64 = 24;
const HEADER: &str = "# Generated by redup-config";
const SECRET_MARK: &str = "*****";
const REQUIRED_MARK: &str = "[required] ";
pub fn render_default<T: Config>() -> String {
let value = T::default();
document(T::DOC, false, |yaml| yaml.root(&value))
}
pub fn render_sample<T: Config>() -> String {
let mut value = T::default();
value.fill();
document(T::DOC, false, |yaml| yaml.root(&value))
}
pub fn render<T: Config>(value: &T) -> String {
document(T::DOC, true, |yaml| yaml.root(value))
}
pub struct Global<E = ()> {
list: PhantomData<fn() -> E>,
}
impl Default for Global<()> {
fn default() -> Self {
Self::new()
}
}
impl Global<()> {
pub fn new() -> Self {
Self { list: PhantomData }
}
}
impl<E: Members> Global<E> {
pub fn with<T: Config>(self) -> Global<(T, E)> {
Global { list: PhantomData }
}
pub fn render_default(&self) -> String {
self.file(false)
}
pub fn render_sample(&self) -> String {
self.file(true)
}
pub fn check(&self, source: &Source) -> Result<Vec<Problem>, Problems> {
let mut keys: Vec<&'static str> = Vec::new();
E::each(false, &mut |key, _, _| keys.push(key));
crate::source::check_global(&keys, source)
}
fn file(&self, sample: bool) -> String {
let mut out = file_header("");
E::each(sample, &mut |key, doc, node| {
out.push_str(&member_text(key, doc, node));
});
out
}
}
pub trait Members: Sized + Default {
fn each(sample: bool, visit: &mut dyn for<'a> FnMut(&'static str, &'static str, &'a dyn Node));
}
impl Members for () {
fn each(
_sample: bool,
_visit: &mut dyn for<'a> FnMut(&'static str, &'static str, &'a dyn Node),
) {
}
}
impl<M: Config, E: Members> Members for (M, E) {
fn each(sample: bool, visit: &mut dyn for<'a> FnMut(&'static str, &'static str, &'a dyn Node)) {
E::each(sample, visit);
let mut value = M::default();
if sample {
value.fill();
}
visit(M::KEY, M::DOC, &value);
}
}
fn member_text(key: &str, doc: &str, node: &dyn Node) -> String {
let mut yaml = Yaml {
out: String::new(),
hide: false,
};
yaml.item(
node,
&Place {
lead: "",
name: Some(key),
element: false,
},
&Note {
comments: true,
desc: doc,
variants: node.variants(),
required: false,
},
);
yaml.out
}
fn document(doc: &str, hide: bool, body: impl FnOnce(&mut Yaml)) -> String {
let mut out = file_header(doc);
let mut yaml = Yaml {
out: String::new(),
hide,
};
body(&mut yaml);
out.push_str(&yaml.out);
out
}
fn file_header(doc: &str) -> String {
let mut out = String::from(HEADER);
out.push('\n');
if !doc.is_empty() {
out.push_str("# ");
out.push_str(doc);
out.push('\n');
}
out
}
struct Place<'a> {
lead: &'a str,
name: Option<&'a str>,
element: bool,
}
impl Place<'_> {
fn header(&self, tail: &str) -> String {
match self.name {
Some(name) => format!("{}{}:{}", self.lead, name, tail),
None => format!("{}{}", self.lead, tail),
}
}
fn statement(&self, value: &str) -> String {
match self.name {
Some(name) if self.element => format!("{}{}:{}", self.lead, name, value),
Some(name) => format!("{}{}: {}", self.lead, name, value),
None => format!("{}{}", self.lead, value),
}
}
fn child(&self) -> String {
let mut child = " ".repeat(self.lead.len());
if !self.element {
child.push_str(TAB);
}
child
}
}
struct Note<'a> {
comments: bool,
desc: &'a str,
variants: Vec<Variant>,
required: bool,
}
impl Note<'_> {
fn field(&self, field: &Field<'_>) -> Note<'_> {
Note {
comments: self.comments,
desc: field.doc,
variants: field.node.variants(),
required: field.required && matches!(field.node.shape(), Shape::Optional(None)),
}
}
}
struct Yaml {
out: String,
hide: bool,
}
impl Yaml {
fn root(&mut self, node: &dyn Node) {
if let Shape::Section(fields) = node.shape() {
for field in fields {
let place = Place {
lead: "",
name: Some(field.name),
element: false,
};
let note = Note {
comments: true,
desc: field.doc,
variants: field.node.variants(),
required: field.required && matches!(field.node.shape(), Shape::Optional(None)),
};
self.item(field.node, &place, ¬e);
}
}
}
fn item(&mut self, node: &dyn Node, place: &Place, note: &Note) {
if self.hide
&& place.name.is_some_and(is_secret_name)
&& !matches!(node.shape(), Shape::Optional(None))
{
let statement = format!("{}{}", place.header(" "), escape(SECRET_MARK));
self.statement_with_comment(&statement, note);
return;
}
match node.shape() {
Shape::Scalar(text) => self.scalar(&text, place, note),
Shape::Optional(None) => self.absent(place, note),
Shape::Optional(Some(inner)) => {
let note = Note {
comments: note.comments,
desc: note.desc,
variants: inner.variants(),
required: false,
};
self.item(inner, place, ¬e);
}
Shape::Section(fields) => self.section(fields, place, note),
Shape::Sequence(items) => {
if items.iter().copied().all(scalar_like) && !items.iter().copied().any(multiline) {
self.inline(&items, place, note);
} else {
self.sequence(&items, place, note);
}
}
Shape::Dictionary(entries) => self.dictionary(entries, place, note),
}
}
fn scalar(&mut self, text: &str, place: &Place, note: &Note) {
let value = if self.hide && place.name.is_some_and(is_secret_name) {
SECRET_MARK.to_owned()
} else {
text.to_owned()
};
if value.contains('\n') {
let indent = " ".repeat(place.lead.len());
if note.comments && !note.desc.is_empty() {
let desc = with_possible_values(note.desc, ¬e.variants);
for line in nice_comment(&indent, &desc) {
self.line(line);
}
}
let (body, indicator) = match value.strip_suffix('\n') {
Some(body) => (body, "|2+"),
None => (value.as_str(), "|2-"),
};
let separator = if place.element { "" } else { " " };
self.line(format!("{}{indicator}", place.header(separator)));
let pad = if place.element { "" } else { TAB };
for line in body.split('\n') {
self.line(format!("{indent}{pad}{line}"));
}
return;
}
self.statement_with_comment(&place.statement(&escape(&value)), note);
}
fn absent(&mut self, place: &Place, note: &Note) {
self.statement_marked(&place.statement("~"), note, note.required);
}
fn statement_with_comment(&mut self, statement: &str, note: &Note) {
self.statement_marked(statement, note, false);
}
fn statement_marked(&mut self, statement: &str, note: &Note, required: bool) {
let desc = with_possible_values(note.desc, ¬e.variants);
let desc = if required {
format!("{REQUIRED_MARK}{desc}")
} else {
desc
};
if note.comments && !desc.is_empty() {
for line in nice_comment(statement, &desc) {
self.line(line);
}
} else {
self.line(statement);
}
}
fn section(&mut self, fields: Vec<Field<'_>>, place: &Place, note: &Note) {
let header = place.header("");
let mut written = false;
if note.comments && !note.desc.is_empty() {
for line in nice_comment(&header, note.desc) {
self.line(line);
}
written = true;
} else if !place.element {
self.line(&header);
written = true;
}
let mut lead_of_first = if place.element && !written {
Some(header)
} else {
None
};
let child = place.child();
for field in fields {
let lead = lead_of_first.take().unwrap_or_else(|| child.clone());
let field_place = Place {
lead: &lead,
name: Some(field.name),
element: false,
};
let field_note = note.field(&field);
self.item(field.node, &field_place, &field_note);
}
}
fn sequence(&mut self, items: &[&dyn Node], place: &Place, note: &Note) {
let header = place.header("");
let mut first = true;
if note.comments && !note.desc.is_empty() {
for line in nice_comment(&header, note.desc) {
self.line(line);
first = false;
}
} else if !place.element {
self.line(&header);
first = false;
}
let child = format!("{}{}", " ".repeat(place.lead.len()), "- ");
let first_tab = format!("{header}{TAB_LEFT}");
let item_of = format!("Item of {}", display(place.name));
let mut comments = note.comments;
for &node in items {
let lead = if first {
first_tab.as_str()
} else {
child.as_str()
};
let item_place = Place {
lead,
name: None,
element: true,
};
let item_note = Note {
comments,
desc: &item_of,
variants: node.variants(),
required: false,
};
self.item(node, &item_place, &item_note);
comments = false;
first = false;
}
}
fn inline(&mut self, items: &[&dyn Node], place: &Place, note: &Note) {
let mut parts: Vec<String> = Vec::with_capacity(items.len());
for item in items {
let text = match item.shape() {
Shape::Scalar(text) => Some(text),
Shape::Optional(Some(inner)) => match inner.shape() {
Shape::Scalar(text) => Some(text),
_ => None,
},
_ => None,
};
parts.push(text.map_or_else(|| "~".to_owned(), |text| escape_flow(&text)));
}
let body = format!("[{}]", parts.join(", "));
let statement = if place.element {
place.header(&body)
} else {
place.header(&format!(" {body}"))
};
self.statement_with_comment(&statement, note);
}
fn dictionary(&mut self, entries: Vec<(&str, &dyn Node)>, place: &Place, note: &Note) {
let mut header = place.header("");
if entries.is_empty() {
header.push_str(if place.element { "{}" } else { " {}" });
}
if note.comments && !note.desc.is_empty() {
for line in nice_comment(&header, note.desc) {
self.line(line);
}
} else {
self.line(&header);
}
let child = place.child();
let item_of = format!("Item of {}", display(place.name));
let mut comments = note.comments;
for (key, node) in entries {
let entry_place = Place {
lead: &child,
name: Some(key),
element: false,
};
let entry_note = Note {
comments,
desc: &item_of,
variants: node.variants(),
required: false,
};
self.item(node, &entry_place, &entry_note);
comments = false;
}
}
fn line(&mut self, text: impl AsRef<str>) {
self.out.push_str(text.as_ref());
self.out.push('\n');
}
}
const TAB_LEFT: &str = "- ";
fn scalar_like(node: &dyn Node) -> bool {
match node.shape() {
Shape::Scalar(_) => true,
Shape::Optional(None) => true,
Shape::Optional(Some(inner)) => matches!(inner.shape(), Shape::Scalar(_)),
_ => false,
}
}
fn multiline(node: &dyn Node) -> bool {
let shape = node.shape();
match shape {
Shape::Scalar(text) => text.contains('\n'),
Shape::Optional(Some(inner)) => multiline(inner),
_ => false,
}
}
fn display(name: Option<&str>) -> String {
match name {
Some(name) => upper_first(name),
None => "#".to_owned(),
}
}
pub(crate) fn upper_first(name: &str) -> String {
let mut letters = name.chars();
match letters.next() {
Some(head) => head.to_uppercase().collect::<String>() + letters.as_str(),
None => String::new(),
}
}
pub(crate) fn is_secret_name(name: &str) -> bool {
let lowered = name.to_lowercase();
lowered.contains("password") || lowered.contains("secret")
}
fn escape(text: &str) -> String {
if text.is_empty() {
return "''".to_owned();
}
let leading = text.starts_with([
' ', '$', '~', '#', '!', '-', '{', '}', '[', ']', '&', '\\', '\'', '"', '*', '%', '@', '|',
'>', '?', ',', ':', '`', '=',
]);
let trailing = text.ends_with([' ', '-']);
let inside = text.contains(['#', '\t']) || text.contains(": ") || text.ends_with(':');
if !text.eq_ignore_ascii_case("null") && !leading && !trailing && !inside {
return text.to_owned();
}
format!("'{}'", text.replace('\'', "''"))
}
fn escape_flow(text: &str) -> String {
if text.contains([',', '[', ']', '{', '}']) {
return format!("'{}'", text.replace('\'', "''"));
}
escape(text)
}
fn with_possible_values(desc: &str, variants: &[Variant]) -> String {
if desc.is_empty() || variants.is_empty() {
return desc.to_owned();
}
let tokens = collect_tokens(desc);
let flags = variants
.iter()
.any(|variant| matches!(variant, Variant::Flag(..)));
let mut mentioned = false;
let mut missing: Vec<String> = Vec::new();
for variant in variants {
let (name, shown) = match variant {
Variant::Value(name) => (*name, (*name).to_owned()),
Variant::Flag(name, weight) => (*name, format!("{}({weight})", lower_camel(name))),
};
if tokens.iter().any(|token| *token == normalize(name)) {
mentioned = true;
} else {
missing.push(shown);
}
}
if missing.is_empty() {
return desc.to_owned();
}
let head = match (mentioned, flags) {
(false, false) => "Возможные значения",
(false, true) => "Возможные флаговые значения",
(true, false) => "Другие возможные значения",
(true, true) => "Другие возможные флаговые значения",
};
let mut res = desc.to_owned();
if !ends_with_punctuation(&res) {
res.push('.');
}
format!("{res} {head}: {}.", missing.join(", "))
}
fn collect_tokens(text: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut token = String::new();
for character in text.chars() {
if character.is_alphanumeric() || matches!(character, '_' | '-') {
token.push(character);
} else if !token.is_empty() {
tokens.push(normalize(&token));
token.clear();
}
}
if !token.is_empty() {
tokens.push(normalize(&token));
}
tokens
}
fn normalize(text: &str) -> String {
text.chars()
.filter(|character| character.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect()
}
fn ends_with_punctuation(text: &str) -> bool {
text.chars().next_back().is_some_and(|character| {
matches!(
character,
'.' | ',' | '!' | '?' | ';' | ':' | ')' | ']' | '"' | '\'' | '»' | '…' | '—' | '–'
)
})
}
fn nice_comment(statement: &str, comment: &str) -> Vec<String> {
let space = if !statement.is_empty() && !statement.ends_with(' ') {
" "
} else {
""
};
let mut comment = comment.replace('\n', " ").trim().to_owned();
if comment
.chars()
.next_back()
.is_some_and(|character| character.is_alphanumeric())
{
comment.push('.');
}
let width = statement.chars().count() as i64;
let extra = 2 + space.chars().count() as i64;
let max_len = MAX_LINE - width - extra;
if comment.chars().count() as i64 <= max_len {
return vec![format!("{statement}{space}# {comment}")];
}
let trimmed = statement.trim_start();
let content = trimmed.chars().count() as i64;
if max_len < MIN_INLINE_COMMENT && content > 0 {
let indent = statement.strip_suffix(trimmed).unwrap_or(statement);
let mut lines = nice_comment(indent, &comment);
lines.push(statement.to_owned());
return lines;
}
let words: Vec<&str> = comment
.split([' ', '\t'])
.filter(|word| !word.is_empty())
.collect();
let mut lines = Vec::new();
if words.is_empty() || max_len <= 0 {
lines.push(format!("{statement}{space}# {comment}"));
return lines;
}
let total = comment.chars().count() as f64;
let average =
words.iter().map(|word| word.chars().count()).sum::<usize>() as f64 / words.len() as f64;
let count = (total / max_len as f64).ceil().max(1.0);
let corrected = (total / count + 2.0 * average / count).floor() as i64;
let limit = width + extra + corrected;
let head = format!("{}{space}# ", " ".repeat(width as usize));
let mut rest: &[&str] = &words;
if let Some(word) = rest.first() {
let mut line = format!("{statement}{space}# {word}");
rest = &rest[1..];
while let Some(next) = rest.first() {
if (line.chars().count() as i64) + 1 + next.chars().count() as i64 >= limit {
break;
}
line.push(' ');
line.push_str(next);
rest = &rest[1..];
}
lines.push(line);
}
while let Some(word) = rest.first() {
let mut line = format!("{head}{word}");
rest = &rest[1..];
while let Some(next) = rest.first() {
if (line.chars().count() as i64) + 1 + next.chars().count() as i64 >= limit {
break;
}
line.push(' ');
line.push_str(next);
rest = &rest[1..];
}
lines.push(line);
}
lines
}