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
2.1 KiB

4 years ago
package input
4 years ago
import (
"gitoa.ru/go-4devs/console/input/argument"
"gitoa.ru/go-4devs/console/input/option"
)
4 years ago
func NewDefinition() *Definition {
return &Definition{
4 years ago
options: make(map[string]option.Option),
args: make(map[string]argument.Argument),
4 years ago
short: make(map[string]string),
}
}
type Definition struct {
4 years ago
options map[string]option.Option
4 years ago
posOpt []string
4 years ago
args map[string]argument.Argument
4 years ago
posArgs []string
short map[string]string
}
func (d *Definition) Options() []string {
return d.posOpt
}
func (d *Definition) Arguments() []string {
return d.posArgs
}
4 years ago
func (d *Definition) SetOption(name, description string, opts ...func(*option.Option)) *Definition {
return d.SetOptions(option.New(name, description, opts...))
4 years ago
}
4 years ago
func (d *Definition) SetOptions(opts ...option.Option) *Definition {
4 years ago
for _, opt := range opts {
if _, has := d.options[opt.Name]; !has {
d.posOpt = append([]string{opt.Name}, d.posOpt...)
}
d.options[opt.Name] = opt
if opt.HasShort() {
d.short[opt.Short] = opt.Name
}
}
return d
}
4 years ago
func (d *Definition) SetArgument(name, description string, opts ...func(*argument.Argument)) *Definition {
return d.SetArguments(argument.New(name, description, opts...))
4 years ago
}
4 years ago
func (d *Definition) SetArguments(args ...argument.Argument) *Definition {
4 years ago
for _, arg := range args {
if _, ok := d.args[arg.Name]; !ok {
d.posArgs = append(d.posArgs, arg.Name)
}
d.args[arg.Name] = arg
}
return d
}
4 years ago
func (d *Definition) Argument(pos int) (argument.Argument, error) {
4 years ago
if len(d.posArgs) == 0 {
4 years ago
return argument.Argument{}, ErrNoArgs
4 years ago
}
lastPos := len(d.posArgs) - 1
if lastPos < pos {
arg := d.args[d.posArgs[lastPos]]
if arg.IsArray() {
return arg, nil
}
4 years ago
return argument.Argument{}, ErrToManyArgs
4 years ago
}
return d.args[d.posArgs[pos]], nil
}
4 years ago
func (d *Definition) ShortOption(short string) (option.Option, error) {
4 years ago
name, ok := d.short[short]
if !ok {
4 years ago
return option.Option{}, ErrNotFound
4 years ago
}
return d.Option(name)
}
4 years ago
func (d *Definition) Option(name string) (option.Option, error) {
4 years ago
if opt, ok := d.options[name]; ok {
return opt, nil
}
4 years ago
return option.Option{}, ErrNotFound
4 years ago
}