go-enum

repository·master·Indexed 21 days ago

https://github.com/abice/go-enum

An enum generator for Go that creates type-safe enumerations from commented type declarations. It generates constants, String() methods, and parsing functions, with optional support for JSON/SQL marshaling, custom prefixes, and nullable SQL types.

Tokens
2.7K
Snippets
9
Records
12
Agent score
73%

What's inside go-enum

  1. Define enums using the ENUM() syntax

    master

    The go-enum parser identifies enum declarations by looking for an ENUM(...) block within comments preceding a type definition. You can list values on a single line or multiple lines. To assign a specific numeric value to an enum member, use the =numericValue syntax. Note that assigning a specific value resets the sequence for all subsequent members (e.g., if you set a value to 50, the next will be 51).

    /* ENUM(
    Black, White, Red
    Green = 33
    )
    */
    type Color int32
  2. How go-enum works: Syntax and Generated Code

    master

    The generator parses a commented type declaration and produces a companion file containing constants, string conversion, and marshaling logic.

    Input Syntax

    // ENUM(jpeg, jpg, png, tiff, gif)
    type ImageType int

    Generated Output

    For the input above, go-enum generates:

    • Constants: ImageTypeJpeg, ImageTypeJpg, etc., using iota.
    • Stringer: A String() method for the type.
    • Parser: A ParseImageType(name string) function to convert strings back to the type.
    • Marshaling: MarshalText() and UnmarshalText() methods (which are also used by the standard encoding/json package).
    // ENUM(jpeg, jpg, png, tiff, gif)
    type ImageType int
  3. Integrate go-enum with go generate

    master

    You can automate enum generation by adding a //go:generate directive to your Go files.

    For Go 1.24+ (with tool dependency)

    Add this to your file:

    //go:generate go tool go-enum --marshal

    For older Go versions

    Add this to your file:

    //go:generate go-enum --marshal

    Then run go generate ./... in your terminal.

    //go:generate go tool go-enum --marshal
  4. Add comments to generated enum constants

    master

    To include comments in the generated code, place a // comment on the same line as the enum value inside the ENUM() block. The parser will attach these comments to the corresponding generated constant.

    /*
    ENUM(
    value1 // Commented value 1
    value2
    value3 // Commented value 3
    )
    */
    type Commented int
  5. Install go-enum

    master

    Depending on your Go version, use one of the following methods to install go-enum:

    Install as a project tool to track it in your go.mod file:

    go get -tool github.com/abice/go-enum@latest

    Then run it using go tool go-enum.

    Older Go Versions

    Install directly to your $GOPATH/bin:

    go install github.com/abice/go-enum@latest

    Then run it using the go-enum command.

    Using Docker

    Run the tool without local installation:

    docker run -w /app -v $(pwd):/app abice/go-enum:latest
    go get -tool github.com/abice/go-enum@latest
  6. Quick Start: Generate an enum

    master

    To generate an enum, follow these steps:

    1. Declare your type in a Go file using the // ENUM(val1, val2, ...) comment syntax.
    2. Run the generator pointing to your file using the -f flag.
    3. Use the generated methods like .String() and Parse<TypeName>() in your code.

    Example declaration:

    // ENUM(red, green, blue)
    type Color int
    go tool go-enum -f your_file.go
  7. Use string-typed enums

    master

    You can define enums where the underlying type is a string instead of an int. This is useful for APIs or documentation where string values are preferred over integer constants.

    Example:

    // ENUM(pending, running, completed, failed)
    type StrState string

    This generates constants like StrStatePending StrState = "pending".

    // ENUM(pending, running, completed, failed)
    type StrState string
  8. Reference: go-enum CLI flags

    master

    Full list of available CLI flags for go-enum:

    FlagDescription
    --file value, -f valueThe file(s) to generate enums. Use more than one flag for more files.
    --noprefixPrevents the constants generated from having the Enum as a prefix. (default: false)
    --lowerAdds lowercase variants of the enum strings for lookup. (default: false)
    --nocaseAdds case insensitive parsing to the enumeration (forces lower flag). (default: false)
    --marshalAdds text (and inherently json) marshalling functions. (default: false)
    --sqlAdds SQL database scan and value functions. (default: false)
    --sqlintTells the generator that a string typed enum should be stored in sql as an integer value. (default: false)
    --flagAdds golang flag functions. (default: false)
    --jsonpkg valueCustom json package for imports instead encoding/json.
    --prefix valueAdds a prefix with a user one. If you would like to replace the prefix, then combine this option with --noprefix.
    --namesGenerates a 'Names() []string' function, and adds the possible enum values in the error response during parsing (default: false)
    --valuesGenerates a 'Values() []{{ENUM}}' function. (default: false)
    --nocamelRemoves the snake_case to CamelCase name changing (default: false)
    --ptrAdds a pointer method to get a pointer from const values (default: false)
    --sqlnullintAdds a Null{{ENUM}} type for marshalling a nullable int value to sql (default: false)
    --sqlnullstrAdds a Null{{ENUM}} type for marshalling a nullable string value to sql. If sqlnullint is specified too, it will be Null{{ENUM}}Str (default: false)
    --template value, -t valueAdditional template file(s) to generate enums. Templates will be executed in alphabetical order.
    --alias value, -a valueAdds or replaces aliases for a non alphanumeric value. Format: "key:value,key2:value2".
    --mustparseAdds a Must version of the Parse that will panic on failure. (default: false)
    --forcelowerForces a camel cased comment to generate lowercased names. (default: false)
    --forceupperForces a camel cased comment to generate uppercased names. (default: false)
    --nocommentsRemoves auto generated comments. (default: false)
    --buildtag value, -b valueAdds build tags to a generated enum file.
    --output-suffix .goChanges the default filename suffix of _enum to something else.
    --no-iotaDisables the use of iota in generated enums. (default: false)
  9. Use go-enum CLI global options

    master

    The go-enum CLI tool accepts several global options to customize the generated code. Common options include:

    • --file, -f: The file(s) to generate enums from.
    • --marshal: Adds text (and JSON) marshalling functions.
    • --sql: Adds SQL database scan and value functions.
    • --names: Generates a Names() []string function.
    • --values: Generates a Values() []{{ENUM}} function.
    • --ptr: Adds a .Ptr() method to get a pointer from constant values.
    • --mustparse: Adds a MustParse version of the Parse function that panics on failure.
    • --no-iota: Disables the use of iota in generated enums.
    • --jsonpkg <value>: Specifies a custom JSON package for imports instead of encoding/json.
    go-enum --help
  10. Reference: go-enum command options

    master

    Common flags for the go-enum CLI tool:

    FlagDescription
    -f <file>The Go file containing the enum declaration.
    --marshalGenerate MarshalText and UnmarshalText methods.
    --jsonpkg="<pkg>"Specify a custom JSON package (e.g., github.com/goccy/go-json) instead of encoding/json.
    --no-iotaDisable the use of iota in generated constants.
    --sqlintUse integer values for SQL integration while allowing string values elsewhere.
    --output-suffix="<suffix>"Change the default _enum.go suffix (e.g., --output-suffix="_generated").
  11. Configure go-enum generation via CLI flags

    master

    The go-enum CLI provides several flags to control the behavior and features of the generated code. Below are the available configuration options:

    File & Output

    • --file, -f (Required): The file(s) to generate enums from. Supports glob patterns.
    • --output-suffix: Changes the default filename suffix (default is _enum). .go is always appended.
    • --buildtag, -b: Adds Go build tags to the generated file.
    • --template, -t: Additional template file(s) to use for generation. Templates are executed in alphabetical order.

    Enum Behavior

    • --noprefix: Prevents the constants from having the Enum name as a prefix.
    • --prefix <string>: Adds a custom prefix to constants. Combine with --noprefix to replace the default.
    • --no-iota: Disables the use of iota in generated enums.
    • --nocamel: Removes the automatic snake_case to CamelCase name conversion.
    • --forcelower: Forces camel-cased comments to generate lowercased names.
    • --forceupper: Forces camel-cased comments to generate uppercased names.
    • --nocomments: Removes auto-generated comments (user-added comments are preserved).
    • --noparse: Prevents generating the Parse method (or makes it unexported).
    • --mustparse: Adds a MustParse version of the Parse method that panics on failure. (Incompatible with --noparse).
    • --alias, -a: Adds or replaces aliases for non-alphanumeric values. Format: "key:value,key2:value2".

    Feature Additions

    • --marshal: Adds text (and JSON) marshalling functions.
    • --jsonpkg <string>: Specifies a custom JSON package to import instead of encoding/json.
    • --sql: Adds SQL database Scan and Value functions.
    • --sqlint: For string-typed enums, tells the generator to store them as integer values in SQL.
    • --sqlnullint: Adds a Null{{ENUM}} type for nullable integer SQL values.
    • --sqlnullstr: Adds a Null{{ENUM}} type for nullable string SQL values. If --sqlint is also set, this becomes Null{{ENUM}}Str.
    • --flag: Adds Go flag package functions for the enum.
    • --lower: Adds lowercase variants of enum strings for lookup.
    • --nocase: Adds case-insensitive parsing (automatically enables --lower).
    • --names: Generates a Names() []string function and includes possible values in error responses.
    • --values: Generates a Values() []{{ENUM}} function.
    • --ptr: Adds a pointer method to get a pointer from constant values.
  12. Use the go-enum CLI to generate enums

    master

    The go-enum CLI tool parses Go source files and generates companion enum files. By default, it appends _enum.go to the original filename. You can specify input files using the --file (or -f) flag, which supports glob patterns (e.g., *.go).

    Common workflows include adding JSON marshalling, SQL support, or pointer methods to your generated enums via CLI flags.

    # Basic usage with a specific file
    go-enum --file my_types.go
    
    # Using glob patterns to process multiple files
    go-enum --file models/*.go
    
    # Generating enums with JSON and SQL support
    go-enum --file types.go --marshal --sql