@clerc/plugin-completions 1.0.3 → 1.1.1

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
@@ -2,23 +2,9 @@
2
2
 
3
3
  [![NPM version](https://img.shields.io/npm/v/@clerc/plugin-completions?color=a1b858&label=)](https://www.npmjs.com/package/@clerc/plugin-completions)
4
4
 
5
- Clerc plugin to add shell completions to your cli.
5
+ ## Documenation
6
6
 
7
- ## 📦 Installation
8
-
9
- ```bash
10
- $ npm install @clerc/plugin-completions
11
- $ yarn add @clerc/plugin-completions
12
- $ pnpm add @clerc/plugin-completions
13
- ```
14
-
15
- ## 🚀 Usage
16
-
17
- ```ts
18
- import { completionsPlugin } from "@clerc/plugin-completions";
19
-
20
- cli.use(completionsPlugin());
21
- ```
7
+ Read the [documentation](https://clerc.so1ve.dev/official-plugins/plugin-completions.html) for more details.
22
8
 
23
9
  ## 📝 License
24
10
 
@@ -1,5 +1,5 @@
1
- import { ArgumentHandler, Command, OptionHandler } from "@bomb.sh/tab";
2
1
  import { Plugin } from "@clerc/core";
2
+ import { ArgumentHandler, Command, OptionHandler } from "@bomb.sh/tab";
3
3
 
4
4
  //#region src/index.d.ts
5
5
  declare module "@clerc/core" {
package/dist/index.mjs ADDED
@@ -0,0 +1,710 @@
1
+ import e from"node:assert";import{Types as t,definePlugin as n,extractParameterInfo as r,normalizeFlagValue as i,normalizeParameterValue as a}from"@clerc/core";function o(e,t){return`#compdef ${e}
2
+ compdef _${e} ${e}
3
+
4
+ # zsh completion for ${e} -*- shell-script -*-
5
+
6
+ __${e}_debug() {
7
+ local file="$BASH_COMP_DEBUG_FILE"
8
+ if [[ -n \${file} ]]; then
9
+ echo "$*" >> "\${file}"
10
+ fi
11
+ }
12
+
13
+ _${e}() {
14
+ local shellCompDirectiveError=${u.ShellCompDirectiveError}
15
+ local shellCompDirectiveNoSpace=${u.ShellCompDirectiveNoSpace}
16
+ local shellCompDirectiveNoFileComp=${u.ShellCompDirectiveNoFileComp}
17
+ local shellCompDirectiveFilterFileExt=${u.ShellCompDirectiveFilterFileExt}
18
+ local shellCompDirectiveFilterDirs=${u.ShellCompDirectiveFilterDirs}
19
+ local shellCompDirectiveKeepOrder=${u.ShellCompDirectiveKeepOrder}
20
+
21
+ local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
22
+ local -a completions
23
+
24
+ __${e}_debug "\\n========= starting completion logic =========="
25
+ __${e}_debug "CURRENT: \${CURRENT}, words[*]: \${words[*]}"
26
+
27
+ # The user could have moved the cursor backwards on the command-line.
28
+ # We need to trigger completion from the $CURRENT location, so we need
29
+ # to truncate the command-line ($words) up to the $CURRENT location.
30
+ # (We cannot use $CURSOR as its value does not work when a command is an alias.)
31
+ words=( "\${=words[1,CURRENT]}" )
32
+ __${e}_debug "Truncated words[*]: \${words[*]},"
33
+
34
+ lastParam=\${words[-1]}
35
+ lastChar=\${lastParam[-1]}
36
+ __${e}_debug "lastParam: \${lastParam}, lastChar: \${lastChar}"
37
+
38
+ # For zsh, when completing a flag with an = (e.g., ${e} -n=<TAB>)
39
+ # completions must be prefixed with the flag
40
+ setopt local_options BASH_REMATCH
41
+ if [[ "\${lastParam}" =~ '-.*=' ]]; then
42
+ # We are dealing with a flag with an =
43
+ flagPrefix="-P \${BASH_REMATCH}"
44
+ fi
45
+
46
+ # Prepare the command to obtain completions, ensuring arguments are quoted for eval
47
+ local -a args_to_quote=("\${(@)words[2,-1]}")
48
+ if [ "\${lastChar}" = "" ]; then
49
+ # If the last parameter is complete (there is a space following it)
50
+ # We add an extra empty parameter so we can indicate this to the go completion code.
51
+ __${e}_debug "Adding extra empty parameter"
52
+ args_to_quote+=("")
53
+ fi
54
+
55
+ # Use Zsh's (q) flag to quote each argument safely for eval
56
+ local quoted_args=("\${(@q)args_to_quote}")
57
+
58
+ # Join the main command and the quoted arguments into a single string for eval
59
+ requestComp="${t} complete -- \${quoted_args[*]}"
60
+
61
+ __${e}_debug "About to call: eval \${requestComp}"
62
+
63
+ # Use eval to handle any environment variables and such
64
+ out=$(eval \${requestComp} 2>/dev/null)
65
+ __${e}_debug "completion output: \${out}"
66
+
67
+ # Extract the directive integer following a : from the last line
68
+ local lastLine
69
+ while IFS='\n' read -r line; do
70
+ lastLine=\${line}
71
+ done < <(printf "%s\n" "\${out[@]}")
72
+ __${e}_debug "last line: \${lastLine}"
73
+
74
+ if [ "\${lastLine[1]}" = : ]; then
75
+ directive=\${lastLine[2,-1]}
76
+ # Remove the directive including the : and the newline
77
+ local suffix
78
+ (( suffix=\${#lastLine}+2))
79
+ out=\${out[1,-$suffix]}
80
+ else
81
+ # There is no directive specified. Leave $out as is.
82
+ __${e}_debug "No directive found. Setting to default"
83
+ directive=0
84
+ fi
85
+
86
+ __${e}_debug "directive: \${directive}"
87
+ __${e}_debug "completions: \${out}"
88
+ __${e}_debug "flagPrefix: \${flagPrefix}"
89
+
90
+ if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
91
+ __${e}_debug "Completion received error. Ignoring completions."
92
+ return
93
+ fi
94
+
95
+ local activeHelpMarker="%"
96
+ local endIndex=\${#activeHelpMarker}
97
+ local startIndex=$((\${#activeHelpMarker}+1))
98
+ local hasActiveHelp=0
99
+ while IFS='\n' read -r comp; do
100
+ # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
101
+ if [ "\${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
102
+ __${e}_debug "ActiveHelp found: $comp"
103
+ comp="\${comp[$startIndex,-1]}"
104
+ if [ -n "$comp" ]; then
105
+ compadd -x "\${comp}"
106
+ __${e}_debug "ActiveHelp will need delimiter"
107
+ hasActiveHelp=1
108
+ fi
109
+ continue
110
+ fi
111
+
112
+ if [ -n "$comp" ]; then
113
+ # If requested, completions are returned with a description.
114
+ # The description is preceded by a TAB character.
115
+ # For zsh's _describe, we need to use a : instead of a TAB.
116
+ # We first need to escape any : as part of the completion itself.
117
+ comp=\${comp//:/\\:}
118
+
119
+ local tab="$(printf '\\t')"
120
+ comp=\${comp//$tab/:}
121
+
122
+ __${e}_debug "Adding completion: \${comp}"
123
+ completions+=\${comp}
124
+ lastComp=$comp
125
+ fi
126
+ done < <(printf "%s\n" "\${out[@]}")
127
+
128
+ # Add a delimiter after the activeHelp statements, but only if:
129
+ # - there are completions following the activeHelp statements, or
130
+ # - file completion will be performed (so there will be choices after the activeHelp)
131
+ if [ $hasActiveHelp -eq 1 ]; then
132
+ if [ \${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
133
+ __${e}_debug "Adding activeHelp delimiter"
134
+ compadd -x "--"
135
+ hasActiveHelp=0
136
+ fi
137
+ fi
138
+
139
+ if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
140
+ __${e}_debug "Activating nospace."
141
+ noSpace="-S ''"
142
+ fi
143
+
144
+ if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
145
+ __${e}_debug "Activating keep order."
146
+ keepOrder="-V"
147
+ fi
148
+
149
+ if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
150
+ # File extension filtering
151
+ local filteringCmd
152
+ filteringCmd='_files'
153
+ for filter in \${completions[@]}; do
154
+ if [ \${filter[1]} != '*' ]; then
155
+ # zsh requires a glob pattern to do file filtering
156
+ filter="\\*.$filter"
157
+ fi
158
+ filteringCmd+=" -g $filter"
159
+ done
160
+ filteringCmd+=" \${flagPrefix}"
161
+
162
+ __${e}_debug "File filtering command: $filteringCmd"
163
+ _arguments '*:filename:'"$filteringCmd"
164
+ elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
165
+ # File completion for directories only
166
+ local subdir
167
+ subdir="\${completions[1]}"
168
+ if [ -n "$subdir" ]; then
169
+ __${e}_debug "Listing directories in $subdir"
170
+ pushd "\${subdir}" >/dev/null 2>&1
171
+ else
172
+ __${e}_debug "Listing directories in ."
173
+ fi
174
+
175
+ local result
176
+ _arguments '*:dirname:_files -/'" \${flagPrefix}"
177
+ result=$?
178
+ if [ -n "$subdir" ]; then
179
+ popd >/dev/null 2>&1
180
+ fi
181
+ return $result
182
+ else
183
+ __${e}_debug "Calling _describe"
184
+ if eval _describe $keepOrder "completions" completions -Q \${flagPrefix} \${noSpace}; then
185
+ __${e}_debug "_describe found some completions"
186
+
187
+ # Return the success of having called _describe
188
+ return 0
189
+ else
190
+ __${e}_debug "_describe did not find completions."
191
+ __${e}_debug "Checking if we should do file completion."
192
+ if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
193
+ __${e}_debug "deactivating file completion"
194
+
195
+ # Return 0 to indicate completion is finished and prevent zsh from
196
+ # trying other completion algorithms (which could cause hanging).
197
+ # We use NoFileComp directive to explicitly disable file completion.
198
+ return 0
199
+ else
200
+ # Perform file completion
201
+ __${e}_debug "Activating file completion"
202
+
203
+ # We must return the result of this command, so it must be the
204
+ # last command, or else we must store its result to return it.
205
+ _arguments '*:filename:_files'" \${flagPrefix}"
206
+ fi
207
+ fi
208
+ fi
209
+ }
210
+
211
+ # don't run the completion function when being sourced or eval-ed
212
+ if [ "\${funcstack[1]}" = "_${e}" ]; then
213
+ _${e}
214
+ fi
215
+ `}function s(e,t){let n=e.replace(/[-:]/g,`_`);return`# bash completion for ${e}
216
+
217
+ # Define shell completion directives
218
+ readonly ShellCompDirectiveError=${u.ShellCompDirectiveError}
219
+ readonly ShellCompDirectiveNoSpace=${u.ShellCompDirectiveNoSpace}
220
+ readonly ShellCompDirectiveNoFileComp=${u.ShellCompDirectiveNoFileComp}
221
+ readonly ShellCompDirectiveFilterFileExt=${u.ShellCompDirectiveFilterFileExt}
222
+ readonly ShellCompDirectiveFilterDirs=${u.ShellCompDirectiveFilterDirs}
223
+ readonly ShellCompDirectiveKeepOrder=${u.ShellCompDirectiveKeepOrder}
224
+
225
+ # Function to debug completion
226
+ __${n}_debug() {
227
+ if [[ -n \${BASH_COMP_DEBUG_FILE:-} ]]; then
228
+ echo "$*" >> "\${BASH_COMP_DEBUG_FILE}"
229
+ fi
230
+ }
231
+
232
+ # Function to handle completions
233
+ __${n}_complete() {
234
+ local cur prev words cword
235
+ _get_comp_words_by_ref -n "=:" cur prev words cword
236
+
237
+ local requestComp out directive
238
+
239
+ # Build the command to get completions
240
+ requestComp="${t} complete -- \${words[@]:1}"
241
+
242
+ # Add an empty parameter if the last parameter is complete
243
+ if [[ -z "$cur" ]]; then
244
+ requestComp="$requestComp ''"
245
+ fi
246
+
247
+ # Get completions from the program
248
+ out=$(eval "$requestComp" 2>/dev/null)
249
+
250
+ # Extract directive if present
251
+ directive=0
252
+ if [[ "$out" == *:* ]]; then
253
+ directive=\${out##*:}
254
+ out=\${out%:*}
255
+ fi
256
+
257
+ # Process completions based on directive
258
+ if [[ $((directive & $ShellCompDirectiveError)) -ne 0 ]]; then
259
+ # Error, no completion
260
+ return
261
+ fi
262
+
263
+ # Apply directives
264
+ if [[ $((directive & $ShellCompDirectiveNoSpace)) -ne 0 ]]; then
265
+ compopt -o nospace
266
+ fi
267
+ if [[ $((directive & $ShellCompDirectiveKeepOrder)) -ne 0 ]]; then
268
+ compopt -o nosort
269
+ fi
270
+ if [[ $((directive & $ShellCompDirectiveNoFileComp)) -ne 0 ]]; then
271
+ compopt +o default
272
+ fi
273
+
274
+ # Handle file extension filtering
275
+ if [[ $((directive & $ShellCompDirectiveFilterFileExt)) -ne 0 ]]; then
276
+ local filter=""
277
+ for ext in $out; do
278
+ filter="$filter|$ext"
279
+ done
280
+ filter="\\.($filter)"
281
+ compopt -o filenames
282
+ COMPREPLY=( $(compgen -f -X "!$filter" -- "$cur") )
283
+ return
284
+ fi
285
+
286
+ # Handle directory filtering
287
+ if [[ $((directive & $ShellCompDirectiveFilterDirs)) -ne 0 ]]; then
288
+ compopt -o dirnames
289
+ COMPREPLY=( $(compgen -d -- "$cur") )
290
+ return
291
+ fi
292
+
293
+ # Process completions
294
+ local IFS=$'\\n'
295
+ local tab=$(printf '\\t')
296
+
297
+ # Parse completions with descriptions
298
+ local completions=()
299
+ while read -r comp; do
300
+ if [[ "$comp" == *$tab* ]]; then
301
+ # Split completion and description
302
+ local value=\${comp%%$tab*}
303
+ local desc=\${comp#*$tab}
304
+ completions+=("$value")
305
+ else
306
+ completions+=("$comp")
307
+ fi
308
+ done <<< "$out"
309
+
310
+ # Return completions
311
+ COMPREPLY=( $(compgen -W "\${completions[*]}" -- "$cur") )
312
+ }
313
+
314
+ # Register completion function
315
+ complete -F __${n}_complete ${e}
316
+ `}function c(e,t){let n=e.replace(/[-:]/g,`_`);return`# fish completion for ${e} -*- shell-script -*-
317
+
318
+ # Define shell completion directives
319
+ set -l ShellCompDirectiveError ${u.ShellCompDirectiveError}
320
+ set -l ShellCompDirectiveNoSpace ${u.ShellCompDirectiveNoSpace}
321
+ set -l ShellCompDirectiveNoFileComp ${u.ShellCompDirectiveNoFileComp}
322
+ set -l ShellCompDirectiveFilterFileExt ${u.ShellCompDirectiveFilterFileExt}
323
+ set -l ShellCompDirectiveFilterDirs ${u.ShellCompDirectiveFilterDirs}
324
+ set -l ShellCompDirectiveKeepOrder ${u.ShellCompDirectiveKeepOrder}
325
+
326
+ function __${n}_debug
327
+ set -l file "$BASH_COMP_DEBUG_FILE"
328
+ if test -n "$file"
329
+ echo "$argv" >> $file
330
+ end
331
+ end
332
+
333
+ function __${n}_perform_completion
334
+ __${n}_debug "Starting __${n}_perform_completion"
335
+
336
+ # Extract all args except the completion flag
337
+ set -l args (string match -v -- "--completion=" (commandline -opc))
338
+
339
+ # Extract the current token being completed
340
+ set -l current_token (commandline -ct)
341
+
342
+ # Check if current token starts with a dash
343
+ set -l flag_prefix ""
344
+ if string match -q -- "-*" $current_token
345
+ set flag_prefix "--flag="
346
+ end
347
+
348
+ __${n}_debug "Current token: $current_token"
349
+ __${n}_debug "All args: $args"
350
+
351
+ # Call the completion program and get the results
352
+ set -l requestComp "${t} complete -- $args"
353
+ __${n}_debug "Calling $requestComp"
354
+ set -l results (eval $requestComp 2> /dev/null)
355
+
356
+ # Some programs may output extra empty lines after the directive.
357
+ # Let's ignore them or else it will break completion.
358
+ # Ref: https://github.com/spf13/cobra/issues/1279
359
+ for line in $results[-1..1]
360
+ if test (string sub -s 1 -l 1 -- $line) = ":"
361
+ # The directive
362
+ set -l directive (string sub -s 2 -- $line)
363
+ set -l directive_num (math $directive)
364
+ break
365
+ end
366
+ end
367
+
368
+ # No directive specified, use default
369
+ if not set -q directive_num
370
+ set directive_num 0
371
+ end
372
+
373
+ __${n}_debug "Directive: $directive_num"
374
+
375
+ # Process completions based on directive
376
+ if test $directive_num -eq $ShellCompDirectiveError
377
+ # Error code. No completion.
378
+ __${n}_debug "Received error directive: aborting."
379
+ return 1
380
+ end
381
+
382
+ # Filter out the directive (last line)
383
+ if test (count $results) -gt 0 -a (string sub -s 1 -l 1 -- $results[-1]) = ":"
384
+ set results $results[1..-2]
385
+ end
386
+
387
+ # No completions, let fish handle file completions unless forbidden
388
+ if test (count $results) -eq 0
389
+ if test $directive_num -ne $ShellCompDirectiveNoFileComp
390
+ __${n}_debug "No completions, performing file completion"
391
+ return 1
392
+ end
393
+ __${n}_debug "No completions, but file completion forbidden"
394
+ return 0
395
+ end
396
+
397
+ # Filter file extensions
398
+ if test $directive_num -eq $ShellCompDirectiveFilterFileExt
399
+ __${n}_debug "File extension filtering"
400
+ set -l file_extensions
401
+ for item in $results
402
+ if test -n "$item" -a (string sub -s 1 -l 1 -- $item) != "-"
403
+ set -a file_extensions "*$item"
404
+ end
405
+ end
406
+ __${n}_debug "File extensions: $file_extensions"
407
+
408
+ # Use the file extensions as completions
409
+ set -l completions
410
+ for ext in $file_extensions
411
+ # Get all files matching the extension
412
+ set -a completions (string replace -r '^.*/' '' -- $ext)
413
+ end
414
+
415
+ for item in $completions
416
+ echo -e "$item\t"
417
+ end
418
+ return 0
419
+ end
420
+
421
+ # Filter directories
422
+ if test $directive_num -eq $ShellCompDirectiveFilterDirs
423
+ __${n}_debug "Directory filtering"
424
+ set -l dirs
425
+ for item in $results
426
+ if test -d "$item"
427
+ set -a dirs "$item/"
428
+ end
429
+ end
430
+
431
+ for item in $dirs
432
+ echo -e "$item\t"
433
+ end
434
+ return 0
435
+ end
436
+
437
+ # Process remaining completions
438
+ for item in $results
439
+ if test -n "$item"
440
+ # Check if the item has a description
441
+ if string match -q "*\t*" -- "$item"
442
+ set -l completion_parts (string split \t -- "$item")
443
+ set -l comp $completion_parts[1]
444
+ set -l desc $completion_parts[2]
445
+
446
+ # Add the completion and description
447
+ echo -e "$comp\t$desc"
448
+ else
449
+ # Add just the completion
450
+ echo -e "$item\t"
451
+ end
452
+ end
453
+ end
454
+
455
+ # If directive contains NoSpace, tell fish not to add a space after completion
456
+ if test (math "$directive_num & $ShellCompDirectiveNoSpace") -ne 0
457
+ return 2
458
+ end
459
+
460
+ return 0
461
+ end
462
+
463
+ # Set up the completion for the ${e} command
464
+ complete -c ${e} -f -a "(eval __${n}_perform_completion)"
465
+ `}function l(e,t){let n=e.replace(/[-:]/g,`_`);return`# powershell completion for ${e} -*- shell-script -*-
466
+
467
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
468
+ function __${e}_debug {
469
+ if ($env:BASH_COMP_DEBUG_FILE) {
470
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
471
+ }
472
+ }
473
+
474
+ filter __${e}_escapeStringWithSpecialChars {
475
+ $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\\||<|>|&','\`$&'
476
+ }
477
+
478
+ [scriptblock]$__${n}CompleterBlock = {
479
+ param(
480
+ $WordToComplete,
481
+ $CommandAst,
482
+ $CursorPosition
483
+ )
484
+
485
+ # Get the current command line and convert into a string
486
+ $Command = $CommandAst.CommandElements
487
+ $Command = "$Command"
488
+
489
+ __${e}_debug ""
490
+ __${e}_debug "========= starting completion logic =========="
491
+ __${e}_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
492
+
493
+ # The user could have moved the cursor backwards on the command-line.
494
+ # We need to trigger completion from the $CursorPosition location, so we need
495
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
496
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
497
+ # This happens because the $Command does not include the last space.
498
+ if ($Command.Length -gt $CursorPosition) {
499
+ $Command = $Command.Substring(0, $CursorPosition)
500
+ }
501
+ __${e}_debug "Truncated command: $Command"
502
+
503
+ $ShellCompDirectiveError=${u.ShellCompDirectiveError}
504
+ $ShellCompDirectiveNoSpace=${u.ShellCompDirectiveNoSpace}
505
+ $ShellCompDirectiveNoFileComp=${u.ShellCompDirectiveNoFileComp}
506
+ $ShellCompDirectiveFilterFileExt=${u.ShellCompDirectiveFilterFileExt}
507
+ $ShellCompDirectiveFilterDirs=${u.ShellCompDirectiveFilterDirs}
508
+ $ShellCompDirectiveKeepOrder=${u.ShellCompDirectiveKeepOrder}
509
+
510
+ # Prepare the command to request completions for the program.
511
+ # Split the command at the first space to separate the program and arguments.
512
+ $Program, $Arguments = $Command.Split(" ", 2)
513
+
514
+ $RequestComp = "& ${t} complete -- $Arguments"
515
+ __${e}_debug "RequestComp: $RequestComp"
516
+
517
+ # we cannot use $WordToComplete because it
518
+ # has the wrong values if the cursor was moved
519
+ # so use the last argument
520
+ if ($WordToComplete -ne "" ) {
521
+ $WordToComplete = $Arguments.Split(" ")[-1]
522
+ }
523
+ __${e}_debug "New WordToComplete: $WordToComplete"
524
+
525
+
526
+ # Check for flag with equal sign
527
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
528
+ if ( $IsEqualFlag ) {
529
+ __${e}_debug "Completing equal sign flag"
530
+ # Remove the flag part
531
+ $Flag, $WordToComplete = $WordToComplete.Split("=", 2)
532
+ }
533
+
534
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
535
+ # If the last parameter is complete (there is a space following it)
536
+ # We add an extra empty parameter so we can indicate this to the go method.
537
+ __${e}_debug "Adding extra empty parameter"
538
+ # PowerShell 7.2+ changed the way how the arguments are passed to executables,
539
+ # so for pre-7.2 or when Legacy argument passing is enabled we need to use
540
+ if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
541
+ ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
542
+ (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
543
+ $PSNativeCommandArgumentPassing -eq 'Legacy')) {
544
+ $RequestComp="$RequestComp" + ' \`"\`"'
545
+ } else {
546
+ $RequestComp = "$RequestComp" + ' ""'
547
+ }
548
+ }
549
+
550
+ __${e}_debug "Calling $RequestComp"
551
+ # First disable ActiveHelp which is not supported for Powershell
552
+ $env:ActiveHelp = 0
553
+
554
+ # call the command store the output in $out and redirect stderr and stdout to null
555
+ # $Out is an array contains each line per element
556
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
557
+
558
+ # get directive from last line
559
+ [int]$Directive = $Out[-1].TrimStart(':')
560
+ if ($Directive -eq "") {
561
+ # There is no directive specified
562
+ $Directive = 0
563
+ }
564
+ __${e}_debug "The completion directive is: $Directive"
565
+
566
+ # remove directive (last element) from out
567
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
568
+ __${e}_debug "The completions are: $Out"
569
+
570
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
571
+ # Error code. No completion.
572
+ __${e}_debug "Received error from custom completion go code"
573
+ return
574
+ }
575
+
576
+ $Longest = 0
577
+ [Array]$Values = $Out | ForEach-Object {
578
+ # Split the output in name and description
579
+ $Name, $Description = $_.Split("\`t", 2)
580
+ __${e}_debug "Name: $Name Description: $Description"
581
+
582
+ # Look for the longest completion so that we can format things nicely
583
+ if ($Longest -lt $Name.Length) {
584
+ $Longest = $Name.Length
585
+ }
586
+
587
+ # Set the description to a one space string if there is none set.
588
+ # This is needed because the CompletionResult does not accept an empty string as argument
589
+ if (-Not $Description) {
590
+ $Description = " "
591
+ }
592
+ @{ Name = "$Name"; Description = "$Description" }
593
+ }
594
+
595
+
596
+ $Space = " "
597
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
598
+ # remove the space here
599
+ __${e}_debug "ShellCompDirectiveNoSpace is called"
600
+ $Space = ""
601
+ }
602
+
603
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
604
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
605
+ __${e}_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
606
+
607
+ # return here to prevent the completion of the extensions
608
+ return
609
+ }
610
+
611
+ $Values = $Values | Where-Object {
612
+ # filter the result
613
+ $_.Name -like "$WordToComplete*"
614
+
615
+ # Join the flag back if we have an equal sign flag
616
+ if ( $IsEqualFlag ) {
617
+ __${e}_debug "Join the equal sign flag back to the completion value"
618
+ $_.Name = $Flag + "=" + $_.Name
619
+ }
620
+ }
621
+
622
+ # we sort the values in ascending order by name if keep order isn't passed
623
+ if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
624
+ $Values = $Values | Sort-Object -Property Name
625
+ }
626
+
627
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
628
+ __${e}_debug "ShellCompDirectiveNoFileComp is called"
629
+
630
+ if ($Values.Length -eq 0) {
631
+ # Just print an empty string here so the
632
+ # shell does not start to complete paths.
633
+ # We cannot use CompletionResult here because
634
+ # it does not accept an empty string as argument.
635
+ ""
636
+ return
637
+ }
638
+ }
639
+
640
+ # Get the current mode
641
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object { $_.Key -eq "Tab" }).Function
642
+ __${e}_debug "Mode: $Mode"
643
+
644
+ $Values | ForEach-Object {
645
+
646
+ # store temporary because switch will overwrite $_
647
+ $comp = $_
648
+
649
+ # PowerShell supports three different completion modes
650
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
651
+ # - Complete (works like bash)
652
+ # - MenuComplete (works like zsh)
653
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
654
+
655
+ # CompletionResult Arguments:
656
+ # 1) CompletionText text to be used as the auto completion result
657
+ # 2) ListItemText text to be displayed in the suggestion list
658
+ # 3) ResultType type of completion result
659
+ # 4) ToolTip text for the tooltip with details about the object
660
+
661
+ switch ($Mode) {
662
+
663
+ # bash like
664
+ "Complete" {
665
+
666
+ if ($Values.Length -eq 1) {
667
+ __${e}_debug "Only one completion left"
668
+
669
+ # insert space after value
670
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${e}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
671
+
672
+ } else {
673
+ # Add the proper number of spaces to align the descriptions
674
+ while($comp.Name.Length -lt $Longest) {
675
+ $comp.Name = $comp.Name + " "
676
+ }
677
+
678
+ # Check for empty description and only add parentheses if needed
679
+ if ($($comp.Description) -eq " " ) {
680
+ $Description = ""
681
+ } else {
682
+ $Description = " ($($comp.Description))"
683
+ }
684
+
685
+ [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
686
+ }
687
+ }
688
+
689
+ # zsh like
690
+ "MenuComplete" {
691
+ # insert space after value
692
+ # MenuComplete will automatically show the ToolTip of
693
+ # the highlighted value at the bottom of the suggestions.
694
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${e}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
695
+ }
696
+
697
+ # TabCompleteNext and in case we get something unknown
698
+ Default {
699
+ # Like MenuComplete but we don't want to add a space here because
700
+ # the user need to press space anyway to get the completion.
701
+ # Description will not be shown because that's not possible with TabCompleteNext
702
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${e}_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
703
+ }
704
+ }
705
+
706
+ }
707
+ }
708
+
709
+ Register-ArgumentCompleter -CommandName '${e}' -ScriptBlock $__${n}CompleterBlock
710
+ `}const u={ShellCompDirectiveError:1,ShellCompDirectiveNoSpace:2,ShellCompDirectiveNoFileComp:4,ShellCompDirectiveFilterFileExt:8,ShellCompDirectiveFilterDirs:16,ShellCompDirectiveKeepOrder:32,shellCompDirectiveMaxValue:64,ShellCompDirectiveDefault:0};var d=class{name;variadic;command;handler;constructor(e,t,n,r=!1){this.command=e,this.name=t,this.handler=n,this.variadic=r}},f=class{value;description;command;handler;alias;isBoolean;constructor(e,t,n,r,i,a){this.command=e,this.value=t,this.description=n,this.handler=r,this.alias=i,this.isBoolean=a}},p=class{value;description;options=new Map;arguments=new Map;parent;constructor(e,t){this.value=e,this.description=t}option(e,t,n,r){let i,a,o;typeof n==`function`?(i=n,a=r,o=!1):typeof n==`string`?(i=void 0,a=n,o=!0):(i=void 0,a=void 0,o=!0);let s=new f(this,e,t,i,a,o);return this.options.set(e,s),this}argument(e,t,n=!1){let r=new d(this,e,t,n);return this.arguments.set(e,r),this}},m=class extends p{commands=new Map;completions=[];directive=u.ShellCompDirectiveDefault;constructor(){super(``,``)}command(e,t){let n=new p(e,t);return this.commands.set(e,n),n}stripOptions(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.startsWith(`-`)){n++;let t=!1,i=this.findOption(this,r);if(i)t=i.isBoolean??!1;else for(let[,e]of this.commands){let n=this.findOption(e,r);if(n){t=n.isBoolean??!1;break}}!t&&n<e.length&&!e[n].startsWith(`-`)&&n++}else t.push(r),n++}return t}matchCommand(e){e=this.stripOptions(e);let t=[],n=[],r=null;for(let i=0;i<e.length;i++){let a=e[i];t.push(a);let o=this.commands.get(t.join(` `));if(o)r=o;else{n=e.slice(i,e.length);break}}return[r||this,n]}shouldCompleteFlags(e,t){if(t.startsWith(`-`))return!0;if(e?.startsWith(`-`)){let t=this.findOption(this,e);if(!t){for(let[,n]of this.commands)if(t=this.findOption(n,e),t)break}return!(t&&t.isBoolean)}return!1}shouldCompleteCommands(e){return!e.startsWith(`-`)}handleFlagCompletion(e,t,n,r){let i;if(n.includes(`=`)){let[e]=n.split(`=`);i=e}else r?.startsWith(`-`)&&(i=r);if(i){let t=this.findOption(e,i);if(t?.handler){let n=[];t.handler.call(t,(e,t)=>n.push({value:e,description:t}),e.options),this.completions=n}return}if(n.startsWith(`-`)){let t=n.startsWith(`-`)&&!n.startsWith(`--`),r=n.replace(/^-+/,``);for(let[i,a]of e.options)t&&a.alias&&`-${a.alias}`.startsWith(n)?this.completions.push({value:`-${a.alias}`,description:a.description}):!t&&i.startsWith(r)&&this.completions.push({value:`--${i}`,description:a.description})}}findOption(e,t){let n=e.options.get(t);if(n||(n=e.options.get(t.replace(/^-+/,``)),n))return n;for(let[n,r]of e.options)if(r.alias&&`-${r.alias}`===t)return r}handleCommandCompletion(e,t){let n=this.stripOptions(e);for(let[e,r]of this.commands){if(e===``)continue;let i=e.split(` `);i.slice(0,n.length).every((e,t)=>e===n[t])&&i[n.length]?.startsWith(t)&&this.completions.push({value:i[n.length],description:r.description})}}handlePositionalCompletion(e,t){let n=e.value.split(` `).length,r=Math.max(0,t.length-n),i=Array.from(e.arguments.entries());if(i.length>0){let t;if(r<i.length){let[e,n]=i[r];t=n}else{let e=i[i.length-1][1];e.variadic&&(t=e)}if(t&&t.handler&&typeof t.handler==`function`){let n=[];t.handler.call(t,(e,t)=>n.push({value:e,description:t}),e.options),this.completions.push(...n)}}}complete(e){this.directive=u.ShellCompDirectiveNoFileComp;let t=new Set;this.completions.filter(e=>t.has(e.value)?!1:(t.add(e.value),!0)).filter(t=>{if(e.includes(`=`)){let[,n]=e.split(`=`);return t.value.startsWith(n)}return t.value.startsWith(e)}).forEach(e=>console.log(`${e.value}\t${e.description??``}`)),console.log(`:${this.directive}`)}parse(e){this.completions=[];let t=e[e.length-1]===``;t&&e.pop();let n=e[e.length-1]||``,r=e.slice(0,-1);t&&(n!==``&&r.push(n),n=``);let[i]=this.matchCommand(r),a=r[r.length-1];if(this.shouldCompleteFlags(a,n))this.handleFlagCompletion(i,r,n,a);else{if(a?.startsWith(`-`)&&n===``&&t){let e=this.findOption(this,a);if(!e){for(let[,t]of this.commands)if(e=this.findOption(t,a),e)break}if(e&&e.isBoolean){this.complete(n);return}}this.shouldCompleteCommands(n)&&this.handleCommandCompletion(r,n),i&&i.arguments.size>0&&this.handlePositionalCompletion(i,r)}this.complete(n)}setup(t,n,r){switch(e(r===`zsh`||r===`bash`||r===`fish`||r===`powershell`,`Unsupported shell`),r){case`zsh`:{let e=o(t,n);console.log(e);break}case`bash`:{let e=s(t,n);console.log(e);break}case`fish`:{let e=c(t,n);console.log(e);break}case`powershell`:{let e=l(t,n);console.log(e);break}}}};new m;function h(e,t,n){let r=i(n),a=r.description??``;if(r.type===Boolean)e.option(t,a,r.short);else{let n=r.completions?.handler??(async()=>{});e.option(t,a,n,r.short)}}function g(e,t){for(let[n,r]of Object.entries(e))h(t,n,r)}function _(e,t,n){g(t,e);for(let i of n.values()){if(i.completions?.show===!1)continue;let n=e;i.name!==``&&(n=e.command(i.name,i.description??``),g(t,n)),i.completions?.handler?.(n);for(let e of i.parameters??[]){let t=a(e),{name:i,isVariadic:o}=r(t.key);n.argument(i,t.completions?.handler,o)}for(let[e,t]of Object.entries(i.flags??{}))h(n,e,t)}}const v=()=>n({setup:e=>{let n=new m,r=t.Enum(`zsh`,`bash`,`fish`,`powershell`);return e.command(`completions`,`Generate shell completion scripts`,{flags:{shell:{description:`Shell type`,type:r}},parameters:[{key:`[shell]`,description:`Shell type`,type:r}]}).on(`completions`,async t=>{let r=t.parameters.shell??t.flags.shell;if(!r)throw Error(`Shell type is required. Please provide it via --shell flag or [shell] parameter.`);_(n,e._globalFlags,e._commands),n.setup(e._scriptName,e._scriptName,r)}),e.command(`complete`,{help:{show:!1},completions:{show:!1},parameters:[`--`,`[input...]`]}).on(`complete`,async t=>{_(n,e._globalFlags,e._commands);let{input:r}=t.parameters;n.parse(r)}),e}});export{v as completionsPlugin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/plugin-completions",
3
- "version": "1.0.3",
3
+ "version": "1.1.1",
4
4
  "author": "Ray <i@mk1.io> (https://github.com/so1ve)",
5
5
  "type": "module",
6
6
  "description": "Clerc plugin completions",
@@ -25,33 +25,24 @@
25
25
  "license": "MIT",
26
26
  "sideEffects": false,
27
27
  "exports": {
28
- ".": "./dist/index.js"
28
+ ".": "./dist/index.mjs",
29
+ "./package.json": "./package.json"
29
30
  },
30
31
  "bin": {
31
32
  "my-cli": "./src/a.mjs"
32
33
  },
33
- "main": "./dist/index.js",
34
- "module": "./dist/index.js",
35
- "types": "dist/index.d.ts",
36
- "typesVersions": {
37
- "*": {
38
- "*": [
39
- "./dist/*",
40
- "./dist/index.d.ts"
41
- ]
42
- }
43
- },
34
+ "main": "./dist/index.mjs",
35
+ "module": "./dist/index.mjs",
36
+ "types": "./dist/index.d.mts",
44
37
  "files": [
45
38
  "dist"
46
39
  ],
47
40
  "publishConfig": {
48
41
  "access": "public"
49
42
  },
50
- "dependencies": {
51
- "@bomb.sh/tab": "^0.0.10"
52
- },
53
43
  "devDependencies": {
54
- "@clerc/core": "1.0.3"
44
+ "@bomb.sh/tab": "^0.0.10",
45
+ "@clerc/core": "1.1.1"
55
46
  },
56
47
  "peerDependencies": {
57
48
  "@clerc/core": "*"
package/dist/index.js DELETED
@@ -1,70 +0,0 @@
1
- import { RootCommand } from "@bomb.sh/tab";
2
- import { Types, definePlugin, extractParameterInfo, normalizeFlagValue, normalizeParameterValue } from "@clerc/core";
3
-
4
- //#region src/t.ts
5
- function registerFlag(tc, flagName, def) {
6
- const normalized = normalizeFlagValue(def);
7
- const desc = normalized.description ?? "";
8
- if (normalized.type === Boolean) tc.option(flagName, desc, normalized.short);
9
- else {
10
- const handler = normalized.completions?.handler ?? (async () => {});
11
- tc.option(flagName, desc, handler, normalized.short);
12
- }
13
- }
14
- function registerGlobalFlags(globalFlags, tc) {
15
- for (const [flagName, def] of Object.entries(globalFlags)) registerFlag(tc, flagName, def);
16
- }
17
- function buildTabModel(t, globalFlags, commands) {
18
- registerGlobalFlags(globalFlags, t);
19
- for (const cmd of commands.values()) {
20
- if (cmd.completions?.show === false) continue;
21
- let command = t;
22
- if (cmd.name !== "") {
23
- command = t.command(cmd.name, cmd.description ?? "");
24
- registerGlobalFlags(globalFlags, command);
25
- }
26
- cmd.completions?.handler?.(command);
27
- for (const def of cmd.parameters ?? []) {
28
- const normalized = normalizeParameterValue(def);
29
- const { name, isVariadic } = extractParameterInfo(normalized.key);
30
- command.argument(name, normalized.completions?.handler, isVariadic);
31
- }
32
- for (const [flagName, def] of Object.entries(cmd.flags ?? {})) registerFlag(command, flagName, def);
33
- }
34
- }
35
-
36
- //#endregion
37
- //#region src/index.ts
38
- const completionsPlugin = () => definePlugin({ setup: (cli) => {
39
- const t = new RootCommand();
40
- const supportedShellEnum = Types.Enum("zsh", "bash", "fish", "powershell");
41
- cli.command("completions", "Generate shell completion scripts", {
42
- flags: { shell: {
43
- description: "Shell type",
44
- type: supportedShellEnum
45
- } },
46
- parameters: [{
47
- key: "[shell]",
48
- description: "Shell type",
49
- type: supportedShellEnum
50
- }]
51
- }).on("completions", async (ctx) => {
52
- const shell = ctx.parameters.shell ?? ctx.flags.shell;
53
- if (!shell) throw new Error("Shell type is required. Please provide it via --shell flag or [shell] parameter.");
54
- buildTabModel(t, cli._globalFlags, cli._commands);
55
- t.setup(cli._scriptName, cli._scriptName, shell);
56
- });
57
- cli.command("complete", {
58
- help: { show: false },
59
- completions: { show: false },
60
- parameters: ["--", "[input...]"]
61
- }).on("complete", async (ctx) => {
62
- buildTabModel(t, cli._globalFlags, cli._commands);
63
- const { input } = ctx.parameters;
64
- t.parse(input);
65
- });
66
- return cli;
67
- } });
68
-
69
- //#endregion
70
- export { completionsPlugin };