Debian Codegraph @

internal/cli/completion.go

raw symbols SCIP
1 package cli
2
3 import (
4 "bytes"
5 "fmt"
6 "sort"
7 "strings"
8 "text/template"
9
10 "github.com/alecthomas/kong"
11 "github.com/tomwright/dasel/v3/parsing"
12 )
13
14 type CompletionCmd struct {
15 Shell string `arg:"" enum:"bash,zsh,fish,powershell" help:"Shell type (bash, zsh, fish, powershell)"`
16 }
17
18 type completionFlag struct {
19 Name string
20 Short string
21 Help string
22 Bool bool
23 }
24
25 type completionSubcommand struct {
26 Name string
27 Help string
28 Flags []completionFlag
29 }
30
31 type completionData struct {
32 Name string
33 Subcommands []completionSubcommand
34 GlobalFlags []completionFlag
35 QueryFlags []completionFlag
36 FormatList string
37 Formats []string
38 ShellList string
39 }
40
41 func extractCompletionData(k *kong.Kong) completionData {
42 app := k.Model
43
44 data := completionData{
45 Name: app.Name,
46 ShellList: "bash zsh fish powershell",
47 }
48
49 // Collect formats from registered readers, sorted for stable output.
50 readers := parsing.RegisteredReaders()
51 formats := make([]string, 0, len(readers))
52 for _, f := range readers {
53 formats = append(formats, f.String())
54 }
55 sort.Strings(formats)
56 data.Formats = formats
57 data.FormatList = strings.Join(formats, " ")
58
59 // Global flags from the root node.
60 for _, flag := range app.Flags {
61 if flag.Hidden {
62 continue
63 }
64 cf := completionFlag{
65 Name: flag.Name,
66 Help: flag.Help,
67 Bool: flag.IsBool(),
68 }
69 if flag.Short != 0 {
70 cf.Short = string(flag.Short)
71 }
72 data.GlobalFlags = append(data.GlobalFlags, cf)
73 }
74
75 // Walk children for subcommands.
76 for _, child := range app.Children {
77 if child.Hidden {
78 continue
79 }
80 if child.Type != kong.CommandNode {
81 continue
82 }
83 sub := completionSubcommand{
84 Name: child.Name,
85 Help: child.Help,
86 }
87 for _, flag := range child.Flags {
88 if flag.Hidden {
89 continue
90 }
91 cf := completionFlag{
92 Name: flag.Name,
93 Help: flag.Help,
94 Bool: flag.IsBool(),
95 }
96 if flag.Short != 0 {
97 cf.Short = string(flag.Short)
98 }
99 sub.Flags = append(sub.Flags, cf)
100 }
101 if child.Name == "query" {
102 data.QueryFlags = sub.Flags
103 }
104 data.Subcommands = append(data.Subcommands, sub)
105 }
106
107 return data
108 }
109
110 func (c *CompletionCmd) Run(ctx *Globals) error {
111 data := extractCompletionData(ctx.Kong)
112
113 var tmplStr string
114 switch c.Shell {
115 case "bash":
116 tmplStr = bashCompletionTmpl
117 case "zsh":
118 tmplStr = zshCompletionTmpl
119 case "fish":
120 tmplStr = fishCompletionTmpl
121 case "powershell":
122 tmplStr = powershellCompletionTmpl
123 default:
124 return fmt.Errorf("unsupported shell: %s", c.Shell)
125 }
126
127 tmpl, err := template.New("completion").Parse(tmplStr)
128 if err != nil {
129 return fmt.Errorf("error parsing completion template: %w", err)
130 }
131
132 var buf bytes.Buffer
133 if err := tmpl.Execute(&buf, data); err != nil {
134 return fmt.Errorf("error executing completion template: %w", err)
135 }
136
137 _, err = ctx.Stdout.Write(buf.Bytes())
138 return err
139 }
140
141 const bashCompletionTmpl = `#!/bin/bash
142
143 _{{.Name}}() {
144 local cur prev words cword
145 _init_completion || return
146
147 local commands="{{range $i, $s := .Subcommands}}{{if $i}} {{end}}{{$s.Name}}{{end}}"
148 local formats="{{.FormatList}}"
149 local shells="{{.ShellList}}"
150
151 # Find if a subcommand has been specified
152 local cmd=""
153 for ((i=1; i < cword; i++)); do
154 case "${words[i]}" in
155 {{range $i, $s := .Subcommands}}{{if $i}}|{{end}}{{$s.Name}}{{end}})
156 cmd="${words[i]}"
157 break
158 ;;
159 esac
160 done
161
162 # Complete format names for --in/--out/-i/-o
163 case "${prev}" in
164 --in|--out|-i|-o)
165 COMPREPLY=($(compgen -W "${formats}" -- "${cur}"))
166 return
167 ;;
168 esac
169
170 if [[ "${cur}" == -* ]]; then
171 local flags=""
172 case "${cmd}" in
173 "")
174 # No subcommand yet: offer global flags + query flags (default command)
175 flags="{{range .GlobalFlags}}--{{.Name}} {{end}}{{range .QueryFlags}}--{{.Name}} {{if .Short}}-{{.Short}} {{end}}{{end}}"
176 ;;{{range .Subcommands}}
177 {{.Name}})
178 flags="{{range $.GlobalFlags}}--{{.Name}} {{end}}{{range .Flags}}--{{.Name}} {{if .Short}}-{{.Short}} {{end}}{{end}}"
179 ;;{{end}}
180 esac
181 COMPREPLY=($(compgen -W "${flags}" -- "${cur}"))
182 return
183 fi
184
185 # If no subcommand yet, complete with subcommand names
186 if [[ -z "${cmd}" ]]; then
187 COMPREPLY=($(compgen -W "${commands}" -- "${cur}"))
188 fi
189 }
190
191 complete -F _{{.Name}} {{.Name}}
192 `
193
194 const zshCompletionTmpl = `#compdef {{.Name}}
195
196 _{{.Name}}() {
197 local -a commands formats
198 commands=(
199 {{- range .Subcommands}}
200 '{{.Name}}:{{.Help}}'
201 {{- end}}
202 )
203 formats=({{range .Formats}}{{.}} {{end}})
204
205 _arguments -C \
206 '1:command:->command' \
207 '*::arg:->args'
208
209 case "${state}" in
210 command)
211 _describe 'command' commands
212 _arguments \
213 {{- range .GlobalFlags}}
214 '--{{.Name}}[{{.Help}}]' \
215 {{- if .Short}}
216 '-{{.Short}}[{{.Help}}]' \
217 {{- end}}
218 {{- end}}
219 {{- range .QueryFlags}}
220 '--{{.Name}}[{{.Help}}]' \
221 {{- if .Short}}
222 '-{{.Short}}[{{.Help}}]' \
223 {{- end}}
224 {{- end}}
225
226 ;;
227 args)
228 case "${words[1]}" in
229 {{- range .Subcommands}}
230 {{.Name}})
231 _arguments \
232 {{- range .Flags}}
233 '--{{.Name}}[{{.Help}}]' \
234 {{- if .Short}}
235 '-{{.Short}}[{{.Help}}]' \
236 {{- end}}
237 {{- end}}
238 {{- range $.GlobalFlags}}
239 '--{{.Name}}[{{.Help}}]' \
240 {{- end}}
241
242 ;;
243 {{- end}}
244 esac
245
246 # Complete format names for --in/--out
247 if [[ "${words[CURRENT-1]}" == --in || "${words[CURRENT-1]}" == --out || "${words[CURRENT-1]}" == -i || "${words[CURRENT-1]}" == -o ]]; then
248 _describe 'format' formats
249 fi
250 ;;
251 esac
252 }
253
254 compdef _{{.Name}} {{.Name}}
255 `
256
257 const fishCompletionTmpl = `# Fish completion for {{.Name}}
258
259 # Disable file completions by default
260 complete -c {{.Name}} -f
261
262 # Subcommands
263 {{range .Subcommands}}complete -c {{$.Name}} -n __fish_use_subcommand -a {{.Name}} -d '{{.Help}}'
264 {{end}}
265 # Global flags
266 {{range .GlobalFlags}}complete -c {{$.Name}} -l {{.Name}}{{if .Short}} -s {{.Short}}{{end}} -d '{{.Help}}'
267 {{end}}
268 # Query flags (default command, available at root level)
269 {{range .QueryFlags}}complete -c {{$.Name}} -n '__fish_use_subcommand' -l {{.Name}}{{if .Short}} -s {{.Short}}{{end}} -d '{{.Help}}'
270 {{end}}
271 # Per-subcommand flags
272 {{range .Subcommands}}{{$sub := .Name}}{{range .Flags}}complete -c {{$.Name}} -n '__fish_seen_subcommand_from {{$sub}}' -l {{.Name}}{{if .Short}} -s {{.Short}}{{end}} -d '{{.Help}}'
273 {{end}}{{end}}
274 # Format completions for --in/--out
275 complete -c {{.Name}} -l in -xa '{{.FormatList}}'
276 complete -c {{.Name}} -l out -xa '{{.FormatList}}'
277
278 # Shell completions for completion command
279 complete -c {{.Name}} -n '__fish_seen_subcommand_from completion' -xa '{{.ShellList}}'
280 `
281
282 const powershellCompletionTmpl = `Register-ArgumentCompleter -Native -CommandName {{.Name}} -ScriptBlock {
283 param($wordToComplete, $commandAst, $cursorPosition)
284
285 $commands = @({{range .Subcommands}}'{{.Name}}', {{end}}'help')
286 $formats = @({{range .Formats}}'{{.}}', {{end}}'')
287 $shells = @('bash', 'zsh', 'fish', 'powershell')
288
289 # Find the subcommand
290 $subcommand = $null
291 $tokens = $commandAst.ToString().Split() | Select-Object -Skip 1
292 foreach ($token in $tokens) {
293 if ($commands -contains $token) {
294 $subcommand = $token
295 break
296 }
297 }
298
299 # Get the previous word for context-sensitive completion
300 $previousWord = $null
301 $allTokens = $commandAst.ToString().Split()
302 if ($allTokens.Count -gt 1) {
303 $previousWord = $allTokens[-1]
304 if ($wordToComplete -ne '') {
305 if ($allTokens.Count -gt 2) {
306 $previousWord = $allTokens[-2]
307 }
308 }
309 }
310
311 # Complete format names
312 if ($previousWord -in @('--in', '--out', '-i', '-o')) {
313 $formats | Where-Object { $_ -ne '' -and $_ -like "$wordToComplete*" } | ForEach-Object {
314 [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
315 }
316 return
317 }
318
319 # Complete shell names for completion command
320 if ($subcommand -eq 'completion') {
321 $shells | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
322 [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
323 }
324 return
325 }
326
327 if ($wordToComplete -like '-*') {
328 $flags = @()
329 switch ($subcommand) {
330 $null {
331 # No subcommand: global + query flags
332 $flags = @({{range .GlobalFlags}}'--{{.Name}}', {{end}}{{range .QueryFlags}}'--{{.Name}}', {{if .Short}}'-{{.Short}}', {{end}}{{end}}'')
333 }
334 {{range .Subcommands}}'{{.Name}}' {
335 $flags = @({{range $.GlobalFlags}}'--{{.Name}}', {{end}}{{range .Flags}}'--{{.Name}}', {{if .Short}}'-{{.Short}}', {{end}}{{end}}'')
336 }
337 {{end}}
338 }
339 $flags | Where-Object { $_ -ne '' -and $_ -like "$wordToComplete*" } | ForEach-Object {
340 [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterName', $_)
341 }
342 return
343 }
344
345 # Complete subcommands
346 if (-not $subcommand) {
347 $commands | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
348 [System.Management.Automation.CompletionResult]::new($_, $_, 'Command', $_)
349 }
350 }
351 }
352 `