use std::collections::BTreeMap;
use crate::schema::ValueDef;
use crate::value::Value;
pub const INTERFACE_VERSION: u32 = 2;
pub const MIN_INTERFACE_VERSION: u32 = 1;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Needs {
pub required: Vec<String>,
pub order: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Choice {
pub id: String,
pub reason: String,
}
impl Choice {
pub fn new(id: &str, reason: &str) -> Self {
Choice {
id: id.to_owned(),
reason: reason.to_owned(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ActionKind {
Note,
DataTransfer {
from: String,
to: String,
},
Step(Box<crate::exec::Step>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Action {
pub description: String,
pub kind: ActionKind,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Plan {
pub actions: Vec<Action>,
}
pub trait Module {
fn name(&self) -> &str;
fn interface_version(&self) -> u32 {
MIN_INTERFACE_VERSION
}
fn list_choices(&self, needs: &Needs) -> Vec<Choice>;
fn validate(&self, value: &Value) -> Result<(), String>;
fn validate_for(&self, def: &ValueDef, value: &Value) -> Result<(), String> {
let _ = def;
self.validate(value)
}
fn validate_all(&self, values: &[(&str, &Value)]) -> Vec<(String, String)> {
let _ = values;
Vec::new()
}
fn on_change(&self, old: &Value, new: &Value) -> Plan {
let _ = (old, new);
Plan::default()
}
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ModuleError {
#[error("module `{module}` speaks interface version {got}; this library speaks {want}")]
InterfaceMismatch {
module: String,
got: u32,
want: u32,
},
#[error("a module named `{0}` is already registered")]
Duplicate(String),
}
#[derive(Default)]
pub struct Modules {
by_name: BTreeMap<String, Box<dyn Module>>,
}
impl Modules {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, module: Box<dyn Module>) -> Result<(), ModuleError> {
let name = module.name().to_owned();
if !(MIN_INTERFACE_VERSION..=INTERFACE_VERSION).contains(&module.interface_version()) {
return Err(ModuleError::InterfaceMismatch {
module: name,
got: module.interface_version(),
want: INTERFACE_VERSION,
});
}
if self.by_name.contains_key(&name) {
return Err(ModuleError::Duplicate(name));
}
self.by_name.insert(name, module);
Ok(())
}
pub fn get(&self, name: &str) -> Option<&dyn Module> {
self.by_name.get(name).map(|m| m.as_ref())
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.by_name.keys().map(String::as_str)
}
}
pub struct ChoiceList {
name: String,
choices: Vec<Choice>,
}
impl ChoiceList {
pub fn new(name: &str, choices: Vec<Choice>) -> Self {
ChoiceList {
name: name.to_owned(),
choices,
}
}
}
impl Module for ChoiceList {
fn name(&self) -> &str {
&self.name
}
fn list_choices(&self, _needs: &Needs) -> Vec<Choice> {
self.choices.clone()
}
fn validate(&self, value: &Value) -> Result<(), String> {
let id = match value {
Value::String(s) | Value::Enum(s) => s,
other => {
return Err(format!(
"expected a choice id, found {}",
other.type_of().name()
));
}
};
if self.choices.iter().any(|c| &c.id == id) {
Ok(())
} else {
let ids: Vec<&str> = self.choices.iter().map(|c| c.id.as_str()).collect();
Err(format!("`{id}` is not one of: {}", ids.join(", ")))
}
}
fn on_change(&self, old: &Value, new: &Value) -> Plan {
match (old, new) {
(Value::String(a) | Value::Enum(a), Value::String(b) | Value::Enum(b)) if a != b => {
Plan {
actions: vec![Action {
description: format!("`{}` changed from `{a}` to `{b}`", self.name),
kind: ActionKind::Note,
}],
}
}
_ => Plan::default(),
}
}
}