/
mappings.go
92 lines (76 loc) · 1.94 KB
/
mappings.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
package mapping
import (
"github.com/RincewindsHat/thola/config"
"github.com/RincewindsHat/thola/internal/tholaerr"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"io/ioutil"
"path/filepath"
"sync"
)
type mapping map[string]string
var mappings struct {
sync.Once
sync.Mutex
mappings map[string]mapping
}
func (m mapping) get(key string) (string, error) {
if model, ok := m[key]; ok {
return model, nil
}
return "", tholaerr.NewNotFoundError("oid is not in model mapping")
}
func readMapping(file string) (mapping, error) {
f, err := config.FileSystem.Open(filepath.Join("mapping", file))
if err != nil {
return nil, errors.New("failed to open mappings file")
}
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.New("failed to read mappings file")
}
m := make(map[string]string)
err = yaml.Unmarshal(b, &m)
if err != nil {
return nil, errors.New("failed to unmarshal sysObjectID mappings file")
}
return m, nil
}
func initializeMapping(file string) error {
mappings.Do(func() {
mappings.mappings = make(map[string]mapping)
})
if mappings.mappings == nil {
return errors.New("Mappings were not initialized")
}
mappings.Lock()
defer mappings.Unlock()
_, ok := mappings.mappings[file]
if !ok {
m, err := readMapping(file)
if err != nil {
return errors.Wrap(err, "failed to read mapping")
}
mappings.mappings[file] = m
}
if mappings.mappings[file] == nil {
return errors.New("Mapping was not initialized")
}
return nil
}
// GetMappedValue returns the value which the key is associated with in the specified file.
func GetMappedValue(file, key string) (string, error) {
err := initializeMapping(file)
if err != nil {
return "", err
}
return mappings.mappings[file].get(key)
}
// GetMapping returns the mapping of the specified file.
func GetMapping(file string) (map[string]string, error) {
err := initializeMapping(file)
if err != nil {
return nil, err
}
return mappings.mappings[file], nil
}