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.

103 lines
2.2 KiB

4 years ago
package input
4 years ago
import (
"gitoa.ru/go-4devs/console/input/argument"
"gitoa.ru/go-4devs/console/input/errs"
4 years ago
"gitoa.ru/go-4devs/console/input/option"
"gitoa.ru/go-4devs/console/input/variable"
4 years ago
)
4 years ago
func NewDefinition() *Definition {
return &Definition{
options: make(map[string]variable.Variable),
args: make(map[string]variable.Variable),
4 years ago
short: make(map[string]string),
}
}
type Definition struct {
options map[string]variable.Variable
4 years ago
posOpt []string
args map[string]variable.Variable
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
}
func (d *Definition) SetOption(name, description string, opts ...variable.Option) *Definition {
return d.SetOptions(option.String(name, description, opts...))
4 years ago
}
func (d *Definition) SetOptions(opts ...variable.Variable) *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.Alias] = opt.Name
4 years ago
}
}
return d
}
func (d *Definition) SetArgument(name, description string, opts ...variable.Option) *Definition {
return d.SetArguments(argument.String(name, description, opts...))
4 years ago
}
func (d *Definition) SetArguments(args ...variable.Variable) *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
}
func (d *Definition) Argument(pos int) (variable.Variable, error) {
4 years ago
if len(d.posArgs) == 0 {
return variable.Variable{}, errs.ErrNoArgs
4 years ago
}
lastPos := len(d.posArgs) - 1
if lastPos < pos {
arg := d.args[d.posArgs[lastPos]]
if arg.IsArray() {
return arg, nil
}
return variable.Variable{}, errs.ErrToManyArgs
4 years ago
}
return d.args[d.posArgs[pos]], nil
}
func (d *Definition) ShortOption(short string) (variable.Variable, error) {
4 years ago
name, ok := d.short[short]
if !ok {
return variable.Variable{}, errs.ErrNotFound
4 years ago
}
return d.Option(name)
}
func (d *Definition) Option(name string) (variable.Variable, error) {
4 years ago
if opt, ok := d.options[name]; ok {
return opt, nil
}
return variable.Variable{}, errs.ErrNotFound
4 years ago
}