-
Notifications
You must be signed in to change notification settings - Fork 23
/
flagusages.go
86 lines (72 loc) · 1.82 KB
/
flagusages.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
// SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Open Component Model contributors.
//
// SPDX-License-Identifier: Apache-2.0
package groups
import (
"bytes"
"fmt"
"strings"
"github.com/spf13/pflag"
"github.com/open-component-model/ocm/pkg/utils"
)
const FlagGroupAnnotation = "flag-group-annotation"
// FlagUsagesWrapped returns a string containing the usage information
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
// wrapping)
// It groups flags according to group annotation.
func FlagUsagesWrapped(f *pflag.FlagSet, cols int) string {
lines := DetermineGroups(f, cols)
sep := ""
buf := new(bytes.Buffer)
for _, g := range utils.StringMapKeys(lines) {
if g != "" {
fmt.Fprintln(buf, sep+" "+g+":")
}
sep = "\n"
for _, line := range lines[g] {
fmt.Fprintln(buf, line)
}
}
return buf.String()
}
type UsageGroup struct {
Title string
Usages string
}
func GroupedFlagUsagesWrapped(f *pflag.FlagSet, cols int) []UsageGroup {
lines := DetermineGroups(f, cols)
var groups []UsageGroup
for _, g := range utils.StringMapKeys(lines) {
buf := new(bytes.Buffer)
for _, line := range lines[g] {
fmt.Fprintln(buf, line)
}
groups = append(groups, UsageGroup{
Title: g,
Usages: buf.String(),
})
}
return groups
}
func DetermineGroups(f *pflag.FlagSet, cols int) map[string][]string {
lines := map[string][]string{}
for _, line := range strings.Split(f.FlagUsagesWrapped(cols), "\n") {
i := strings.Index(line, "--")
if i < 0 {
continue
}
name := line[i+2 : i+strings.Index(line[i:], " ")]
flag := f.Lookup(name)
groups := []string{""}
if flag.Annotations != nil {
g := flag.Annotations[FlagGroupAnnotation]
if len(g) > 0 {
groups = g
}
}
for _, g := range groups {
lines[g] = append(lines[g], line)
}
}
return lines
}