-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_config.go
108 lines (89 loc) · 2.06 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
100
101
102
103
104
105
106
107
108
package pluginconfig
import (
"sync"
"code.cloudfoundry.org/cli/cf/configuration"
)
//go:generate counterfeiter . PluginConfiguration
type PluginConfiguration interface {
Plugins() map[string]PluginMetadata
SetPlugin(string, PluginMetadata)
GetPluginPath() string
RemovePlugin(string)
ListCommands() []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), persistor configuration.Persistor, pluginPath string) *PluginConfig {
return &PluginConfig{
data: NewData(),
mutex: new(sync.RWMutex),
initOnce: new(sync.Once),
persistor: persistor,
onError: errorHandler,
pluginPath: pluginPath,
}
}
func (c *PluginConfig) GetPluginPath() string {
return c.pluginPath
}
func (c *PluginConfig) Plugins() map[string]PluginMetadata {
c.read()
return c.data.Plugins
}
func (c *PluginConfig) SetPlugin(name string, metadata PluginMetadata) {
if c.data.Plugins == nil {
c.data.Plugins = make(map[string]PluginMetadata)
}
c.write(func() {
c.data.Plugins[name] = metadata
})
}
func (c *PluginConfig) RemovePlugin(name string) {
c.write(func() {
delete(c.data.Plugins, name)
})
}
func (c *PluginConfig) ListCommands() []string {
plugins := c.Plugins()
allCommands := []string{}
for _, plugin := range plugins {
for _, command := range plugin.Commands {
allCommands = append(allCommands, command.Name)
}
}
return allCommands
}
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)
}
}
func (c *PluginConfig) Close() {
c.read()
// perform a read to ensure write lock has been cleared
}