You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 lines
2.3 KiB

4 years ago
package arg
import (
"context"
"fmt"
"os"
"strings"
"gitoa.ru/go-4devs/config"
"gitoa.ru/go-4devs/config/value"
"gopkg.in/yaml.v3"
)
const Name = "arg"
4 years ago
var _ config.Provider = (*Provider)(nil)
type Option func(*Provider)
func WithKeyFactory(factory func(s ...string) string) Option {
4 years ago
return func(p *Provider) { p.key = factory }
}
func New(opts ...Option) *Provider {
prov := Provider{
key: func(s ...string) string {
return strings.Join(s, "-")
},
args: make(map[string][]string, len(os.Args[1:])),
name: Name,
4 years ago
}
for _, opt := range opts {
opt(&prov)
4 years ago
}
return &prov
4 years ago
}
type Provider struct {
args map[string][]string
key func(...string) string
name string
4 years ago
}
// nolint: cyclop
// return name, value, error.
func (p *Provider) parseOne(arg string) (string, string, error) {
4 years ago
if arg[0] != '-' {
return "", "", nil
4 years ago
}
numMinuses := 1
if arg[1] == '-' {
numMinuses++
}
name := strings.TrimSpace(arg[numMinuses:])
4 years ago
if len(name) == 0 {
return name, "", nil
4 years ago
}
if name[0] == '-' || name[0] == '=' {
return "", "", fmt.Errorf("%w: bad flag syntax: %s", config.ErrInvalidValue, arg)
}
var val string
for idx := 1; idx < len(name); idx++ {
if name[idx] == '=' || name[idx] == ' ' {
val = strings.TrimSpace(name[idx+1:])
name = name[0:idx]
4 years ago
break
}
}
if val == "" && numMinuses == 1 && len(arg) > 2 {
name, val = name[:1], name[1:]
}
return name, val, nil
}
func (p *Provider) parse() error {
if len(p.args) > 0 {
return nil
}
for _, arg := range os.Args[1:] {
name, value, err := p.parseOne(arg)
if err != nil {
return err
}
if name != "" {
p.args[name] = append(p.args[name], value)
}
}
return nil
}
func (p *Provider) Name() string {
return p.name
4 years ago
}
func (p *Provider) Value(ctx context.Context, path ...string) (config.Value, error) {
4 years ago
if err := p.parse(); err != nil {
return nil, err
4 years ago
}
name := p.key(path...)
if val, ok := p.args[name]; ok {
4 years ago
switch {
case len(val) == 1:
return value.JString(val[0]), nil
4 years ago
default:
var yNode yaml.Node
4 years ago
if err := yaml.Unmarshal([]byte("["+strings.Join(val, ",")+"]"), &yNode); err != nil {
return nil, fmt.Errorf("arg: failed unmarshal yaml:%w", err)
4 years ago
}
return value.Decode(yNode.Decode), nil
4 years ago
}
}
return nil, fmt.Errorf("%s:%w", p.Name(), config.ErrValueNotFound)
4 years ago
}