capy-cli 0.9.0

The command-line interface for the Capy web framework.
Documentation
use anyhow::{bail, Context, Result};
use heck::ToSnakeCase;
use std::collections::BTreeSet;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
    String,
    Text,
    Boolean,
    Integer,
    Bigint,
    Float,
    Uuid,
    Datetime,
    Date,
}

#[derive(Clone, Debug)]
pub(crate) struct Field {
    pub name: String,
    pub kind: Kind,
    pub nullable: bool,
    pub unique: bool,
    pub index: bool,
    pub default: Option<String>,
}

impl Field {
    pub fn parse_all(definitions: &[String]) -> Result<Vec<Self>> {
        if definitions.is_empty() || definitions.len() > 32 {
            bail!(
                "A resource needs 1..=32 fields, for example title:string published:boolean=false."
            );
        }
        let mut names = BTreeSet::new();
        definitions
            .iter()
            .map(|definition| {
                let field = Self::parse(definition)
                    .with_context(|| format!("Invalid resource field `{definition}`"))?;
                if !names.insert(field.name.clone()) {
                    bail!("Duplicate resource field `{}`.", field.name);
                }
                Ok(field)
            })
            .collect()
    }

    fn parse(definition: &str) -> Result<Self> {
        let (shape, default) = definition
            .split_once('=')
            .map_or((definition, None), |(shape, value)| {
                (shape, Some(value.to_owned()))
            });
        let mut parts = shape.split(':');
        let name = parts.next().unwrap_or_default();
        crate::names::validate_name(name, false)?;
        if name != name.to_snake_case()
            || name.len() > 48
            || name.bytes().any(|c| c.is_ascii_uppercase())
            || name == "id"
            || name.starts_with('_')
        {
            bail!("Use a lowercase snake_case field name; `id` is generated automatically.");
        }
        let ty = parts
            .next()
            .context("Expected name:type, for example title:string")?;
        let nullable = ty.ends_with('?');
        let kind = match ty.trim_end_matches('?') {
            "string" => Kind::String, "text" => Kind::Text, "boolean" => Kind::Boolean,
            "integer" => Kind::Integer, "bigint" => Kind::Bigint, "float" => Kind::Float,
            "uuid" => Kind::Uuid, "datetime" => Kind::Datetime, "date" => Kind::Date,
            "decimal" => bail!("Decimal fields are not generated in 0.9. Use bigint minor units (string on the JSON wire), or add an application-owned decimal type and schema."),
            _ => bail!("Supported field types: string, text, boolean, integer, bigint, float, uuid, datetime, date; append ? for nullable."),
        };
        if ty.matches('?').count() > 1 {
            bail!("Use a single trailing ? for nullable fields.");
        }
        let mut field = Self {
            name: name.into(),
            kind,
            nullable,
            unique: false,
            index: false,
            default,
        };
        for flag in parts {
            match flag {
                "unique" if !field.unique => field.unique = true,
                "index" if !field.index => field.index = true,
                _ => bail!("Unknown or repeated modifier `{flag}`; use :unique or :index."),
            }
        }
        if field.unique && field.index {
            bail!(":unique already creates an index; do not combine it with :index.");
        }
        if let Some(value) = &field.default {
            field.validate_literal(value)?;
            // One canonical constant feeds Rust, SQL, JSON and browser defaults.
            // In particular +001 must not become a different bigint string on read.
            if !(field.nullable && value == "null") {
                field.default = Some(match field.kind {
                    Kind::Integer | Kind::Bigint => value.parse::<i64>()?.to_string(),
                    Kind::Float => value.parse::<f64>()?.to_string(),
                    Kind::Uuid => uuid::Uuid::parse_str(value)?.to_string(),
                    Kind::Datetime => chrono::DateTime::parse_from_rfc3339(value)?
                        .with_timezone(&chrono::Utc)
                        .to_rfc3339(),
                    Kind::Date => chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d")?.to_string(),
                    _ => value.clone(),
                });
            }
        }
        Ok(field)
    }

    fn validate_literal(&self, value: &str) -> Result<()> {
        if value == "null" && self.nullable {
            return Ok(());
        }
        match self.kind {
            Kind::String | Kind::Text => {
                let max = if self.kind == Kind::String {
                    255
                } else {
                    50_000
                };
                if value.is_empty() || value.chars().count() > max {
                    bail!("String defaults must contain 1..={max} characters.");
                }
            }
            Kind::Boolean => {
                value
                    .parse::<bool>()
                    .context("Boolean defaults must be true or false")?;
            }
            Kind::Integer => {
                value
                    .parse::<i32>()
                    .context("Integer defaults must fit i32")?;
            }
            Kind::Bigint => {
                value
                    .parse::<i64>()
                    .context("Bigint defaults must fit i64")?;
            }
            Kind::Float => {
                if !value
                    .parse::<f64>()
                    .context("Float defaults must be numeric")?
                    .is_finite()
                {
                    bail!("Float defaults must be finite JSON numbers.");
                }
            }
            Kind::Uuid => {
                uuid::Uuid::parse_str(value).context("UUID defaults must be valid UUIDs")?;
            }
            Kind::Datetime => {
                let datetime = chrono::DateTime::parse_from_rfc3339(value)
                    .context("Datetime defaults must include an RFC3339 timezone")?;
                let year = chrono::Datelike::year(&datetime.with_timezone(&chrono::Utc));
                if !(1..=9999).contains(&year)
                    || datetime.timestamp_subsec_nanos() >= 1_000_000_000
                    || !datetime.timestamp_subsec_nanos().is_multiple_of(1000)
                {
                    bail!("Portable datetime defaults require UTC years 0001..9999, no leap seconds and at most microsecond precision.");
                }
            }
            Kind::Date => {
                let date = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d")
                    .context("Date defaults must use YYYY-MM-DD")?;
                if !(1..=9999).contains(&chrono::Datelike::year(&date)) {
                    bail!("Portable date defaults require years 0001..9999.");
                }
            }
        }
        Ok(())
    }

