//! Configuration files: TOML (`.toml`) for people, JSON (`.json`) for generated //! configuration, with the same keys: the long option names. Nested tables join their //! keys with `-`, so `[mycelium] key-file = …` is `mycelium-key-file`. //! //! `include = [paths]` loads other files first (relative to this one), in the order //! listed; an entry `{ path = "…", optional = true }` is skipped where missing. This //! file's own values win over theirs, and later includes over earlier ones. A cycle is //! an error. //! //! `[meta.importer]` names importers (`import::Importers`): `NAME = { command = […] }` //! makes `NAME:REST` and `{ NAME = "REST" }` that importer, with `REST` as its variable //! `name`. A name counts in every file and argument of the configuration, wherever it //! is given; of two of one name, the later source's: a file's own over its includes', //! a later file's over an earlier one's, an argument's over them all. //! //! `unset = [options]` sets options back to their defaults, overriding includes and //! earlier files; in JSON, `null` does the same for one option. use std::path::{Path, PathBuf}; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Map as JsonMap, Value as JsonValue}; use crate::import; use crate::layer::{ Entry, Layer, Overlay, Provenance, overlay, resolve_file_value_in, unset_entry, }; use crate::option::Schema; /// Configuration about the configuration: what a file says under `meta`. const META: &str = "meta"; /// Under `meta`: the importers the file names. const IMPORTERS: &str = "importer"; const INCLUDE: &str = "include"; /// Undoing a value set before: the key `unset` in a file, and the argument `--unset`. pub const UNSET: &str = "unset"; /// Gone: optional includes are entries of `include`, so the order is the list's. const INCLUDE_OPTIONAL: &str = "include-optional"; /// The importers `path` names (`[meta.importer]`), its includes' first, its own over /// theirs. pub fn importers(path: &Path) -> Result { importers_inner(path, &mut Vec::new()) } fn importers_inner(path: &Path, loading: &mut Vec) -> Result { let canonical = path .canonicalize() .with_context(|| format!("configuration file {}", path.display()))?; if loading.contains(&canonical) { bail!("{} includes itself (through {:?})", path.display(), loading); } let dir = canonical .parent() .map(Path::to_owned) .unwrap_or_else(|| PathBuf::from("/")); let mut root = parse(&canonical)?; let includes = take_includes(&mut root, &canonical)?; let mut named = import::Importers::new(); loading.push(canonical.clone()); for (include, required) in includes { let include = dir.join(include); if !required && !include.exists() { continue; } named.extend( importers_inner(&include, loading) .with_context(|| format!("included from {}", canonical.display()))?, ); } loading.pop(); named .extend(take_meta(&mut root, &dir).with_context(|| format!("in {}", canonical.display()))?); Ok(named) } /// What `root` says under `meta`, taken out of it: the importers it names. fn take_meta(root: &mut JsonMap, dir: &Path) -> Result { let Some(meta) = root.remove(META) else { return Ok(import::Importers::new()); }; let JsonValue::Object(mut meta) = meta else { bail!("meta must be a table"); }; let importers = match meta.remove(IMPORTERS) { None => import::Importers::new(), Some(JsonValue::Object(table)) => import::named_in_table(&table, dir)?, Some(other) => bail!("meta.importer must be a table, not {other}"), }; if let Some(unknown) = meta.keys().next() { bail!("unknown key {unknown:?} in meta"); } Ok(importers) } /// The settings `path` makes of the options of `schema`, as `load_in`, by the /// importers it names itself. pub fn load(path: &Path, schema: &Schema) -> Result { load_in(path, schema, &importers(path)?) } /// The settings `path` makes of the options of `schema`, its includes resolved: a key /// naming none of them is an error. `named` are the importers the configuration /// names, here and elsewhere. pub fn load_in(path: &Path, schema: &Schema, named: &import::Importers) -> Result { load_inner(path, schema, named, &mut Vec::new()) } fn load_inner( path: &Path, schema: &Schema, named: &import::Importers, loading: &mut Vec, ) -> Result { let canonical = path .canonicalize() .with_context(|| format!("configuration file {}", path.display()))?; if loading.contains(&canonical) { bail!("{} includes itself (through {:?})", path.display(), loading); } let dir = canonical .parent() .map(Path::to_owned) .unwrap_or_else(|| PathBuf::from("/")); let mut root = parse(&canonical)?; if root.contains_key(INCLUDE_OPTIONAL) { bail!( "{}: include-optional is gone; list the file in include as {{ path = \"…\", optional = true }}, where it goes in the order", canonical.display() ); } let includes = take_includes(&mut root, &canonical)?; // Read apart, for every file and argument (`importers`). take_meta(&mut root, &dir).with_context(|| format!("in {}", canonical.display()))?; let unsets = take_paths(&mut root, UNSET, &canonical)?; loading.push(canonical.clone()); let mut layer = Layer::new(); for (include, required) in includes { let include = dir.join(include); if !required && !include.exists() { #[cfg(feature = "tracing")] tracing::debug!(file = %include.display(), "Optional configuration file is missing; skipped"); continue; } let included = load_inner(&include, schema, named, loading) .with_context(|| format!("included from {}", canonical.display()))?; for (name, entry) in included { overlay(&mut layer, name, entry, Overlay::IncludeOverInclude, schema); } } loading.pop(); for name in unsets { if schema.spec(&name).is_none() { if let Some(why) = schema.gone(&name) { bail!( "option {name:?} in unset, in {}, is gone: {why}", canonical.display() ); } bail!( "unknown option {name:?} in unset, in {}", canonical.display() ); } let entry = unset_entry(Provenance::File(canonical.clone())); overlay(&mut layer, name, entry, Overlay::FileOverFile, schema); } let mut own = Vec::new(); flatten(&root, "", &dir, named, &mut own) .with_context(|| format!("in {}", canonical.display()))?; for (name, value) in own { let spec = schema.spec(&name).ok_or_else(|| match schema.gone(&name) { Some(why) => anyhow!("option {name:?} in {} is gone: {why}", canonical.display()), None => anyhow!("unknown option {name:?} in {}", canonical.display()), })?; let (value, sources) = resolve_file_value_in(spec, value, &dir, named) .with_context(|| format!("option {name} in {}", canonical.display()))?; let entry = Entry { origin: sources.origin( Provenance::File(canonical.clone()), value.is_null(), spec.kind, ), value, }; overlay(&mut layer, name, entry, Overlay::FileOverFile, schema); } Ok(layer) } fn parse(path: &Path) -> Result> { let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; let value: JsonValue = match path.extension().and_then(|e| e.to_str()) { #[cfg(feature = "toml")] Some("toml") => { let value: toml::Value = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; serde_json::to_value(value).with_context(|| format!("converting {}", path.display()))? } #[cfg(not(feature = "toml"))] Some("toml") => bail!( "{}: this program reads no TOML (it is built without the config crate's feature \ toml): use .json", path.display() ), Some("json") => { serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))? } _ => bail!( "{}: unknown configuration format (use .toml or .json)", path.display() ), }; match value { JsonValue::Object(map) => Ok(map), _ => bail!("{}: the top level must be a table", path.display()), } } /// The files `include` names, in its order, and whether each is required: a path, or /// `{ path = "…", optional = true }`. fn take_includes( root: &mut JsonMap, path: &Path, ) -> Result> { let items = match root.remove(INCLUDE) { None => return Ok(Vec::new()), Some(JsonValue::Array(items)) => items, Some(single) => vec![single], }; items .into_iter() .map(|item| match item { JsonValue::String(file) => Ok((file, true)), JsonValue::Object(mut entry) => { let file = match entry.remove("path") { Some(JsonValue::String(file)) => file, _ => bail!("{}: an include entry needs a path", path.display()), }; let optional = match entry.remove("optional") { None => false, Some(JsonValue::Bool(optional)) => optional, Some(other) => bail!( "{}: include's optional is true or false, not {other}", path.display() ), }; if let Some(key) = entry.keys().next() { bail!( "{}: unknown key {key:?} in an include entry", path.display() ); } Ok((file, !optional)) } other => Err(anyhow!( "{}: include entries are paths or {{ path, optional }}, not {other}", path.display() )), }) .collect() } fn take_paths( root: &mut JsonMap, key: &str, path: &Path, ) -> Result> { match root.remove(key) { None => Ok(Vec::new()), Some(JsonValue::String(single)) => Ok(vec![single]), Some(JsonValue::Array(items)) => items .into_iter() .map(|item| match item { JsonValue::String(item) => Ok(item), other => Err(anyhow!( "{}: {key} entries must be paths, not {other}", path.display() )), }) .collect(), Some(other) => bail!( "{}: {key} must be a list of paths, not {other}", path.display() ), } } /// Option names and values, with nested tables joined by `-`. Importer tables are /// values, not nesting. fn flatten( table: &JsonMap, prefix: &str, dir: &Path, named: &import::Importers, out: &mut Vec<(String, JsonValue)>, ) -> Result<()> { for (key, value) in table { let name = if prefix.is_empty() { key.clone() } else { format!("{prefix}-{key}") }; match value { JsonValue::Object(nested) if import::parse_table_in(nested, dir, named)?.is_none() => { flatten(nested, &name, dir, named, out)? } _ => out.push((name, value.clone())), } } Ok(()) }