-
Notifications
You must be signed in to change notification settings - Fork 9
/
file.go
123 lines (95 loc) · 2.11 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Package file provides config file support for uconfig
package file
import (
"io"
"io/ioutil"
"os"
"github.com/omeid/uconfig/plugins"
)
// Files represents a set of file paths and the appropriate
// unmarshal function for the given file.
type Files []struct {
Path string
Unmarshal Unmarshal
Optional bool
}
// Plugins constructs a slice of Plugin from the Files list of
// paths and unmarshal functions.
func (f Files) Plugins() []plugins.Plugin {
ps := make([]plugins.Plugin, 0, len(f))
for _, f := range f {
fp := New(
f.Path,
f.Unmarshal,
Config{Optional: f.Optional},
)
ps = append(ps, fp)
}
return ps
}
// Unmarshal is any function that maps the source bytes to the provided
// config.
type Unmarshal func(src []byte, v interface{}) error
// NewReader returns a uconfig plugin that unmarshals the content of
// the provided io.Reader into the config using the provided unmarshal
// function. The src will be closed if it is an io.Closer.
func NewReader(src io.Reader, unmarshal Unmarshal) plugins.Plugin {
return &walker{
src: src,
unmarshal: unmarshal,
}
}
// Config describes the options required for a file.
type Config struct {
// indicates if a file that does not exist should be ignored.
Optional bool
}
// New returns an EnvSet.
func New(path string, unmarshal Unmarshal, config Config) plugins.Plugin {
plug := &walker{
filepath: path,
unmarshal: unmarshal,
}
src, err := os.Open(path)
if err == nil {
plug.src = src
}
if config.Optional && os.IsNotExist(err) {
err = nil
}
plug.err = err
return plug
}
type walker struct {
filepath string
src io.Reader
conf interface{}
unmarshal Unmarshal
err error
}
func (v *walker) Walk(conf interface{}) error {
if v.err != nil {
return v.err
}
v.conf = conf
return v.err
}
func (v *walker) Parse() error {
if v.err != nil {
return v.err
}
if v.src == nil {
return nil
}
src, err := ioutil.ReadAll(v.src)
if err != nil {
return err
}
if closer, ok := v.src.(io.Closer); ok {
err := closer.Close()
if err != nil {
return err
}
}
return v.unmarshal(src, v.conf)
}