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.

109 lines
1.9 KiB

package input
import (
"context"
"gitoa.ru/go-4devs/console/input/errs"
"gitoa.ru/go-4devs/console/input/value"
)
type Array struct {
4 years ago
Map
defaults Map
}
4 years ago
func (a *Array) Option(ctx context.Context, name string) value.Value {
if v := a.Map.Option(ctx, name); !value.IsEmpty(v) {
return v
}
4 years ago
if v := a.defaults.Option(ctx, name); !value.IsEmpty(v) {
return v
}
4 years ago
return value.Empty()
}
4 years ago
func (a *Array) Argument(ctx context.Context, name string) value.Value {
if v := a.Map.Argument(ctx, name); !value.IsEmpty(v) {
return v
}
4 years ago
if v := a.defaults.Argument(ctx, name); !value.IsEmpty(v) {
return v
}
4 years ago
return value.Empty()
}
func (a *Array) Bind(ctx context.Context, d *Definition) error {
4 years ago
if err := a.bindArguments(ctx, d); err != nil {
return err
}
4 years ago
return a.bindOption(ctx, d)
}
4 years ago
func (a *Array) bindOption(ctx context.Context, def *Definition) error {
for _, name := range def.Options() {
opt, err := def.Option(name)
if err != nil {
return err
}
4 years ago
if !a.HasOption(name) {
switch {
case opt.HasDefault():
a.defaults.SetOption(name, opt.Default)
4 years ago
continue
case opt.IsRequired():
return errs.Option(name, errs.ErrRequired)
default:
continue
}
}
4 years ago
v := a.Map.Option(ctx, name)
if value.IsEmpty(v) {
continue
}
4 years ago
if err := opt.Validate(v); err != nil {
return errs.Option(name, err)
}
}
return nil
}
4 years ago
func (a *Array) bindArguments(ctx context.Context, def *Definition) error {
for pos, name := range def.Arguments() {
arg, err := def.Argument(pos)
if err != nil {
return err
}
4 years ago
if !a.HasArgument(name) {
switch {
case arg.HasDefault():
a.defaults.SetArgument(name, arg.Default)
4 years ago
continue
case arg.IsRequired():
return errs.Argument(name, errs.ErrRequired)
default:
continue
}
}
4 years ago
if v := a.Map.Argument(ctx, name); !value.IsEmpty(v) {
if err := arg.Validate(v); err != nil {
return errs.Argument(name, err)
}
}
}
return nil
}