-
Notifications
You must be signed in to change notification settings - Fork 4
/
cobra.go
388 lines (334 loc) · 11.2 KB
/
cobra.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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package help
import (
_ "embed"
"fmt"
"github.com/Masterminds/sprig"
glazed_cobra "github.com/go-go-golems/glazed/pkg/cmds/layers"
"github.com/go-go-golems/glazed/pkg/helpers/templating"
"github.com/spf13/cobra"
"os"
"strings"
"text/template"
)
type HelpFunc = func(c *cobra.Command, args []string)
type UsageFunc = func(c *cobra.Command) error
func GetCobraHelpUsageFuncs(hs *HelpSystem) (HelpFunc, UsageFunc) {
helpFunc := func(c *cobra.Command, args []string) {
qb := NewSectionQuery().
ReturnAllTypes()
longHelp, _ := c.Flags().GetBool("long-help")
options := &RenderOptions{
Query: qb,
ShowAllSections: false,
ShowShortTopic: false,
LongHelp: longHelp,
HelpCommand: c.Root().CommandPath() + " help",
}
c.NamePadding()
if c.Parent() == nil {
options.OnlyTopLevel = true
}
cobra.CheckErr(renderCommandHelpPage(c, options, hs))
}
usageFunc := func(c *cobra.Command) error {
qb := NewSectionQuery().
ReturnExamples()
longHelp, _ := c.Flags().GetBool("long-help")
options := &RenderOptions{
Query: qb,
ShowAllSections: false,
ShowShortTopic: true,
LongHelp: longHelp,
HelpCommand: c.Root().CommandPath() + " help",
}
if c.Parent() == nil {
options.OnlyTopLevel = true
}
return renderCommandHelpPage(c, options, hs)
}
return helpFunc, usageFunc
}
func renderCommandHelpPage(c *cobra.Command, options *RenderOptions, hs *HelpSystem) error {
t := template.New("commandUsage")
isTopLevel := c.Parent() == nil
userQuery := options.Query
userQuery.OnlyTopLevel = options.OnlyTopLevel
if !isTopLevel {
userQuery = userQuery.SearchForCommand(c.Name())
}
data, noResultsFound := hs.ComputeRenderData(userQuery)
t.Funcs(templating.TemplateFuncs).Funcs(sprig.TxtFuncMap())
var tmpl string
if options.ListSections || noResultsFound {
tmpl = COBRA_COMMAND_SHORT_HELP_TEMPLATE + HELP_LIST_TEMPLATE
} else {
if options.ShowShortTopic {
tmpl = COBRA_COMMAND_SHORT_HELP_TEMPLATE
} else {
tmpl = COBRA_COMMAND_HELP_TEMPLATE
}
if !userQuery.HasOnlyQueries() && !userQuery.HasRestrictedReturnTypes() {
tmpl += c.UsageTemplate()
}
if options.LongHelp {
if options.ShowAllSections {
tmpl += HELP_LONG_SECTION_TEMPLATE
} else {
tmpl += HELP_SHORT_SECTION_TEMPLATE
}
}
}
template.Must(t.Parse(tmpl))
flagGroupUsage := glazed_cobra.ComputeCommandFlagGroupUsage(c)
// if we are showing the short help and shortHelpLayers annotation was set,
// skip all the groups that are not in the list
if !options.LongHelp {
shortHelpLayers_, ok := c.Annotations["shortHelpLayers"]
if ok {
shortHelpLayers := map[string]interface{}{}
for _, v := range strings.Split(shortHelpLayers_, ",") {
shortHelpLayers[v] = true
}
localGroupUsages := []*glazed_cobra.FlagGroupUsage{}
inheritedGroupUsages := []*glazed_cobra.FlagGroupUsage{}
for _, f := range flagGroupUsage.LocalGroupUsages {
if _, ok = shortHelpLayers[f.Slug]; ok {
localGroupUsages = append(localGroupUsages, f)
}
}
for _, f := range flagGroupUsage.InheritedGroupUsages {
if _, ok = shortHelpLayers[f.Slug]; ok {
inheritedGroupUsages = append(inheritedGroupUsages, f)
}
}
flagGroupUsage.LocalGroupUsages = localGroupUsages
flagGroupUsage.InheritedGroupUsages = inheritedGroupUsages
}
}
// really this is where we need to compute the max length, not on a group basis
maxLength := 0
for _, group := range flagGroupUsage.LocalGroupUsages {
for _, usage := range group.FlagUsages {
if len(usage.FlagString) > maxLength {
maxLength = len(usage.FlagString)
}
}
}
data["Command"] = c
data["FlagGroupUsage"] = flagGroupUsage
data["FlagUsageMaxLength"] = maxLength
data["HelpCommand"] = options.HelpCommand
data["Slug"] = c.Name()
data["LongHelp"] = options.LongHelp
maxCommandNameLen := 0
for _, c := range c.Commands() {
if len(c.Name()) > maxCommandNameLen {
maxCommandNameLen = len(c.Name())
}
}
data["MaxCommandNameLen"] = maxCommandNameLen
s, err := RenderToMarkdown(t, data, os.Stderr)
if err != nil {
return err
}
_, _ = fmt.Fprint(c.OutOrStderr(), s)
return err
}
func GetCobraHelpUsageTemplates(hs *HelpSystem) (string, string) {
_ = hs
return COBRA_COMMAND_HELP_TEMPLATE, COBRA_COMMAND_USAGE_TEMPLATE
}
// NewCobraHelpCommand uses the InitDefaultHelpCommand code from cobra.
// This code is lifted from cobra and modified to accommodate help sections
//
// # Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 2022-12-03 - Manuel Odendahl - Added support for help sections
// 2022-12-04 - Manuel Odendahl - Significantly reworked to support markdown sections
func NewCobraHelpCommand(hs *HelpSystem) *cobra.Command {
var ret *cobra.Command
ret = &cobra.Command{
Use: "help [topic/command]",
Short: "Help about any command or topic",
Long: `Help provides help for any command and topic in the application.`,
ValidArgsFunction: func(c *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// copied from cobra itself
var completions []string
for _, section := range hs.Sections {
completions = append(completions, fmt.Sprintf("%s\t%s", section.Slug, section.Title))
}
cmd, _, e := c.Root().Find(args)
if e != nil {
// couldn't find a command by that name
return nil, cobra.ShellCompDirectiveNoFileComp
}
if cmd == nil {
// Root help command.
cmd = c.Root()
}
for _, subCmd := range cmd.Commands() {
if subCmd.IsAvailableCommand() || subCmd == ret {
if strings.HasPrefix(subCmd.Name(), toComplete) {
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
}
}
}
return completions, cobra.ShellCompDirectiveNoFileComp
},
Run: func(c *cobra.Command, args []string) {
root := c.Root()
qb := NewSectionQuery()
topic := c.Flag("topic").Value.String()
if topic != "" {
qb = qb.ReturnOnlyTopics(topic)
}
flag := c.Flag("flag").Value.String()
if flag != "" {
qb = qb.ReturnOnlyFlags(flag)
}
command := c.Flag("command").Value.String()
if command != "" {
qb = qb.ReturnOnlyCommands(command)
}
showAllSections, _ := c.Flags().GetBool("all")
showShortTopic, _ := c.Flags().GetBool("short")
topics, _ := c.Flags().GetBool("topics")
if topics {
qb = qb.ReturnTopics()
qb.OnlyTopLevel = false
showAllSections = true
showShortTopic = true
}
examples, _ := c.Flags().GetBool("examples")
if examples {
qb = qb.ReturnExamples()
qb.OnlyTopLevel = false
showAllSections = true
showShortTopic = true
}
applications, _ := c.Flags().GetBool("applications")
if applications {
qb = qb.ReturnApplications()
qb.OnlyTopLevel = false
showAllSections = true
showShortTopic = true
}
tutorials, _ := c.Flags().GetBool("tutorials")
if tutorials {
qb = qb.ReturnTutorials()
qb.OnlyTopLevel = false
showAllSections = true
showShortTopic = true
}
if !topics && !examples && !applications && !tutorials {
qb = qb.ReturnAllTypes()
}
list, _ := c.Flags().GetBool("list")
if showAllSections || topics || examples || applications || tutorials {
list = true
}
options := &RenderOptions{
Query: qb,
ShowAllSections: showAllSections,
ShowShortTopic: showShortTopic,
ListSections: list,
HelpCommand: root.CommandPath() + " help",
}
// first, we check if we can find an explicit help topic
if len(args) >= 1 {
topicSection, err := hs.GetSectionWithSlug(args[0])
// if we found a topic with that slug, show it
if err == nil {
// TODO(manuel, 2022-12-10) Potentially allow subtopics search
options.Query = options.Query.
ReturnAnyOfTopics(args[0]).
FilterSections(topicSection)
s, err := hs.RenderTopicHelp(
topicSection,
options)
if err != nil {
// need to show the default error page here
c.Printf("Unknown help topic: %s", args[0])
cobra.CheckErr(root.Usage())
}
_, _ = fmt.Fprint(c.OutOrStderr(), s)
return
}
} else {
// TODO(manuel, 2022-12-09): We could show a main help page if specified
cobra.CheckErr(renderCommandHelpPage(root, options, hs))
return
}
// if we couldn't find an explicit help page, show command help
// NOTE(manuel, 2024-04-04) This code is never reached, is it?
cmd, _, e := root.Find(args)
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q\n", args)
if list {
// TODO(manuel, 2022-12-09): We could show a main help page if specified
cobra.CheckErr(renderCommandHelpPage(root, options, hs))
} else {
cobra.CheckErr(renderCommandHelpPage(root, options, hs))
}
} else {
cobra.CheckErr(renderCommandHelpPage(cmd, options, hs))
}
},
}
ret.Flags().String("topic", "", "Show help related to topic")
ret.Flags().String("command", "", "Show help related to command")
ret.Flags().String("flag", "", "Show help related to flag")
ret.Flags().Bool("list", false, "List all sections")
ret.Flags().Bool("topics", false, "Show all topics")
ret.Flags().Bool("examples", false, "Show all examples")
ret.Flags().Bool("applications", false, "Show all applications")
ret.Flags().Bool("tutorials", false, "Show all tutorials")
ret.Flags().Bool("all", false, "Show all sections, not just default")
ret.Flags().Bool("short", false, "Show short version")
// TODO(manuel, 2022-12-04): Additional verbs to build
// - toc -- done with --list
// - topics
// - search
// - serve
return ret
}
// COBRA_COMMAND_USAGE_TEMPLATE - template used by the glazed library help cobra command.
// This template has been adapted from the cobra usage command template.
//
// Original: https://github.com/spf13/cobra
//
// # Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 2022-12-03 - Manuel Odendahl - Augmented template with sections
// 2022-12-04 - Manuel Odendahl - Significantly reworked to support markdown sections
//
//go:embed templates/cobra-usage.tmpl
var COBRA_COMMAND_USAGE_TEMPLATE string
//go:embed templates/cobra-help.tmpl
var COBRA_COMMAND_HELP_TEMPLATE string
//go:embed templates/cobra-short-help.tmpl
var COBRA_COMMAND_SHORT_HELP_TEMPLATE string