Skip to main content

spin_templates/
constraints.rs

1use regex::Regex;
2
3#[derive(Clone, Debug)]
4pub(crate) struct StringConstraints {
5    pub regex: Option<Regex>,
6    pub allowed_values: Option<Vec<String>>,
7}
8
9impl StringConstraints {
10    pub fn validate(&self, text: String) -> anyhow::Result<String> {
11        if let Some(regex) = self.regex.as_ref()
12            && !regex.is_match(&text)
13        {
14            anyhow::bail!("Input '{}' does not match pattern '{}'", text, regex);
15        }
16        if let Some(allowed_values) = self.allowed_values.as_ref()
17            && !allowed_values.contains(&text)
18        {
19            anyhow::bail!(
20                "Input '{}' is not one of the allowed values ({})",
21                text,
22                allowed_values.join(", ")
23            );
24        }
25        Ok(text)
26    }
27}