Skip to main content

stratum_node_config/
seed.rs

1//! Generation of the canonical, commented seed document.
2
3use std::fmt::Write as _;
4
5use crate::document::SCHEMA_VERSION_KEY;
6use crate::schema::{FieldDescriptor, Schema, SCHEMA_VERSION};
7
8/// Width that comment lines in the seed are wrapped to, including `# `.
9const COMMENT_WIDTH: usize = 79;
10
11const HEADER: &str = "\
12# stratum.toml: configuration of a Stratum node.
13#
14# Every field is listed at its default, with its description above it. The
15# node's store holds the authoritative copy of this file: change settings with
16# `stratum config` or the setup page, because a hand edit is overwritten from
17# the store at the next start.
18";
19
20impl Schema {
21    /// Returns the canonical seed `stratum.toml`: every field at its default,
22    /// grouped by table in schema order, each preceded by its description
23    /// and apply class as comments.
24    ///
25    /// The seed always parses, validates, and has exactly the default
26    /// effective configuration.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// use stratum_node_config::{schema, ConfigDocument};
32    ///
33    /// let seed = schema().seed_text();
34    /// assert!(seed.contains("\n[listen]\n"));
35    /// let doc = ConfigDocument::parse(&seed)?;
36    /// assert_eq!(doc.config().node_name(), "stratum");
37    /// # Ok::<(), Box<dyn std::error::Error>>(())
38    /// ```
39    pub fn seed_text(&self) -> String {
40        let mut out = String::from(HEADER);
41        out.push('\n');
42        push_comment(
43            &mut out,
44            &format!("Version of this file's format. Must be {SCHEMA_VERSION}."),
45        );
46        // Writing to a String cannot fail.
47        let _ = writeln!(out, "{SCHEMA_VERSION_KEY} = {SCHEMA_VERSION}");
48        for section in self.sections() {
49            let _ = write!(out, "\n[{section}]\n");
50            for field in self.fields().filter(|f| f.section() == section) {
51                push_field(&mut out, field);
52            }
53        }
54        out
55    }
56}
57
58fn push_field(out: &mut String, field: &FieldDescriptor) {
59    out.push('\n');
60    push_comment(out, field.description());
61    push_comment(out, &format!("Apply class: {}.", field.apply_class()));
62    out.push_str(field.key());
63    out.push_str(" = ");
64    field.default_value().write_canonical(out);
65    out.push('\n');
66}
67
68/// Appends `text` as `# ` comment lines, wrapped at word boundaries.
69fn push_comment(out: &mut String, text: &str) {
70    let mut line = String::from("#");
71    for word in text.split_whitespace() {
72        if line.len() > 1 && line.len() + 1 + word.len() > COMMENT_WIDTH {
73            out.push_str(&line);
74            out.push('\n');
75            line = String::from("#");
76        }
77        line.push(' ');
78        line.push_str(word);
79    }
80    out.push_str(&line);
81    out.push('\n');
82}