-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
87 lines (76 loc) · 2.13 KB
/
cli.go
File metadata and controls
87 lines (76 loc) · 2.13 KB
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
package cli
import (
"bytes"
"flag"
"io/ioutil"
"sort"
"strings"
)
//DoubleMinus is the argument to determine if the flag package has stopped parsing
//after seeing this argument.
const DoubleMinus = "--"
//Output values that affect error and help output.
const (
Usage = "usage:"
ParameterName = "parameter"
ParametersName = "parameters"
ArgumentSeparator = " | "
)
//FlagSetter allows implementations to receive values from flag.FlagSets while
//argument parsing occurs.
//Implementations should not retain references to f.
type FlagSetter interface {
SetFlags(f *flag.FlagSet)
}
//FormatArgument formats an argument's name given whether or not it is optional
//or multiple values are allowed.
func FormatArgument(name string, optional, many bool) string {
result := name
if many {
result += "..."
}
if optional {
result = "[" + result + "]"
} else {
result = "<" + result + ">"
}
return result
}
//NewFlagSet creates a new flag.FlagSet with name and flag.ContinueOnError and
//calls fs with it if fs is not nil. If fs is nil, then a new, empty flag.FlagSet
//is returned.
func NewFlagSet(name string, fs FlagSetter) *flag.FlagSet {
f := flag.NewFlagSet(name, flag.ContinueOnError)
f.Usage = func() {}
f.SetOutput(ioutil.Discard)
if fs != nil {
fs.SetFlags(f)
}
return f
}
//CountFlags returns the total number of flags (set or unset) in f.
func CountFlags(f *flag.FlagSet) int {
count := 0
f.VisitAll(func(_ *flag.Flag) {
count++
})
return count
}
//GetFlagSetDefaults returns the result of f.PrintDefaults() with the optionally
//trailing "\n" removed.
func GetFlagSetDefaults(f *flag.FlagSet) string {
out := bytes.NewBuffer([]byte{})
f.SetOutput(out)
f.PrintDefaults()
return strings.TrimRight(out.String(), "\n")
}
//GetJoinedNameSortedAliases returns name followed by the cloned and sorted aliases
//all joined by ", ".
// GetJoinedNameSortedAliases("c", []string{"b", "a"}) // "c, a, b"
func GetJoinedNameSortedAliases(name string, aliases []string) string {
toSort := make([]string, len(aliases))
copy(toSort, aliases)
sort.Strings(toSort)
all := append([]string{name}, toSort...)
return strings.Join(all, ", ")
}