oxidecomputer / typify

JSON Schema -> Rust type converter
Apache License 2.0
367 stars 53 forks source link

Type name collision fix #601

Open SRetip opened 1 month ago

SRetip commented 1 month ago

Problem: If we try to generate schema from this schema:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "definitions": {
        "Foo": {
            "properties": {
                "Bar": {
                    "oneOf": [
                        {
                            "$ref": "#/definitions/FooBar"
                        },
                        {
                            "$ref": "#/definitions/Baz"
                        }
                    ]
                }
            },
            "type": "object"
        },
        "FooBar": {
            "type": "string"
        },
        "Baz": {
            "type": "string"
        }
    }
}

we get:

pub struct Baz(pub String);

pub struct Foo {
    pub bar: Option<FooBar>,
}

pub struct FooBar(pub String);

pub enum FooBar {
    FooBar(FooBar),
    Baz(Baz),
}

where struct FooBar - structure from definition:

  "FooBar": {
            "type": "string"
        },

and enum FooBar - enum which come from property definition:

 "Bar": {
                    "oneOf": [
                        {
                            "$ref": "#/definitions/FooBar"
                        },
                        {
                            "$ref": "#/definitions/Baz"
                        }
                    ]
                }

and as a result, we have a name conflict.

With my solution result will be:

pub struct Baz(pub String);

pub struct Foo {
    pub bar: Option<FooBarAlias>,
}

pub struct FooBar(pub String);

pub enum FooBarAlias {
    FooBar(FooBar),
    Baz(Baz),
}

I'd be happy to have a feedback :)

SRetip commented 3 weeks ago

If I understand you correctly, I have corrected what was required:

P.S. The "Alias" post-fix is generated only when there is a name conflict.