-
Notifications
You must be signed in to change notification settings - Fork 86
/
flags.go
90 lines (72 loc) · 1.77 KB
/
flags.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.
package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/pflag"
)
var ErrNoCmd = fmt.Errorf("no cmd")
type Command struct {
Str string
Aliases []string
Desc string
HandleFunc func(ctx context.Context, args []string)
Usage string
Options map[string]string
Example string
LongLived bool
MayConnect bool
}
func (cmd Command) PrintUsage() {
fmt.Fprintf(os.Stderr, "%s - %s\n", cmd.Str, cmd.Desc)
fmt.Fprintf(os.Stderr, "\nUsage:\n %s %s\n", cmd.Str, strings.TrimSpace(cmd.Usage))
if len(cmd.Options) > 0 {
fmt.Fprint(os.Stderr, "\nOptions:\n")
for f, desc := range cmd.Options {
fmt.Fprintf(os.Stderr, " %-17s %s\n", f, desc)
}
}
if cmd.Example != "" {
fmt.Fprintf(os.Stderr, "\nExample:\n %s\n", strings.TrimSpace(cmd.Example))
}
fmt.Fprint(os.Stderr, "\n")
}
func parseFlags(args []string) (cmd Command, arguments []string) {
var options []string
var err error
cmd, options, arguments, err = findCommand(args)
if err != nil {
pflag.Usage()
os.Exit(1)
}
optionsSet().Parse(options)
if len(arguments) == 0 {
arguments = append(arguments, "")
}
switch arguments[0] {
case "--help", "-help", "help", "-h":
cmd.PrintUsage()
os.Exit(1)
}
return
}
func findCommand(args []string) (cmd Command, pre, post []string, err error) {
cmdMap := make(map[string]Command, len(commands))
for _, c := range commands {
cmdMap[c.Str] = c
for _, alias := range c.Aliases {
cmdMap[alias] = c
}
}
for i, arg := range args {
if cmd, ok := cmdMap[arg]; ok {
return cmd, args[1:i], args[i+1:], nil
}
}
err = ErrNoCmd
return
}