Opinionated Code Generators For Functional Options In Golang
whittle options -type TypeToGenerateOptionsFor
generate functional options for the current directories package
e.g. given package
package worker
//go:generate whittle options -type Worker
type Worker struct {
times int `opts`
namespace string `opts:"SetNamespace"`
}
func New() *Worker { &Worker }
go generate
will produce:
package worker
type Option func(*Worker)
type Options []Option
func (o Options) Apply(w *Worker) {
for _, opt := range o {
opt(w)
}
}
func WithTimes(times int) Option {
return func(w *Worker) {
w.times = times
}
}
func SetNamespace(namespace string) Option {
return func(w *Worker) {
w.namespace = namespace
}
}
Now to wire in the new options, all you have to do is:
func New(opts ...Option) *Worker {
worker := &Worker{
times: 5, // some sensible default
namespace: "default_namespace" // another sensible default
}
Options(opts).Apply(worker)
return worker
}
-
lib/options
: initial simple implementation of generating source for functional options -
lib/parse
: initial implementation of source code -> fun internals parsing -
cmd/fun
: initial implemenation of the executable -
lib/parse
: support parsing field tags on target structs -
lib/options
: support generation of provided options e.g. generatefunc WithSomeFieldName(value string) Option
-
cmd/fun
: update binary to support wiring new options together -
cmd/opt
: renamefun
toopt
as it will now live as a sub-command ofwhittle
-
cmd/whittle/options
: renamed (again) tooptions
for clarity