-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
66 lines (53 loc) · 1.21 KB
/
options.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package peco
import (
"bytes"
"fmt"
"os"
"reflect"
"github.com/jessevdk/go-flags"
"github.com/pkg/errors"
)
func (options *CLIOptions) parse(s []string) ([]string, error) {
p := flags.NewParser(options, flags.PrintErrors)
args, err := p.ParseArgs(s)
if err != nil {
os.Stderr.Write(options.help())
return nil, errors.Wrap(err, "invalid command line options")
}
if err := options.Validate(); err != nil {
return nil, errors.Wrap(err, "invalid command line arguments")
}
return args, nil
}
func (options CLIOptions) Validate() error {
if options.OptLayout != "" {
if !IsValidLayoutType(LayoutType(options.OptLayout)) {
return errors.New("unknown layout: '" + options.OptLayout + "'")
}
}
return nil
}
func (options CLIOptions) help() []byte {
buf := bytes.Buffer{}
fmt.Fprintf(&buf, `
Usage: peco [options] [FILE]
Options:
`)
t := reflect.TypeOf(options)
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
var o string
if s := tag.Get("short"); s != "" {
o = fmt.Sprintf("-%s, --%s", tag.Get("short"), tag.Get("long"))
} else {
o = fmt.Sprintf("--%s", tag.Get("long"))
}
fmt.Fprintf(
&buf,
" %-21s %s\n",
o,
tag.Get("description"),
)
}
return buf.Bytes()
}