odk-cli 0.1.0

ODK CLI - Unified schema compilation from TypeScript, WASM, or JSON to multiple targets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Python model generation.
//!
//! Emits a `models.py` of stdlib dataclasses with JSON round-tripping, one
//! dataclass per model and one `Literal` alias per string union.
//!
//! # Why dataclasses rather than pydantic
//!
//! Generated code inherits its dependencies onto every consumer. A schema
//! describing a file format (the motivating case is a DAW project document)
//! wants to be loadable in a notebook, a build script, or a CI job without
//! pulling a validation framework in first. Dataclasses are stdlib, and
//! `from_dict`/`to_dict` cover the round trip that matters.
//!
//! The cost is that this validates nothing beyond shape: an out-of-range value
//! that the JSON Schema would reject is preserved as-is. Constraints in the IR
//! are emitted as comments so they are visible, not enforced.
//!
//! # Ordering
//!
//! Definitions are emitted in dependency order where possible, and forward
//! references fall back to `from __future__ import annotations`, which makes
//! every annotation lazy and cycles harmless.

use std::collections::BTreeMap;

use odk_schema::{CompiledField, CompiledSchema, CompiledType, LiteralValue, ScalarType};

/// Generate Python models for a schema.
pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
    let mut output = BTreeMap::new();

    if schema.models.is_empty() && schema.unions.is_empty() {
        return output;
    }

    output.insert("models.py".to_string(), generate_models(schema));
    output
}

fn generate_models(schema: &CompiledSchema) -> String {
    let mut out = String::new();

    out.push_str(&format!(
        "\"\"\"{} models.\n\nGenerated by ODK. Do not edit by hand.\n\"\"\"\n\n",
        schema.name
    ));
    // lazy annotations so models can reference each other in any order
    out.push_str("from __future__ import annotations\n\n");
    out.push_str("from dataclasses import dataclass, field, fields, is_dataclass\n");
    out.push_str("from functools import lru_cache\n");
    out.push_str(
        "from typing import Any, Literal, Optional, Union, get_args, get_origin, get_type_hints\n\n\n",
    );

    for union in &schema.unions {
        let variants: Vec<String> = union
            .variants
            .iter()
            .map(|v| format!("\"{}\"", escape(&v.name)))
            .collect();

        if let Some(desc) = &union.description {
            out.push_str(&format!("# {}\n", one_line(desc)));
        }
        out.push_str(&format!(
            "{} = Literal[{}]\n\n",
            union.name,
            variants.join(", ")
        ));
    }

    if !schema.unions.is_empty() {
        out.push('\n');
    }

    for model in &schema.models {
        out.push_str(&dataclass(model));
        out.push('\n');
    }

    out.push_str(DECODE_HELPERS);
    out
}

fn dataclass(model: &odk_schema::CompiledModel) -> String {
    let mut out = String::new();

    out.push_str("@dataclass\n");
    out.push_str(&format!("class {}:\n", model.name));

    if let Some(desc) = &model.description {
        out.push_str(&format!("    \"\"\"{}\"\"\"\n\n", one_line(desc)));
    }

    if model.fields.is_empty() {
        out.push_str("    pass\n");
        return out;
    }

    // Required fields must precede defaulted ones, or the dataclass is invalid
    let (required, optional): (Vec<&CompiledField>, Vec<&CompiledField>) =
        model.fields.iter().partition(|f| f.optional != Some(true));

    for f in required.iter().chain(optional.iter()) {
        let is_optional = f.optional == Some(true);
        let annotation = if is_optional {
            format!("Optional[{}]", type_to_py(&f.field_type))
        } else {
            type_to_py(&f.field_type)
        };

        if let Some(desc) = &f.description {
            out.push_str(&format!("    # {}\n", one_line(desc)));
        }
        if let Some(note) = constraint_note(f) {
            out.push_str(&format!("    # {note}\n"));
        }

        let name = py_name(&f.name);
        // a JSON key that is not a Python identifier is carried in metadata so
        // the decoder can still find it
        let metadata = if name == f.name {
            String::new()
        } else {
            format!(", metadata={{\"json\": \"{}\"}}", escape(&f.name))
        };

        if is_optional {
            out.push_str(&format!(
                "    {name}: {annotation} = field(default=None{metadata})\n"
            ));
        } else if metadata.is_empty() {
            out.push_str(&format!("    {name}: {annotation}\n"));
        } else {
            out.push_str(&format!(
                "    {name}: {annotation} = field({})\n",
                &metadata[2..]
            ));
        }
    }

    out
}

