https://github.com/lindell/string-enumer
Code generation for enums defined as strings
https://github.com/lindell/string-enumer
code-generation enum enums go go-generate golang
Last synced: 17 days ago
JSON representation
Code generation for enums defined as strings
- Host: GitHub
- URL: https://github.com/lindell/string-enumer
- Owner: lindell
- License: mit
- Created: 2019-12-22T10:47:06.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2022-03-24T18:06:14.000Z (almost 4 years ago)
- Last Synced: 2025-01-20T04:02:09.306Z (12 months ago)
- Topics: code-generation, enum, enums, go, go-generate, golang
- Language: Go
- Homepage:
- Size: 38.1 KB
- Stars: 4
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
🧵 string-enumer
String enumer is a golang code generator for enums declared as strings.
The function `func (v X) Valid() bool` will always be generated on the defined types together with `func XValues() []X`. But options to generate more code exist.
It is especially useful with the `--text` option, that generates an `UnmarshalText` function which forces any unmarshaling of the type (via for JSON/XML/etc.) to be limited to the defined types.
The tool is primarily intended to be used with [go:generate](https://blog.golang.org/generate), but can be used as a separate CLI tool.
# Example usage with go generate
```go
//go:generate string-enumer --text -t Country -o ./generated.go .
// or
//go:generate go run github.com/lindell/string-enumer --text -t Country -o ./generated.go .
type Country string
const (
CountryCanada Country = "CA"
CountryChina Country = "CN"
CountrySweden Country = "SE"
CountryUnitedStates Country = "US"
)
```
When you run `go generate` for that package, it will generate:
```go
// Valid validates if a value is a valid Country
func (v Country) Valid() bool {
...
}
// CountryValues returns a list of all (valid) Country values
func CountryValues() []Country {
...
}
// UnmarshalText takes a text, verifies that it is a correct Country and unmarshals it
func (v *Country) UnmarshalText(text []byte) error {
...
}
```
([Please click this link for a real example at Go Playgrounds example](https://play.golang.org/p/5Sg2yl0Z5x_L))
## CLI Description:
```
$ string-enumer --help
Usage of string-enumer:
string-enumer [flags] --type T --type T2 [directory]
string-enumer [flags] --type T --type T2 files... # Must be a single package
For more information, see:
https://github.com/lindell/string-enumer
Flags:
-o, --output string output file name; default is stdout
-T, --text if set, text unmarshaling methods will be generated. Default: false
-t, --type strings the type name(s), can be multiple, but at least on must be set
```