-
Notifications
You must be signed in to change notification settings - Fork 21
/
central_config_yaml_reader.go
88 lines (72 loc) · 2.14 KB
/
central_config_yaml_reader.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
// Copyright 2024 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package centralconfig implements an interface to deal with the central configuration.
package centralconfig
import (
"fmt"
"os"
"reflect"
"gopkg.in/yaml.v3"
)
// KeyNotFoundError represents an error when the key is not found in the central configuration.
type KeyNotFoundError struct {
Key string
}
func (e *KeyNotFoundError) Error() string {
return fmt.Sprintf("key '%s' not found in central config", e.Key)
}
type centralConfigYamlReader struct {
// configFile is the path to the central config file.
configFile string
}
// Make sure centralConfigYamlReader implements CentralConfig
var _ CentralConfig = ¢ralConfigYamlReader{}
// parseConfigFile reads the central config file and returns the parsed yaml content.
// If the file does not exist, it does not return an error because some central repositories
// may choose not to have a central config file.
func (c *centralConfigYamlReader) parseConfigFile() (map[string]interface{}, error) {
// Check if the central config file exists.
if _, err := os.Stat(c.configFile); os.IsNotExist(err) {
// The central config file is optional, don't return an error if it does not exist.
return nil, nil
}
bytes, err := os.ReadFile(c.configFile)
if err != nil {
return nil, err
}
var content map[string]interface{}
err = yaml.Unmarshal(bytes, &content)
if err != nil {
return nil, err
}
return content, nil
}
func (c *centralConfigYamlReader) GetCentralConfigEntry(key string, out interface{}) error {
values, err := c.parseConfigFile()
if err != nil {
return err
}
ok, err := extractValue(out, values, key)
if err != nil {
return err
}
if !ok {
return &KeyNotFoundError{Key: key}
}
return nil
}
func extractValue(out interface{}, values map[string]interface{}, key string) (bool, error) {
res, ok := values[key]
if !ok {
return false, nil
}
v := reflect.ValueOf(out)
if v.Kind() != reflect.Ptr || v.IsNil() {
return false, fmt.Errorf("out must be a pointer to a value")
}
yamlBytes, err := yaml.Marshal(res)
if err == nil {
err = yaml.Unmarshal(yamlBytes, out)
}
return ok, err
}