| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | ) |
| 6 | |
| 7 | // delayedEnvironment is an implementation of the Environment which wraps the legacy |
| 8 | // behavior of `*config.Configuration.loadGitConfig()`. |
| 9 | // |
| 10 | // It is functionally equivalent to call `cfg.loadGitConfig()` before calling |
| 11 | // methods on the Environment type. |
| 12 | type delayedEnvironment struct { |
| 13 | env Environment |
| 14 | loading sync.Mutex |
| 15 | callback func() Environment |
| 16 | } |
| 17 | |
| 18 | // Get is shorthand for calling the e.Load(), and then returning |
| 19 | // `e.env.Get(key)`. |
| 20 | func (e *delayedEnvironment) Get(key string) (string, bool) { |
| 21 | e.Load() |
| 22 | return e.env.Get(key) |
| 23 | } |
| 24 | |
| 25 | // Get is shorthand for calling the e.Load(), and then returning |
| 26 | // `e.env.GetAll(key)`. |
| 27 | func (e *delayedEnvironment) GetAll(key string) []string { |
| 28 | e.Load() |
| 29 | return e.env.GetAll(key) |
| 30 | } |
| 31 | |
| 32 | // Get is shorthand for calling the e.Load(), and then returning |
| 33 | // `e.env.Bool(key, def)`. |
| 34 | func (e *delayedEnvironment) Bool(key string, def bool) bool { |
| 35 | e.Load() |
| 36 | return e.env.Bool(key, def) |
| 37 | } |
| 38 | |
| 39 | // Get is shorthand for calling the e.Load(), and then returning |
| 40 | // `e.env.Int(key, def)`. |
| 41 | func (e *delayedEnvironment) Int(key string, def int) int { |
| 42 | e.Load() |
| 43 | return e.env.Int(key, def) |
| 44 | } |
| 45 | |
| 46 | // Int64 is shorthand for calling the e.Load(), and then returning |
| 47 | // `e.env.Int64(key, def)`. |
| 48 | func (e *delayedEnvironment) Int64(key string, def int64) int64 { |
| 49 | e.Load() |
| 50 | return e.env.Int64(key, def) |
| 51 | } |
| 52 | |
| 53 | // All returns a copy of all the key/value pairs for the current git config. |
| 54 | func (e *delayedEnvironment) All() map[string][]string { |
| 55 | e.Load() |
| 56 | return e.env.All() |
| 57 | } |
| 58 | |
| 59 | // Load reads and parses the .gitconfig by calling ReadGitConfig. It |
| 60 | // also sets values on the configuration instance `g.config`. |
| 61 | // |
| 62 | // If Load has already been called, this method will bail out early, |
| 63 | // and return false. Otherwise it will perform the entire parse and return true. |
| 64 | // |
| 65 | // Load is safe to call across multiple goroutines. |
| 66 | func (e *delayedEnvironment) Load() { |
| 67 | e.loading.Lock() |
| 68 | defer e.loading.Unlock() |
| 69 | |
| 70 | if e.env != nil { |
| 71 | return |
| 72 | } |
| 73 | |
| 74 | e.env = e.callback() |
| 75 | } |