-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfile.go
103 lines (78 loc) · 2.31 KB
/
file.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
package configr
import (
"errors"
"io/ioutil"
"path/filepath"
"strings"
)
type FileDecoder interface {
Unmarshal([]byte, interface{}) error
}
var (
RegisteredFileEncoders = make(map[string]Encoder)
RegisteredFileDecoders = make(map[string]FileDecoder)
ExtensionToDecoderName = make(map[string]string)
ExtensionToEncoderName = make(map[string]string)
ErrUnknownEncoding = errors.New("configr: Unable to determine file encoding, please set manually")
)
func RegisterFileEncoder(name string, encoder Encoder, fileExtensions ...string) {
RegisteredFileEncoders[name] = encoder
registerExtensionsToMap(name, fileExtensions, ExtensionToEncoderName)
}
func RegisterFileDecoder(name string, source FileDecoder, fileExtensions ...string) {
RegisteredFileDecoders[name] = source
registerExtensionsToMap(name, fileExtensions, ExtensionToDecoderName)
}
func registerExtensionsToMap(name string, fileExtensions []string, extMap map[string]string) {
if len(fileExtensions) == 0 {
fileExtensions = append(fileExtensions, name)
}
for _, fileExtension := range fileExtensions {
extMap[fileExtension] = name
}
}
type File struct {
filePath string
encodingName string
}
func NewFile(path string) *File {
f := &File{}
f.SetPath(path)
return f
}
func (f *File) SetPath(path string) {
f.filePath = path
fileExt := getFileExtension(path)
if encodingName, found := ExtensionToDecoderName[fileExt]; found {
f.encodingName = encodingName
}
}
func (f *File) SetEncodingName(name string) {
f.encodingName = name
}
func (f *File) Path() string {
return f.filePath
}
func (f *File) Unmarshal(_ []string, _ KeySplitter) (map[string]interface{}, error) {
if decoder, found := RegisteredFileDecoders[f.encodingName]; found {
values := make(map[string]interface{})
fileBytes, err := ioutil.ReadFile(f.filePath)
if err != nil {
return values, err
}
if err := decoder.Unmarshal(fileBytes, &values); err != nil {
return values, err
}
return values, nil
}
return map[string]interface{}{}, ErrUnknownEncoding
}
func (f *File) Marshal(v interface{}) ([]byte, error) {
if encoder, found := RegisteredFileEncoders[f.encodingName]; found {
return encoder.Marshal(v)
}
return []byte{}, ErrUnknownEncoding
}
func getFileExtension(filePath string) string {
return strings.TrimPrefix(filepath.Ext(filePath), ".")
}