{"id":13563058,"url":"https://github.com/dmarkham/enumer","last_synced_at":"2026-01-22T06:31:53.503Z","repository":{"id":35045769,"uuid":"179358518","full_name":"dmarkham/enumer","owner":"dmarkham","description":"A Go tool to auto generate methods for your enums","archived":false,"fork":false,"pushed_at":"2025-02-18T17:21:09.000Z","size":2013,"stargazers_count":449,"open_issues_count":33,"forks_count":69,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-02-18T18:21:35.679Z","etag":null,"topics":["code-generation","codegeneration","codegenerator","enum","enums","generator","golang"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dmarkham.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-04-03T19:42:20.000Z","updated_at":"2025-02-18T17:00:52.000Z","dependencies_parsed_at":"2023-01-15T12:41:44.840Z","dependency_job_id":"95f431ad-9388-4b64-8c9d-8c78b5c2f3fe","html_url":"https://github.com/dmarkham/enumer","commit_stats":null,"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmarkham%2Fenumer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmarkham%2Fenumer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmarkham%2Fenumer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmarkham%2Fenumer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dmarkham","download_url":"https://codeload.github.com/dmarkham/enumer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247065405,"owners_count":20877768,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code-generation","codegeneration","codegenerator","enum","enums","generator","golang"],"created_at":"2024-08-01T13:01:14.711Z","updated_at":"2025-10-31T02:15:31.980Z","avatar_url":"https://github.com/dmarkham.png","language":"Go","readme":"# Enumer [![GoDoc](https://godoc.org/github.com/dmarkham/enumer?status.svg)](https://godoc.org/github.com/dmarkham/enumer) [![Go Report Card](https://goreportcard.com/badge/github.com/dmarkham/enumer)](https://goreportcard.com/report/github.com/dmarkham/enumer) [![GitHub Release](https://img.shields.io/github/release/dmarkham/enumer.svg)](https://github.com/dmarkham/enumer/releases)\n\nEnumer is a tool to generate Go code that adds useful methods to Go enums (constants with a specific type).\nIt started as a fork of [Rob Pike’s Stringer tool](https://godoc.org/golang.org/x/tools/cmd/stringer)\nmaintained by [Álvaro López Espinosa](https://github.com/alvaroloes/enumer). \nThis was again forked here as (https://github.com/dmarkham/enumer) picking up where Álvaro left off.\n\n\n```\n$ enumer --help\nEnumer is a tool to generate Go code that adds useful methods to Go enums (constants with a specific type).\nUsage of enumer:\n        Enumer [flags] -type T [directory]\n        Enumer [flags] -type T files... # Must be a single package\nFor more information, see:\n        http://godoc.org/github.com/dmarkham/enumer\nFlags:\n  -addprefix string\n        transform each item name by adding a prefix. Default: \"\"\n  -comment value\n        comments to include in generated code, can repeat. Default: \"\"\n  -gqlgen\n        if true, GraphQL marshaling methods for gqlgen will be generated. Default: false\n  -json\n        if true, json marshaling methods will be generated. Default: false\n  -linecomment\n        use line comment text as printed text when present\n  -output string\n        output file name; default srcdir/\u003ctype\u003e_string.go\n  -sql\n        if true, the Scanner and Valuer interface will be implemented.\n  -text\n        if true, text marshaling methods will be generated. Default: false\n  -transform string\n        enum item name transformation method. Default: noop (default \"noop\")\n  -trimprefix string\n        transform each item name by removing a prefix or comma separated list of prefixes. Default: \"\"\n  -type string\n        comma-separated list of type names; must be set\n  -typederrors\n        if true, errors from enumerrs/ will be errors.Join()-ed for errors.Is(...) to simplify invalid value handling. Default: false\n  -values\n        if true, alternative string values method will be generated. Default: false\n  -yaml\n        if true, yaml marshaling methods will be generated. Default: false\n```\n\n\n## Generated functions and methods\n\nWhen Enumer is applied to a type, it will generate:\n\n- The following basic methods/functions:\n\n  - Method `String()`: returns the string representation of the enum value. This makes the enum conform\n    the `Stringer` interface, so whenever you print an enum value, you'll get the string name instead of a number.\n  - Function `\u003cType\u003eString(s string)`: returns the enum value from its string representation. This is useful\n    when you need to read enum values from command line arguments, from a configuration file, or\n    from a REST API request... In short, from those places where using the real enum value (an integer) would\n    be almost meaningless or hard to trace or use by a human. `s` string is Case Insensitive.\n  - Function `\u003cType\u003eValues()`: returns a slice with all the values of the enum\n  - Function `\u003cType\u003eStrings()`: returns a slice with all the Strings of the enum\n  - Method `IsA\u003cType\u003e()`: returns true only if the current value is among the values of the enum. Useful for validations.\n\n- When the flag `json` is provided, two additional methods will be generated, `MarshalJSON()` and `UnmarshalJSON()`. These make\n  the enum conform to the `json.Marshaler` and `json.Unmarshaler` interfaces. Very useful to use it in JSON APIs.\n- When the flag `text` is provided, two additional methods will be generated, `MarshalText()` and `UnmarshalText()`. These make\n  the enum conform to the `encoding.TextMarshaler` and `encoding.TextUnmarshaler` interfaces.\n  **Note:** If you use your enum values as keys in a map and you encode the map as _JSON_, you need this flag set to true to properly\n  convert the map keys to json (strings). If not, the numeric values will be used instead\n- When the flag `yaml` is provided, two additional methods will be generated, `MarshalYAML()` and `UnmarshalYAML()`. These make\n  the enum conform to the `gopkg.in/yaml.v2.Marshaler` and `gopkg.in/yaml.v2.Unmarshaler` interfaces.\n- When the flag `sql` is provided, the methods for implementing the `Scanner` and `Valuer` interfaces.\n  Useful when storing the enum in a database.\n- When the flag `typederrors` is provided, the string conversion functions will return errors wrapped with\n  `errors.Join()` containing a typed error from the `enumerrs` package. This allows you to use `errors.Is()` to\n  check for specific enum validation failures.\n\n\nFor example, if we have an enum type called `Pill`,\n\n```go\ntype Pill int\n\nconst (\n\tPlacebo Pill = iota\n\tAspirin\n\tIbuprofen\n\tParacetamol\n\tAcetaminophen = Paracetamol\n)\n```\n\nexecuting `enumer -type=Pill -json` will generate a new file with four basic methods and two extra for JSON:\n\n```go\nfunc (i Pill) String() string {\n\t//...\n}\n\nfunc PillString(s string) (Pill, error) {\n\t//...\n}\n\nfunc PillValues() []Pill {\n\t//...\n}\n\nfunc PillStrings() []string {\n\t//...\n}\n\nfunc (i Pill) IsAPill() bool {\n\t//...\n}\n\nfunc (i Pill) MarshalJSON() ([]byte, error) {\n\t//...\n}\n\nfunc (i *Pill) UnmarshalJSON(data []byte) error {\n\t//...\n}\n```\n\nFrom now on, we can:\n\n```go\n// Convert any Pill value to string\nvar aspirinString string = Aspirin.String()\n// (or use it in any place where a Stringer is accepted)\nfmt.Println(\"I need \", Paracetamol) // Will print \"I need Paracetamol\"\n\n// Convert a string with the enum name to the corresponding enum value\npill, err := PillString(\"Ibuprofen\") // \"ibuprofen\" will also work.\nif err != nil {\n    fmt.Println(\"Unrecognized pill: \", err)\n    return\n}\n// Now pill == Ibuprofen\n\n// Get all the values of the string\nallPills := PillValues()\nfmt.Println(allPills) // Will print [Placebo Aspirin Ibuprofen Paracetamol]\n\n// Check if a value belongs to the Pill enum values\nvar notAPill Pill = 42\nif (notAPill.IsAPill()) {\n\tfmt.Println(notAPill, \"is not a value of the Pill enum\")\n}\n\n// Marshal/unmarshal to/from json strings, either directly or automatically when\n// the enum is a field of a struct\npillJSON := Aspirin.MarshalJSON()\n// Now pillJSON == `\"Aspirin\"`\n```\n\nThe generated code is exactly the same as the Stringer tool plus the mentioned additions, so you can use\n**Enumer** where you are already using **Stringer** without any code change.\n\n## Transforming the string representation of the enum value\n\nBy default, Enumer uses the same name of the enum value for generating the string representation (usually CamelCase in Go).\n\n```go\ntype MyType int\n\n ...\n\nname := MyTypeValue.String() // name =\u003e \"MyTypeValue\"\n```\n\nSometimes you need to use some other string representation format than CamelCase (i.e. in JSON).\n\nTo transform it from CamelCase to another format, you can use the `transform` flag.\n\nFor example, the command `enumer -type=MyType -json -transform=snake` would generate the following string representation:\n\n```go\nname := MyTypeValue.String() // name =\u003e \"my_type_value\"\n```\n\n**Note**: The transformation only works from CamelCase to snake_case or kebab-case, not the other way around.\n\n### Transformers\n\n- snake\n- snake-upper\n- kebab\n- kebab-upper\n- lower (lowercase)\n- upper (UPPERCASE)\n- title (TitleCase)\n- title-lower (titleCase)\n- first (Use first character of string)\n- first-lower (same as first only lower case)\n- first-upper (same as first only upper case)\n- whitespace\n\n## How to use\n\nFor a module-aware repo with `enumer` in the `go.mod` file, generation can be called by adding the following to a `.go` source file:\n\n```golang\n//go:generate go run github.com/dmarkham/enumer -type=YOURTYPE\n```\n\nThere are five boolean flags: `json`, `text`, `yaml`, `sql`, and `typederrors`. You can use any combination of them (i.e. `enumer -type=Pill -json -text -typederrors`),\n\nFor enum string representation transformation the `transform` and `trimprefix` flags\nwere added (i.e. `enumer -type=MyType -json -transform=snake`).\nPossible transform values are listed above in the [transformers](#transformers) section.\nThe default value for `transform` flag is `noop` which means no transformation will be performed.\n\nIf a prefix is provided via the `trimprefix` flag, it will be trimmed from the start of each name (before\nit is transformed). You can trim multiple prefixes by passing a comma separated list.\nIf a name doesn't have the prefix it will be passed unchanged.\n\nIf a prefix is provided via the `addprefix` flag, it will be added to the start of each name (after trimming and after transforming).\n\nThe boolean flag `values` will additionally create an alternative string values method `Values() []string` to fullfill the `EnumValues` interface of [ent](https://entgo.io/docs/schema-fields/#enum-fields).\n\n## Typed Error Handling\n\nWhen using the `typederrors` flag, you can handle enum validation errors specifically using `errors.Is()`:\n\n```go\nimport (\n    \"errors\"\n    \"github.com/dmarkham/enumer/enumerrs\"\n)\n\n// This will return a typed error that can be checked\npill, err := PillString(\"InvalidValue\")\nif err != nil {\n    if errors.Is(err, enumerrs.ErrValueInvalid) {\n        // Handle invalid enum value specifically\n        fmt.Println(\"Invalid pill value provided\")\n    }\n    // The error also contains a descriptive message\n    fmt.Printf(\"Error: %v\\n\", err)\n}\n```\n\n## Inspiring projects\n\n- [Álvaro López Espinosa](https://github.com/alvaroloes/enumer)\n- [Stringer](https://godoc.org/golang.org/x/tools/cmd/stringer)\n- [jsonenums](https://github.com/campoy/jsonenums)\n","funding_links":[],"categories":["Go"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdmarkham%2Fenumer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdmarkham%2Fenumer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdmarkham%2Fenumer/lists"}