/// Map an IR type onto a Python annotation.
fn type_to_py(t: &CompiledType) -> String {
    match t {
        CompiledType::Scalar { name } => scalar_to_py(name).to_string(),
        CompiledType::Array { items, .. } => format!("list[{}]", type_to_py(items)),
        CompiledType::Ref { name } => name.clone(),
        CompiledType::Literal { value } => match value {
            LiteralValue::String(s) => format!("Literal[\"{}\"]", escape(s)),
            LiteralValue::Number(n) => format!("Literal[{n}]"),
            LiteralValue::Bool(b) => format!("Literal[{}]", if *b { "True" } else { "False" }),
        },
        CompiledType::Union { variants } => {
            let parts: Vec<String> = variants.iter().map(type_to_py).collect();
            format!("Union[{}]", parts.join(", "))
        }
        // an inline object has no name to reference, so it stays a plain mapping
        CompiledType::Object { .. } => "dict[str, Any]".to_string(),
    }
}

fn scalar_to_py(s: &ScalarType) -> &'static str {
    match s {
        ScalarType::String
        | ScalarType::Date
        | ScalarType::Datetime
        | ScalarType::UtcDateTime
        | ScalarType::OffsetDateTime
        | ScalarType::PlainDate
        | ScalarType::PlainTime
        | ScalarType::Duration
        | ScalarType::Url => "str",
        ScalarType::Int32 | ScalarType::Int64 => "int",
        ScalarType::Float32 | ScalarType::Float64 => "float",
        ScalarType::Boolean => "bool",
        ScalarType::Bytes => "bytes",
        ScalarType::Unknown => "Any",
    }
}

/// Render a field's constraints as a human-readable note.
fn constraint_note(f: &CompiledField) -> Option<String> {
    let c = f.constraints.as_ref()?;
    let mut parts = Vec::new();

    if let Some(v) = c.min_length {
        parts.push(format!("minLength {v}"));
    }
    if let Some(v) = c.max_length {
        parts.push(format!("maxLength {v}"));
    }
    if let Some(v) = c.min_value {
        parts.push(format!("minimum {v}"));
    }
    if let Some(v) = c.max_value {
        parts.push(format!("maximum {v}"));
    }
    if let Some(v) = &c.pattern {
        parts.push(format!("pattern {v}"));
    }
    if let Some(v) = &c.format {
        parts.push(format!("format {v}"));
    }
    if let Some(v) = c.multiple_of {
        parts.push(format!("multipleOf {v}"));
    }

    if parts.is_empty() {
        None
    } else {
        // not enforced: dataclasses validate nothing, so this is documentation
        Some(format!("constraints: {}", parts.join(", ")))
    }
}

/// Python keywords that cannot be used as field names.
const KEYWORDS: &[&str] = &[
    "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif",
    "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is",
    "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "while",
    "with", "yield",
];

/// Make a JSON property name safe as a Python attribute.
fn py_name(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();

    let cleaned = if cleaned.chars().next().is_some_and(char::is_numeric) {
        format!("_{cleaned}")
    } else {
        cleaned
    };

    if KEYWORDS.contains(&cleaned.as_str()) {
        format!("{cleaned}_")
    } else {
        cleaned
    }
}

fn escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

/// Collapse a description to a single line so it cannot break out of a comment.
fn one_line(s: &str) -> String {
    s.replace(['\n', '\r'], " ").trim().to_string()
}

