use serde_json::{json, Value};
mod shapes;
use shapes::all as described_shapes;
const CONDITIONAL_FIELDS: &[(&str, &str, &str)] = &[
(
"meta commands",
"globals",
"arrives only with `--with-globals`, because the invocation-wide flags are \
published once here rather than repeated under all sixty-three commands",
),
(
"conn test",
"warning",
"arrives only when the server gave cause for one, so its absence is the \
ordinary answer and never a field that went missing",
),
];
#[must_use]
pub fn conditional_fields() -> Vec<(&'static str, &'static str)> {
CONDITIONAL_FIELDS
.iter()
.map(|(leaf, field, _)| (*leaf, *field))
.collect()
}
#[must_use]
pub fn field_is_conditional(command: &str, field: &str) -> bool {
CONDITIONAL_FIELDS
.iter()
.any(|(leaf, name, _)| *leaf == command && *name == field)
}
const DATA_SHAPE_VARIES: &[(&str, &str)] = &[(
"meta schema",
"this command answers with a different set of fields depending on what was asked: a listing \
when nothing is named, a contract when a command is named, a shorter one when a group is \
named, and one further field when the named command marks absence; validate the answer you \
asked for rather than a single published shape",
)];
#[must_use]
pub fn data_shape_of(command: &str) -> Value {
if let Some((_, why)) = DATA_SHAPE_VARIES.iter().find(|(name, _)| *name == command) {
return json!({ "shape_varies_by_input": why });
}
let Some((_, fields)) = described_shapes().find(|(name, _)| *name == command) else {
return json!({
"declared_limit": "the fields of `data` are not published for this command in this \
build; a caller that must validate them reads them from an answer and not from \
here",
});
};
let mut shape = serde_json::Map::new();
for (field, about) in *fields {
let described = CONDITIONAL_FIELDS
.iter()
.find(|(leaf, name, _)| *leaf == command && name == field)
.map_or_else(
|| (*about).to_owned(),
|(_, _, when)| format!("{about}; {when}"),
);
shape.insert((*field).to_owned(), Value::String(described));
}
Value::Object(shape)
}
#[must_use]
pub fn commands_with_published_data() -> Vec<&'static str> {
described_shapes().map(|(name, _)| *name).collect()
}
#[must_use]
pub fn commands_whose_data_varies() -> Vec<&'static str> {
DATA_SHAPE_VARIES.iter().map(|(name, _)| *name).collect()
}