glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
11.76k stars 1.04k forks source link

[FEATURE]: Optionally append enum type name to Golang enum constants #2624

Open alpoi-x opened 5 days ago

alpoi-x commented 5 days ago

Context (Input, Language)

Input Format: schema Output Language: go

Description

When generating go code from schemas within a single package, different enums with the same named members will conflict with each-other. With a --enum-type-name-suffix flag (default false), we can instead append the enum type name to the end of the constant (which is a common approach to avoid these conflicts). See a worked example below šŸ˜

Current Behaviour / Output

Consider the following json schemas:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "tree_part.json",
    "title": "TreePart",
    "additionalProperties": false,
    "type": "string",
    "enum": ["BARK", "LEAF", "ROOT"]
}
{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "dog_noise.json",
    "title": "DogNoise",
    "additionalProperties": false,
    "type": "string",
    "enum": ["BARK", "GROWL", "HOWL"]
}

Currently, running the following two commands:

quicktype --src-lang schema --src "schemas/dog_noise.json" --lang go --just-types-and-package --package types --multi-file-output --out "schemas/DogNoise.go"
quicktype --src-lang schema --src "schemas/tree_part.json" --lang go --just-types-and-package --package types --multi-file-output --out "schemas/TreePart.go"

will generate the following files:

package types

type TreePart string

const (
    Bark TreePart = "BARK"
    Leaf TreePart = "LEAF"
    Root TreePart = "ROOT"
)
package types

type DogNoise string

const (
    Bark  DogNoise = "BARK"
    Growl DogNoise = "GROWL"
    Howl  DogNoise = "HOWL"
)

which will cause a redeclared in this block error.

Proposed Behaviour / Output

When passing an additional flag --enum-type-name-suffix to the quicktype command, generate:

package types

type TreePart string

const (
    BarkTreePart TreePart = "BARK"
    LeafTreePart TreePart = "LEAF"
    RootTreePart TreePart = "ROOT"
)
package types

type DogNoise string

const (
    BarkDogNoise  DogNoise = "BARK"
    GrowlDogNoise DogNoise = "GROWL"
    HowlDogNoise  DogNoise = "HOWL"
)

Solution

a two line change (that I'll PR after submitting this issue)

Alternatives

Generating with different package names would "resolve" the conflicts, but does not work for our use case (we have many enums that conflict with each-other in this manner, and would rather not create a separate package for each).