Skip to content

Enumizer is a command-line tool for golang to generate enum helpers and check enum coverage in switch statements.

License

Notifications You must be signed in to change notification settings

neglect-yp/enumizer

Repository files navigation

enumizer

test license

Enumizer is a command-line tool for golang to generate enum helpers and check enum coverage in switch statements.

Installation

$ go install github.com/neglect-yp/enumizer@latest

Usage

You need to add marker comments before you try it. See the Examples section.

$ enumizer help
enumizer is a command-line tool to generate enum helpers and check enum coverage.

Usage:
  enumizer [command]

Examples:
* Generate enum helpers
  enumizer generate ./...

* Check enum coverage
  enumizer cover ./...

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  cover       Check that switch statements cover all variants of passed enum
  generate    Generate enum helpers that include stringer and validation methods
  help        Help about any command

Flags:
  -h, --help   help for enumizer

Use "enumizer [command] --help" for more information about a command.

Examples

Add marker comments like // enumizer:target above your const blocks for enum variants.

package myenum

type MyEnum int

// enumizer:target
const (
	A MyEnum = iota
	B
	C
)

Then you can generate enum helpers with enumizer generate ./.... The generated file name is enumizer.gen.go by default. enumizer.gen.go is as follows:

// Code generated by enumizer; DO NOT EDIT.
package myenum

import "fmt"

var myEnumSet = map[MyEnum]struct{}{
	A: {},
	B: {},
	C: {},
}

func MyEnumList() []MyEnum {
	ret := make([]MyEnum, 0, len(myEnumSet))
	for v := range myEnumSet {
		ret = append(ret, v)
	}
	return ret
}

func (m MyEnum) String() string {
	switch m {
	case A:
		return "A"
	case B:
		return "B"
	case C:
		return "C"
	default:
		return "<unknown MyEnum>"
	}
}

func (m MyEnum) IsValid() bool {
	_, ok := myEnumSet[m]
	return ok
}

func (m MyEnum) Validate() error {
	if !m.IsValid() {
		return fmt.Errorf("MyEnum(%v) is invalid", m)
	}
	return nil
}

And you can check that switch statements cover all variants of passed enum. If you have code that uses MyEnum, such as the following, you will be warned because there are no A and C cases in the switch statement.

package myenumuser

import "github.com/neglect-yp/enumizer/examples/myenum"

func Foo(a myenum.MyEnum) {
	switch a {
	case myenum.B:
	}
}
$ enumizer cover ./examples/...
/<path to homedir>/enumizer/examples/myenumuser/myenumuser.go:6:2: this switch statement doesn't cover enum variants. missing cases: A, C

About

Enumizer is a command-line tool for golang to generate enum helpers and check enum coverage in switch statements.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages