@gunshi/plugin-completion 0.27.0-alpha.6 → 0.27.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # `@gunshi/plugin-completion`
2
2
 
3
- TODO(kazupon): more explanation
3
+ > completion plugin for gunshi
4
+
5
+ <!-- eslint-disable markdown/no-missing-label-refs -->
6
+
7
+ > ![WARNING]
8
+ > This package is still work in progress
9
+
10
+ <!-- eslint-enable markdown/no-missing-label-refs -->
4
11
 
5
12
  ## ©️ License
6
13
 
package/lib/index.d.ts CHANGED
@@ -1,11 +1,72 @@
1
- import { PluginWithoutExtension } from "@gunshi/plugin";
1
+ import { PluginWithExtension } from "@gunshi/plugin";
2
+ import { Handler } from "@bombsh/tab";
2
3
 
3
- //#region src/index.d.ts
4
+ //#region ../shared/src/constants.d.ts
5
+ /**
6
+ * @author kazuya kawaguchi (a.k.a. kazupon)
7
+ * @license MIT
8
+ */
9
+ /**
10
+ * @author kazuya kawaguchi (a.k.a. kazupon)
11
+ * @license MIT
12
+ */
13
+ declare const BUILT_IN_PREFIX = "_";
14
+ declare const PLUGIN_PREFIX = "g";
15
+ declare const BUILT_IN_KEY_SEPARATOR = ":";
16
+ //#endregion
17
+ //#region ../shared/src/types.d.ts
4
18
 
19
+ /**
20
+ * Generate a namespaced key.
21
+ */
22
+ type GenerateNamespacedKey<Key extends string, Prefixed extends string = typeof BUILT_IN_PREFIX> = `${Prefixed}${typeof BUILT_IN_KEY_SEPARATOR}${Key}`;
23
+ /**
24
+ * Command i18n built-in arguments keys.
25
+ */
26
+ //#endregion
27
+ //#region src/types.d.ts
28
+ /**
29
+ * The unique identifier for the completion plugin.
30
+ */
31
+ declare const pluginId: GenerateNamespacedKey<'completion', typeof PLUGIN_PREFIX>;
32
+ /**
33
+ * Type representing the unique identifier for the completion plugin.
34
+ */
35
+ type PluginId = typeof pluginId;
36
+ /**
37
+ * Extended command context which provides utilities via completion plugin.
38
+ * These utilities are available via `CommandContext.extensions['g:completion']`.
39
+ */
5
40
  interface CompletionCommandContext {}
41
+ /**
42
+ * Completion configuration, which structure is similar `bombsh/tab`'s `CompletionConfig`.
43
+ */
44
+ interface CompletionConfig {
45
+ handler?: Handler;
46
+ args?: Record<string, {
47
+ handler: Handler;
48
+ }>;
49
+ }
50
+ /**
51
+ * Completion plugin options.
52
+ */
53
+ interface CompletionOptions {
54
+ config?: {
55
+ /**
56
+ * The entry point completion configuration.
57
+ */
58
+ entry?: CompletionConfig;
59
+ /**
60
+ * The handlers for subcommands.
61
+ */
62
+ subCommands?: Record<string, CompletionConfig>;
63
+ };
64
+ }
65
+ //#endregion
66
+ //#region src/index.d.ts
6
67
  /**
7
68
  * completion plugin for gunshi
8
69
  */
9
- declare function completion(): PluginWithoutExtension<CompletionCommandContext>;
70
+ declare function completion(options?: CompletionOptions): PluginWithExtension<CompletionCommandContext>;
10
71
  //#endregion
11
- export { CompletionCommandContext, completion as default };
72
+ export { CompletionCommandContext, CompletionConfig, CompletionOptions, PluginId, completion as default, pluginId };
package/lib/index.js CHANGED
@@ -1,16 +1,1124 @@
1
1
  import { plugin } from "@gunshi/plugin";
2
2
 
3
+ //#region ../../node_modules/.pnpm/tab@https+++pkg.pr.new+bombshell-dev+tab@main/node_modules/tab/dist/zsh-Bm75fLuV.js
4
+ function generate$3(name, exec) {
5
+ const nameForVar = name.replace(/[-:]/g, "_");
6
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
7
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
8
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
9
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
10
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
11
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
12
+ return `# bash completion for ${name}
13
+
14
+ # Define shell completion directives
15
+ readonly ShellCompDirectiveError=${ShellCompDirectiveError}
16
+ readonly ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
17
+ readonly ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
18
+ readonly ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
19
+ readonly ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
20
+ readonly ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
21
+
22
+ # Function to debug completion
23
+ __${nameForVar}_debug() {
24
+ if [[ -n \${BASH_COMP_DEBUG_FILE:-} ]]; then
25
+ echo "$*" >> "\${BASH_COMP_DEBUG_FILE}"
26
+ fi
27
+ }
28
+
29
+ # Function to handle completions
30
+ __${nameForVar}_complete() {
31
+ local cur prev words cword
32
+ _get_comp_words_by_ref -n "=:" cur prev words cword
33
+
34
+ local requestComp out directive
35
+
36
+ # Build the command to get completions
37
+ requestComp="${exec} complete -- \${words[@]:1}"
38
+
39
+ # Add an empty parameter if the last parameter is complete
40
+ if [[ -z "$cur" ]]; then
41
+ requestComp="$requestComp ''"
42
+ fi
43
+
44
+ # Get completions from the program
45
+ out=$(eval "$requestComp" 2>/dev/null)
46
+
47
+ # Extract directive if present
48
+ directive=0
49
+ if [[ "$out" == *:* ]]; then
50
+ directive=\${out##*:}
51
+ out=\${out%:*}
52
+ fi
53
+
54
+ # Process completions based on directive
55
+ if [[ $((directive & $ShellCompDirectiveError)) -ne 0 ]]; then
56
+ # Error, no completion
57
+ return
58
+ fi
59
+
60
+ # Apply directives
61
+ if [[ $((directive & $ShellCompDirectiveNoSpace)) -ne 0 ]]; then
62
+ compopt -o nospace
63
+ fi
64
+ if [[ $((directive & $ShellCompDirectiveKeepOrder)) -ne 0 ]]; then
65
+ compopt -o nosort
66
+ fi
67
+ if [[ $((directive & $ShellCompDirectiveNoFileComp)) -ne 0 ]]; then
68
+ compopt +o default
69
+ fi
70
+
71
+ # Handle file extension filtering
72
+ if [[ $((directive & $ShellCompDirectiveFilterFileExt)) -ne 0 ]]; then
73
+ local filter=""
74
+ for ext in $out; do
75
+ filter="$filter|$ext"
76
+ done
77
+ filter="\\.($filter)"
78
+ compopt -o filenames
79
+ COMPREPLY=( $(compgen -f -X "!$filter" -- "$cur") )
80
+ return
81
+ fi
82
+
83
+ # Handle directory filtering
84
+ if [[ $((directive & $ShellCompDirectiveFilterDirs)) -ne 0 ]]; then
85
+ compopt -o dirnames
86
+ COMPREPLY=( $(compgen -d -- "$cur") )
87
+ return
88
+ fi
89
+
90
+ # Process completions
91
+ local IFS=$'\\n'
92
+ local tab=$(printf '\\t')
93
+
94
+ # Parse completions with descriptions
95
+ local completions=()
96
+ while read -r comp; do
97
+ if [[ "$comp" == *$tab* ]]; then
98
+ # Split completion and description
99
+ local value=\${comp%%$tab*}
100
+ local desc=\${comp#*$tab}
101
+ completions+=("$value")
102
+ else
103
+ completions+=("$comp")
104
+ fi
105
+ done <<< "$out"
106
+
107
+ # Return completions
108
+ COMPREPLY=( $(compgen -W "\${completions[*]}" -- "$cur") )
109
+ }
110
+
111
+ # Register completion function
112
+ complete -F __${nameForVar}_complete ${name}
113
+ `;
114
+ }
115
+ function generate$2(name, exec) {
116
+ const nameForVar = name.replace(/[-:]/g, "_");
117
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
118
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
119
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
120
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
121
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
122
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
123
+ return `# fish completion for ${name} -*- shell-script -*-
124
+
125
+ # Define shell completion directives
126
+ set -l ShellCompDirectiveError ${ShellCompDirectiveError}
127
+ set -l ShellCompDirectiveNoSpace ${ShellCompDirectiveNoSpace}
128
+ set -l ShellCompDirectiveNoFileComp ${ShellCompDirectiveNoFileComp}
129
+ set -l ShellCompDirectiveFilterFileExt ${ShellCompDirectiveFilterFileExt}
130
+ set -l ShellCompDirectiveFilterDirs ${ShellCompDirectiveFilterDirs}
131
+ set -l ShellCompDirectiveKeepOrder ${ShellCompDirectiveKeepOrder}
132
+
133
+ function __${nameForVar}_debug
134
+ set -l file "$BASH_COMP_DEBUG_FILE"
135
+ if test -n "$file"
136
+ echo "$argv" >> $file
137
+ end
138
+ end
139
+
140
+ function __${nameForVar}_perform_completion
141
+ __${nameForVar}_debug "Starting __${nameForVar}_perform_completion"
142
+
143
+ # Extract all args except the completion flag
144
+ set -l args (string match -v -- "--completion=" (commandline -opc))
145
+
146
+ # Extract the current token being completed
147
+ set -l current_token (commandline -ct)
148
+
149
+ # Check if current token starts with a dash
150
+ set -l flag_prefix ""
151
+ if string match -q -- "-*" $current_token
152
+ set flag_prefix "--flag="
153
+ end
154
+
155
+ __${nameForVar}_debug "Current token: $current_token"
156
+ __${nameForVar}_debug "All args: $args"
157
+
158
+ # Call the completion program and get the results
159
+ set -l requestComp "${exec} complete -- $args"
160
+ __${nameForVar}_debug "Calling $requestComp"
161
+ set -l results (eval $requestComp 2> /dev/null)
162
+
163
+ # Some programs may output extra empty lines after the directive.
164
+ # Let's ignore them or else it will break completion.
165
+ # Ref: https://github.com/spf13/cobra/issues/1279
166
+ for line in $results[-1..1]
167
+ if test (string sub -s 1 -l 1 -- $line) = ":"
168
+ # The directive
169
+ set -l directive (string sub -s 2 -- $line)
170
+ set -l directive_num (math $directive)
171
+ break
172
+ end
173
+ end
174
+
175
+ # No directive specified, use default
176
+ if not set -q directive_num
177
+ set directive_num 0
178
+ end
179
+
180
+ __${nameForVar}_debug "Directive: $directive_num"
181
+
182
+ # Process completions based on directive
183
+ if test $directive_num -eq $ShellCompDirectiveError
184
+ # Error code. No completion.
185
+ __${nameForVar}_debug "Received error directive: aborting."
186
+ return 1
187
+ end
188
+
189
+ # Filter out the directive (last line)
190
+ if test (count $results) -gt 0 -a (string sub -s 1 -l 1 -- $results[-1]) = ":"
191
+ set results $results[1..-2]
192
+ end
193
+
194
+ # No completions, let fish handle file completions unless forbidden
195
+ if test (count $results) -eq 0
196
+ if test $directive_num -ne $ShellCompDirectiveNoFileComp
197
+ __${nameForVar}_debug "No completions, performing file completion"
198
+ return 1
199
+ end
200
+ __${nameForVar}_debug "No completions, but file completion forbidden"
201
+ return 0
202
+ end
203
+
204
+ # Filter file extensions
205
+ if test $directive_num -eq $ShellCompDirectiveFilterFileExt
206
+ __${nameForVar}_debug "File extension filtering"
207
+ set -l file_extensions
208
+ for item in $results
209
+ if test -n "$item" -a (string sub -s 1 -l 1 -- $item) != "-"
210
+ set -a file_extensions "*$item"
211
+ end
212
+ end
213
+ __${nameForVar}_debug "File extensions: $file_extensions"
214
+
215
+ # Use the file extensions as completions
216
+ set -l completions
217
+ for ext in $file_extensions
218
+ # Get all files matching the extension
219
+ set -a completions (string replace -r '^.*/' '' -- $ext)
220
+ end
221
+
222
+ for item in $completions
223
+ echo -e "$item\t"
224
+ end
225
+ return 0
226
+ end
227
+
228
+ # Filter directories
229
+ if test $directive_num -eq $ShellCompDirectiveFilterDirs
230
+ __${nameForVar}_debug "Directory filtering"
231
+ set -l dirs
232
+ for item in $results
233
+ if test -d "$item"
234
+ set -a dirs "$item/"
235
+ end
236
+ end
237
+
238
+ for item in $dirs
239
+ echo -e "$item\t"
240
+ end
241
+ return 0
242
+ end
243
+
244
+ # Process remaining completions
245
+ for item in $results
246
+ if test -n "$item"
247
+ # Check if the item has a description
248
+ if string match -q "*\t*" -- "$item"
249
+ set -l completion_parts (string split \t -- "$item")
250
+ set -l comp $completion_parts[1]
251
+ set -l desc $completion_parts[2]
252
+
253
+ # Add the completion and description
254
+ echo -e "$comp\t$desc"
255
+ else
256
+ # Add just the completion
257
+ echo -e "$item\t"
258
+ end
259
+ end
260
+ end
261
+
262
+ # If directive contains NoSpace, tell fish not to add a space after completion
263
+ if test (math "$directive_num & $ShellCompDirectiveNoSpace") -ne 0
264
+ return 2
265
+ end
266
+
267
+ return 0
268
+ end
269
+
270
+ # Set up the completion for the ${name} command
271
+ complete -c ${name} -f -a "(eval __${nameForVar}_perform_completion)"
272
+ `;
273
+ }
274
+ function generate$1(name, exec, includeDesc = false) {
275
+ const nameForVar = name.replace(/[-:]/g, "_");
276
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
277
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
278
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
279
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
280
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
281
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
282
+ return `# powershell completion for ${name} -*- shell-script -*-
283
+
284
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
285
+ function __${name}_debug {
286
+ if ($env:BASH_COMP_DEBUG_FILE) {
287
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
288
+ }
289
+ }
290
+
291
+ filter __${name}_escapeStringWithSpecialChars {
292
+ $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\\||<|>|&','\`$&'
293
+ }
294
+
295
+ [scriptblock]$__${nameForVar}CompleterBlock = {
296
+ param(
297
+ $WordToComplete,
298
+ $CommandAst,
299
+ $CursorPosition
300
+ )
301
+
302
+ # Get the current command line and convert into a string
303
+ $Command = $CommandAst.CommandElements
304
+ $Command = "$Command"
305
+
306
+ __${name}_debug ""
307
+ __${name}_debug "========= starting completion logic =========="
308
+ __${name}_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
309
+
310
+ # The user could have moved the cursor backwards on the command-line.
311
+ # We need to trigger completion from the $CursorPosition location, so we need
312
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
313
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
314
+ # This happens because the $Command does not include the last space.
315
+ if ($Command.Length -gt $CursorPosition) {
316
+ $Command = $Command.Substring(0, $CursorPosition)
317
+ }
318
+ __${name}_debug "Truncated command: $Command"
319
+
320
+ $ShellCompDirectiveError=${ShellCompDirectiveError}
321
+ $ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
322
+ $ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
323
+ $ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
324
+ $ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
325
+ $ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
326
+
327
+ # Prepare the command to request completions for the program.
328
+ # Split the command at the first space to separate the program and arguments.
329
+ $Program, $Arguments = $Command.Split(" ", 2)
330
+
331
+ $RequestComp = "& ${exec} complete -- $Arguments"
332
+ __${name}_debug "RequestComp: $RequestComp"
333
+
334
+ # we cannot use $WordToComplete because it
335
+ # has the wrong values if the cursor was moved
336
+ # so use the last argument
337
+ if ($WordToComplete -ne "" ) {
338
+ $WordToComplete = $Arguments.Split(" ")[-1]
339
+ }
340
+ __${name}_debug "New WordToComplete: $WordToComplete"
341
+
342
+
343
+ # Check for flag with equal sign
344
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
345
+ if ( $IsEqualFlag ) {
346
+ __${name}_debug "Completing equal sign flag"
347
+ # Remove the flag part
348
+ $Flag, $WordToComplete = $WordToComplete.Split("=", 2)
349
+ }
350
+
351
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
352
+ # If the last parameter is complete (there is a space following it)
353
+ # We add an extra empty parameter so we can indicate this to the go method.
354
+ __${name}_debug "Adding extra empty parameter"
355
+ # PowerShell 7.2+ changed the way how the arguments are passed to executables,
356
+ # so for pre-7.2 or when Legacy argument passing is enabled we need to use
357
+ if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
358
+ ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
359
+ (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
360
+ $PSNativeCommandArgumentPassing -eq 'Legacy')) {
361
+ $RequestComp="$RequestComp" + ' \`"\`"'
362
+ } else {
363
+ $RequestComp = "$RequestComp" + ' ""'
364
+ }
365
+ }
366
+
367
+ __${name}_debug "Calling $RequestComp"
368
+ # First disable ActiveHelp which is not supported for Powershell
369
+ $env:ActiveHelp = 0
370
+
371
+ # call the command store the output in $out and redirect stderr and stdout to null
372
+ # $Out is an array contains each line per element
373
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
374
+
375
+ # get directive from last line
376
+ [int]$Directive = $Out[-1].TrimStart(':')
377
+ if ($Directive -eq "") {
378
+ # There is no directive specified
379
+ $Directive = 0
380
+ }
381
+ __${name}_debug "The completion directive is: $Directive"
382
+
383
+ # remove directive (last element) from out
384
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
385
+ __${name}_debug "The completions are: $Out"
386
+
387
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
388
+ # Error code. No completion.
389
+ __${name}_debug "Received error from custom completion go code"
390
+ return
391
+ }
392
+
393
+ $Longest = 0
394
+ [Array]$Values = $Out | ForEach-Object {
395
+ # Split the output in name and description
396
+ $Name, $Description = $_.Split("\`t", 2)
397
+ __${name}_debug "Name: $Name Description: $Description"
398
+
399
+ # Look for the longest completion so that we can format things nicely
400
+ if ($Longest -lt $Name.Length) {
401
+ $Longest = $Name.Length
402
+ }
403
+
404
+ # Set the description to a one space string if there is none set.
405
+ # This is needed because the CompletionResult does not accept an empty string as argument
406
+ if (-Not $Description) {
407
+ $Description = " "
408
+ }
409
+ @{ Name = "$Name"; Description = "$Description" }
410
+ }
411
+
412
+
413
+ $Space = " "
414
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
415
+ # remove the space here
416
+ __${name}_debug "ShellCompDirectiveNoSpace is called"
417
+ $Space = ""
418
+ }
419
+
420
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
421
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
422
+ __${name}_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
423
+
424
+ # return here to prevent the completion of the extensions
425
+ return
426
+ }
427
+
428
+ $Values = $Values | Where-Object {
429
+ # filter the result
430
+ $_.Name -like "$WordToComplete*"
431
+
432
+ # Join the flag back if we have an equal sign flag
433
+ if ( $IsEqualFlag ) {
434
+ __${name}_debug "Join the equal sign flag back to the completion value"
435
+ $_.Name = $Flag + "=" + $_.Name
436
+ }
437
+ }
438
+
439
+ # we sort the values in ascending order by name if keep order isn't passed
440
+ if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
441
+ $Values = $Values | Sort-Object -Property Name
442
+ }
443
+
444
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
445
+ __${name}_debug "ShellCompDirectiveNoFileComp is called"
446
+
447
+ if ($Values.Length -eq 0) {
448
+ # Just print an empty string here so the
449
+ # shell does not start to complete paths.
450
+ # We cannot use CompletionResult here because
451
+ # it does not accept an empty string as argument.
452
+ ""
453
+ return
454
+ }
455
+ }
456
+
457
+ # Get the current mode
458
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object { $_.Key -eq "Tab" }).Function
459
+ __${name}_debug "Mode: $Mode"
460
+
461
+ $Values | ForEach-Object {
462
+
463
+ # store temporary because switch will overwrite $_
464
+ $comp = $_
465
+
466
+ # PowerShell supports three different completion modes
467
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
468
+ # - Complete (works like bash)
469
+ # - MenuComplete (works like zsh)
470
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
471
+
472
+ # CompletionResult Arguments:
473
+ # 1) CompletionText text to be used as the auto completion result
474
+ # 2) ListItemText text to be displayed in the suggestion list
475
+ # 3) ResultType type of completion result
476
+ # 4) ToolTip text for the tooltip with details about the object
477
+
478
+ switch ($Mode) {
479
+
480
+ # bash like
481
+ "Complete" {
482
+
483
+ if ($Values.Length -eq 1) {
484
+ __${name}_debug "Only one completion left"
485
+
486
+ # insert space after value
487
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
488
+
489
+ } else {
490
+ # Add the proper number of spaces to align the descriptions
491
+ while($comp.Name.Length -lt $Longest) {
492
+ $comp.Name = $comp.Name + " "
493
+ }
494
+
495
+ # Check for empty description and only add parentheses if needed
496
+ if ($($comp.Description) -eq " " ) {
497
+ $Description = ""
498
+ } else {
499
+ $Description = " ($($comp.Description))"
500
+ }
501
+
502
+ [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
503
+ }
504
+ }
505
+
506
+ # zsh like
507
+ "MenuComplete" {
508
+ # insert space after value
509
+ # MenuComplete will automatically show the ToolTip of
510
+ # the highlighted value at the bottom of the suggestions.
511
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
512
+ }
513
+
514
+ # TabCompleteNext and in case we get something unknown
515
+ Default {
516
+ # Like MenuComplete but we don't want to add a space here because
517
+ # the user need to press space anyway to get the completion.
518
+ # Description will not be shown because that's not possible with TabCompleteNext
519
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
520
+ }
521
+ }
522
+
523
+ }
524
+ }
525
+
526
+ Register-ArgumentCompleter -CommandName '${name}' -ScriptBlock $__${nameForVar}CompleterBlock
527
+ `;
528
+ }
529
+ const ShellCompDirective = {
530
+ ShellCompDirectiveError: 1,
531
+ ShellCompDirectiveNoSpace: 2,
532
+ ShellCompDirectiveNoFileComp: 4,
533
+ ShellCompDirectiveFilterFileExt: 8,
534
+ ShellCompDirectiveFilterDirs: 16,
535
+ ShellCompDirectiveKeepOrder: 32,
536
+ shellCompDirectiveMaxValue: 64,
537
+ ShellCompDirectiveDefault: 0
538
+ };
539
+ var Completion = class {
540
+ commands = new Map();
541
+ completions = [];
542
+ directive = ShellCompDirective.ShellCompDirectiveDefault;
543
+ addCommand(name, description, args, handler, parent) {
544
+ const key = parent ? `${parent} ${name}` : name;
545
+ this.commands.set(key, {
546
+ name: key,
547
+ description,
548
+ args,
549
+ handler,
550
+ options: new Map(),
551
+ parent: parent ? this.commands.get(parent) : void 0
552
+ });
553
+ return key;
554
+ }
555
+ addOption(command, option, description, handler, alias) {
556
+ const cmd = this.commands.get(command);
557
+ if (!cmd) throw new Error(`Command ${command} not found.`);
558
+ cmd.options.set(option, {
559
+ description,
560
+ handler,
561
+ alias
562
+ });
563
+ return option;
564
+ }
565
+ stripOptions(args) {
566
+ const parts = [];
567
+ let option = false;
568
+ for (const k of args) {
569
+ if (k.startsWith("-")) {
570
+ option = true;
571
+ continue;
572
+ }
573
+ if (option) {
574
+ option = false;
575
+ continue;
576
+ }
577
+ parts.push(k);
578
+ }
579
+ return parts;
580
+ }
581
+ matchCommand(args) {
582
+ args = this.stripOptions(args);
583
+ const parts = [];
584
+ let remaining = [];
585
+ let matched = this.commands.get("");
586
+ for (let i = 0; i < args.length; i++) {
587
+ const k = args[i];
588
+ parts.push(k);
589
+ const potential = this.commands.get(parts.join(" "));
590
+ if (potential) matched = potential;
591
+ else {
592
+ remaining = args.slice(i, args.length);
593
+ break;
594
+ }
595
+ }
596
+ return [matched, remaining];
597
+ }
598
+ async parse(args) {
599
+ const endsWithSpace = args[args.length - 1] === "";
600
+ if (endsWithSpace) args.pop();
601
+ let toComplete = args[args.length - 1] || "";
602
+ const previousArgs = args.slice(0, -1);
603
+ if (endsWithSpace) {
604
+ previousArgs.push(toComplete);
605
+ toComplete = "";
606
+ }
607
+ const [matchedCommand] = this.matchCommand(previousArgs);
608
+ const lastPrevArg = previousArgs[previousArgs.length - 1];
609
+ if (this.shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace)) await this.handleFlagCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace, lastPrevArg);
610
+ else {
611
+ if (this.shouldCompleteCommands(toComplete, endsWithSpace)) await this.handleCommandCompletion(previousArgs, toComplete);
612
+ if (matchedCommand && matchedCommand.args.length > 0) await this.handlePositionalCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace);
613
+ }
614
+ this.complete(toComplete);
615
+ }
616
+ complete(toComplete) {
617
+ this.directive = ShellCompDirective.ShellCompDirectiveNoFileComp;
618
+ const seen = new Set();
619
+ this.completions.filter((comp) => {
620
+ if (seen.has(comp.value)) return false;
621
+ seen.add(comp.value);
622
+ return true;
623
+ }).filter((comp) => comp.value.startsWith(toComplete)).forEach((comp) => console.log(`${comp.value}\t${comp.description ?? ""}`));
624
+ console.log(`:${this.directive}`);
625
+ }
626
+ shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace) {
627
+ return lastPrevArg?.startsWith("--") || lastPrevArg?.startsWith("-") || toComplete.startsWith("--") || toComplete.startsWith("-");
628
+ }
629
+ shouldCompleteCommands(toComplete, endsWithSpace) {
630
+ return !toComplete.startsWith("-");
631
+ }
632
+ async handleFlagCompletion(command, previousArgs, toComplete, endsWithSpace, lastPrevArg) {
633
+ let flagName;
634
+ let valueToComplete = toComplete;
635
+ if (toComplete.includes("=")) {
636
+ const parts = toComplete.split("=");
637
+ flagName = parts[0];
638
+ valueToComplete = parts[1] || "";
639
+ } else if (lastPrevArg?.startsWith("-")) flagName = lastPrevArg;
640
+ if (flagName) {
641
+ let option = command.options.get(flagName);
642
+ if (!option) {
643
+ for (const [name, opt] of command.options) if (opt.alias && `-${opt.alias}` === flagName) {
644
+ option = opt;
645
+ flagName = name;
646
+ break;
647
+ }
648
+ }
649
+ if (option) {
650
+ const suggestions = await option.handler(previousArgs, valueToComplete, endsWithSpace);
651
+ if (toComplete.includes("=")) this.completions = suggestions.map((suggestion) => ({
652
+ value: `${flagName}=${suggestion.value}`,
653
+ description: suggestion.description
654
+ }));
655
+ else this.completions.push(...suggestions);
656
+ }
657
+ return;
658
+ }
659
+ if (toComplete.startsWith("-")) {
660
+ const isShortFlag = toComplete.startsWith("-") && !toComplete.startsWith("--");
661
+ for (const [name, option] of command.options) if (isShortFlag) {
662
+ if (option.alias && `-${option.alias}`.startsWith(toComplete)) this.completions.push({
663
+ value: `-${option.alias}`,
664
+ description: option.description
665
+ });
666
+ } else if (name.startsWith(toComplete)) this.completions.push({
667
+ value: name,
668
+ description: option.description
669
+ });
670
+ }
671
+ }
672
+ async handleCommandCompletion(previousArgs, toComplete) {
673
+ const commandParts = [...previousArgs].filter(Boolean);
674
+ for (const [k, command] of this.commands) {
675
+ if (k === "") continue;
676
+ const parts = k.split(" ");
677
+ let match = true;
678
+ let i = 0;
679
+ while (i < commandParts.length) {
680
+ if (parts[i] !== commandParts[i]) {
681
+ match = false;
682
+ break;
683
+ }
684
+ i++;
685
+ }
686
+ if (match && parts[i]?.startsWith(toComplete)) this.completions.push({
687
+ value: parts[i],
688
+ description: command.description
689
+ });
690
+ }
691
+ }
692
+ async handlePositionalCompletion(command, previousArgs, toComplete, endsWithSpace) {
693
+ const suggestions = await command.handler(previousArgs, toComplete, endsWithSpace);
694
+ this.completions.push(...suggestions);
695
+ }
696
+ };
697
+ function script(shell, name, x) {
698
+ switch (shell) {
699
+ case "zsh": {
700
+ const script$1 = generate(name, x);
701
+ console.log(script$1);
702
+ break;
703
+ }
704
+ case "bash": {
705
+ const script$1 = generate$3(name, x);
706
+ console.log(script$1);
707
+ break;
708
+ }
709
+ case "fish": {
710
+ const script$1 = generate$2(name, x);
711
+ console.log(script$1);
712
+ break;
713
+ }
714
+ case "powershell": {
715
+ const script$1 = generate$1(name, x);
716
+ console.log(script$1);
717
+ break;
718
+ }
719
+ default: throw new Error(`Unsupported shell: ${shell}`);
720
+ }
721
+ }
722
+ function generate(name, exec) {
723
+ return `#compdef ${name}
724
+ compdef _${name} ${name}
725
+
726
+ # zsh completion for ${name} -*- shell-script -*-
727
+
728
+ __${name}_debug() {
729
+ local file="$BASH_COMP_DEBUG_FILE"
730
+ if [[ -n \${file} ]]; then
731
+ echo "$*" >> "\${file}"
732
+ fi
733
+ }
734
+
735
+ _${name}() {
736
+ local shellCompDirectiveError=${ShellCompDirective.ShellCompDirectiveError}
737
+ local shellCompDirectiveNoSpace=${ShellCompDirective.ShellCompDirectiveNoSpace}
738
+ local shellCompDirectiveNoFileComp=${ShellCompDirective.ShellCompDirectiveNoFileComp}
739
+ local shellCompDirectiveFilterFileExt=${ShellCompDirective.ShellCompDirectiveFilterFileExt}
740
+ local shellCompDirectiveFilterDirs=${ShellCompDirective.ShellCompDirectiveFilterDirs}
741
+ local shellCompDirectiveKeepOrder=${ShellCompDirective.ShellCompDirectiveKeepOrder}
742
+
743
+ local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
744
+ local -a completions
745
+
746
+ __${name}_debug "\\n========= starting completion logic =========="
747
+ __${name}_debug "CURRENT: \${CURRENT}, words[*]: \${words[*]}"
748
+
749
+ # The user could have moved the cursor backwards on the command-line.
750
+ # We need to trigger completion from the $CURRENT location, so we need
751
+ # to truncate the command-line ($words) up to the $CURRENT location.
752
+ # (We cannot use $CURSOR as its value does not work when a command is an alias.)
753
+ words=( "\${=words[1,CURRENT]}" )
754
+ __${name}_debug "Truncated words[*]: \${words[*]},"
755
+
756
+ lastParam=\${words[-1]}
757
+ lastChar=\${lastParam[-1]}
758
+ __${name}_debug "lastParam: \${lastParam}, lastChar: \${lastChar}"
759
+
760
+ # For zsh, when completing a flag with an = (e.g., ${name} -n=<TAB>)
761
+ # completions must be prefixed with the flag
762
+ setopt local_options BASH_REMATCH
763
+ if [[ "\${lastParam}" =~ '-.*=' ]]; then
764
+ # We are dealing with a flag with an =
765
+ flagPrefix="-P \${BASH_REMATCH}"
766
+ fi
767
+
768
+ # Prepare the command to obtain completions, ensuring arguments are quoted for eval
769
+ local -a args_to_quote=("\${(@)words[2,-1]}")
770
+ if [ "\${lastChar}" = "" ]; then
771
+ # If the last parameter is complete (there is a space following it)
772
+ # We add an extra empty parameter so we can indicate this to the go completion code.
773
+ __${name}_debug "Adding extra empty parameter"
774
+ args_to_quote+=("")
775
+ fi
776
+
777
+ # Use Zsh's (q) flag to quote each argument safely for eval
778
+ local quoted_args=("\${(@q)args_to_quote}")
779
+
780
+ # Join the main command and the quoted arguments into a single string for eval
781
+ requestComp="${exec} complete -- \${quoted_args[*]}"
782
+
783
+ __${name}_debug "About to call: eval \${requestComp}"
784
+
785
+ # Use eval to handle any environment variables and such
786
+ out=$(eval \${requestComp} 2>/dev/null)
787
+ __${name}_debug "completion output: \${out}"
788
+
789
+ # Extract the directive integer following a : from the last line
790
+ local lastLine
791
+ while IFS='\n' read -r line; do
792
+ lastLine=\${line}
793
+ done < <(printf "%s\n" "\${out[@]}")
794
+ __${name}_debug "last line: \${lastLine}"
795
+
796
+ if [ "\${lastLine[1]}" = : ]; then
797
+ directive=\${lastLine[2,-1]}
798
+ # Remove the directive including the : and the newline
799
+ local suffix
800
+ (( suffix=\${#lastLine}+2))
801
+ out=\${out[1,-$suffix]}
802
+ else
803
+ # There is no directive specified. Leave $out as is.
804
+ __${name}_debug "No directive found. Setting to default"
805
+ directive=0
806
+ fi
807
+
808
+ __${name}_debug "directive: \${directive}"
809
+ __${name}_debug "completions: \${out}"
810
+ __${name}_debug "flagPrefix: \${flagPrefix}"
811
+
812
+ if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
813
+ __${name}_debug "Completion received error. Ignoring completions."
814
+ return
815
+ fi
816
+
817
+ local activeHelpMarker="%"
818
+ local endIndex=\${#activeHelpMarker}
819
+ local startIndex=$((\${#activeHelpMarker}+1))
820
+ local hasActiveHelp=0
821
+ while IFS='\n' read -r comp; do
822
+ # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
823
+ if [ "\${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
824
+ __${name}_debug "ActiveHelp found: $comp"
825
+ comp="\${comp[$startIndex,-1]}"
826
+ if [ -n "$comp" ]; then
827
+ compadd -x "\${comp}"
828
+ __${name}_debug "ActiveHelp will need delimiter"
829
+ hasActiveHelp=1
830
+ fi
831
+ continue
832
+ fi
833
+
834
+ if [ -n "$comp" ]; then
835
+ # If requested, completions are returned with a description.
836
+ # The description is preceded by a TAB character.
837
+ # For zsh's _describe, we need to use a : instead of a TAB.
838
+ # We first need to escape any : as part of the completion itself.
839
+ comp=\${comp//:/\\:}
840
+
841
+ local tab="$(printf '\\t')"
842
+ comp=\${comp//$tab/:}
843
+
844
+ __${name}_debug "Adding completion: \${comp}"
845
+ completions+=\${comp}
846
+ lastComp=$comp
847
+ fi
848
+ done < <(printf "%s\n" "\${out[@]}")
849
+
850
+ # Add a delimiter after the activeHelp statements, but only if:
851
+ # - there are completions following the activeHelp statements, or
852
+ # - file completion will be performed (so there will be choices after the activeHelp)
853
+ if [ $hasActiveHelp -eq 1 ]; then
854
+ if [ \${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
855
+ __${name}_debug "Adding activeHelp delimiter"
856
+ compadd -x "--"
857
+ hasActiveHelp=0
858
+ fi
859
+ fi
860
+
861
+ if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
862
+ __${name}_debug "Activating nospace."
863
+ noSpace="-S ''"
864
+ fi
865
+
866
+ if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
867
+ __${name}_debug "Activating keep order."
868
+ keepOrder="-V"
869
+ fi
870
+
871
+ if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
872
+ # File extension filtering
873
+ local filteringCmd
874
+ filteringCmd='_files'
875
+ for filter in \${completions[@]}; do
876
+ if [ \${filter[1]} != '*' ]; then
877
+ # zsh requires a glob pattern to do file filtering
878
+ filter="\\*.$filter"
879
+ fi
880
+ filteringCmd+=" -g $filter"
881
+ done
882
+ filteringCmd+=" \${flagPrefix}"
883
+
884
+ __${name}_debug "File filtering command: $filteringCmd"
885
+ _arguments '*:filename:'"$filteringCmd"
886
+ elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
887
+ # File completion for directories only
888
+ local subdir
889
+ subdir="\${completions[1]}"
890
+ if [ -n "$subdir" ]; then
891
+ __${name}_debug "Listing directories in $subdir"
892
+ pushd "\${subdir}" >/dev/null 2>&1
893
+ else
894
+ __${name}_debug "Listing directories in ."
895
+ fi
896
+
897
+ local result
898
+ _arguments '*:dirname:_files -/'" \${flagPrefix}"
899
+ result=$?
900
+ if [ -n "$subdir" ]; then
901
+ popd >/dev/null 2>&1
902
+ fi
903
+ return $result
904
+ else
905
+ __${name}_debug "Calling _describe"
906
+ if eval _describe $keepOrder "completions" completions -Q \${flagPrefix} \${noSpace}; then
907
+ __${name}_debug "_describe found some completions"
908
+
909
+ # Return the success of having called _describe
910
+ return 0
911
+ else
912
+ __${name}_debug "_describe did not find completions."
913
+ __${name}_debug "Checking if we should do file completion."
914
+ if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
915
+ __${name}_debug "deactivating file completion"
916
+
917
+ # We must return an error code here to let zsh know that there were no
918
+ # completions found by _describe; this is what will trigger other
919
+ # matching algorithms to attempt to find completions.
920
+ # For example zsh can match letters in the middle of words.
921
+ return 1
922
+ else
923
+ # Perform file completion
924
+ __${name}_debug "Activating file completion"
925
+
926
+ # We must return the result of this command, so it must be the
927
+ # last command, or else we must store its result to return it.
928
+ _arguments '*:filename:_files'" \${flagPrefix}"
929
+ fi
930
+ fi
931
+ fi
932
+ }
933
+
934
+ # don't run the completion function when being sourced or eval-ed
935
+ if [ "\${funcstack[1]}" = "_${name}" ]; then
936
+ _${name}
937
+ fi
938
+ `;
939
+ }
940
+
941
+ //#endregion
942
+ //#region ../gunshi/src/utils.ts
943
+ function isLazyCommand(cmd) {
944
+ return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
945
+ }
946
+ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
947
+ let command;
948
+ if (isLazyCommand(cmd)) {
949
+ const baseCommand = {
950
+ name: cmd.commandName,
951
+ description: cmd.description,
952
+ args: cmd.args,
953
+ examples: cmd.examples,
954
+ internal: cmd.internal,
955
+ entry: cmd.entry
956
+ };
957
+ if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
958
+ command = Object.assign(create(), baseCommand);
959
+ if (needRunResolving) {
960
+ const loaded = await cmd();
961
+ if (typeof loaded === "function") command.run = loaded;
962
+ else if (typeof loaded === "object") {
963
+ if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
964
+ command.run = loaded.run;
965
+ command.name = loaded.name;
966
+ command.description = loaded.description;
967
+ command.args = loaded.args;
968
+ command.examples = loaded.examples;
969
+ command.internal = loaded.internal;
970
+ command.entry = loaded.entry;
971
+ if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
972
+ } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
973
+ }
974
+ } else command = Object.assign(create(), cmd);
975
+ if (command.name == null && name) command.name = name;
976
+ return deepFreeze(command);
977
+ }
978
+ function create(obj = null) {
979
+ return Object.create(obj);
980
+ }
981
+ function deepFreeze(obj, ignores = []) {
982
+ if (obj === null || typeof obj !== "object") return obj;
983
+ for (const key of Object.keys(obj)) {
984
+ const value = obj[key];
985
+ if (ignores.includes(key)) continue;
986
+ if (typeof value === "object" && value !== null) deepFreeze(value, ignores);
987
+ }
988
+ return Object.freeze(obj);
989
+ }
990
+
991
+ //#endregion
992
+ //#region ../shared/src/constants.ts
993
+ /**
994
+ * @author kazuya kawaguchi (a.k.a. kazupon)
995
+ * @license MIT
996
+ */
997
+ const BUILT_IN_PREFIX = "_";
998
+ const PLUGIN_PREFIX = "g";
999
+ const ARG_PREFIX = "arg";
1000
+ const BUILT_IN_KEY_SEPARATOR = ":";
1001
+ const BUILD_IN_PREFIX_AND_KEY_SEPARATOR = `${BUILT_IN_PREFIX}${BUILT_IN_KEY_SEPARATOR}`;
1002
+ const ARG_PREFIX_AND_KEY_SEPARATOR = `${ARG_PREFIX}${BUILT_IN_KEY_SEPARATOR}`;
1003
+
1004
+ //#endregion
1005
+ //#region ../shared/src/utils.ts
1006
+ function namespacedId(id) {
1007
+ return `${PLUGIN_PREFIX}${BUILT_IN_KEY_SEPARATOR}${id}`;
1008
+ }
1009
+
1010
+ //#endregion
1011
+ //#region src/types.ts
1012
+ /**
1013
+ * The unique identifier for the completion plugin.
1014
+ */
1015
+ const pluginId = namespacedId("completion");
1016
+
1017
+ //#endregion
1018
+ //#region src/utils.ts
1019
+ /**
1020
+ * @author kazuya kawaguchi (a.k.a. kazupon)
1021
+ * @license MIT
1022
+ */
1023
+ function detectRuntime() {
1024
+ if (globalThis.process !== void 0 && globalThis.process.release?.name === "node") return "node";
1025
+ if (globalThis.Deno !== void 0) return "deno";
1026
+ if (globalThis.Bun !== void 0) return "bun";
1027
+ return "unknown";
1028
+ }
1029
+ function quoteIfNeeded(path) {
1030
+ return path.includes(" ") ? `'${path}'` : path;
1031
+ }
1032
+ function quoteExec() {
1033
+ const runtime = detectRuntime();
1034
+ switch (runtime) {
1035
+ case "node": {
1036
+ const execPath = globalThis.process.execPath;
1037
+ const processArgs = globalThis.process.argv.slice(1);
1038
+ const quotedExecPath = quoteIfNeeded(execPath);
1039
+ const quotedProcessArgs = processArgs.map(quoteIfNeeded);
1040
+ const quotedProcessExecArgs = globalThis.process.execArgv.map(quoteIfNeeded);
1041
+ return `${quotedExecPath} ${quotedProcessExecArgs.join(" ")} ${quotedProcessArgs[0]}`;
1042
+ }
1043
+ case "deno": throw new Error("deno not implemented yet, welcome contributions :)");
1044
+ case "bun": throw new Error("bun not implemented yet, welcome contributions :)");
1045
+ default: throw new Error("Unsupported your javascript runtime for completion script generation.");
1046
+ }
1047
+ }
1048
+
1049
+ //#endregion
3
1050
  //#region src/index.ts
1051
+ const TERMINATOR = "--";
1052
+ const NOOP_HANDLER = () => {
1053
+ return [];
1054
+ };
4
1055
  /**
5
1056
  * completion plugin for gunshi
6
1057
  */
7
- function completion() {
1058
+ function completion(options = {}) {
1059
+ const config = options.config || {};
1060
+ const completion$1 = new Completion();
8
1061
  return plugin({
9
- id: "g:completion",
1062
+ id: pluginId,
10
1063
  name: "completion",
11
- setup(_ctx) {}
1064
+ async setup(ctx) {
1065
+ /**
1066
+ * add command for completion script generation
1067
+ */
1068
+ const completeName = "complete";
1069
+ ctx.addCommand(completeName, {
1070
+ name: completeName,
1071
+ description: "Generate shell completion script",
1072
+ run: async (cmdCtx) => {
1073
+ if (!cmdCtx.env.name) throw new Error("your cli name is not defined.");
1074
+ let shell = cmdCtx._[1];
1075
+ if (shell === TERMINATOR) shell = void 0;
1076
+ if (shell === void 0) {
1077
+ const extra = cmdCtx._.slice(cmdCtx._.indexOf(TERMINATOR) + 1);
1078
+ await completion$1.parse(extra);
1079
+ } else script(shell, cmdCtx.env.name, quoteExec());
1080
+ }
1081
+ });
1082
+ /**
1083
+ * disable header renderer
1084
+ */
1085
+ ctx.decorateHeaderRenderer(async (_baseRenderer, _cmdCtx) => "");
1086
+ },
1087
+ extension: (_ctx, _cmd) => {
1088
+ return {};
1089
+ },
1090
+ onExtension: async (ctx, _cmd) => {
1091
+ const subCommands = ctx.env.subCommands;
1092
+ const entry = [...subCommands].map(([_, cmd]) => cmd).find((cmd) => cmd.entry);
1093
+ if (!entry) throw new Error("entry command not found.");
1094
+ const isPositional = hasPositional(await resolveLazyCommand(entry));
1095
+ const root = "";
1096
+ completion$1.addCommand(root, entry.description || "", isPositional ? [false] : [], NOOP_HANDLER);
1097
+ const args = entry.args || Object.create(null);
1098
+ for (const [key, schema] of Object.entries(args)) {
1099
+ if (schema.type === "positional") continue;
1100
+ completion$1.addOption(root, `--${key}`, schema.description || "", config.entry?.args?.[key]?.handler || NOOP_HANDLER, schema.short);
1101
+ }
1102
+ await handleSubCommands(completion$1, subCommands, config.subCommands);
1103
+ }
12
1104
  });
13
1105
  }
1106
+ async function handleSubCommands(completion$1, subCommands, configs = {}) {
1107
+ for (const [name, cmd] of subCommands) {
1108
+ if (cmd.internal || cmd.entry || name === "complete") continue;
1109
+ const resolvedCmd = await resolveLazyCommand(cmd);
1110
+ const isPositional = hasPositional(resolvedCmd);
1111
+ const commandName = completion$1.addCommand(name, resolvedCmd.description || "", isPositional ? [false] : [], configs?.[name]?.handler || NOOP_HANDLER);
1112
+ const args = resolvedCmd.args || Object.create(null);
1113
+ for (const [key, schema] of Object.entries(args)) {
1114
+ if (schema.type === "positional") continue;
1115
+ completion$1.addOption(commandName, `--${key}`, schema.description || "", configs[commandName]?.args?.[key]?.handler || NOOP_HANDLER, schema.short);
1116
+ }
1117
+ }
1118
+ }
1119
+ function hasPositional(cmd) {
1120
+ return cmd.args && Object.values(cmd.args).some((arg) => arg.type === "positional");
1121
+ }
14
1122
 
15
1123
  //#endregion
16
- export { completion as default };
1124
+ export { completion as default, pluginId };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gunshi/plugin-completion",
3
3
  "description": "completion plugin for gunshi",
4
- "version": "0.27.0-alpha.6",
4
+ "version": "0.27.0-alpha.7",
5
5
  "author": {
6
6
  "name": "kazuya kawaguchi",
7
7
  "email": "kawakazu80@gmail.com"
@@ -52,18 +52,21 @@
52
52
  }
53
53
  },
54
54
  "dependencies": {
55
- "@gunshi/plugin": "0.27.0-alpha.6"
55
+ "@bombsh/tab": "https://pkg.pr.new/bombshell-dev/tab@main",
56
+ "@gunshi/plugin": "0.27.0-alpha.7"
56
57
  },
57
58
  "devDependencies": {
59
+ "@types/node": "^22.16.0",
58
60
  "deno": "^2.4.0",
59
61
  "jsr": "^0.13.5",
60
62
  "jsr-exports-lint": "^0.4.1",
61
63
  "publint": "^0.3.12",
62
- "tsdown": "^0.12.9"
64
+ "tsdown": "^0.12.9",
65
+ "@gunshi/shared": "0.27.0-alpha.7"
63
66
  },
64
67
  "scripts": {
65
68
  "build": "tsdown",
66
69
  "lint:jsr": "jsr publish --dry-run --allow-dirty",
67
- "typecheck:deno": "deno check ./src"
70
+ "typecheck:deno": "deno check --import-map=../../importmap.json ./src"
68
71
  }
69
72
  }