-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_tools.go
68 lines (63 loc) · 1.31 KB
/
file_tools.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
package dragonfly
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
"io"
"os"
"path"
"strings"
)
func jsonDecoder(r io.Reader) func(v interface{}) error {
decoder := json.NewDecoder(r)
decoder.DisallowUnknownFields()
return decoder.Decode
}
func yamlDecoder(r io.Reader) func(v interface{}) error {
decoder := yaml.NewDecoder(r)
decoder.SetStrict(true)
return decoder.Decode
}
func readAndParseFile(fileName string, i interface{}) {
var (
decoder func(r io.Reader) func(v interface{}) error
)
if file, err := os.Open(fileName); err != nil {
panic(err)
} else {
defer func() {
if err := file.Close(); err != nil {
panic(err)
}
}()
switch strings.ToLower(path.Ext(fileName)) {
case ".json":
decoder = jsonDecoder
case ".yaml", ".yml":
decoder = yamlDecoder
default:
var b = make([]byte, 1, 1)
if _, err := file.Read(b); err != nil {
panic(err)
} else {
if _, err := file.Seek(0, 0); err != nil {
panic(err)
}
}
if b[0] == '{' {
decoder = jsonDecoder
} else {
decoder = yamlDecoder
}
}
if err := decoder(file)(i); err != nil {
panic(fmt.Sprintf("<%T>: %s\nOn parsing: "+fileName, err, err))
}
}
}
func ReadDatabaseProjectFile(fileName string) *Root {
var root Root
readAndParseFile(fileName, &root)
root.normalize()
return &root
}