* claim: #11059 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Configuration table, rules, activate and preview: schemas (#11059) config.table, config.rules, config.activate and config.preview get typed contracts and reply types in schema/config.rs and leave unconverted.txt. A new `table` builds the table from ConfigTable; show and the activation build their replies from it, so the unconverted config commands still return the same JSON. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
90e30126ea
commit
38cc3507db
5 files changed
+261
-28
No files matched your search
@@ -7,27 +7,48 @@ use solidcraft_doc::config::{Column, ConfigRow, MAX_COLUMNS, MAX_ROWS};
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, str_, string_list};
|
||||
use crate::schema::config::{ConfigActivation, ConfigRowParams, ConfigTable, ConfigTableParams, ConfigTableReply, ConfigTableRow, ConfigTarget};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const TABLE_CONTRACT: TypedContract<ConfigTableParams> = TypedContract::new();
|
||||
const ROW_CONTRACT: TypedContract<ConfigRowParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("config.configure", "Configure", configure).at("SOLID", "CONFIGURE").icon("params").params(
|
||||
"params?: [parameter names]; features?: [feature names]; materials?: [body names]; appearances?: [body names] (columns to add; with no rows yet, a \"Default\" row takes the current values)",
|
||||
),
|
||||
CommandSpec::new("config.table", "Display Configuration Table", show)
|
||||
CommandSpec::new("config.table", "Display Configuration Table", crate::checked!("config.table", show))
|
||||
.at("SOLID", "CONFIGURE")
|
||||
.icon("configuration_table")
|
||||
.noundo()
|
||||
.contract(&TABLE_CONTRACT)
|
||||
.output(output_schema_for::<ConfigTableReply>)
|
||||
.params("→ columns (param:<name> or suppress:<feature>), rows, the active row and whether the design still matches it"),
|
||||
CommandSpec::new("config.column", "Configuration Column", column).icon("configuration_table").params("param? | feature? | material? | appearance? (target name); delete?: bool"),
|
||||
CommandSpec::new("config.row", "Configuration Row", row).icon("configuration_table").params(
|
||||
"name; from? (row to copy; default current values); values?: {column key: expression, suppression, material name, appearance name or Look object}; rename?; delete?: bool",
|
||||
),
|
||||
CommandSpec::new("config.activate", "Activate Configuration", activate).icon("activate").params("row: name — sets its parameter values and suppressions"),
|
||||
CommandSpec::new("config.preview", "Preview Configuration", preview).icon("eye").noundo().params("row: name — validates a rebuild without changing the design or history"),
|
||||
CommandSpec::new("config.activate", "Activate Configuration", crate::checked!("config.activate", activate))
|
||||
.icon("activate")
|
||||
.contract(&ROW_CONTRACT)
|
||||
.output(output_schema_for::<ConfigActivation>)
|
||||
.params("row: name — sets its parameter values and suppressions"),
|
||||
CommandSpec::new("config.preview", "Preview Configuration", crate::checked!("config.preview", preview))
|
||||
.icon("eye")
|
||||
.noundo()
|
||||
.contract(&ROW_CONTRACT)
|
||||
.output(output_schema_for::<ConfigActivation>)
|
||||
.params("row: name — validates a rebuild without changing the design or history"),
|
||||
CommandSpec::new("config.rule", "Configuration Rule", rule).icon("configuration_table").params(
|
||||
"rule?: {id,name,enabled,condition,effect}; rules?: [rule…] (added or replaced together, then the rows checked once); id? + delete?; id? + index? (ordered move)",
|
||||
),
|
||||
CommandSpec::new("config.rules", "Configuration Rules", show).icon("list").noundo().params("ordered typed rules, rows and active state"),
|
||||
CommandSpec::new("config.rules", "Configuration Rules", crate::checked!("config.rules", show))
|
||||
.icon("list")
|
||||
.noundo()
|
||||
.contract(&TABLE_CONTRACT)
|
||||
.output(output_schema_for::<ConfigTableReply>)
|
||||
.params("ordered typed rules, rows and active state"),
|
||||
];
|
||||
|
||||
fn column_of(s: &Session, p: &Value, cmd: &str) -> Result<Column> {
|
||||
@@ -166,14 +187,21 @@ fn configure(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn show(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let table = table(s, "config.table")?;
|
||||
to_reply("config.table", ConfigTableReply { table, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn to_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
/// The table as the read-only commands, and an activation after its switch, return it.
|
||||
fn table(s: &Session, cmd: &str) -> Result<ConfigTable> {
|
||||
let t = &s.doc.configs;
|
||||
let keys: Vec<String> = t.columns.iter().map(|c| s.doc.config_key(c)).collect();
|
||||
let rows: Vec<Value> = t
|
||||
.rows
|
||||
.iter()
|
||||
.map(|r| json!({"name": r.name, "values": keys.iter().zip(&r.cells).map(|(k, v)| (k.clone(), json!(v))).collect::<serde_json::Map<_, _>>()}))
|
||||
.collect();
|
||||
let targets: Vec<Value> = t
|
||||
let rows =
|
||||
t.rows.iter().map(|r| ConfigTableRow { name: r.name.clone(), values: keys.iter().cloned().zip(r.cells.iter().cloned()).collect() }).collect();
|
||||
let targets = t
|
||||
.columns
|
||||
.iter()
|
||||
.map(|column| {
|
||||
@@ -190,13 +218,22 @@ fn show(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => s.doc.config_key(column),
|
||||
};
|
||||
json!({"key":s.doc.config_key(column),"label":label,"target":column})
|
||||
let target = serde_json::to_value(column).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok(ConfigTarget { key: s.doc.config_key(column), label, target })
|
||||
})
|
||||
.collect();
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let rules = t.rules.iter().map(|r| serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))).collect::<Result<Vec<_>>>()?;
|
||||
let styles = s.doc.configuration_style_status(&s.model.state());
|
||||
Ok(
|
||||
json!({"columns": keys, "targets":targets, "rows": rows, "rules": t.rules, "active": t.active, "matches": s.doc.configuration_matches() && styles.is_ok(), "style_status":styles.as_ref().ok(),"style_error":styles.err().map(|error|error.to_string())}),
|
||||
)
|
||||
Ok(ConfigTable {
|
||||
columns: keys,
|
||||
targets,
|
||||
rows,
|
||||
rules,
|
||||
active: t.active.clone(),
|
||||
matches: s.doc.configuration_matches() && styles.is_ok(),
|
||||
style_error: styles.as_ref().err().map(|error| error.to_string()),
|
||||
style_status: styles.ok(),
|
||||
})
|
||||
}
|
||||
|
||||
fn column(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -412,6 +449,12 @@ fn rule(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
to_reply("config.activate", activation(s, p)?)
|
||||
}
|
||||
|
||||
/// Switch to the row `p` names and say what that did, as `config.activate` and
|
||||
/// `config.preview` return it.
|
||||
fn activation(s: &mut Session, p: &Value) -> Result<ConfigActivation> {
|
||||
let cmd = "config.activate";
|
||||
let r = str_(p, "row").ok_or_else(|| bad(cmd, "`row` is required"))?.to_string();
|
||||
let mut trial = s.scratch();
|
||||
@@ -437,19 +480,18 @@ fn activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc = trial.doc;
|
||||
s.settle_value_edit(&solved)?;
|
||||
let errors: Vec<String> = s.model.results.iter().filter_map(|x| x.error.clone()).collect();
|
||||
let mut out = show(s, p)?;
|
||||
out["errors"] = json!(errors);
|
||||
out["trace"] = json!(trace);
|
||||
out["styles"] = json!(styles);
|
||||
Ok(out)
|
||||
let trace = trace.iter().map(|t| serde_json::to_value(t).map_err(|e| bad(cmd, e.to_string()))).collect::<Result<Vec<_>>>()?;
|
||||
Ok(ConfigActivation { table: table(s, cmd)?, errors, trace, styles, preview: None, parameters: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "config.preview";
|
||||
let mut trial = s.scratch();
|
||||
let mut out = activate(&mut trial, p)?;
|
||||
out["preview"] = json!(true);
|
||||
out["parameters"] = json!(trial.doc.param_rows());
|
||||
Ok(out)
|
||||
let mut out = activation(&mut trial, p)?;
|
||||
out.preview = Some(true);
|
||||
out.parameters =
|
||||
Some(trial.doc.param_rows().iter().map(|r| serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))).collect::<Result<Vec<_>>>()?);
|
||||
to_reply(cmd, out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Contracts and result types for the configuration commands in `cmd/config.rs` that read the
|
||||
//! table and switch between its rows (#11059).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::check::whole;
|
||||
|
||||
/// The configuration table: its columns, rows and rules, the active row, and whether the design
|
||||
/// still matches it. Read-only.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ConfigTableParams {}
|
||||
|
||||
/// Switch to a configuration row: its parameter values, suppressions, materials and appearances
|
||||
/// are set, and its rules run. Refused, with nothing changed, when a feature that builds now
|
||||
/// would fail in it.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ConfigRowParams {
|
||||
/// The row, by name.
|
||||
#[serde(deserialize_with = "row")]
|
||||
pub row: String,
|
||||
}
|
||||
|
||||
/// The row's name, with the handler's message for anything that isn't text.
|
||||
fn row<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(D::Error::custom(whole("`row` is required"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration table, as `config.table` and `config.rules` return it and an activation
|
||||
/// returns it after the switch.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConfigTable {
|
||||
/// Each column's key: `param:<name>`, `suppress:<feature>`, or a material or appearance
|
||||
/// column's.
|
||||
pub columns: Vec<String>,
|
||||
/// Each column: its key, a label to show, and what it drives.
|
||||
pub targets: Vec<ConfigTarget>,
|
||||
/// The rows, in order.
|
||||
pub rows: Vec<ConfigTableRow>,
|
||||
/// The rules, in the order they run: `{id, name, enabled, condition, effect}` each.
|
||||
pub rules: Vec<Value>,
|
||||
/// The active row's name, or `null`.
|
||||
pub active: Option<String>,
|
||||
/// Whether the design still has the active row's values.
|
||||
pub matches: bool,
|
||||
/// Each style column's state, when it could be worked out.
|
||||
pub style_status: Option<Vec<Value>>,
|
||||
/// Why the style columns' state couldn't be worked out.
|
||||
pub style_error: Option<String>,
|
||||
}
|
||||
|
||||
/// One column of the table.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConfigTarget {
|
||||
pub key: String,
|
||||
/// What to show for it, such as `Component: Bracket`.
|
||||
pub label: String,
|
||||
/// What it drives, as the design file saves it.
|
||||
pub target: Value,
|
||||
}
|
||||
|
||||
/// One row of the table.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConfigTableRow {
|
||||
pub name: String,
|
||||
/// Its cell for each column, by column key.
|
||||
pub values: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// What `config.table` and `config.rules` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConfigTableReply {
|
||||
#[serde(flatten)]
|
||||
pub table: ConfigTable,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `config.activate` and `config.preview` return: the table after the switch, and what the
|
||||
/// switch did.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ConfigActivation {
|
||||
#[serde(flatten)]
|
||||
pub table: ConfigTable,
|
||||
/// The features that fail after the switch, `<name>: <error>` each, those that failed
|
||||
/// before included.
|
||||
pub errors: Vec<String>,
|
||||
/// What each rule did.
|
||||
pub trace: Vec<Value>,
|
||||
/// Each style column's state after the switch.
|
||||
pub styles: Vec<Value>,
|
||||
/// For `config.preview`: always true. The design and its history are unchanged.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preview: Option<bool>,
|
||||
/// For `config.preview`: the parameters as the row would set them, as `parameters.list`
|
||||
/// gives them.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameters: Option<Vec<Value>>,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{ConfigActivation, ConfigRowParams, ConfigTableParams, ConfigTableReply};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A box `W` long, with `W` and the box's suppression configured, a `Big` row and a
|
||||
/// `Without` row that suppresses the box.
|
||||
fn configured(s: &mut Session) {
|
||||
run(s, "parameters.add", json!({"name": "W", "expression": "10 mm"}));
|
||||
run(s, "solid.box", json!({"length": "W", "width": 10, "height": 10, "body_name": "A", "name": "Block"}));
|
||||
run(s, "config.configure", json!({"params": ["W"], "features": ["Block"]}));
|
||||
run(s, "config.row", json!({"name": "Big", "values": {"param:W": "20 mm"}}));
|
||||
run(s, "config.row", json!({"name": "Without", "values": {"suppress:Block": true}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<ConfigTableParams>(), &[]);
|
||||
assert_keys(input_schema_for::<ConfigRowParams>(), &["row"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("config.activate", json!({})),
|
||||
("config.activate", json!({"row": 5})),
|
||||
("config.activate", json!({"row": "Nope"})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// A preview runs the activation, whose messages name `config.activate`, where strict names
|
||||
/// `config.preview`; the message after the name is the same.
|
||||
#[test]
|
||||
fn a_preview_keeps_the_activations_messages_in_strict() {
|
||||
for p in [json!({}), json!({"row": 5}), json!({"row": "Nope"})] {
|
||||
let message = |level: ParamCheck| {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
s.execute("config.preview", &p).err().map(|e| e.to_string().split_once("`: ").map(|m| m.1.to_string()))
|
||||
};
|
||||
let off = message(ParamCheck::Off);
|
||||
assert!(off.as_ref().is_some_and(Option::is_some), "{p} should fail today");
|
||||
assert_eq!(message(ParamCheck::Strict), off, "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #11059: the table, the rules, an activation and a preview reply as their output schemas say,
|
||||
/// in Warn without warnings for good calls and with them for a misspelt key.
|
||||
#[test]
|
||||
fn configuration_commands_reply_with_their_schemas() {
|
||||
let (table, activation) = (output_schema_for::<ConfigTableReply>(), output_schema_for::<ConfigActivation>());
|
||||
let matches = |schema: &schemars::Schema, r: &Value, warned: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
|
||||
};
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
matches(&table, &run(&mut s, "config.table", json!({})), false);
|
||||
configured(&mut s);
|
||||
let r = run(&mut s, "config.table", json!({}));
|
||||
matches(&table, &r, false);
|
||||
assert_eq!((r["rows"].as_array().map(Vec::len), r["targets"].as_array().map(Vec::len)), (Some(3), Some(2)), "{r}");
|
||||
matches(&table, &run(&mut s, "config.rules", json!({})), false);
|
||||
let r = run(&mut s, "config.activate", json!({"row": "Big"}));
|
||||
matches(&activation, &r, false);
|
||||
assert!(r["active"] == "Big" && r.get("preview").is_none(), "{r}");
|
||||
let r = run(&mut s, "config.preview", json!({"row": "Without"}));
|
||||
matches(&activation, &r, false);
|
||||
assert!(r["preview"] == true && r["parameters"].is_array() && r["active"] == "Without", "{r}");
|
||||
assert_eq!(s.doc.configs.active.as_deref(), Some("Big"), "a preview changes nothing");
|
||||
matches(&table, &run(&mut s, "config.table", json!({"row": "Big"})), true);
|
||||
matches(&activation, &run(&mut s, "config.activate", json!({"row": "Default", "rows": 1})), true);
|
||||
}
|
||||
@@ -56,6 +56,7 @@ mod tests;
|
||||
// The contracts, by command file.
|
||||
pub mod bom;
|
||||
pub mod component;
|
||||
pub mod config;
|
||||
pub mod construct;
|
||||
pub mod edit;
|
||||
pub mod features;
|
||||
|
||||
@@ -42,14 +42,10 @@ component.replace_with_link
|
||||
component.revert_position
|
||||
component.unlock
|
||||
component.update_links
|
||||
config.activate
|
||||
config.column
|
||||
config.configure
|
||||
config.preview
|
||||
config.row
|
||||
config.rule
|
||||
config.rules
|
||||
config.table
|
||||
contact.check
|
||||
contact.create
|
||||
contact.disable_all
|
||||
|
||||
Reference in new issue
Block a user