stratum-node-config 0.1.0-alpha.2

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Generation of the canonical, commented seed document.

use std::fmt::Write as _;

use crate::document::SCHEMA_VERSION_KEY;
use crate::schema::{FieldDescriptor, Schema, SCHEMA_VERSION};

/// Width that comment lines in the seed are wrapped to, including `# `.
const COMMENT_WIDTH: usize = 79;

const HEADER: &str = "\
# stratum.toml: configuration of a Stratum node.
#
# Every field is listed at its default, with its description above it. The
# node's store holds the authoritative copy of this file: change settings with
# `stratum config` or the setup page, because a hand edit is overwritten from
# the store at the next start.
";

impl Schema {
    /// Returns the canonical seed `stratum.toml`: every field at its default,
    /// grouped by table in schema order, each preceded by its description
    /// and apply class as comments.
    ///
    /// The seed always parses, validates, and has exactly the default
    /// effective configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{schema, ConfigDocument};
    ///
    /// let seed = schema().seed_text();
    /// assert!(seed.contains("\n[listen]\n"));
    /// let doc = ConfigDocument::parse(&seed)?;
    /// assert_eq!(doc.config().node_name(), "stratum");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn seed_text(&self) -> String {
        let mut out = String::from(HEADER);
        out.push('\n');
        push_comment(
            &mut out,
            &format!("Version of this file's format. Must be {SCHEMA_VERSION}."),
        );
        // Writing to a String cannot fail.
        let _ = writeln!(out, "{SCHEMA_VERSION_KEY} = {SCHEMA_VERSION}");
        for section in self.sections() {
            let _ = write!(out, "\n[{section}]\n");
            for field in self.fields().filter(|f| f.section() == section) {
                push_field(&mut out, field);
            }
        }
        out
    }
}

fn push_field(out: &mut String, field: &FieldDescriptor) {
    out.push('\n');
    push_comment(out, field.description());
    push_comment(out, &format!("Apply class: {}.", field.apply_class()));
    out.push_str(field.key());
    out.push_str(" = ");
    field.default_value().write_canonical(out);
    out.push('\n');
}

/// Appends `text` as `# ` comment lines, wrapped at word boundaries.
fn push_comment(out: &mut String, text: &str) {
    let mut line = String::from("#");
    for word in text.split_whitespace() {
        if line.len() > 1 && line.len() + 1 + word.len() > COMMENT_WIDTH {
            out.push_str(&line);
            out.push('\n');
            line = String::from("#");
        }
        line.push(' ');
        line.push_str(word);
    }
    out.push_str(&line);
    out.push('\n');
}