2021-02-17 11:14:47 +02:00
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
2021-11-16 07:22:35 +02:00
|
|
|
"io"
|
2021-02-17 11:14:47 +02:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-kratos/kratos/v2/config"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ config.Source = (*file)(nil)
|
|
|
|
|
|
|
|
type file struct {
|
|
|
|
path string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSource new a file source.
|
|
|
|
func NewSource(path string) config.Source {
|
|
|
|
return &file{path: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *file) loadFile(path string) (*config.KeyValue, error) {
|
|
|
|
file, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
2021-11-16 07:22:35 +02:00
|
|
|
data, err := io.ReadAll(file)
|
2021-02-17 11:14:47 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
info, err := file.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &config.KeyValue{
|
2021-05-17 15:52:23 +02:00
|
|
|
Key: info.Name(),
|
|
|
|
Format: format(info.Name()),
|
|
|
|
Value: data,
|
2021-02-17 11:14:47 +02:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *file) loadDir(path string) (kvs []*config.KeyValue, err error) {
|
2022-05-20 09:37:28 +02:00
|
|
|
files, err := os.ReadDir(path)
|
2021-02-17 11:14:47 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, file := range files {
|
|
|
|
// ignore hidden files
|
|
|
|
if file.IsDir() || strings.HasPrefix(file.Name(), ".") {
|
|
|
|
continue
|
|
|
|
}
|
2022-05-20 09:37:28 +02:00
|
|
|
kv, err := f.loadFile(filepath.Join(path, file.Name()))
|
2021-02-17 11:14:47 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
kvs = append(kvs, kv)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *file) Load() (kvs []*config.KeyValue, err error) {
|
|
|
|
fi, err := os.Stat(f.path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if fi.IsDir() {
|
|
|
|
return f.loadDir(f.path)
|
|
|
|
}
|
|
|
|
kv, err := f.loadFile(f.path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return []*config.KeyValue{kv}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *file) Watch() (config.Watcher, error) {
|
|
|
|
return newWatcher(f)
|
|
|
|
}
|