/// Decoding helpers appended to every generated module.
const DECODE_HELPERS: &str = r#"
def _json_key(f) -> str:
    """JSON key for a dataclass field, honoring a remapped name."""
    return f.metadata.get("json", f.name)


@lru_cache(maxsize=None)
def _hints(cls) -> dict[str, Any]:
    """Resolved annotations for a dataclass.

    `from __future__ import annotations` makes every annotation a string, so
    `field.type` is the text "Track", not the class. Resolving through
    get_type_hints is what lets nested models be rebuilt rather than left as
    dicts.
    """
    return get_type_hints(cls)


def _decode(value: Any, annotation: Any) -> Any:
    """Rebuild nested dataclasses from plain JSON values.

    Unknown or unannotated shapes pass through untouched, which keeps forward
    compatibility cheap: a document carrying fields this build has never heard
    of still loads.
    """
    if is_dataclass(annotation) and isinstance(value, dict):
        return from_dict(annotation, value)

    origin = get_origin(annotation)

    if origin is list and isinstance(value, list):
        (item_type,) = get_args(annotation) or (Any,)
        return [_decode(v, item_type) for v in value]

    if origin is Union:
        args = [a for a in get_args(annotation) if a is not type(None)]
        # Optional[T] is the overwhelmingly common case, and T can itself be a
        # list or a model, so decode through it rather than only unwrapping
        # dataclass members
        if len(args) == 1:
            return _decode(value, args[0])
        for arg in args:
            if is_dataclass(arg) and isinstance(value, dict):
                return from_dict(arg, value)
        return value

    return value


def from_dict(cls, data: dict[str, Any]):
    """Build a dataclass instance from parsed JSON."""
    hints = _hints(cls)
    kwargs = {}
    for f in fields(cls):
        key = _json_key(f)
        if key in data:
            kwargs[f.name] = _decode(data[key], hints.get(f.name, Any))
    return cls(**kwargs)


def to_dict(obj: Any) -> Any:
    """Convert a dataclass instance back to plain JSON values.

    Fields left as None are omitted rather than emitted as null, so an
    optional-by-absence schema round-trips to the same document it came from.
    """
    if is_dataclass(obj):
        out: dict[str, Any] = {}
        for f in fields(obj):
            value = getattr(obj, f.name)
            if value is None:
                continue
            out[_json_key(f)] = to_dict(value)
        return out

    if isinstance(obj, list):
        return [to_dict(v) for v in obj]

    return obj
"#;

#[cfg(test)]
mod tests {
    use super::*;
    use odk_schema::{CompiledModel, CompiledUnion, CompiledUnionVariant, FieldConstraints};

    fn scalar(name: ScalarType) -> CompiledType {
        CompiledType::Scalar { name }
    }

    fn schema_with(models: Vec<CompiledModel>) -> CompiledSchema {
        let mut schema = CompiledSchema::new("Test");
        for m in models {
            schema.add_model(m);
        }
        schema
    }

    fn render(schema: &CompiledSchema) -> String {
        generate(schema)
            .get("models.py")
            .expect("models.py emitted")
            .clone()
    }

    #[test]
    fn an_empty_schema_emits_nothing() {
        assert!(generate(&CompiledSchema::new("Empty")).is_empty());
    }

    #[test]
    fn a_model_becomes_a_dataclass() {
        let mut model = CompiledModel::new("Track").with_description("A track");
        model.add_field(CompiledField::new("id", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("@dataclass\nclass Track:"));
        assert!(out.contains("\"\"\"A track\"\"\""));
        assert!(out.contains("    id: str\n"));
    }

    #[test]
    fn scalars_map_to_python_types() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("s", scalar(ScalarType::String)));
        model.add_field(CompiledField::new("i", scalar(ScalarType::Int64)));
        model.add_field(CompiledField::new("f", scalar(ScalarType::Float64)));
        model.add_field(CompiledField::new("b", scalar(ScalarType::Boolean)));
        model.add_field(CompiledField::new("u", scalar(ScalarType::Unknown)));
        model.add_field(CompiledField::new("t", scalar(ScalarType::UtcDateTime)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("s: str"));
        assert!(out.contains("i: int"));
        assert!(out.contains("f: float"));
        assert!(out.contains("b: bool"));
        assert!(out.contains("u: Any"));
        assert!(out.contains("t: str"));
    }

