/
fileRecognizerInfo.go
59 lines (52 loc) · 1.5 KB
/
fileRecognizerInfo.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
package config
import (
"io/ioutil"
"path/filepath"
"github.com/airenas/listgo/internal/pkg/cmdapp"
"github.com/airenas/listgo/internal/pkg/recognizer"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
// FileRecognizerInfoLoader struct loads config from provided path
type FileRecognizerInfoLoader struct {
Path string
}
// NewFileRecognizerInfoLoader creates FileRecognizerInfoLoader instance
func NewFileRecognizerInfoLoader(path string) (*FileRecognizerInfoLoader, error) {
cmdapp.Log.Infof("Init Recognizer Info Loader from: %s", path)
if path == "" {
return nil, errors.New("No path provided")
}
f := FileRecognizerInfoLoader{Path: path}
return &f, nil
}
// Get return recognizer Info by provided key from file key + '.yml'
func (fs *FileRecognizerInfoLoader) Get(key string) (*recognizer.Info, error) {
if key == "" {
return nil, errors.New("No recognizer key provided")
}
file := filepath.Join(fs.Path, key+".yml")
return loadFile(file)
}
func loadFile(file string) (*recognizer.Info, error) {
fData, err := ioutil.ReadFile(file)
if err != nil {
return nil, errors.Wrap(err, "Can't load: "+file)
}
ri, err := loadYaml(fData)
if err != nil {
return nil, errors.Wrap(err, "Can't load: "+file)
}
return ri, nil
}
func loadYaml(data []byte) (*recognizer.Info, error) {
ri := recognizer.Info{}
err := yaml.Unmarshal(data, &ri)
if err != nil {
return nil, errors.Wrap(err, "Can't unmarshal")
}
if ri.Name == "" {
return nil, errors.New("No recognizer name in yaml")
}
return &ri, nil
}