Documentation
¶
Overview ¶
Marshaler is a tool to automate the creation of methods that satisfy the fmt.Stringer, encoding.TextMarshaler and encoding.TextUnmarshaler interfaces. Given the name of a (signed or unsigned) integer type T that has constants defined, marshaler will create a new self-contained Go source file implementing func (t T) String() string func (t T) MarshalText() ([]byte, error) func (t *T) UnmarshalText([]byte) error The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.
Marshaler works best with constants that are consecutive values such as created using iota, but creates good code regardless. In the future it might also provide custom support for constant sets that are bit patterns.
By default marshaler will strip T type name if it prefixes the constant names and will convert the remainder of the constant name to snake_case This can be overridden by passing -noprefix=false -snakecase=false respectively
For example, given this snippet,
package painkiller type Pill int const ( Placebo Pill = iota Aspirin Ibuprofen Paracetamol Acetaminophen = Paracetamol )
running this command
marshaler -type=Pill
in the same directory will create the file pill_marshaler.go, in package painkiller, containing a definitions of
func (Pill) String() string func (Pill) MarshalText() ([]byte, error) func (*Pill) UnarshalText() error
If multiple constants have the same value, the lexically first matching name will be used (in the example, Acetaminophen will print as "Paracetamol").
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.
It is a modified version of golang.org/x/tools/cmd/stringer (Copyright 2014 The Go Authors. All rights reserved.) Use of this source code is governed by a BSD-style license
The camelToSnake function is copied near-verbatim (minus initializms) from github.com/serenize/snaker (Copyright (c) 2015 Serenize UG (haftungsbeschränkt)) Use of this source code is governed by a MIT license