From ff3db8a313d60c2a1e29a4cc7ec5211f37f2d4e1 Mon Sep 17 00:00:00 2001 From: efixler Date: Fri, 16 Feb 2024 09:05:49 -0500 Subject: [PATCH] godoc + badges --- README.md | 2 ++ envflags.go | 23 +++++++++++++++++++++-- go.sum | 0 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 go.sum diff --git a/README.md b/README.md index d9d6d63..e03b214 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # envflags +[![Go Reference](https://pkg.go.dev/badge/github.com/efixler/envflags.svg)](https://pkg.go.dev/github.com/efixler/envflags) +[![Go Report Card](https://goreportcard.com/badge/github.com/efixler/envflags)](https://goreportcard.com/report/github.com/efixler/envflags) ## Description `envflags` is for when you need to provide alternative environment variable settings for command diff --git a/envflags.go b/envflags.go index c11b189..fe2bab0 100644 --- a/envflags.go +++ b/envflags.go @@ -1,3 +1,11 @@ +// envflags provides a way to set flags from environment variables, +// working in conjunction with the flag package; it adds the +// option to look for an environment variable in between the flag and +// its defsult value, and also adds environment variable names to the +// usage string. +// +// The precedence order for values is explicit flag -> environment +// variable -> default. package envflags import ( @@ -13,17 +21,24 @@ import ( ) var ( - EnvPrefix = "" + EnvPrefix = "" + // Will be added to usage strings for flags that have an + // environment variable. The format string substitutes the + // environment variable name. EnvUsageTemplate = "\nEnvironment: %s" ) type Value[T any] struct { + envName string flagValue T converter func(string) (T, error) isBoolFlag bool - envName string } +// NewEnvFlagValue creates a new Value[T] with the given environment +// variable name. Pass "" to the envName to disable environment variables +// for this flag. The defaultValue is used if the environment variable or +// explicit flag are not set or cannot be converted. func NewEnvFlagValue[T any]( envName string, defaultValue T, @@ -37,6 +52,8 @@ func NewEnvFlagValue[T any]( return envFlag } +// AddTo adds the flag to the given flag.FlagSet with the given name. +// usage is appended with environment flag info if applicable. func (p *Value[T]) AddTo(flags *flag.FlagSet, name, usage string) { usage += p.envUsage() flags.Var(p, name, usage) @@ -78,10 +95,12 @@ func (p Value[T]) String() string { return fmt.Sprintf("%v", p.flagValue) } +// Get the value of the flag. func (p Value[T]) Get() T { return p.flagValue } +// Implements flag.Setter func (p *Value[T]) Set(value string) error { if p.converter == nil { return fmt.Errorf("no converter for type %T", p.flagValue) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29