    #[test]
    fn optional_fields_default_to_none_and_sort_after_required_ones() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("maybe", scalar(ScalarType::String)).optional());
        model.add_field(CompiledField::new("must", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));
        let must = out.find("must:").expect("required field");
        let maybe = out.find("maybe:").expect("optional field");

        assert!(must < maybe, "required fields must come first");
        assert!(out.contains("maybe: Optional[str] = field(default=None)"));
    }

    #[test]
    fn arrays_and_refs_nest() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new(
            "tracks",
            CompiledType::Array {
                items: Box::new(CompiledType::Ref {
                    name: "Track".to_string(),
                }),
                length: None,
            },
        ));

        assert!(render(&schema_with(vec![model])).contains("tracks: list[Track]"));
    }

    #[test]
    fn a_union_becomes_a_literal_alias() {
        let mut schema = CompiledSchema::new("Test");
        schema.add_union(CompiledUnion {
            name: "TrackType".to_string(),
            variants: ["audio", "midi"]
                .iter()
                .map(|v| CompiledUnionVariant {
                    name: (*v).to_string(),
                    variant_type: None,
                })
                .collect(),
            tag: None,
            rename_all: None,
            description: None,
            extensions: odk_schema::Extensions::default(),
            source: None,
        });
        schema.add_model(CompiledModel::new("M"));

        assert!(render(&schema).contains("TrackType = Literal[\"audio\", \"midi\"]"));
    }

    #[test]
    fn python_keywords_and_odd_characters_are_renamed_with_a_json_mapping() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("class", scalar(ScalarType::String)));
        model.add_field(CompiledField::new("kebab-case", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("class_: str = field(metadata={\"json\": \"class\"})"));
        assert!(out.contains("kebab_case: str = field(metadata={\"json\": \"kebab-case\"})"));
    }

    #[test]
    fn constraints_are_emitted_as_comments_not_validation() {
        let mut model = CompiledModel::new("M");
        let mut f = CompiledField::new("tempo", scalar(ScalarType::Float64));
        f.constraints = Some(FieldConstraints {
            min_length: None,
            max_length: None,
            min_value: Some(20.0),
            max_value: Some(300.0),
            pattern: None,
            format: None,
            multiple_of: None,
        });
        model.add_field(f);

        let out = render(&schema_with(vec![model]));
        assert!(out.contains("# constraints: minimum 20, maximum 300"));
    }

    #[test]
    fn descriptions_are_collapsed_so_they_cannot_break_the_comment() {
        let mut model = CompiledModel::new("M");
        let mut f = CompiledField::new("a", scalar(ScalarType::String));
        f.description = Some("line one\nline two".to_string());
        model.add_field(f);

        let out = render(&schema_with(vec![model]));
        assert!(out.contains("# line one line two"));
    }

    #[test]
    fn an_empty_model_is_still_valid_python() {
        let out = render(&schema_with(vec![CompiledModel::new("Empty")]));
        assert!(out.contains("class Empty:\n    pass"));
    }

    #[test]
    fn round_trip_helpers_are_included() {
        let mut model = CompiledModel::new("M");
        model.add_field(CompiledField::new("a", scalar(ScalarType::String)));

        let out = render(&schema_with(vec![model]));

        assert!(out.contains("def from_dict("));
        assert!(out.contains("def to_dict("));
        assert!(out.contains("from __future__ import annotations"));
        // lazy annotations are strings, so the decoder has to resolve them or
        // nested models come back as plain dicts
        assert!(out.contains("get_type_hints"));
    }
}