This tool is a programmatic wrapper for standard stringer utility. Unlike the basic CLI, go-stringer-gen can be
configured to handle multiple packages or types with distinct options in a single pass.
go-stringer-gen can be used as a standalone CLI tool or integrated into your own custom generator as a library. This
is a component of my code generation toolbox.
When running as a standalone generator, go-stringer-gen requires the pkl binary to be available on your PATH. It is
used at runtime to evaluate .pkl configuration files. You can install it via:
# macOS
brew install pklFor other platforms, see pkl-lang installation docs.
First let's set up a golang module
module github.com/gen/project
go 1.24pkl config
// file: stringer.pkl
amends "package://nhatp.com/go/stringer-gen/pkl@0.5.0#/Config.pkl"
packages {
["github.com/gen/project"] {
types { "Pill" }
}
}source code
// file: input.go
package painkiller
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)expected generated code
// golden-file: gen_stringer.go
// Code generated by go-stringer-gen - dev. DO NOT EDIT.
package painkiller
import "strconv"
// Unnamed variable used to ensure `import "strconv"` is generated, as it is required below.
var _ = strconv.FormatInt(0, 10)
// --- Code generated by go run golang.org/x/tools/cmd/stringer@latest -type Pill -output /dev/stdout
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Placebo-0]
_ = x[Aspirin-1]
_ = x[Ibuprofen-2]
_ = x[Paracetamol-3]
}
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
idx := int(i) - 0
if i < 0 || idx >= len(_Pill_index)-1 {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[idx]:_Pill_index[idx+1]]
}
// --- End code generated by go run golang.org/x/tools/cmd/stringer@latest -type Pill -output /dev/stdoutExample code
package yourgenerator
import (
"fmt"
"nhatp.com/go/stringer-gen"
)
func UseAsLibrary(sourceDir string) {
// fileManager instance can be shared between commands in the toolbox
fileManager := stringergen.NewFileManager(sourceDir, stringergen.WithBinaryName("your-generator"))
var configs []stringergen.Config // build your configs here ...
generator := stringergen.New(fileManager)
pkgs, err := stringergen.LoadPackages(sourceDir)
if err != nil {
panic(err)
}
for _, pkg := range pkgs {
if err := generator.Generate(pkg, configs); err != nil {
panic(err)
}
}
fmt.Println(fileManager.Files())
}Explore the features directory to see how go-stringer-gen handles various real-world scenarios:
PRs are welcome! See the CONTRIBUTING. Distributed under the Apache License 2.0.
If you like the project, feel free to buy me a coffee. Thank you!