Skip to content
This repository has been archived by the owner on Jun 12, 2024. It is now read-only.

Commit

Permalink
Generate const if enum has exactly one element (#41)
Browse files Browse the repository at this point in the history
**What**
- Generate a Go `const` if the enum values has exactly one element
- See OAI/OpenAPI-Specification#1313 and
  OAI/OpenAPI-Specification#1620 as examples
  where the openapi team blessed the "singleton enum" example

Signed-off-by: Lucas Roesler <[email protected]>
  • Loading branch information
LucasRoesler authored Jul 20, 2020
1 parent 725f32a commit 627b323
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
24 changes: 23 additions & 1 deletion pkg/generators/models/enums.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ func GenerateEnums(specFile io.Reader, dst string, opts Options) error {
return err
}

err = enumTemplate.Execute(f, tctx)
if len(tctx.Values) == 1 {
err = constTemplate.Execute(f, tctx)
} else {
err = enumTemplate.Execute(f, tctx)
}
if err != nil {
return fmt.Errorf("failed to generate enum code: %w", err)
}
Expand Down Expand Up @@ -138,6 +142,12 @@ var enumTemplate = template.Must(
Parse(enumTemplateSource),
)

var constTemplate = template.Must(
template.New("const").
Funcs(fmap).
Parse(constTemplateSource),
)

var fmap = template.FuncMap{
"firstLower": tpl.FirstLower,
"firstUpper": tpl.FirstUpper,
Expand Down Expand Up @@ -190,3 +200,15 @@ var (
)
)
`

var constTemplateSource = `
// This file is auto-generated, DO NOT EDIT.
//
// Source:
// Title: {{.SpecTitle}}
// Version: {{.SpecVersion}}
package {{ .PackageName }}
{{ (printf "%s is an enum. %s" .Name .Description) | commentBlock }}
const {{.VarName}} = {{ (index .Values 0).Value}}
`
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,5 @@
// Version: 0.1.0
package testpkg

import (
validation "github.com/go-ozzo/ozzo-validation"
)

// HighlightIndicatorStart is an enum.
type HighlightIndicatorStart string

var (
HighlightIndicatorStartValue0 HighlightIndicatorStart = "{{{"

// KnownHighlightIndicatorStart is the list of valid HighlightIndicatorStart
KnownHighlightIndicatorStart = []HighlightIndicatorStart{
HighlightIndicatorStartValue0,
}
// KnownHighlightIndicatorStartString is the list of valid HighlightIndicatorStart as string
KnownHighlightIndicatorStartString = []string{
string(HighlightIndicatorStartValue0),
}

// InKnownHighlightIndicatorStart is an ozzo-validator for HighlightIndicatorStart
InKnownHighlightIndicatorStart = validation.In(
HighlightIndicatorStartValue0,
)
)
const HighlightIndicatorStart = "{{{"

0 comments on commit 627b323

Please sign in to comment.