1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/cli/browser/flags.go

125 lines
1.9 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package browser
import (
"fmt"
"sort"
"strings"
"github.com/pkg/errors"
2018-09-18 22:42:38 +02:00
)
type Flags map[string]interface{}
func (flags Flags) Get(arg string) (interface{}, error) {
var values interface{}
var err error
if !flags.Has(arg) {
err = errors.Errorf("The specified argument '%s' does not exist", arg)
} else {
values = flags[arg]
}
return values, err
}
func (flags Flags) GetString(arg string) (string, error) {
found, err := flags.Get(arg)
if err != nil {
return "", err
}
str, ok := found.(string)
if ok {
return str, nil
}
return "", nil
}
func (flags Flags) GetInt(arg string) (int, error) {
found, err := flags.Get(arg)
if err != nil {
return 0, err
}
num, ok := found.(int)
if ok {
return num, nil
}
return 0, nil
}
func (flags Flags) Has(arg string) bool {
_, exists := flags[arg]
return exists
}
func (flags Flags) List() []string {
orderedFlags := make([]string, 0, 10)
for arg := range flags {
orderedFlags = append(orderedFlags, arg)
}
sort.Strings(orderedFlags)
list := make([]string, len(orderedFlags))
for i, arg := range orderedFlags {
2018-09-18 22:42:38 +02:00
val, err := flags.Get(arg)
if err != nil {
continue
}
switch v := val.(type) {
2018-09-18 22:42:38 +02:00
case int:
arg = fmt.Sprintf("--%s=%d", arg, v)
2018-09-18 22:42:38 +02:00
case string:
arg = fmt.Sprintf("--%s=%s", arg, v)
2018-09-18 22:42:38 +02:00
default:
arg = fmt.Sprintf("--%s", arg)
}
list[i] = arg
2018-09-18 22:42:38 +02:00
}
return list
}
func (flags Flags) Set(arg string, value interface{}) (err error) {
if value == nil {
if _, ok := flags[arg]; !ok {
flags[arg] = nil
}
}
if value != nil {
switch value.(type) {
case int:
flags[arg] = value
case string:
flags[arg] = value
default:
return errors.Errorf("Invalid data type '%T' for argument %s: %+v", value, arg, value)
}
}
return nil
}
func (flags Flags) SetN(arg string) (err error) {
return flags.Set(arg, nil)
}
func (flags Flags) String() string {
return strings.Join(flags.List(), " ")
}