go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/configutil/option.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package configutil 9 10 import ( 11 "bytes" 12 "context" 13 "io" 14 ) 15 16 // Option is a modification of config options. 17 type Option func(*ConfigOptions) error 18 19 // OptEnv sets the env vars on the options. 20 func OptEnv(vars map[string]string) Option { 21 return func(co *ConfigOptions) error { 22 co.Env = vars 23 return nil 24 } 25 } 26 27 // OptDeserializer sets the deserializer on the options. 28 func OptDeserializer(fn func(io.Reader, any) error) Option { 29 return func(co *ConfigOptions) error { 30 co.Deserializer = fn 31 return nil 32 } 33 } 34 35 // OptContext sets the context on the options. 36 func OptContext(ctx context.Context) Option { 37 return func(co *ConfigOptions) error { 38 co.Context = ctx 39 return nil 40 } 41 } 42 43 // OptContents sets config contents on the options. 44 func OptContents(contents ...io.Reader) Option { 45 return func(co *ConfigOptions) error { 46 co.Contents = contents 47 return nil 48 } 49 } 50 51 // OptAddContent adds contents to the options as a reader. 52 func OptAddContent(content io.Reader) Option { 53 return func(co *ConfigOptions) error { 54 co.Contents = append(co.Contents, 55 content, 56 ) 57 return nil 58 } 59 } 60 61 // OptAddContentString adds contents to the options as a string. 62 func OptAddContentString(contents string) Option { 63 return func(co *ConfigOptions) error { 64 co.Contents = append(co.Contents, bytes.NewReader([]byte(contents))) 65 return nil 66 } 67 } 68 69 // OptAddPaths adds paths to search for the config file. 70 // 71 // These paths will be added after the default paths. 72 func OptAddPaths(paths ...string) Option { 73 return func(co *ConfigOptions) error { 74 co.FilePaths = append(co.FilePaths, paths...) 75 return nil 76 } 77 } 78 79 // OptAddFilePaths is deprecated; use `OptAddPaths` 80 func OptAddFilePaths(paths ...string) Option { 81 return OptAddPaths(paths...) 82 } 83 84 // OptAddPreferredPaths adds paths to search first for the config file. 85 func OptAddPreferredPaths(paths ...string) Option { 86 return func(co *ConfigOptions) error { 87 co.FilePaths = append(paths, co.FilePaths...) 88 return nil 89 } 90 } 91 92 // OptPaths sets paths to search for the config file. 93 func OptPaths(paths ...string) Option { 94 return func(co *ConfigOptions) error { 95 co.FilePaths = paths 96 return nil 97 } 98 } 99 100 // OptUnsetPaths removes default paths from the paths set. 101 func OptUnsetPaths() Option { 102 return func(co *ConfigOptions) error { 103 co.FilePaths = nil 104 return nil 105 } 106 }