Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

enumgen

A Go code generator that creates helper functions for string enum types.

Features

For each type T string with const values, enumgen generates:

  • AllT() []T - Returns a slice of all enum values
  • (t T) IsValid() bool - Returns true if t is a valid enum value
  • (t T) Order() int - Returns the display order (opt-in via directive)

Installation

go install github.com/5n7/enumgen@latest

Usage

With go:generate (recommended)

Add a go:generate directive to your package:

//go:generate enumgen

Then run:

go generate ./...

With directory argument

enumgen ./path/to/package

As a library

import "github.com/5n7/enumgen"

// Generate and write to enums.gen.go
err := enumgen.Run("./mypackage")

// Generate without writing (for custom processing)
code, err := enumgen.Generate("./mypackage")

Example

Input (constants.go):

package user

//go:generate enumgen

type Status string

const (
    StatusActive   Status = "active"
    StatusInactive Status = "inactive"
    StatusPending  Status = "pending"
)

Output (enums.gen.go):

// Code generated by enumgen; DO NOT EDIT.
package user

// AllStatus returns a slice containing all valid Status values.
func AllStatus() []Status {
    return []Status{
        StatusActive,
        StatusInactive,
        StatusPending,
    }
}

// IsValid returns true if s is a valid Status value.
func (s Status) IsValid() bool {
    switch s {
    case StatusActive,
        StatusInactive,
        StatusPending:
        return true
    default:
        return false
    }
}

Order Method

To generate an Order() method for sorting or display purposes, add the @enumgen:order directive to the type:

// @enumgen:order
type Priority string

const (
    PriorityUnknown Priority = "unknown" // @order:99
    PriorityLow     Priority = "low"
    PriorityMedium  Priority = "medium"
    PriorityHigh    Priority = "high"
)

This generates:

// Order returns the display order of p.
func (p Priority) Order() int {
    switch p {
    case PriorityUnknown:
        return 99
    case PriorityLow:
        return 1
    case PriorityMedium:
        return 2
    case PriorityHigh:
        return 3
    default:
        return 999
    }
}

Order rules:

  • Constants without @order:N are assigned sequential orders starting from 1
  • Use @order:N to override the default order for specific values
  • Invalid values return 999

File Handling

  • Scans all .go files in the current directory
  • Excludes *_test.go, *.gen.go, and *_gen.go files
  • Writes output to enums.gen.go

License

MIT

About

A Go code generator that creates helper functions for string enum types

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages