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.

101 lines
1.5 KiB

4 years ago
package option
import (
4 years ago
"gitoa.ru/go-4devs/console/input/flag"
4 years ago
"gitoa.ru/go-4devs/console/input/value"
)
4 years ago
func Required(o *Option) {
o.Flag |= flag.Required
4 years ago
}
4 years ago
func Default(in interface{}) func(*Option) {
return func(o *Option) {
4 years ago
o.Default = value.New(in)
}
}
4 years ago
func Short(s string) func(*Option) {
return func(o *Option) {
4 years ago
o.Short = s
}
}
4 years ago
func Array(o *Option) {
o.Flag |= flag.Array
4 years ago
}
4 years ago
func Value(flag flag.Flag) func(*Option) {
return func(o *Option) {
4 years ago
o.Flag |= flag
}
}
4 years ago
func Flag(in flag.Flag) func(*Option) {
return func(o *Option) {
4 years ago
o.Flag = in
}
}
4 years ago
func Valid(f ...func(value.Value) error) func(*Option) {
return func(o *Option) {
4 years ago
o.Valid = f
}
}
4 years ago
func New(name, description string, opts ...func(*Option)) Option {
o := Option{
Name: name,
Description: description,
}
for _, opt := range opts {
opt(&o)
}
return o
}
type Option struct {
Name string
Description string
Short string
Flag flag.Flag
Default value.Value
Valid []func(value.Value) error
}
func (o Option) HasShort() bool {
return len(o.Short) == 1
}
func (o Option) HasDefault() bool {
return o.Default != nil
}
func (o Option) IsBool() bool {
return o.Flag.IsBool()
}
func (o Option) IsArray() bool {
return o.Flag.IsArray()
}
func (o Option) IsRequired() bool {
return o.Flag.IsRequired()
}
func (o Option) Validate(v value.Value) error {
for _, valid := range o.Valid {
if err := valid(v); err != nil {
return Error(o.Name, err)
}
}
return nil
}
func Error(name string, err error) error {
return err
}