-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
file.go
87 lines (71 loc) · 1.41 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
// Package file is a file source. Expected format is json
package file
import (
"io"
"io/fs"
"os"
"go-micro.dev/v5/config/source"
)
type file struct {
opts source.Options
fs fs.FS
path string
}
var (
DefaultPath = "config.json"
)
func (f *file) Read() (*source.ChangeSet, error) {
var fh fs.File
var err error
if f.fs != nil {
fh, err = f.fs.Open(f.path)
} else {
fh, err = os.Open(f.path)
}
if err != nil {
return nil, err
}
defer fh.Close()
b, err := io.ReadAll(fh)
if err != nil {
return nil, err
}
info, err := fh.Stat()
if err != nil {
return nil, err
}
cs := &source.ChangeSet{
Format: format(f.path, f.opts.Encoder),
Source: f.String(),
Timestamp: info.ModTime(),
Data: b,
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (f *file) String() string {
return "file"
}
func (f *file) Watch() (source.Watcher, error) {
// do not watch if fs.FS instance is provided
if f.fs != nil {
return source.NewNoopWatcher()
}
if _, err := os.Stat(f.path); err != nil {
return nil, err
}
return newWatcher(f)
}
func (f *file) Write(cs *source.ChangeSet) error {
return nil
}
func NewSource(opts ...source.Option) source.Source {
options := source.NewOptions(opts...)
fs, _ := options.Context.Value(fsKey{}).(fs.FS)
path := DefaultPath
f, ok := options.Context.Value(filePathKey{}).(string)
if ok {
path = f
}
return &file{opts: options, fs: fs, path: path}
}