Imported Upstream version 2.3.3
[scm/test.git] / config / git_environment.go
1 package config
2
3 // gitEnvironment is an implementation of the Environment which wraps the legacy
4 // behavior or `*config.Configuration.loadGitConfig()`.
5 //
6 // It is functionally equivelant to call `cfg.loadGitConfig()` before calling
7 // methods on the Environment type.
8 type gitEnvironment struct {
9         // git is the Environment which gitEnvironment wraps.
10         git Environment
11         // config is the *Configuration instance which is mutated by
12         // `loadGitConfig`.
13         config *Configuration
14 }
15
16 // Get is shorthand for calling the loadGitConfig, and then returning
17 // `g.git.Get(key)`.
18 func (g *gitEnvironment) Get(key string) (val string, ok bool) {
19         g.loadGitConfig()
20
21         return g.git.Get(key)
22 }
23
24 // Get is shorthand for calling the loadGitConfig, and then returning
25 // `g.git.GetAll(key)`.
26 func (g *gitEnvironment) GetAll(key string) []string {
27         g.loadGitConfig()
28
29         return g.git.GetAll(key)
30 }
31
32 // Get is shorthand for calling the loadGitConfig, and then returning
33 // `g.git.Bool(key, def)`.
34 func (g *gitEnvironment) Bool(key string, def bool) (val bool) {
35         g.loadGitConfig()
36
37         return g.git.Bool(key, def)
38 }
39
40 // Get is shorthand for calling the loadGitConfig, and then returning
41 // `g.git.Int(key, def)`.
42 func (g *gitEnvironment) Int(key string, def int) (val int) {
43         g.loadGitConfig()
44
45         return g.git.Int(key, def)
46 }
47
48 // All returns a copy of all the key/value pairs for the current git config.
49 func (g *gitEnvironment) All() map[string][]string {
50         g.loadGitConfig()
51
52         return g.git.All()
53 }
54
55 // loadGitConfig reads and parses the .gitconfig by calling ReadGitConfig. It
56 // also sets values on the configuration instance `g.config`.
57 //
58 // If loadGitConfig has already been called, this method will bail out early,
59 // and return false. Otherwise it will preform the entire parse and return true.
60 //
61 // loadGitConfig is safe to call across multiple goroutines.
62 func (g *gitEnvironment) loadGitConfig() bool {
63         g.config.loading.Lock()
64         defer g.config.loading.Unlock()
65
66         if g.git != nil {
67                 return false
68         }
69
70         gf, extensions, uniqRemotes := ReadGitConfig(getGitConfigs()...)
71
72         g.git = EnvironmentOf(gf)
73
74         g.config.extensions = extensions
75
76         g.config.remotes = make([]string, 0, len(uniqRemotes))
77         for remote, isOrigin := range uniqRemotes {
78                 if isOrigin {
79                         continue
80                 }
81                 g.config.remotes = append(g.config.remotes, remote)
82         }
83
84         return true
85 }