-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathio.go
455 lines (378 loc) · 9.73 KB
/
io.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package config
import (
"bufio"
"bytes"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"github.com/speakeasy-api/sdk-gen-config/workspace"
"gopkg.in/yaml.v3"
)
const (
configFile = "gen.yaml"
lockFile = "gen.lock"
)
type Config struct {
Config *Configuration
ConfigPath string
LockFile *LockFile
}
type FS interface {
fs.ReadFileFS
fs.StatFS
WriteFile(name string, data []byte, perm os.FileMode) error
}
type Option func(*options)
type (
GetLanguageDefaultFunc func(string, bool) (*LanguageConfig, error)
TransformerFunc func(*Config) (*Config, error)
ValidateFunc func(Config) error
)
type options struct {
FS FS
UpgradeFunc UpgradeFunc
getLanguageDefaultFunc GetLanguageDefaultFunc
langs []string
transformerFunc TransformerFunc
validateFunc ValidateFunc
dontWrite bool
}
func WithFileSystem(fs FS) Option {
return func(o *options) {
o.FS = fs
}
}
func WithDontWrite() Option {
return func(o *options) {
o.dontWrite = true
}
}
func WithUpgradeFunc(f UpgradeFunc) Option {
return func(o *options) {
o.UpgradeFunc = f
}
}
func WithLanguageDefaultFunc(f GetLanguageDefaultFunc) Option {
return func(o *options) {
o.getLanguageDefaultFunc = f
}
}
func WithLanguages(langs ...string) Option {
return func(o *options) {
o.langs = langs
}
}
func WithTransformerFunc(f TransformerFunc) Option {
return func(o *options) {
o.transformerFunc = f
}
}
func WithValidateFunc(f ValidateFunc) Option {
return func(o *options) {
o.validateFunc = f
}
}
func FindConfigFile(dir string, fileSystem FS) (*workspace.FindWorkspaceResult, error) {
configRes, err := workspace.FindWorkspace(dir, workspace.FindWorkspaceOptions{
FindFile: configFile,
AllowOutside: true,
Recursive: true,
FS: fileSystem,
})
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
configRes = &workspace.FindWorkspaceResult{
Path: filepath.Join(dir, workspace.SpeakeasyFolder, configFile),
}
} else {
return nil, err
}
}
return configRes, nil
}
func Load(dir string, opts ...Option) (*Config, error) {
o := applyOptions(opts)
newConfig := false
newSDK := false
newForLang := map[string]bool{}
// Find existing config file
configRes, err := FindConfigFile(dir, o.FS)
if err != nil {
return nil, err
}
if configRes.Data == nil {
newConfig = true
newSDK = true
for _, lang := range o.langs {
newForLang[lang] = true
}
}
// Make sure to use the same workspace dir type as the config file
workspaceDir := filepath.Base(filepath.Dir(configRes.Path))
if workspaceDir != workspace.SpeakeasyFolder && workspaceDir != workspace.GenFolder {
workspaceDir = workspace.SpeakeasyFolder
}
newLockFile := false
lockFileRes, err := workspace.FindWorkspace(filepath.Join(dir, workspaceDir), workspace.FindWorkspaceOptions{
FindFile: lockFile,
FS: o.FS,
})
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("could not read gen.lock: %w", err)
}
lockFileRes = &workspace.FindWorkspaceResult{
Path: filepath.Join(dir, workspaceDir, lockFile),
}
newLockFile = true
}
if !newConfig {
// Unmarshal config file and check version
cfgMap := map[string]any{}
if err := yaml.Unmarshal(configRes.Data, &cfgMap); err != nil {
return nil, fmt.Errorf("could not unmarshal gen.yaml: %w", err)
}
var lockFileMap map[string]any
lockFilePresent := false
if lockFileRes.Data != nil {
if err := yaml.Unmarshal(lockFileRes.Data, &lockFileMap); err != nil {
return nil, fmt.Errorf("could not unmarshal gen.lock: %w", err)
}
lockFilePresent = true
}
version := ""
v, ok := cfgMap["configVersion"]
if ok {
version, ok = v.(string)
if !ok {
version = ""
}
}
// If we aren't upgrading we assume if we are missing a lock file then this is a new SDK
if version == Version {
newSDK = newSDK || newLockFile
}
if version != Version && o.UpgradeFunc != nil {
// Upgrade config file if version is different and write it
cfgMap, lockFileMap, err = upgrade(version, cfgMap, lockFileMap, o.UpgradeFunc)
if err != nil {
return nil, err
}
// Write back out to disk and update data
configRes.Data, err = write(configRes.Path, cfgMap, o)
if err != nil {
return nil, err
}
if lockFileMap != nil {
lockFileRes.Data, err = write(lockFileRes.Path, lockFileMap, o)
if err != nil {
return nil, err
}
}
}
if lockFileMap != nil {
if lockFileMap["features"] == nil && version != "" {
for _, lang := range o.langs {
newForLang[lang] = true
}
} else if features, ok := lockFileMap["features"].(map[string]interface{}); ok {
for _, lang := range o.langs {
if _, ok := features[lang]; !ok {
newForLang[lang] = true
}
}
}
} else if !lockFilePresent {
for _, lang := range o.langs {
newForLang[lang] = true
}
}
}
requiredDefaults := map[string]bool{}
for _, lang := range o.langs {
requiredDefaults[lang] = newForLang[lang]
}
defaultCfg, err := GetDefaultConfig(newSDK, o.getLanguageDefaultFunc, requiredDefaults)
if err != nil {
return nil, err
}
cfg, err := GetDefaultConfig(newSDK, o.getLanguageDefaultFunc, requiredDefaults)
if err != nil {
return nil, err
}
// If this is a totally new config, we need to write out to disk for following operations
if newConfig && o.UpgradeFunc != nil {
// Write new cfg
configRes.Data, err = write(configRes.Path, cfg, o)
if err != nil {
return nil, err
}
}
if lockFileRes.Data == nil && o.UpgradeFunc != nil {
lockFile := NewLockFile()
lockFileRes.Data, err = write(lockFileRes.Path, lockFile, o)
if err != nil {
return nil, err
}
}
// Okay finally able to unmarshal the config file into expected struct
if err := yaml.Unmarshal(configRes.Data, cfg); err != nil {
return nil, fmt.Errorf("could not unmarshal gen.yaml: %w", err)
}
var lockFile LockFile
if err := yaml.Unmarshal(lockFileRes.Data, &lockFile); err != nil {
return nil, fmt.Errorf("could not unmarshal gen.lock: %w", err)
}
cfg.New = newForLang
// Maps are overwritten by unmarshal, so we need to ensure that the defaults are set
for lang, langCfg := range defaultCfg.Languages {
if _, ok := cfg.Languages[lang]; !ok {
cfg.Languages[lang] = langCfg
}
for k, v := range langCfg.Cfg {
if cfg.Languages[lang].Cfg == nil {
langCfg = cfg.Languages[lang]
langCfg.Cfg = map[string]interface{}{}
cfg.Languages[lang] = langCfg
}
if _, ok := cfg.Languages[lang].Cfg[k]; !ok {
cfg.Languages[lang].Cfg[k] = v
}
}
}
if lockFile.Features == nil {
lockFile.Features = make(map[string]map[string]string)
}
config := &Config{
Config: cfg,
ConfigPath: configRes.Path,
LockFile: &lockFile,
}
if o.transformerFunc != nil {
config, err = o.transformerFunc(config)
if err != nil {
return nil, err
}
}
if o.UpgradeFunc != nil {
// Finally write out the files to solidfy any defaults, upgrades or transformations
if _, err := write(configRes.Path, config.Config, o); err != nil {
return nil, err
}
if _, err := write(lockFileRes.Path, config.LockFile, o); err != nil {
return nil, err
}
}
if o.validateFunc != nil {
if err := o.validateFunc(*config); err != nil {
return nil, err
}
}
return config, nil
}
func GetTemplateVersion(dir, target string, opts ...Option) (string, error) {
o := applyOptions(opts)
configRes, err := FindConfigFile(dir, o.FS)
if err != nil {
return "", err
}
if configRes.Data == nil {
return "", nil
}
cfg := &Configuration{}
if err := yaml.Unmarshal(configRes.Data, cfg); err != nil {
return "", fmt.Errorf("could not unmarshal gen.yaml: %w", err)
}
if cfg.Languages == nil {
return "", nil
}
langCfg, ok := cfg.Languages[target]
if !ok {
return "", nil
}
tv, ok := langCfg.Cfg["templateVersion"]
if !ok {
return "", nil
}
return tv.(string), nil
}
func SaveConfig(dir string, cfg *Configuration, opts ...Option) error {
o := applyOptions(opts)
configRes, err := FindConfigFile(dir, o.FS)
if err != nil {
return err
}
if _, err := write(configRes.Path, cfg, o); err != nil {
return err
}
return nil
}
func SaveLockFile(dir string, lf *LockFile, opts ...Option) error {
o := applyOptions(opts)
lockFileRes, err := workspace.FindWorkspace(dir, workspace.FindWorkspaceOptions{
FindFile: lockFile,
FS: o.FS,
})
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return err
}
lockFileRes = &workspace.FindWorkspaceResult{
Path: filepath.Join(dir, workspace.SpeakeasyFolder, lockFile),
}
}
if _, err := write(lockFileRes.Path, lf, o); err != nil {
return err
}
return nil
}
func GetConfigChecksum(dir string, opts ...Option) (string, error) {
o := applyOptions(opts)
configRes, err := FindConfigFile(dir, o.FS)
if err != nil {
return "", err
}
if configRes.Data == nil {
return "", nil
}
hash := md5.Sum(configRes.Data)
return hex.EncodeToString(hash[:]), nil
}
func write(path string, cfg any, o *options) ([]byte, error) {
var b bytes.Buffer
buf := bufio.NewWriter(&b)
e := yaml.NewEncoder(buf)
e.SetIndent(2)
if err := e.Encode(cfg); err != nil {
return nil, fmt.Errorf("could not marshal %s: %w", path, err)
}
if err := buf.Flush(); err != nil {
return nil, fmt.Errorf("could not marshal %s: %w", path, err)
}
data := b.Bytes()
if o.dontWrite {
return data, nil
}
writeFileFunc := os.WriteFile
if o.FS != nil {
writeFileFunc = o.FS.WriteFile
}
if err := writeFileFunc(path, data, 0o666); err != nil {
return nil, fmt.Errorf("could not write gen.yaml: %w", err)
}
return data, nil
}
func applyOptions(opts []Option) *options {
o := &options{
FS: nil,
langs: []string{},
}
for _, opt := range opts {
opt(o)
}
return o
}