github.com/psexton/git-lfs@v2.1.1-0.20170517224304-289a18b2bc53+incompatible/config/environment.go (about) 1 package config 2 3 import ( 4 "strconv" 5 "strings" 6 ) 7 8 // An Environment adds additional behavior to a Fetcher, such a type conversion, 9 // and default values. 10 // 11 // `Environment`s are the primary way to communicate with various configuration 12 // sources, such as the OS environment variables, the `.gitconfig`, and even 13 // `map[string]string`s. 14 type Environment interface { 15 // Get is shorthand for calling `e.Fetcher.Get(key)`. 16 Get(key string) (val string, ok bool) 17 18 // Get is shorthand for calling `e.Fetcher.GetAll(key)`. 19 GetAll(key string) (vals []string) 20 21 // Bool returns the boolean state associated with a given key, or the 22 // value "def", if no value was associated. 23 // 24 // The "boolean state associated with a given key" is defined as the 25 // case-insensitive string comparison with the following: 26 // 27 // 1) true if... 28 // "true", "1", "on", "yes", or "t" 29 // 2) false if... 30 // "false", "0", "off", "no", "f", or otherwise. 31 Bool(key string, def bool) (val bool) 32 33 // Int returns the int value associated with a given key, or the value 34 // "def", if no value was associated. 35 // 36 // To convert from a the string value attached to a given key, 37 // `strconv.Atoi(val)` is called. If `Atoi` returned a non-nil error, 38 // then the value "def" will be returned instead. 39 // 40 // Otherwise, if the value was converted `string -> int` successfully, 41 // then it will be returned wholesale. 42 Int(key string, def int) (val int) 43 44 // All returns a copy of all the key/value pairs for the current 45 // environment. 46 All() map[string][]string 47 } 48 49 type environment struct { 50 // Fetcher is the `environment`'s source of data. 51 Fetcher Fetcher 52 } 53 54 // EnvironmentOf creates a new `Environment` initialized with the givne 55 // `Fetcher`, "f". 56 func EnvironmentOf(f Fetcher) Environment { 57 return &environment{f} 58 } 59 60 func (e *environment) Get(key string) (val string, ok bool) { 61 return e.Fetcher.Get(key) 62 } 63 64 func (e *environment) GetAll(key string) []string { 65 return e.Fetcher.GetAll(key) 66 } 67 68 func (e *environment) Bool(key string, def bool) (val bool) { 69 s, _ := e.Fetcher.Get(key) 70 if len(s) == 0 { 71 return def 72 } 73 74 switch strings.ToLower(s) { 75 case "true", "1", "on", "yes", "t": 76 return true 77 case "false", "0", "off", "no", "f": 78 return false 79 default: 80 return false 81 } 82 } 83 84 func (e *environment) Int(key string, def int) (val int) { 85 s, _ := e.Fetcher.Get(key) 86 if len(s) == 0 { 87 return def 88 } 89 90 i, err := strconv.Atoi(s) 91 if err != nil { 92 return def 93 } 94 95 return i 96 } 97 98 func (e *environment) All() map[string][]string { 99 return e.Fetcher.All() 100 }