forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_config.go
99 lines (84 loc) · 1.94 KB
/
plugin_config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package plugin_config
import (
"path/filepath"
"sync"
"github.com/cloudfoundry/cli/cf/configuration"
"github.com/cloudfoundry/cli/cf/configuration/config_helpers"
)
type PluginConfiguration interface {
Plugins() map[string]string
SetPlugin(string, string)
GetPluginPath() string
RemovePlugin(string)
}
type PluginConfig struct {
mutex *sync.RWMutex
initOnce *sync.Once
persistor configuration.Persistor
onError func(error)
data *PluginData
pluginPath string
}
func NewPluginConfig(errorHandler func(error)) *PluginConfig {
pluginPath := filepath.Join(config_helpers.PluginRepoDir(), ".cf", "plugins")
return &PluginConfig{
data: NewData(),
mutex: new(sync.RWMutex),
initOnce: new(sync.Once),
persistor: configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
onError: errorHandler,
pluginPath: pluginPath,
}
}
/* getter methods */
func (c *PluginConfig) GetPluginPath() string {
return c.pluginPath
}
func (c *PluginConfig) Plugins() map[string]string {
c.read()
return c.data.Plugins
}
/* setter methods */
func (c *PluginConfig) SetPlugin(name, location string) {
if c.data.Plugins == nil {
c.data.Plugins = make(map[string]string)
}
c.write(func() {
c.data.Plugins[name] = location
})
}
func (c *PluginConfig) RemovePlugin(name string) {
c.write(func() {
delete(c.data.Plugins, name)
})
}
/* Functions that handel locking */
func (c *PluginConfig) init() {
//only read from disk if it was never read
c.initOnce.Do(func() {
err := c.persistor.Load(c.data)
if err != nil {
c.onError(err)
}
})
}
func (c *PluginConfig) read() {
c.mutex.RLock()
defer c.mutex.RUnlock()
c.init()
}
func (c *PluginConfig) write(cb func()) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.init()
cb()
err := c.persistor.Save(c.data)
if err != nil {
c.onError(err)
}
}
// CLOSERS
func (c *PluginConfig) Close() {
c.read()
// perform a read to ensure write lock has been cleared
}