Repository navigation
Expand file tree
/
Copy pathparse.go
More file actions
273 lines (232 loc) · 8.34 KB
/
Copy pathparse.go
File metadata and controls
273 lines (232 loc) · 8.34 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Package commandsgen reads YAML command definitions and generates code from them.
package commandsgen
import (
"bytes"
"fmt"
"regexp"
"slices"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
type (
// Option represents the structure of an option within option sets.
Option struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
DisplayType string `yaml:"display-type"`
Description string `yaml:"description"`
Deprecated string `yaml:"deprecated"`
Short string `yaml:"short,omitempty"`
Default string `yaml:"default,omitempty"`
ImpliedEnv string `yaml:"implied-env,omitempty"`
Required bool `yaml:"required,omitempty"`
Aliases []string `yaml:"aliases,omitempty"`
EnumValues []string `yaml:"enum-values,omitempty"`
Experimental bool `yaml:"experimental,omitempty"`
Hidden bool `yaml:"hidden,omitempty"`
HiddenLegacyValues []string `yaml:"hidden-legacy-values,omitempty"`
}
// Command represents the structure of each command in the commands map.
Command struct {
FullName string `yaml:"name"`
NamePath []string
Summary string `yaml:"summary"`
Description string `yaml:"description"`
DescriptionPlain string
DescriptionHighlighted string
Deprecated string `yaml:"deprecated"`
HasInit bool `yaml:"has-init"`
ExactArgs int `yaml:"exact-args"`
MaximumArgs int `yaml:"maximum-args"`
IgnoreMissingEnv bool `yaml:"ignores-missing-env"`
SubcommandsOptional bool `yaml:"subcommands-optional"`
Options []Option `yaml:"options"`
OptionSets []string `yaml:"option-sets"`
Docs Docs `yaml:"docs"`
}
// Docs represents docs-only information that is not used in CLI generation.
Docs struct {
Keywords []string `yaml:"keywords"`
DescriptionHeader string `yaml:"description-header"`
Tags []string `yaml:"tags"`
}
// OptionSets represents the structure of option sets.
OptionSets struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Options []Option `yaml:"options"`
ExternalPackage string `yaml:"external-package"`
}
// Commands represents the top-level structure holding commands and option sets.
Commands struct {
CommandList []Command `yaml:"commands"`
OptionSets []OptionSets `yaml:"option-sets"`
}
)
// ParseCommands parses command definitions from one or more YAML byte slices.
func ParseCommands(yamlDataList ...[]byte) (Commands, error) {
var res Commands
optionSetNames := make(map[string]bool)
commandNames := make(map[string]bool)
for _, yamlData := range yamlDataList {
// Fix CRLF
md := bytes.ReplaceAll(yamlData, []byte("\r\n"), []byte("\n"))
var m Commands
err := yaml.Unmarshal(md, &m)
if err != nil {
return Commands{}, fmt.Errorf("failed unmarshalling yaml: %w", err)
}
for _, optSet := range m.OptionSets {
// Skip external option-sets (imports) when checking for duplicates
if optSet.ExternalPackage != "" {
res.OptionSets = append(res.OptionSets, optSet)
continue
}
if optionSetNames[optSet.Name] {
return Commands{}, fmt.Errorf("duplicate option set %q", optSet.Name)
}
optionSetNames[optSet.Name] = true
res.OptionSets = append(res.OptionSets, optSet)
}
for _, cmd := range m.CommandList {
if commandNames[cmd.FullName] {
return Commands{}, fmt.Errorf("duplicate command %q", cmd.FullName)
}
commandNames[cmd.FullName] = true
res.CommandList = append(res.CommandList, cmd)
}
}
for i, optionSet := range res.OptionSets {
if err := res.OptionSets[i].processSection(); err != nil {
return Commands{}, fmt.Errorf("failed parsing option set section %q: %w", optionSet.Name, err)
}
}
for i, command := range res.CommandList {
if err := res.CommandList[i].processSection(); err != nil {
return Commands{}, fmt.Errorf("failed parsing command section %q: %w", command.FullName, err)
}
}
// alphabetize commands
sort.Slice(res.CommandList, func(i, j int) bool {
return res.CommandList[i].FullName < res.CommandList[j].FullName
})
return res, nil
}
var markdownLinkPattern = regexp.MustCompile(`\[(.*?)\]\((.*?)\)`)
var markdownBlockCodeRegex = regexp.MustCompile("```([\\s\\S]+?)```")
var markdownInlineCodeRegex = regexp.MustCompile("`([^`]+)`")
const ansiReset = "\033[0m"
const ansiBold = "\033[1m"
func (o OptionSets) processSection() error {
if o.Name == "" {
return fmt.Errorf("missing option set name")
}
for i, option := range o.Options {
if err := o.Options[i].processSection(); err != nil {
return fmt.Errorf("failed parsing option '%v': %w", option.Name, err)
}
}
return nil
}
func (c *Command) processSection() error {
if c.FullName == "" {
return fmt.Errorf("missing command name")
}
c.NamePath = strings.Split(c.FullName, " ")
if c.Summary == "" {
return fmt.Errorf("missing summary for command")
}
if c.Summary[len(c.Summary)-1] == '.' {
return fmt.Errorf("summary should not end in a '.'")
}
if c.MaximumArgs != 0 && c.ExactArgs != 0 {
return fmt.Errorf("cannot have both maximum-args and exact-args")
}
if c.Description == "" {
return fmt.Errorf("missing description for command: %s", c.FullName)
}
if len(c.NamePath) == 2 {
if c.Docs.Keywords == nil {
return fmt.Errorf("missing keywords for root command: %s", c.FullName)
}
if c.Docs.DescriptionHeader == "" {
return fmt.Errorf("missing description for root command: %s", c.FullName)
}
if len(c.Docs.Tags) == 0 {
return fmt.Errorf("missing tags for root command: %s", c.FullName)
}
}
// Strip trailing newline for description
c.Description = strings.TrimRight(c.Description, "\n")
// Strip links for long plain/highlighted
c.DescriptionPlain = markdownLinkPattern.ReplaceAllString(c.Description, "$1")
c.DescriptionHighlighted = c.DescriptionPlain
// Highlight code for long highlighted
c.DescriptionHighlighted = markdownBlockCodeRegex.ReplaceAllStringFunc(c.DescriptionHighlighted, func(s string) string {
s = strings.Trim(s, "`")
s = strings.Trim(s, " ")
s = strings.Trim(s, "\n")
return ansiBold + s + ansiReset
})
c.DescriptionHighlighted = markdownInlineCodeRegex.ReplaceAllStringFunc(c.DescriptionHighlighted, func(s string) string {
s = strings.Trim(s, "`")
return ansiBold + s + ansiReset
})
// Each option
for i, option := range c.Options {
if err := c.Options[i].processSection(); err != nil {
return fmt.Errorf("failed parsing option '%v': %w", option.Name, err)
}
}
return nil
}
func (c *Command) isSubCommand(maybeParent *Command) bool {
return len(c.NamePath) == len(maybeParent.NamePath)+1 && strings.HasPrefix(c.FullName, maybeParent.FullName+" ")
}
func (c *Command) leafName() string {
return strings.Join(strings.Split(c.FullName, " ")[c.depth():], "")
}
func (c *Command) fileName() string {
if c.depth() <= 0 {
return ""
}
return strings.Split(c.FullName, " ")[1]
}
func (c *Command) depth() int {
return len(strings.Split(c.FullName, " ")) - 1
}
func (o *Option) processSection() error {
if o.Name == "" {
return fmt.Errorf("missing option name")
}
if o.Type == "" {
return fmt.Errorf("missing option type")
}
if o.Type != "string" && o.DisplayType != "" {
return fmt.Errorf("display-type is only allowed for string options")
}
if o.Description == "" {
return fmt.Errorf("missing description for option: %s", o.Name)
}
// Strip all newline for description and trailing whitespace
o.Description = strings.ReplaceAll(o.Description, "\n", " ")
o.Description = strings.TrimRight(o.Description, " ")
// Check that description ends in a "."
if o.Description[len(o.Description)-1] != '.' {
return fmt.Errorf("description should end in a '.'")
}
if o.ImpliedEnv != strings.ToUpper(o.ImpliedEnv) {
return fmt.Errorf("env variables must be in all caps")
}
if len(o.EnumValues) != 0 {
if o.Type != "string-enum" && o.Type != "string-enum[]" {
return fmt.Errorf("enum-values can only specified for string-enum and string-enum[] types")
}
// Check default enum values
if o.Default != "" && !slices.Contains(o.EnumValues, o.Default) {
return fmt.Errorf("default value '%s' must be one of the enum-values options %s", o.Default, o.EnumValues)
}
}
return nil
}