Skip to main content

stratum_node_cli/
changes.rs

1//! Parsing `--set path=value` arguments against the configuration schema.
2
3use stratum_node_config::{schema, Change, Value, ValueType};
4
5/// Parses `--set path=value` arguments into configuration changes, typed by
6/// the schema in `stratum-node-config`.
7///
8/// Each argument is split at its first `=`. The path must name a schema
9/// field, and the value is read according to that field's type:
10///
11/// - **boolean**: `true` or `false`;
12/// - **integer**: a decimal integer, optionally negative (the node checks
13///   the range);
14/// - **string**, **enum** and **secret reference**: the text as given,
15///   which may be empty;
16/// - **list of strings**: comma-separated elements (`a,b`), or the same path
17///   given in several `--set` arguments, whose elements are concatenated in
18///   order. An empty value (`path=`) is the empty list. Elements cannot be
19///   empty and cannot contain a comma.
20///
21/// Changes come out in the order their paths first appear; the node applies
22/// them in schema order regardless.
23///
24/// # Examples
25///
26/// ```
27/// use stratum_node_cli::parse_changes;
28/// use stratum_node_config::Value;
29///
30/// # fn main() -> Result<(), stratum_node_cli::ParseChangeError> {
31/// let changes = parse_changes([
32///     "node.name=alpha",
33///     "limits.max_body_bytes=65536",
34///     "federation.egress_enabled=false",
35/// ])?;
36/// assert_eq!(changes[0].value(), &Value::String("alpha".into()));
37/// assert_eq!(changes[1].value(), &Value::Integer(65_536));
38/// assert_eq!(changes[2].value(), &Value::Boolean(false));
39///
40/// assert!(parse_changes(["no.such.field=1"]).is_err());
41/// # Ok(())
42/// # }
43/// ```
44///
45/// # Errors
46///
47/// Returns a [`ParseChangeError`] for an argument without `=`, an unknown
48/// path, a value that does not read as the field's type, or a non-list path
49/// given twice.
50pub fn parse_changes<I, S>(args: I) -> Result<Vec<Change>, ParseChangeError>
51where
52    I: IntoIterator<Item = S>,
53    S: AsRef<str>,
54{
55    let mut parsed: Vec<(String, Value)> = Vec::new();
56    for arg in args {
57        let arg = arg.as_ref();
58        let (path, raw) = arg
59            .split_once('=')
60            .ok_or_else(|| ParseChangeError::MissingEquals {
61                argument: arg.to_owned(),
62            })?;
63        let field = schema()
64            .field(path)
65            .ok_or_else(|| ParseChangeError::UnknownPath {
66                path: path.to_owned(),
67            })?;
68        let value = parse_value(path, field.value_type(), raw)?;
69        match parsed.iter_mut().find(|(seen, _)| seen == path) {
70            None => parsed.push((path.to_owned(), value)),
71            Some((_, Value::StringList(existing))) => match value {
72                Value::StringList(more) => existing.extend(more),
73                _ => {
74                    return Err(ParseChangeError::Repeated {
75                        path: path.to_owned(),
76                    })
77                }
78            },
79            Some(_) => {
80                return Err(ParseChangeError::Repeated {
81                    path: path.to_owned(),
82                })
83            }
84        }
85    }
86    Ok(parsed
87        .into_iter()
88        .map(|(path, value)| Change::new(path, value))
89        .collect())
90}
91
92/// Reads `raw` as a value of type `value_type`.
93fn parse_value(path: &str, value_type: ValueType, raw: &str) -> Result<Value, ParseChangeError> {
94    let invalid = |expected: &'static str| ParseChangeError::InvalidValue {
95        path: path.to_owned(),
96        expected,
97    };
98    match value_type {
99        ValueType::Boolean => match raw {
100            "true" => Ok(Value::Boolean(true)),
101            "false" => Ok(Value::Boolean(false)),
102            _ => Err(invalid("true or false")),
103        },
104        ValueType::Integer { .. } => raw
105            .parse::<i64>()
106            .map(Value::Integer)
107            .map_err(|_| invalid("a decimal integer")),
108        ValueType::String | ValueType::Enum { .. } | ValueType::SecretRef => {
109            Ok(Value::String(raw.to_owned()))
110        }
111        ValueType::StringList => {
112            if raw.is_empty() {
113                return Ok(Value::StringList(Vec::new()));
114            }
115            let elements: Vec<String> = raw.split(',').map(str::to_owned).collect();
116            if elements.iter().any(String::is_empty) {
117                return Err(invalid("comma-separated non-empty strings"));
118            }
119            Ok(Value::StringList(elements))
120        }
121        _ => Err(ParseChangeError::UnsupportedType {
122            path: path.to_owned(),
123        }),
124    }
125}
126
127/// Why a `--set` argument could not be parsed.
128///
129/// Values are never quoted back, since a value may be a secret reference.
130#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
131#[non_exhaustive]
132pub enum ParseChangeError {
133    /// The argument has no `=`.
134    #[error("--set {argument:?} is not of the form path=value")]
135    MissingEquals {
136        /// The argument as given.
137        argument: String,
138    },
139    /// The path is not a field of the configuration schema.
140    #[error("--set: unknown configuration path {path:?} (see `stratum config schema`)")]
141    UnknownPath {
142        /// The path as given.
143        path: String,
144    },
145    /// The value does not read as the field's type.
146    #[error("--set {path}: expected {expected}")]
147    InvalidValue {
148        /// The field's path.
149        path: String,
150        /// What the field accepts.
151        expected: &'static str,
152    },
153    /// A field that is not a list was given more than once.
154    #[error("--set {path} given more than once")]
155    Repeated {
156        /// The field's path.
157        path: String,
158    },
159    /// The field has a type this version of the client cannot write.
160    #[error("--set {path}: this client cannot write values of this field's type")]
161    UnsupportedType {
162        /// The field's path.
163        path: String,
164    },
165}