first commit
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
andrey1s
2021-04-27 14:58:19 +03:00
commit 913ca9672d
55 changed files with 4355 additions and 0 deletions

71
provider/toml/provider.go Normal file
View File

@@ -0,0 +1,71 @@
package toml
import (
"context"
"fmt"
"github.com/pelletier/go-toml"
"gitoa.ru/go-4devs/config"
"gitoa.ru/go-4devs/config/key"
"gitoa.ru/go-4devs/config/value"
)
var _ config.Provider = (*Provider)(nil)
func NewFile(file string, opts ...Option) (*Provider, error) {
tree, err := toml.LoadFile(file)
if err != nil {
return nil, fmt.Errorf("toml: failed load file: %w", err)
}
return configure(tree, opts...), nil
}
type Option func(*Provider)
func configure(tree *toml.Tree, opts ...Option) *Provider {
p := &Provider{
tree: tree,
key: key.Name,
}
for _, opt := range opts {
opt(p)
}
return p
}
func New(data []byte, opts ...Option) (*Provider, error) {
tree, err := toml.LoadBytes(data)
if err != nil {
return nil, fmt.Errorf("toml failed load data: %w", err)
}
return configure(tree, opts...), nil
}
type Provider struct {
tree *toml.Tree
key config.KeyFactory
}
func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool {
return p.key(ctx, key) != ""
}
func (p *Provider) Name() string {
return "toml"
}
func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) {
if k := p.key(ctx, key); p.tree.Has(k) {
return config.Variable{
Name: k,
Provider: p.Name(),
Value: Value{Value: value.Value{Val: p.tree.Get(k)}},
}, nil
}
return config.Variable{}, config.ErrVariableNotFound
}

View File

@@ -0,0 +1,29 @@
package toml_test
import (
"testing"
"github.com/stretchr/testify/require"
"gitoa.ru/go-4devs/config/provider/toml"
"gitoa.ru/go-4devs/config/test"
)
func TestProvider(t *testing.T) {
t.Parallel()
prov, err := toml.NewFile(test.FixturePath("config.toml"))
require.NoError(t, err)
m := []int{}
read := []test.Read{
test.NewRead("database.server", "192.168.1.1"),
test.NewRead("title", "TOML Example"),
test.NewRead("servers.alpha.ip", "10.0.0.1"),
test.NewRead("database.enabled", true),
test.NewRead("database.connection_max", 5000),
test.NewReadUnmarshal("database.ports", &[]int{8001, 8001, 8002}, &m),
}
test.Run(t, prov, read)
}

41
provider/toml/value.go Normal file
View File

@@ -0,0 +1,41 @@
package toml
import (
"encoding/json"
"fmt"
"gitoa.ru/go-4devs/config"
"gitoa.ru/go-4devs/config/value"
)
type Value struct {
value.Value
}
func (s Value) Int() int {
v, _ := s.ParseInt()
return v
}
func (s Value) ParseInt() (int, error) {
v, err := s.ParseInt64()
if err != nil {
return 0, fmt.Errorf("toml failed parce int: %w", err)
}
return int(v), nil
}
func (s Value) Unmarshal(target interface{}) error {
b, err := json.Marshal(s.Raw())
if err != nil {
return fmt.Errorf("%w: %s", config.ErrInvalidValue, err)
}
if err := json.Unmarshal(b, target); err != nil {
return fmt.Errorf("%w: %s", config.ErrInvalidValue, err)
}
return nil
}