github.com/googollee/clic@v0.1.5/source/env.go (about) 1 package source 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "strings" 8 9 "github.com/googollee/clic/structtags" 10 ) 11 12 type EnvOption func(*envSource) error 13 14 func EnvSplitter(splitter string) EnvOption { 15 return func(s *envSource) error { 16 if splitter == "" { 17 return fmt.Errorf("invalid splitter: %q", splitter) 18 } 19 s.splitter = splitter 20 return nil 21 } 22 } 23 24 type envSource struct { 25 splitter string 26 err error 27 fields []structtags.Field 28 } 29 30 func Env(options ...EnvOption) Source { 31 ret := envSource{ 32 splitter: "_", 33 } 34 35 for _, option := range options { 36 if err := option(&ret); err != nil { 37 ret.err = err 38 } 39 } 40 41 return &ret 42 } 43 44 func (s *envSource) Error() error { 45 return s.err 46 } 47 48 func (s *envSource) Register(fset FlagSet, fields []structtags.Field) error { 49 if s.err != nil { 50 return s.err 51 } 52 53 s.fields = fields 54 55 return nil 56 } 57 58 func (s *envSource) Parse(ctx context.Context, args []string) error { 59 if s.err != nil { 60 return s.err 61 } 62 63 for _, field := range s.fields { 64 name := field.Name 65 66 envKey := strings.ToUpper(strings.Join(name, s.splitter)) 67 envValue, exist := os.LookupEnv(envKey) 68 if !exist { 69 continue 70 } 71 72 if err := field.UnmarshalText([]byte(envValue)); err != nil { 73 return fmt.Errorf("parse env (%s: %q) error: %w", envKey, envValue, err) 74 } 75 } 76 77 return nil 78 }