use std::{collections::BTreeSet, fmt};
use super::{ConfigIssues, ConfigValidationError};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigDocument {
title: String,
sections: Vec<ConfigSectionDoc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigExampleMode {
RequiredOnly,
Recommended,
Complete,
}
impl ConfigDocument {
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into().trim().to_owned(),
sections: Vec::new(),
}
}
#[must_use]
pub fn with_section(mut self, section: ConfigSectionDoc) -> Self {
self.sections.push(section);
self
}
#[must_use]
pub fn with_sections(mut self, sections: impl IntoIterator<Item = ConfigSectionDoc>) -> Self {
self.sections.extend(sections);
self
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
#[must_use]
pub fn sections(&self) -> &[ConfigSectionDoc] {
&self.sections
}
pub fn validate(&self) -> Result<(), ConfigValidationError> {
let mut issues = ConfigIssues::new();
let mut section_names = BTreeSet::new();
for section in &self.sections {
issues.require(
is_toml_path(§ion.name),
format!("[{}]", section.name),
"section name must be a TOML bare-key path",
);
if !section_names.insert(section.name.as_str()) {
issues.push(format!("[{}]", section.name), "section name must be unique");
}
let mut field_names = BTreeSet::new();
for field in §ion.fields {
let field_path = format!("{}.{}", section.name, field.name);
issues.require(
is_toml_path(field.name()),
&field_path,
"field name must be a TOML bare-key path",
);
issues.require(
!field.example_value().trim().is_empty(),
&field_path,
"example value must not be empty",
);
if !field_names.insert(field.name()) {
issues.push(&field_path, "field name must be unique within section");
}
}
}
issues.into_result()
}
#[must_use]
pub fn render_markdown(&self) -> String {
let mut output = String::new();
output.push_str("# ");
output.push_str(if self.title.is_empty() {
"Configuration"
} else {
&self.title
});
output.push_str("\n\n");
for section in &self.sections {
section.render_markdown_into(&mut output);
}
output
}
#[must_use]
pub fn render_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::Complete)
}
#[must_use]
pub fn render_required_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::RequiredOnly)
}
#[must_use]
pub fn render_recommended_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::Recommended)
}
#[must_use]
pub fn render_toml(&self, mode: ConfigExampleMode) -> String {
let mut output = String::new();
for section in &self.sections {
section.render_toml_into(&mut output, mode);
}
output
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigSectionDoc {
name: String,
description: String,
fields: Vec<ConfigFieldDoc>,
}
impl ConfigSectionDoc {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into().trim().trim_matches(['[', ']']).to_owned(),
description: String::new(),
fields: Vec::new(),
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into().trim().to_owned();
self
}
#[must_use]
pub fn with_field(mut self, field: ConfigFieldDoc) -> Self {
self.fields.push(field);
self
}
#[must_use]
pub fn with_fields(mut self, fields: impl IntoIterator<Item = ConfigFieldDoc>) -> Self {
self.fields.extend(fields);
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
#[must_use]
pub fn fields(&self) -> &[ConfigFieldDoc] {
&self.fields
}
#[must_use]
pub fn field(&self, name: &str) -> Option<&ConfigFieldDoc> {
self.fields.iter().find(|field| field.name() == name)
}
fn render_markdown_into(&self, output: &mut String) {
output.push_str("## [");
output.push_str(&self.name);
output.push_str("]\n\n");
if !self.description.is_empty() {
output.push_str(&self.description);
output.push_str("\n\n");
}
for field in &self.fields {
output.push_str("- `");
output.push_str(field.name());
output.push('`');
if field.is_required() {
output.push_str(" required");
}
if field.is_secret() {
output.push_str(", secret");
}
if field.is_recommended() && !field.is_required() {
output.push_str(", recommended");
}
if field.restart_required() {
output.push_str(", restart required");
}
if let Some(default) = field.default_value() {
output.push_str(", default `");
output.push_str(default);
output.push('`');
}
if let Some(env_var) = field.env_var() {
output.push_str(", env `");
output.push_str(env_var);
output.push('`');
}
if !field.description().is_empty() {
output.push_str(": ");
output.push_str(field.description());
}
output.push('\n');
}
output.push('\n');
}
fn render_toml_into(&self, output: &mut String, mode: ConfigExampleMode) {
let fields = self
.fields
.iter()
.filter(|field| field.included_in_example(mode));
let mut wrote_header = false;
for field in fields {
if !wrote_header {
output.push('[');
output.push_str(&self.name);
output.push_str("]\n");
wrote_header = true;
}
if matches!(mode, ConfigExampleMode::Complete) && !field.is_required() {
output.push_str("# ");
}
output.push_str(field.name());
output.push_str(" = ");
output.push_str(field.example_value());
if field.is_secret() {
output.push_str(" # secret");
} else if !field.description().is_empty() {
output.push_str(" # ");
output.push_str(field.description());
}
output.push('\n');
}
if wrote_header {
output.push('\n');
}
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigFieldDoc {
name: String,
description: String,
example_value: String,
default_value: Option<String>,
required: bool,
recommended: bool,
secret: bool,
restart_required: bool,
env_var: Option<String>,
}
impl fmt::Debug for ConfigFieldDoc {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = formatter.debug_struct("ConfigFieldDoc");
debug
.field("name", &self.name)
.field("description", &self.description);
if self.secret {
debug.field("example_value", &"[REDACTED]").field(
"default_value",
&self.default_value.as_ref().map(|_| "[REDACTED]"),
);
} else {
debug
.field("example_value", &self.example_value)
.field("default_value", &self.default_value);
}
debug
.field("required", &self.required)
.field("recommended", &self.recommended)
.field("secret", &self.secret)
.field("restart_required", &self.restart_required)
.field("env_var", &self.env_var)
.finish()
}
}
impl ConfigFieldDoc {
#[must_use]
pub fn required(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self::new(name, example_value, description, true, None)
}
#[must_use]
pub fn optional(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self::new(name, example_value, description, false, None)
}
#[must_use]
pub fn optional_default(
name: impl Into<String>,
default_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
let default_value = default_value.into();
Self::new(
name,
default_value.clone(),
description,
false,
Some(default_value),
)
}
#[must_use]
pub fn secret(mut self) -> Self {
self.secret = true;
self
}
#[must_use]
pub const fn recommended(mut self) -> Self {
self.recommended = true;
self
}
#[must_use]
pub fn with_restart_required(mut self) -> Self {
self.restart_required = true;
self
}
#[must_use]
pub fn with_env_var(mut self, env_var: impl Into<String>) -> Self {
let env_var = env_var.into().trim().to_owned();
if !env_var.is_empty() {
self.env_var = Some(env_var);
}
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
#[must_use]
pub fn example_value(&self) -> &str {
&self.example_value
}
#[must_use]
pub fn default_value(&self) -> Option<&str> {
self.default_value.as_deref()
}
#[must_use]
pub const fn is_required(&self) -> bool {
self.required
}
#[must_use]
pub const fn is_recommended(&self) -> bool {
self.recommended
}
#[must_use]
pub const fn is_secret(&self) -> bool {
self.secret
}
#[must_use]
pub const fn restart_required(&self) -> bool {
self.restart_required
}
#[must_use]
pub fn env_var(&self) -> Option<&str> {
self.env_var.as_deref()
}
fn new(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
required: bool,
default_value: Option<String>,
) -> Self {
Self {
name: name.into().trim().to_owned(),
description: description.into().trim().to_owned(),
example_value: example_value.into().trim().to_owned(),
default_value,
required,
recommended: required,
secret: false,
restart_required: false,
env_var: None,
}
}
const fn included_in_example(&self, mode: ConfigExampleMode) -> bool {
match mode {
ConfigExampleMode::RequiredOnly => self.required,
ConfigExampleMode::Recommended => self.required || self.recommended,
ConfigExampleMode::Complete => true,
}
}
}
fn is_toml_path(value: &str) -> bool {
let value = value.trim();
!value.is_empty()
&& value.split('.').all(|part| {
!part.is_empty()
&& part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
})
}