Skip to content

Commit

Permalink
fix: set default options in Usage (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane authored May 2, 2024
1 parent 9f684ec commit d416254
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 11 deletions.
27 changes: 16 additions & 11 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"strings"
)

// Options are the options for the [Load] function.
// Options are the options for the [Load] and [Usage] functions.
type Options struct {
Source Source // The source of environment variables. The default is [OS].
SliceSep string // The separator used to parse slice values. The default is space.
Expand Down Expand Up @@ -61,21 +61,13 @@ func (e *NotSetError) Error() string {
// - required: marks the environment variable as required
// - expand: expands the value of the environment variable using [os.Expand]
func Load(cfg any, opts *Options) error {
if opts == nil {
opts = new(Options)
}
if opts.Source == nil {
opts.Source = OS
}
if opts.SliceSep == "" {
opts.SliceSep = " "
}

pv := reflect.ValueOf(cfg)
if !structPtr(pv) {
panic("env: cfg must be a non-nil struct pointer")
}

opts = setDefaultOptions(opts)

v := pv.Elem()
vars := parseVars(v, opts)
cache[v.Type()] = vars
Expand Down Expand Up @@ -112,6 +104,19 @@ func Load(cfg any, opts *Options) error {
return nil
}

func setDefaultOptions(opts *Options) *Options {
if opts == nil {
opts = new(Options)
}
if opts.Source == nil {
opts.Source = OS
}
if opts.SliceSep == "" {
opts.SliceSep = " "
}
return opts
}

func parseVars(v reflect.Value, opts *Options) []Var {
var vars []Var

Expand Down
2 changes: 2 additions & 0 deletions usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ func Usage(cfg any, w io.Writer, opts *Options) {
panic("env: cfg must be a non-nil struct pointer")
}

opts = setDefaultOptions(opts)

v := pv.Elem()
vars, ok := cache[v.Type()]
if !ok {
Expand Down
11 changes: 11 additions & 0 deletions usage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ func TestUsage(t *testing.T) {
assert.Equal[E](t, buf.String(), " FOO string default <empty>\n")
})

t.Run("with Options.NameSep", func(t *testing.T) {
var buf bytes.Buffer
var cfg struct {
A struct {
Foo int `env:"FOO"`
} `env:"A"`
}
env.Usage(&cfg, &buf, &env.Options{NameSep: "_"})
assert.Equal[E](t, buf.String(), " A_FOO int default 0\n")
})

t.Run("custom usage message", func(t *testing.T) {
var buf bytes.Buffer
var cfg Config
Expand Down

0 comments on commit d416254

Please sign in to comment.