This commit is contained in:
nora 2024-04-15 20:00:29 +02:00
parent f3c37539f0
commit e0f753c0c2
2 changed files with 21 additions and 8 deletions

View file

@ -4,7 +4,7 @@ use terustform::{
framework::{ framework::{
datasource::{self, DataSource}, datasource::{self, DataSource},
provider::Provider, provider::Provider,
AttrPath, DResult, Diagnostics, StringValue, ValueModel, AttrPath, DResult, StringValue, ValueModel,
}, },
values::Value, values::Value,
}; };
@ -75,11 +75,8 @@ impl DataSource for ExampleDataSource {
fn read(&self, config: Value) -> DResult<Value> { fn read(&self, config: Value) -> DResult<Value> {
let mut model = ExampleDataSourceModel::from_value(config, &AttrPath::root())?; let mut model = ExampleDataSourceModel::from_value(config, &AttrPath::root())?;
let StringValue::Known(name_str) = &model.name else { let name_str = model.name.expect_known(AttrPath::attr("name"))?;
return Err(Diagnostics::error_string(
"model name must be known".to_owned(),
));
};
let meow = format!("mrrrrr i am {name_str}"); let meow = format!("mrrrrr i am {name_str}");
model.meow = StringValue::Known(meow); model.meow = StringValue::Known(meow);

View file

@ -17,9 +17,9 @@ pub struct Diagnostics {
pub type DResult<T> = Result<T, Diagnostics>; pub type DResult<T> = Result<T, Diagnostics>;
impl Diagnostics { impl Diagnostics {
pub fn error_string(msg: String) -> Self { pub fn error_string(msg: impl Into<String>) -> Self {
Self { Self {
errors: vec![msg], errors: vec![msg.into()],
attr: None, attr: None,
} }
} }
@ -56,6 +56,9 @@ impl AttrPath {
pub fn root() -> Self { pub fn root() -> Self {
Self::default() Self::default()
} }
pub fn attr(name: impl Into<String>) -> Self {
Self(vec![AttrPathSegment::AttributeName(name.into())])
}
pub fn append_attribute_name(&self, name: String) -> Self { pub fn append_attribute_name(&self, name: String) -> Self {
let mut p = self.clone(); let mut p = self.clone();
p.0.push(AttrPathSegment::AttributeName(name)); p.0.push(AttrPathSegment::AttributeName(name));
@ -85,6 +88,19 @@ impl<T> BaseValue<T> {
Self::Known(v) => BaseValue::Known(f(v)?), Self::Known(v) => BaseValue::Known(f(v)?),
}) })
} }
pub fn expect_known(&self, path: AttrPath) -> DResult<&T> {
match self {
BaseValue::Null => {
Err(Diagnostics::error_string("expected value, found null value").with_path(path))
}
BaseValue::Unknown => Err(Diagnostics::error_string(
"expected known value, found unknown value",
)
.with_path(path)),
BaseValue::Known(v) => Ok(v),
}
}
} }
pub trait ValueModel: Sized { pub trait ValueModel: Sized {