-
Notifications
You must be signed in to change notification settings - Fork 266
/
config-store.ts
302 lines (249 loc) · 8.23 KB
/
config-store.ts
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
* Copyright (C) 2018-2020 Garden Technologies, Inc. <info@garden.io>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import yaml from "js-yaml"
import { join } from "path"
import { ensureFile, readFile } from "fs-extra"
import { get, isPlainObject, unset, mapValues } from "lodash"
import { Primitive, joiArray, joiPrimitive, joi } from "./config/common"
import { validateSchema } from "./config/validation"
import { LocalConfigError } from "./exceptions"
import { dumpYaml } from "./util/util"
import { LOCAL_CONFIG_FILENAME, GLOBAL_CONFIG_FILENAME, GARDEN_GLOBAL_PATH } from "./constants"
import { linkedSourceSchema } from "./config/project"
export type ConfigValue = Primitive | Primitive[] | Object[] | Object
export type SetManyParam = { keyPath: Array<string>; value: ConfigValue }[]
export abstract class ConfigStore<T extends object = any> {
private config: null | T
protected configPath: string
constructor(gardenDirPath: string) {
this.configPath = this.getConfigPath(gardenDirPath)
this.config = null
}
abstract getConfigPath(gardenDirPath: string): string
abstract validate(config): T
/**
* Would've been nice to allow something like: set(["path", "to", "valA", valA], ["path", "to", "valB", valB]...)
* but Typescript support is missing at the moment
*/
public async set(param: SetManyParam): Promise<void>
public async set(keyPath: string[], value: ConfigValue): Promise<void>
public async set(...args): Promise<void> {
let config = await this.getConfig()
let entries: SetManyParam
if (args.length === 1) {
entries = args[0]
} else {
entries = [{ keyPath: args[0], value: args[1] }]
}
for (const { keyPath, value } of entries) {
config = this.updateConfig(config, keyPath, value)
}
await this.saveConfig(config)
}
public async get(): Promise<T>
public async get(keyPath: string[]): Promise<Object | ConfigValue>
public async get(keyPath?: string[]): Promise<Object | ConfigValue> {
const config = await this.getConfig()
if (keyPath) {
const value = get(config, keyPath)
if (value === undefined) {
this.throwKeyNotFound(config, keyPath)
}
return value
}
return config
}
public async clear() {
await this.saveConfig(<T>{})
}
public async delete(keyPath: string[]) {
let config = await this.getConfig()
if (get(config, keyPath) === undefined) {
this.throwKeyNotFound(config, keyPath)
}
const success = unset(config, keyPath)
if (!success) {
throw new LocalConfigError(`Unable to delete key ${keyPath.join(".")} in user config`, {
keyPath,
config,
})
}
await this.saveConfig(config)
}
private async getConfig(): Promise<T> {
if (!this.config) {
await this.loadConfig()
}
// Spreading does not work on generic types, see: https://github.com/Microsoft/TypeScript/issues/13557
return Object.assign(this.config, {})
}
private updateConfig(config: T, keyPath: string[], value: ConfigValue): T {
let currentValue = config
for (let i = 0; i < keyPath.length; i++) {
const k = keyPath[i]
if (i === keyPath.length - 1) {
currentValue[k] = value
} else if (currentValue[k] === undefined) {
currentValue[k] = {}
} else if (!isPlainObject(currentValue[k])) {
const path = keyPath.slice(i + 1).join(".")
throw new LocalConfigError(
`Attempting to assign a nested key on non-object (current value at ${path}: ${currentValue[k]})`,
{
currentValue: currentValue[k],
path,
}
)
}
currentValue = currentValue[k]
}
return config
}
private async ensureConfigFile() {
await ensureFile(this.configPath)
}
private async loadConfig() {
await this.ensureConfigFile()
const config = yaml.safeLoad((await readFile(this.configPath)).toString()) || {}
this.config = this.validate(config)
}
private async saveConfig(config: T) {
this.config = null
const validated = this.validate(config)
await dumpYaml(this.configPath, validated)
this.config = validated
}
private throwKeyNotFound(config: T, keyPath: string[]) {
throw new LocalConfigError(`Could not find key ${keyPath.join(".")} in user config`, {
keyPath,
config,
})
}
}
/*********************************************
* *
* LocalConfigStore implementation *
* *
**********************************************/
export interface LinkedSource {
name: string
path: string
}
export interface AnalyticsLocalConfig {
projectId: string
}
export interface LocalConfig {
linkedModuleSources?: LinkedSource[] // TODO Use KeyedSet instead of array
linkedProjectSources?: LinkedSource[]
analytics: AnalyticsLocalConfig
}
const analyticsLocalConfigSchema = () =>
joi
.object()
.keys({
projectId: joi.string(),
})
.meta({ internal: true })
const localConfigSchemaKeys = {
linkedModuleSources: () => joiArray(linkedSourceSchema()),
linkedProjectSources: () => joiArray(linkedSourceSchema()),
analytics: () => analyticsLocalConfigSchema(),
}
export const localConfigKeys = () =>
Object.keys(localConfigSchemaKeys).reduce((acc, key) => {
acc[key] = key
return acc
}, {}) as { [K in keyof typeof localConfigSchemaKeys]: K }
const localConfigSchema = () =>
joi
.object()
.keys(mapValues(localConfigSchemaKeys, (schema) => schema()))
.meta({ internal: true })
// TODO: we should not be passing this to provider actions
export const configStoreSchema = () =>
joi.object().description("Helper class for managing local configuration for plugins.")
export class LocalConfigStore extends ConfigStore<LocalConfig> {
getConfigPath(gardenDirPath: string): string {
return join(gardenDirPath, LOCAL_CONFIG_FILENAME)
}
validate(config): LocalConfig {
return validateSchema(config, localConfigSchema(), {
context: this.configPath,
ErrorClass: LocalConfigError,
})
}
}
/*********************************************
* *
* GlobalConfigStore implementation *
* *
**********************************************/
export type AnalyticsGlobalConfig = {
userId?: string
optedIn?: boolean
firstRun?: boolean
showOptInMessage?: boolean
} & {
[key: string]: any
}
export interface VersionCheckGlobalConfig {
lastRun: Date
}
export interface GlobalConfig {
analytics?: AnalyticsGlobalConfig
lastVersionCheck?: VersionCheckGlobalConfig
}
const analyticsGlobalConfigSchema = () =>
joi
.object()
.keys({
userId: joiPrimitive().allow("").optional(),
optedIn: joi.boolean().optional(),
firstRun: joi.boolean().optional(),
showOptInMessage: joi.boolean().optional(),
})
.unknown(true)
.meta({ internal: true })
const versionCheckGlobalConfigSchema = () =>
joi
.object()
.keys({
lastRun: joi.date().optional(),
})
.meta({ internal: true })
const globalConfigSchemaKeys = {
analytics: analyticsGlobalConfigSchema(),
lastVersionCheck: versionCheckGlobalConfigSchema(),
}
/* This contains a config key, key string pair to be used when setting/getting values in the store
eg.
globalConfigKeys = {
analytics: "analytics"
}
used like:
globalConfigStore.set([globalConfigKeys.analytics], { data: value })
*/
export const globalConfigKeys = Object.keys(globalConfigSchemaKeys).reduce((acc, key) => {
acc[key] = key
return acc
}, {}) as { [K in keyof typeof globalConfigSchemaKeys]: K }
const globalConfigSchema = () => joi.object().keys(globalConfigSchemaKeys).meta({ internal: true })
export class GlobalConfigStore extends ConfigStore<GlobalConfig> {
constructor() {
super(GARDEN_GLOBAL_PATH)
}
getConfigPath(): string {
return join(GARDEN_GLOBAL_PATH, GLOBAL_CONFIG_FILENAME)
}
validate(config): GlobalConfig {
return validateSchema(config, globalConfigSchema(), {
context: this.configPath,
ErrorClass: LocalConfigError,
})
}
}