use std::fmt::Write as _;
use crate::document::SCHEMA_VERSION_KEY;
use crate::schema::{FieldDescriptor, Schema, SCHEMA_VERSION};
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 {
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}."),
);
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');
}
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');
}