Debian Codegraph @

packages/cobra/main.go

raw symbols SCIP
1 /*
2 *
3 * NOTE: This package directory has been deprecated and won't be updated anymore,
4 * update this package in the `integrations/cobra/` instead of here
5 *
6 */
7
8 package genFigSpec
9
10 import (
11 "fmt"
12 "strings"
13
14 "github.com/spf13/cobra"
15 "github.com/spf13/pflag"
16 )
17
18 var includeHidden bool
19 var figGenCmdUse string = ""
20
21 var generateCommandArgs func(*cobra.Command) Args
22
23 type Opts struct {
24 Use string
25 Short string
26 Visible bool
27 Long string
28 commandArgGenerator func(*cobra.Command) Args
29 }
30
31 func CreateCompletionSpecCommand(options ...Opts) * cobra.Command {
32 Use := "generate-fig-spec"
33 Aliases := []string{"generateFigSpec", "genFigSpec"}
34 Short := "Generate a fig spec"
35 Hidden := true
36 Long := `
37 Fig is a tool for your command line that adds autocomplete.
38 This command generates a TypeScript file with the skeleton
39 Fig autocomplete spec for your Cobra CLI.
40 `
41 if len(options) > 0 {
42 if options[0].Use != "" {
43 Use = options[0].Use
44 }
45 if options[0].Short != "" {
46 Short = options[0].Short
47 }
48 if options[0].Long != "" {
49 Long = options[0].Long
50 }
51 if options[0].Visible {
52 Hidden = false
53 }
54 if options[0].commandArgGenerator != nil {
55 generateCommandArgs = options[0].commandArgGenerator
56 }
57 }
58 figGenCmdUse = Use
59 var cmd = &cobra.Command{
60 Use: Use,
61 Aliases: Aliases,
62 Short: Short,
63 Hidden: Hidden,
64 Long: Long,
65 Run: func(cmd *cobra.Command, args []string) {
66 root := cmd.Root()
67 spec := GenerateCompletionSpec(root)
68 fmt.Println(spec.ToTypescript())
69 },
70 }
71 cmd.Flags().BoolVar(
72 &includeHidden, "include-hidden", false,
73 "Include hidden commands in generated Fig autocomplete spec")
74 return cmd
75 }
76
77 // Deprecated:
78 // this function has been renamed to `CreateCompletionSpecCommand` and may not be available in future releases
79 func NewCmdGenFigSpec(options ...Opts) *cobra.Command {
80 return CreateCompletionSpecCommand(options...)
81 }
82
83 func GenerateCompletionSpec(root *cobra.Command) Spec {
84 opts := append(options(root.LocalNonPersistentFlags(), false), options(root.PersistentFlags(), true)...)
85 opts = append(opts, makeHelpOption())
86 spec := Spec{
87 Subcommand: &Subcommand{
88 BaseSuggestion: &BaseSuggestion{
89 description: root.Short,
90 },
91 options: opts,
92 subcommands: append(subcommands(root, false, Options{}), makeHelpCommand(root)), // We assume CLI is using default help command
93 args: commandArguments(root),
94 },
95 name: root.Name(),
96 }
97 return spec
98 }
99
100 // Deprecated:
101 // this function has been renamed to `GenerateCompletionSpec` and may not be available in future releases
102 func MakeFigSpec(root *cobra.Command) Spec {
103 return GenerateCompletionSpec(root)
104 }
105
106 func subcommands(cmd *cobra.Command, overrideOptions bool, overrides Options) Subcommands {
107 var subs []Subcommand
108 for _, sub := range cmd.Commands() {
109 if sub.Name() == "help" || (!includeHidden && sub.Hidden) || (sub.Use == figGenCmdUse) {
110 continue
111 }
112 var opts Options
113 if overrideOptions {
114 opts = overrides
115 } else {
116 opts = append(options(sub.LocalNonPersistentFlags(), false), options(sub.PersistentFlags(), true)...)
117 }
118 subs = append(subs, Subcommand{
119 BaseSuggestion: &BaseSuggestion{
120 description: sub.Short,
121 hidden: sub.Hidden,
122 },
123 name: append(sub.Aliases, sub.Name()),
124 options: opts,
125 subcommands: subcommands(sub, overrideOptions, overrides),
126 args: commandArguments(sub),
127 })
128 }
129 return subs
130 }
131
132 func options(flagSet *pflag.FlagSet, persistent bool) []Option {
133 var opts []Option
134 attachFlags := func(flag *pflag.Flag) {
135
136 option := Option{
137 BaseSuggestion: &BaseSuggestion{
138 description: flag.Usage,
139 hidden: flag.Hidden,
140 },
141 name: []string{fmt.Sprintf("--%v", flag.Name)},
142 isRepeatable: strings.Contains(strings.ToLower(flag.Value.Type()), "array"),
143 }
144 if flag.Shorthand != "" {
145 option.name = append(option.name, fmt.Sprintf("-%v", flag.Shorthand))
146 }
147 if persistent != false {
148 option.isPersistent = true
149 }
150 requiredAnnotation, found := flag.Annotations[cobra.BashCompOneRequiredFlag]
151 if found && requiredAnnotation[0] == "true" {
152 option.isRequired = true
153 }
154 option.args = flagArguments(flag)
155 opts = append(opts, option)
156 }
157
158 flagSet.VisitAll(attachFlags)
159 return opts
160 }
161
162 /*
163 * In Cobra, you only specify the number of arguments.
164 * Not sure how we want to handle this (if at all)
165 * https://github.com/spf13/cobra/blob/v1.2.1/user_guide.md#positional-and-custom-arguments
166 */
167 func commandArguments(cmd *cobra.Command) []Arg {
168 if generateCommandArgs != nil {
169 return generateCommandArgs(cmd)
170 }
171 return []Arg{}
172 }
173
174 func flagArguments(flag *pflag.Flag) []Arg {
175 var args []Arg
176 defaultVal := flag.DefValue
177 if defaultVal == "[]" {
178 defaultVal = ""
179 }
180 if flag.Value.Type() != "bool" {
181 arg := Arg{
182 name: flag.Name,
183 defaultVal: defaultVal,
184 }
185 _, foundFilenameAnnotation := flag.Annotations[cobra.BashCompFilenameExt]
186 if foundFilenameAnnotation {
187 arg.template = append(arg.template, FILEPATHS)
188 }
189 _, foundDirectoryAnnotation := flag.Annotations[cobra.BashCompSubdirsInDir]
190 if foundDirectoryAnnotation {
191 arg.template = append(arg.template, FOLDERS)
192 }
193 args = append(args, arg)
194 }
195 return args
196 }
197
198 func makeHelpCommand(root *cobra.Command) Subcommand {
199 return Subcommand{
200 BaseSuggestion: &BaseSuggestion{
201 description: "Help about any command",
202 },
203 name: []string{"help"},
204 subcommands: subcommands(root, true, []Option{}),
205 }
206 }
207
208 func makeHelpOption() Option {
209 return Option{
210 BaseSuggestion: &BaseSuggestion{
211 description: fmt.Sprintf("Display help"),
212 },
213 isPersistent: true,
214 name: []string{"--help", "-h"},
215 }
216 }