    pub fn entity_type(&self) -> String {
        self.wrap(match self.kind {
            Kind::String | Kind::Text => "String",
            Kind::Boolean => "bool",
            Kind::Integer => "i32",
            Kind::Bigint => "i64",
            Kind::Float => "f64",
            Kind::Uuid => "capy::uuid::Uuid",
            Kind::Datetime => "capy::chrono::DateTime<capy::chrono::FixedOffset>",
            Kind::Date => "capy::chrono::NaiveDate",
        })
    }

    pub fn wire_type(&self) -> String {
        if self.kind == Kind::Bigint {
            self.wrap("String")
        } else {
            self.entity_type()
        }
    }

    fn wrap(&self, ty: &str) -> String {
        if self.nullable {
            format!("Option<{ty}>")
        } else {
            ty.into()
        }
    }

    /// An ordinary Rust literal/expression; only validated input reaches code generation.
    pub fn literal(&self, value: &str, wire: bool) -> String {
        if value == "null" && self.nullable {
            return "None".into();
        }
        let literal = match self.kind {
            Kind::String | Kind::Text => format!("{value:?}.to_owned()"),
            Kind::Bigint if wire => format!("{value:?}.to_owned()"),
            Kind::Boolean => value.to_owned(),
            Kind::Integer | Kind::Bigint => {
                value.parse::<i64>().expect("validated integer").to_string()
            }
            Kind::Float => format!("{:?}_f64", value.parse::<f64>().expect("validated float")),
            Kind::Uuid | Kind::Datetime | Kind::Date => {
                format!("{value:?}.parse().expect(\"validated generated default\")")
            }
        };
        if self.nullable {
            format!("Some({literal})")
        } else {
            literal
        }
    }

    pub fn sample(&self) -> &str {
        self.default.as_deref().unwrap_or(match self.kind {
            Kind::String => "Example",
            Kind::Text => "Example content",
            Kind::Boolean => "false",
            Kind::Integer | Kind::Bigint => "1",
            Kind::Float => "1.5",
            Kind::Uuid => "00000000-0000-4000-8000-000000000001",
            Kind::Datetime => "2026-01-01T00:00:00+00:00",
            Kind::Date => "2026-01-01",
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_types_modifiers_and_literals_are_validated_before_generation() {
        for definition in [
            "title:string",
            "body:text",
            "active:boolean=false",
            "count:integer=-42",
            "amount:bigint=9223372036854775807",
            "ratio:float=1.25",
            "key:uuid=00000000-0000-4000-8000-000000000001",
            "created_at:datetime=2026-01-01T00:00:00Z",
            "created_at:datetime=2026-01-01T00:00:00.123456Z",
            "birthday:date=2024-02-29",
            "slug:string:unique",
            "category:integer:index",
            "published_at:datetime?",
            "title:string?=null",
            "caption:string?=Hello=world",
        ] {
            let field = Field::parse_all(&[definition.into()])
                .unwrap_or_else(|error| panic!("{definition}: {error:#}"));
            if let Some(default) = &field[0].default {
                syn::parse_str::<syn::Expr>(&field[0].literal(default, true)).unwrap();
            }
        }
        assert_eq!(Field::parse("amount:bigint").unwrap().wire_type(), "String");
        assert_eq!(
            Field::parse("amount:bigint?").unwrap().entity_type(),
            "Option<i64>"
        );
        assert_eq!(
            Field::parse("amount:bigint=+001")
                .unwrap()
                .default
                .as_deref(),
            Some("1")
        );
        assert_eq!(
            Field::parse("key:uuid=123E4567E89B12D3A456426614174000")
                .unwrap()
                .default
                .as_deref(),
            Some("123e4567-e89b-12d3-a456-426614174000")
        );
        assert_eq!(
            Field::parse("occurred:datetime=2026-01-01T12:00:00+02:00")
                .unwrap()
                .default
                .as_deref(),
            Some("2026-01-01T10:00:00+00:00")
        );
    }

    #[test]
    fn invalid_or_ambiguous_definitions_are_rejected() {
        for definition in [
            "",
            "title",
            "title:unknown",
            "title:string??",
            "id:integer",
            "Title:string",
            "type:string",
            "x:string:unique:index",
            "x:string:index:index",
            "x:boolean=1",
            "x:integer=2147483648",
            "x:bigint=9223372036854775808",
            "x:float=NaN",
            "x:float=inf",
            "x:uuid=no",
            "x:datetime=2026-01-01",
            "x:datetime=2026-01-01T00:00:00.123456789Z",
            "x:datetime=2016-12-31T23:59:60Z",
            "x:datetime=0000-01-01T00:00:00Z",
            "x:datetime=9999-12-31T23:59:59-01:00",
            "x:date=2026-02-30",
            "x:date=0000-01-01",
            "x:date=+10000-01-01",
            "x:string=",
            "x:boolean=null",
            "x:string:default",
            "x:decimal",
            "a/b:string",
            "x:integer=1;panic!()",
        ] {
            assert!(
                Field::parse_all(&[definition.into()]).is_err(),
                "{definition}"
            );
        }
        assert!(Field::parse_all(&[]).is_err());
        assert!(Field::parse_all(&["name:string".into(), "name:text".into()]).is_err());
    }
}