2019-05-30 23:11:13 +01:00
|
|
|
// Package file is a file source. Expected format is json
|
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
2021-10-31 02:24:40 +08:00
|
|
|
"io"
|
2022-09-24 02:46:18 +02:00
|
|
|
"io/fs"
|
2019-05-30 23:11:13 +01:00
|
|
|
"os"
|
|
|
|
|
2024-06-04 21:40:43 +01:00
|
|
|
"go-micro.dev/v5/config/source"
|
2019-05-30 23:11:13 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type file struct {
|
2023-04-26 00:16:34 +00:00
|
|
|
opts source.Options
|
2022-09-24 02:46:18 +02:00
|
|
|
fs fs.FS
|
2019-05-30 23:11:13 +01:00
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
DefaultPath = "config.json"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (f *file) Read() (*source.ChangeSet, error) {
|
2022-09-24 02:46:18 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2019-05-30 23:11:13 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer fh.Close()
|
2021-10-31 02:24:40 +08:00
|
|
|
b, err := io.ReadAll(fh)
|
2019-05-30 23:11:13 +01:00
|
|
|
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) {
|
2022-09-24 02:46:18 +02:00
|
|
|
// do not watch if fs.FS instance is provided
|
|
|
|
if f.fs != nil {
|
|
|
|
return source.NewNoopWatcher()
|
|
|
|
}
|
|
|
|
|
2019-05-30 23:11:13 +01:00
|
|
|
if _, err := os.Stat(f.path); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return newWatcher(f)
|
|
|
|
}
|
|
|
|
|
2019-12-23 08:42:57 +00:00
|
|
|
func (f *file) Write(cs *source.ChangeSet) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-30 23:11:13 +01:00
|
|
|
func NewSource(opts ...source.Option) source.Source {
|
|
|
|
options := source.NewOptions(opts...)
|
2022-09-24 02:46:18 +02:00
|
|
|
|
|
|
|
fs, _ := options.Context.Value(fsKey{}).(fs.FS)
|
|
|
|
|
2019-05-30 23:11:13 +01:00
|
|
|
path := DefaultPath
|
|
|
|
f, ok := options.Context.Value(filePathKey{}).(string)
|
|
|
|
if ok {
|
|
|
|
path = f
|
|
|
|
}
|
2022-09-24 02:46:18 +02:00
|
|
|
return &file{opts: options, fs: fs, path: path}
|
2019-05-30 23:11:13 +01:00
|
|
|
}
|