/
instance.go
251 lines (212 loc) · 6.51 KB
/
instance.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package config
import (
"database/sql"
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
C "github.com/ActiveState/cli/internal/constants"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/installation/storage"
"github.com/ActiveState/cli/internal/logging"
mediator "github.com/ActiveState/cli/internal/mediators/config"
"github.com/ActiveState/cli/internal/multilog"
"github.com/ActiveState/cli/internal/profile"
"github.com/ActiveState/cli/internal/rtutils/singlethread"
"github.com/spf13/cast"
"gopkg.in/yaml.v2"
_ "modernc.org/sqlite"
)
// Instance holds our main config logic
type Instance struct {
appDataDir string
thread *singlethread.Thread
closeThread bool
db *sql.DB
closed bool
}
func New() (*Instance, error) {
defer profile.Measure("config.New", time.Now())
return NewCustom("", singlethread.New(), true)
}
// NewCustom is intended only to be used from tests or internally to this package
func NewCustom(localPath string, thread *singlethread.Thread, closeThread bool) (*Instance, error) {
i := &Instance{}
i.thread = thread
i.closeThread = closeThread
var err error
if localPath != "" {
i.appDataDir, err = storage.AppDataPathWithParent(localPath)
} else {
i.appDataDir, err = storage.AppDataPath()
}
if err != nil {
return nil, errs.Wrap(err, "Could not detect appdata dir")
}
// Ensure appdata dir exists, because the sqlite driver sure doesn't
if _, err := os.Stat(i.appDataDir); os.IsNotExist(err) {
err = os.MkdirAll(i.appDataDir, os.ModePerm)
if err != nil {
return nil, errs.Wrap(err, "Could not create config dir")
}
}
path := filepath.Join(i.appDataDir, C.InternalConfigFileName)
t := time.Now()
i.db, err = sql.Open("sqlite", path)
if err != nil {
return nil, errs.Wrap(err, "Could not create sqlite connection to %s", path)
}
profile.Measure("config.sqlOpen", t)
t = time.Now()
_, err = i.db.Exec(`CREATE TABLE IF NOT EXISTS config (key string NOT NULL PRIMARY KEY, value text)`)
if err != nil {
return nil, errs.Wrap(err, "Could not seed settings database")
}
profile.Measure("config.createTable", t)
return i, nil
}
func (i *Instance) Close() error {
mutex := sync.Mutex{}
mutex.Lock()
defer mutex.Unlock()
if i.closed {
return nil
}
i.closed = true
if i.closeThread {
i.thread.Close()
}
return i.db.Close()
}
func (i *Instance) Closed() bool {
return i.closed
}
// GetThenSet updates a value at the given key. The valueF argument returns the
// new value to set based on the previous one. If the function returns with an error, the
// update is cancelled. The function ensures that no-other process or thread can modify
// the key between reading of the old value and setting the new value.
func (i *Instance) GetThenSet(key string, valueF func(currentValue interface{}) (interface{}, error)) error {
return i.thread.Run(func() error {
return i.setWithCallback(key, valueF)
})
}
const CancelSet = "__CANCEL__"
func (i *Instance) setWithCallback(key string, valueF func(currentValue interface{}) (interface{}, error)) (rerr error) {
defer func() {
if rerr != nil {
logging.Warning("setWithCallback error: %v", errs.JoinMessage(rerr))
}
}()
v, err := valueF(i.Get(key))
if err != nil {
return errs.Wrap(err, "valueF failed")
}
if v == CancelSet {
logging.Debug("setWithCallback cancelled")
return nil
}
q, err := i.db.Prepare(`INSERT OR REPLACE INTO config(key, value) VALUES(?,?)`)
if err != nil {
return errs.Wrap(err, "Could not modify settings")
}
defer q.Close()
valueMarshaled, err := yaml.Marshal(v)
if err != nil {
return errs.Wrap(err, "Could not marshal config value: %v", v)
}
_, err = q.Exec(key, valueMarshaled)
if err != nil {
return errs.Wrap(err, "Could not store setting")
}
return nil
}
// Set sets a value at the given key.
func (i *Instance) Set(key string, value interface{}) error {
return i.GetThenSet(key, func(_ interface{}) (interface{}, error) {
return value, nil
})
}
func (i *Instance) IsSet(key string) bool {
return i.rawGet(key) != nil
}
func (i *Instance) rawGet(key string) interface{} {
row := i.db.QueryRow(`SELECT value FROM config WHERE key=?`, key)
if row.Err() != nil {
multilog.Error("config:get query failed: %s", errs.JoinMessage(row.Err()))
return nil
}
var value string
if err := row.Scan(&value); err != nil {
return nil // No results
}
var result interface{}
if err := yaml.Unmarshal([]byte(value), &result); err != nil {
if err2 := json.Unmarshal([]byte(value), &result); err2 != nil {
multilog.Error("config:get unmarshal failed: %s (json err: %s)", errs.JoinMessage(err), errs.JoinMessage(err2))
return nil
}
}
return result
}
func (i *Instance) Get(key string) interface{} {
result := i.rawGet(key)
if result != nil {
return result
}
if opt := mediator.GetOption(key); mediator.KnownOption(opt) {
return opt.Default
}
return nil
}
// GetString retrieves a string for a given key
func (i *Instance) GetString(key string) string {
return cast.ToString(i.Get(key))
}
// GetInt retrieves an int for a given key
func (i *Instance) GetInt(key string) int {
return cast.ToInt(i.Get(key))
}
// AllKeys returns all of the curent config keys
func (i *Instance) AllKeys() []string {
rows, err := i.db.Query(`SELECT key FROM config`)
if err != nil {
multilog.Error("config:AllKeys query failed: %s", errs.JoinMessage(err))
return nil
}
var keys []string
defer rows.Close()
for rows.Next() {
var key string
if err = rows.Scan(&key); err != nil {
multilog.Error("config:AllKeys scan failed: %s", errs.JoinMessage(err))
return nil
}
keys = append(keys, key)
}
return keys
}
// GetStringMapStringSlice retrieves a map of string slices for a given key
func (i *Instance) GetStringMapStringSlice(key string) map[string][]string {
return cast.ToStringMapStringSlice(i.Get(key))
}
// GetBool retrieves a boolean value for a given key
func (i *Instance) GetBool(key string) bool {
return cast.ToBool(i.Get(key))
}
// GetStringSlice retrieves a slice of strings for a given key
func (i *Instance) GetStringSlice(key string) []string {
return cast.ToStringSlice(i.Get(key))
}
// GetTime retrieves a time instance for a given key
func (i *Instance) GetTime(key string) time.Time {
return cast.ToTime(i.Get(key))
}
// GetStringMap retrieves a map of strings to values for a given key
func (i *Instance) GetStringMap(key string) map[string]interface{} {
return cast.ToStringMap(i.Get(key))
}
// ConfigPath returns the path at which our configuration is stored
func (i *Instance) ConfigPath() string {
return i.appDataDir
}