enumer

command module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2021 License: MIT Imports: 13 Imported by: 0

README

enumer

Build Status Coverage Status GoDevDoc Time Tracker Code lines Comments

A Go tool to generate enumerations of type constants.

Fork

This is a fork of stringer changed to generate a map of names and values instead of String() string.

Installation

go install github.com/vearutop/enumer@latest

Usage

Having day.go with this contents:

//go:generate enumer -type=Day

type Day int
const (
	Monday Day = iota
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	Sunday
)

Alternatively, in go1.17 and newer, you can set up generation with

//go:generate go run github.com/vearutop/enumer@latest -type=Day

After running go generate you will get day_enum.go with

// Enum returns a list of values declared for a type.
func (Day) Enum() []interface{} {
	return []interface{}{
		Monday,
		Tuesday,
		Wednesday,
		Thursday,
		Friday,
		Saturday,
		Sunday,
	}
}

that implements jsonschema.Enum.

Documentation

Overview

Enumer is a tool to automate the creation of methods that satisfy the jsonschema.Enum (https://pkg.go.dev/github.com/swaggest/jsonschema-go#Enum) interface.

For example, given this snippet,

package painkiller

type Pill int

const (
	Placebo Pill = iota
	Aspirin
	Ibuprofen
	Paracetamol
	Acetaminophen = Paracetamol
)

running this command

enumer -type=Pill

in the same directory will create the file pill_enum.go, in package painkiller, containing a definition of

func (Pill) Enum() []interface{}

Typically this process would be run using go generate, like this:

//go:generate enumer -type=Pill

With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_string.go, where t is the lower-cased name of the first type listed. It can be overridden with the -output flag.

This file originates from https://github.com/golang/tools/blob/master/cmd/stringer/stringer.go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL