gnostic icon indicating copy to clipboard operation
gnostic copied to clipboard

protoc-gen-openapi: Enum types that use stringified boolean values like `"TRUE"` are treated as the real boolean values

Open zaakn opened this issue 2 years ago • 2 comments

env

  • protoc-gen-openapi: v0.6.8
  • protoc flags: --openapi_opt naming=proto,enum_type=string

proto file

enum Trinary {
	NULL = 0;
	TRUE = 1;
	FALSE = 2;
}

message Condition {
	Trinary attached = 1;
}

expected output

Condition:
    type: object
    properties:
        attached:
            enum:
                - 'NULL'
                - 'TRUE'
                - 'FALSE'
            type: string
            format: enum

actual output

Condition:
    type: object
    properties:
        attached:
            enum:
                - NULL
                - TRUE
                - FALSE
            type: string
            format: enum

I know it's better not to use reserved words, so this is just for usage feedback.

zaakn avatar Sep 16 '23 19:09 zaakn

Related code lines: https://github.com/google/gnostic/blob/ee84fd2a96205f519ad7b86d989673d2ada03a3b/cmd/protoc-gen-openapi/generator/wellknown/schemas.go#L53-L63

My simple solution is:

schema.Enum = append(schema.Enum, &v3.Any{
	Yaml: strconv.Quote(string(field.Enum().Values().Get(i).Name())),
})

But is it correct to add Quote here? It has to be said that TRUE (string without quotes) will be treated as a boolean which is the expected behavior of YAML.

See also: https://github.com/google/gnostic-models/blob/c7be7c783f49e86348a1081eb387e01a347a4f23/openapiv3/OpenAPIv3.go#L6712-L6716

zaakn avatar Sep 17 '23 16:09 zaakn

@zaakn a safer way to handle that instead of using quoting might be to set data type annotation like !!str in the schema.Enum.Yaml field and strip them again when rendering JSON. This allows to avoid adding annotations,

nightlyone avatar Oct 19 '23 15:10 nightlyone